commit_id
stringlengths 40
40
| project
stringclasses 90
values | commit_message
stringlengths 5
2.21k
| type
stringclasses 3
values | url
stringclasses 89
values | git_diff
stringlengths 283
4.32M
|
|---|---|---|---|---|---|
4600b51887de35647220ca47fa1a09042db2cb52
|
Delta Spike
|
DELTASPIKE-286 Comparators should be Serializable
|
c
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/Annotateds.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/Annotateds.java
index 71eea5cfc..0b25c99fc 100644
--- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/Annotateds.java
+++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/Annotateds.java
@@ -26,6 +26,7 @@
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.AnnotatedParameter;
import javax.enterprise.inject.spi.AnnotatedType;
+import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
@@ -33,6 +34,7 @@
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
@@ -51,14 +53,21 @@
* <code>Annotated</code> instances.
* </p>
*/
-public class Annotateds
+public final class Annotateds
{
+ private static final char SEPARATOR = ';';
+
+ private Annotateds()
+ {
+ // this is a utility class with statics only
+ }
/**
* Does the first stage of comparing AnnoatedCallables, however it cannot
* compare the method parameters
*/
- private static class AnnotatedCallableComparator<T> implements Comparator<AnnotatedCallable<? super T>>
+ private static class AnnotatedCallableComparator<T>
+ implements Comparator<AnnotatedCallable<? super T>>, Serializable
{
public int compare(AnnotatedCallable<? super T> arg0, AnnotatedCallable<? super T> arg1)
@@ -81,7 +90,8 @@ public int compare(AnnotatedCallable<? super T> arg0, AnnotatedCallable<? super
}
- private static class AnnotatedMethodComparator<T> implements Comparator<AnnotatedMethod<? super T>>
+ private static class AnnotatedMethodComparator<T>
+ implements Comparator<AnnotatedMethod<? super T>>, Serializable
{
private AnnotatedCallableComparator<T> callableComparator = new AnnotatedCallableComparator<T>();
@@ -113,7 +123,8 @@ public int compare(AnnotatedMethod<? super T> arg0, AnnotatedMethod<? super T> a
}
- private static class AnnotatedConstructorComparator<T> implements Comparator<AnnotatedConstructor<? super T>>
+ private static class AnnotatedConstructorComparator<T>
+ implements Comparator<AnnotatedConstructor<? super T>>, Serializable
{
private AnnotatedCallableComparator<T> callableComparator = new AnnotatedCallableComparator<T>();
@@ -145,7 +156,8 @@ public int compare(AnnotatedConstructor<? super T> arg0, AnnotatedConstructor<?
}
- private static class AnnotatedFieldComparator<T> implements Comparator<AnnotatedField<? super T>>
+ private static class AnnotatedFieldComparator<T>
+ implements Comparator<AnnotatedField<? super T>>, Serializable
{
public static <T> Comparator<AnnotatedField<? super T>> instance()
@@ -165,7 +177,7 @@ public int compare(AnnotatedField<? super T> arg0, AnnotatedField<? super T> arg
}
- private static class AnnotationComparator implements Comparator<Annotation>
+ private static class AnnotationComparator implements Comparator<Annotation>, Serializable
{
public static final Comparator<Annotation> INSTANCE = new AnnotationComparator();
@@ -187,12 +199,6 @@ public int compare(Method arg0, Method arg1)
}
}
- private static final char SEPERATOR = ';';
-
- private Annotateds()
- {
- }
-
/**
* Generates a deterministic signature for an {@link AnnotatedType}. Two
* <code>AnnotatedType</code>s that have the same annotations and underlying
@@ -216,7 +222,7 @@ public static <X> String createTypeId(AnnotatedType<X> annotatedType)
* <code>annotations</code>, <code>methods</code>, <code>fields</code> and
* <code>constructors</code> arguments
*
- * @param clazz The java class tyoe
+ * @param clazz The java class type
* @param annotations Annotations present on the java class
* @param methods The AnnotatedMethods to include in the signature
* @param fields The AnnotatedFields to include in the signature
@@ -243,7 +249,7 @@ public static <X> String createTypeId(Class<X> clazz, Collection<Annotation> ann
if (!field.getAnnotations().isEmpty())
{
builder.append(createFieldId(field));
- builder.append(SEPERATOR);
+ builder.append(SEPARATOR);
}
}
@@ -256,7 +262,7 @@ public static <X> String createTypeId(Class<X> clazz, Collection<Annotation> ann
if (!method.getAnnotations().isEmpty() || hasMethodParameters(method))
{
builder.append(createCallableId(method));
- builder.append(SEPERATOR);
+ builder.append(SEPARATOR);
}
}
@@ -269,7 +275,7 @@ public static <X> String createTypeId(Class<X> clazz, Collection<Annotation> ann
if (!constructor.getAnnotations().isEmpty() || hasMethodParameters(constructor))
{
builder.append(createCallableId(constructor));
- builder.append(SEPERATOR);
+ builder.append(SEPARATOR);
}
}
builder.append("}");
@@ -578,10 +584,7 @@ private static String createAnnotationCollectionId(Collection<Annotation> annota
builder.append('(');
Method[] declaredMethods = a.annotationType().getDeclaredMethods();
List<Method> methods = new ArrayList<Method>(declaredMethods.length);
- for (Method m : declaredMethods)
- {
- methods.add(m);
- }
+ methods.addAll(Arrays.asList(declaredMethods));
Collections.sort(methods, MethodComparator.INSTANCE);
for (int i = 0; i < methods.size(); ++i)
|
c225b44f3440d8799f1be96de7e27131ad9086c3
|
spring-framework
|
SPR-5636 - @RequestMapping matching should be- insensitive to trailing slashes--
|
c
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter.java
index 5ba30a4d49e2..2b936b5de378 100644
--- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter.java
+++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter.java
@@ -503,7 +503,15 @@ private boolean isPathMatchInternal(String pattern, String lookupPath) {
if (pattern.equals(lookupPath) || pathMatcher.match(pattern, lookupPath)) {
return true;
}
- return !(pattern.indexOf('.') != -1) && pathMatcher.match(pattern + ".*", lookupPath);
+ boolean hasSuffix = pattern.indexOf('.') != -1;
+ if (!hasSuffix && pathMatcher.match(pattern + ".*", lookupPath)) {
+ return true;
+ }
+ boolean endsWithSlash = pattern.endsWith("/");
+ if (!endsWithSlash && pathMatcher.match(pattern + "/", lookupPath)) {
+ return true;
+ }
+ return false;
}
private boolean checkParameters(RequestMappingInfo mapping, HttpServletRequest request) {
diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/annotation/DefaultAnnotationHandlerMapping.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/annotation/DefaultAnnotationHandlerMapping.java
index 07c136ffb688..f2087c192a0f 100644
--- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/annotation/DefaultAnnotationHandlerMapping.java
+++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/annotation/DefaultAnnotationHandlerMapping.java
@@ -86,10 +86,10 @@ public class DefaultAnnotationHandlerMapping extends AbstractDetectingUrlHandler
/**
* Set whether to register paths using the default suffix pattern as well:
- * i.e. whether "/users" should be registered as "/users.*" too.
+ * i.e. whether "/users" should be registered as "/users.*" and "/users/" too.
* <p>Default is "true". Turn this convention off if you intend to interpret
* your <code>@RequestMapping</code> paths strictly.
- * <p>Note that paths which include a ".xxx" suffix already will not be
+ * <p>Note that paths which include a ".xxx" suffix or end with "/" already will not be
* transformed using the default suffix pattern in any case.
*/
public void setUseDefaultSuffixPattern(boolean useDefaultSuffixPattern) {
@@ -168,8 +168,9 @@ public void doWith(Method method) {
*/
protected void addUrlsForPath(Set<String> urls, String path) {
urls.add(path);
- if (this.useDefaultSuffixPattern && path.indexOf('.') == -1) {
+ if (this.useDefaultSuffixPattern && path.indexOf('.') == -1 && !path.endsWith("/")) {
urls.add(path + ".*");
+ urls.add(path + "/");
}
}
diff --git a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/UriTemplateServletAnnotationControllerTests.java b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/UriTemplateServletAnnotationControllerTests.java
index fd87705ddf32..587f70a9bf9e 100644
--- a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/UriTemplateServletAnnotationControllerTests.java
+++ b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/UriTemplateServletAnnotationControllerTests.java
@@ -152,6 +152,11 @@ public void crud() throws Exception {
servlet.service(request, response);
assertEquals("list", response.getContentAsString());
+ request = new MockHttpServletRequest("GET", "/hotels/");
+ response = new MockHttpServletResponse();
+ servlet.service(request, response);
+ assertEquals("list", response.getContentAsString());
+
request = new MockHttpServletRequest("POST", "/hotels");
response = new MockHttpServletResponse();
servlet.service(request, response);
@@ -162,6 +167,11 @@ public void crud() throws Exception {
servlet.service(request, response);
assertEquals("show-42", response.getContentAsString());
+ request = new MockHttpServletRequest("GET", "/hotels/42/");
+ response = new MockHttpServletResponse();
+ servlet.service(request, response);
+ assertEquals("show-42", response.getContentAsString());
+
request = new MockHttpServletRequest("PUT", "/hotels/42");
response = new MockHttpServletResponse();
servlet.service(request, response);
|
1dc33f9f6d29c6b33de2023d4f2158e70a1c89aa
|
orientdb
|
UPDATE ADD now possible with subdocuments fields--
|
a
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdate.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdate.java
index df9e1a06034..94deb108910 100755
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdate.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdate.java
@@ -275,7 +275,13 @@ else if (returning.equalsIgnoreCase("AFTER"))
// IN ALL OTHER CASES USE A LIST
coll = new ArrayList<Object>();
- record.field(entry.getKey(), coll);
+ // containField's condition above does NOT check subdocument's fields so
+ Collection<Object> currColl = record.field(entry.getKey());
+ if (currColl==null)
+ record.field(entry.getKey(), coll);
+ else
+ coll = currColl;
+
} else {
fieldValue = record.field(entry.getKey());
|
3dea5ee0ddcd7bd07160feaae94569969a9ff6b1
|
brandonborkholder$glg2d
|
Abstracted out some color helper functionality and cleaned up the image shader pipeline.
|
p
|
https://github.com/brandonborkholder/glg2d
|
diff --git a/src/main/java/glg2d/G2DGLSimpleEventListener.java b/src/main/java/glg2d/G2DGLSimpleEventListener.java
index c074274c..0dc9484c 100644
--- a/src/main/java/glg2d/G2DGLSimpleEventListener.java
+++ b/src/main/java/glg2d/G2DGLSimpleEventListener.java
@@ -107,7 +107,7 @@ public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height
* calls.
*/
protected GLGraphics2D createGraphics2D(GLAutoDrawable drawable) {
- return new GLGraphics2D();
+ return new GLShaderGraphics2D();
}
@Override
diff --git a/src/main/java/glg2d/impl/AbstractColorHelper.java b/src/main/java/glg2d/impl/AbstractColorHelper.java
new file mode 100644
index 00000000..894fab20
--- /dev/null
+++ b/src/main/java/glg2d/impl/AbstractColorHelper.java
@@ -0,0 +1,181 @@
+/**************************************************************************
+ Copyright 2012 Brandon Borkholder
+
+ 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 glg2d.impl;
+
+import glg2d.GLG2DColorHelper;
+import glg2d.GLGraphics2D;
+
+import java.awt.AlphaComposite;
+import java.awt.Color;
+import java.awt.Composite;
+import java.awt.Paint;
+import java.awt.RenderingHints.Key;
+import java.util.ArrayDeque;
+import java.util.Deque;
+
+import javax.media.opengl.GL;
+
+public abstract class AbstractColorHelper implements GLG2DColorHelper {
+ protected GLGraphics2D g2d;
+
+ protected Deque<ColorState> stack = new ArrayDeque<ColorState>();
+
+ @Override
+ public void setG2D(GLGraphics2D g2d) {
+ this.g2d = g2d;
+
+ stack.clear();
+ stack.push(new ColorState());
+ }
+
+ @Override
+ public void push(GLGraphics2D newG2d) {
+ stack.push(stack.peek().clone());
+ }
+
+ @Override
+ public void pop(GLGraphics2D parentG2d) {
+ stack.pop();
+
+ // set all the states
+ setComposite(getComposite());
+ setColor(getColor());
+ setBackground(getBackground());
+ }
+
+ @Override
+ public void setHint(Key key, Object value) {
+ // nop
+ }
+
+ @Override
+ public void resetHints() {
+ // nop
+ }
+
+ @Override
+ public void dispose() {
+ }
+
+ @Override
+ public void setComposite(Composite comp) {
+ GL gl = g2d.getGLContext().getGL();
+ gl.glEnable(GL.GL_BLEND);
+ if (comp instanceof AlphaComposite) {
+ switch (((AlphaComposite) comp).getRule()) {
+ /*
+ * Since the destination _always_ covers the entire canvas (i.e. there are
+ * always color components for every pixel), some of these composites can
+ * be collapsed into each other. They matter when Java2D is drawing into
+ * an image and the destination may not take up the entire canvas.
+ */
+ case AlphaComposite.SRC:
+ case AlphaComposite.SRC_IN:
+ gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ZERO);
+ break;
+
+ case AlphaComposite.SRC_OVER:
+ case AlphaComposite.SRC_ATOP:
+ gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
+ break;
+
+ case AlphaComposite.SRC_OUT:
+ case AlphaComposite.CLEAR:
+ gl.glBlendFunc(GL.GL_ZERO, GL.GL_ZERO);
+ break;
+
+ case AlphaComposite.DST:
+ case AlphaComposite.DST_OVER:
+ gl.glBlendFunc(GL.GL_ZERO, GL.GL_ONE);
+ break;
+
+ case AlphaComposite.DST_IN:
+ case AlphaComposite.DST_ATOP:
+ gl.glBlendFunc(GL.GL_ZERO, GL.GL_SRC_ALPHA);
+ break;
+
+ case AlphaComposite.DST_OUT:
+ case AlphaComposite.XOR:
+ gl.glBlendFunc(GL.GL_ZERO, GL.GL_ONE_MINUS_SRC_ALPHA);
+ break;
+ }
+
+ stack.peek().composite = comp;
+ // need to pre-multiply the alpha
+ setColor(getColor());
+ } else {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ @Override
+ public Composite getComposite() {
+ return stack.peek().composite;
+ }
+
+ @Override
+ public void setColor(Color c) {
+ if (c == null) {
+ return;
+ }
+
+ stack.peek().color = c;
+ setColorRespectComposite(c);
+ }
+
+ @Override
+ public Color getColor() {
+ return stack.peek().color;
+ }
+
+ @Override
+ public void setBackground(Color color) {
+ stack.peek().background = color;
+ }
+
+ @Override
+ public Color getBackground() {
+ return stack.peek().background;
+ }
+
+ @Override
+ public void setPaint(Paint paint) {
+ stack.peek().paint = paint;
+ }
+
+ @Override
+ public Paint getPaint() {
+ return stack.peek().paint;
+ }
+
+ protected static class ColorState implements Cloneable {
+ public Composite composite;
+ public Color color;
+ public Paint paint;
+ public Color background;
+
+ @Override
+ public ColorState clone() {
+ try {
+ return (ColorState) super.clone();
+ } catch (CloneNotSupportedException e) {
+ // can't think of a reason this would happen
+ throw new RuntimeException(e);
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/glg2d/impl/gl2/GL2ColorHelper.java b/src/main/java/glg2d/impl/gl2/GL2ColorHelper.java
index 1dc62391..7f2da35f 100644
--- a/src/main/java/glg2d/impl/gl2/GL2ColorHelper.java
+++ b/src/main/java/glg2d/impl/gl2/GL2ColorHelper.java
@@ -16,120 +16,24 @@
package glg2d.impl.gl2;
-import glg2d.G2DDrawingHelper;
-import glg2d.GLG2DColorHelper;
import glg2d.GLGraphics2D;
+import glg2d.impl.AbstractColorHelper;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Paint;
-import java.awt.RenderingHints.Key;
-import java.util.ArrayDeque;
-import java.util.Deque;
-import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GL2GL3;
-public class GL2ColorHelper implements G2DDrawingHelper, GLG2DColorHelper {
- protected GLGraphics2D g2d;
-
+public class GL2ColorHelper extends AbstractColorHelper {
protected GL2 gl;
- protected Deque<ColorState> stack = new ArrayDeque<ColorState>(10);
-
@Override
public void setG2D(GLGraphics2D g2d) {
- this.g2d = g2d;
+ super.setG2D(g2d);
gl = g2d.getGLContext().getGL().getGL2();
-
- stack.clear();
- stack.push(new ColorState());
- }
-
- @Override
- public void push(GLGraphics2D newG2d) {
- stack.push(stack.peek().clone());
- }
-
- @Override
- public void pop(GLGraphics2D parentG2d) {
- stack.pop();
-
- // set all the states
- setComposite(getComposite());
- setColor(getColor());
- setBackground(getBackground());
- }
-
- @Override
- public void setHint(Key key, Object value) {
- // nop
- }
-
- @Override
- public void resetHints() {
- // nop
- }
-
- @Override
- public void dispose() {
- }
-
- @Override
- public void setComposite(Composite comp) {
- gl.glEnable(GL.GL_BLEND);
- if (comp instanceof AlphaComposite) {
- switch (((AlphaComposite) comp).getRule()) {
- /*
- * Since the destination _always_ covers the entire canvas (i.e. there are
- * always color components for every pixel), some of these composites can
- * be collapsed into each other. They matter when Java2D is drawing into
- * an image and the destination may not take up the entire canvas.
- */
- case AlphaComposite.SRC:
- case AlphaComposite.SRC_IN:
- gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ZERO);
- break;
-
- case AlphaComposite.SRC_OVER:
- case AlphaComposite.SRC_ATOP:
- gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
- break;
-
- case AlphaComposite.SRC_OUT:
- case AlphaComposite.CLEAR:
- gl.glBlendFunc(GL.GL_ZERO, GL.GL_ZERO);
- break;
-
- case AlphaComposite.DST:
- case AlphaComposite.DST_OVER:
- gl.glBlendFunc(GL.GL_ZERO, GL.GL_ONE);
- break;
-
- case AlphaComposite.DST_IN:
- case AlphaComposite.DST_ATOP:
- gl.glBlendFunc(GL.GL_ZERO, GL.GL_SRC_ALPHA);
- break;
-
- case AlphaComposite.DST_OUT:
- case AlphaComposite.XOR:
- gl.glBlendFunc(GL.GL_ZERO, GL.GL_ONE_MINUS_SRC_ALPHA);
- break;
- }
-
- stack.peek().composite = comp;
- // need to pre-multiply the alpha
- setColor(getColor());
- } else {
- throw new UnsupportedOperationException();
- }
- }
-
- @Override
- public Composite getComposite() {
- return stack.peek().composite;
}
@Override
@@ -144,30 +48,14 @@ public void setPaint(Paint paint) {
@Override
public Paint getPaint() {
- // until we implement Paint fully
return getColor();
}
- @Override
- public Color getColor() {
- return stack.peek().color;
- }
-
@Override
public void setColorNoRespectComposite(Color c) {
setColor(gl, c, 1);
}
- @Override
- public void setColor(Color c) {
- if (c == null) {
- return;
- }
-
- stack.peek().color = c;
- setColorRespectComposite(c);
- }
-
/**
* Sets the current color with a call to glColor4*. But it respects the
* AlphaComposite if any. If the AlphaComposite wants to pre-multiply an
@@ -189,18 +77,6 @@ private void setColor(GL2 gl, Color c, float preMultiplyAlpha) {
gl.glColor4ub((byte) (rgb >> 16 & 0xFF), (byte) (rgb >> 8 & 0xFF), (byte) (rgb & 0xFF), (byte) ((rgb >> 24 & 0xFF) * preMultiplyAlpha));
}
- @Override
- public void setBackground(Color color) {
- stack.peek().background = color;
- int rgb = color.getRGB();
- gl.glClearColor((rgb >> 16 & 0xFF) / 255F, (rgb >> 8 & 0xFF) / 255F, (rgb & 0xFF) / 255F, (rgb >> 24 & 0xFF) / 255F);
- }
-
- @Override
- public Color getBackground() {
- return stack.peek().background;
- }
-
@Override
public void setPaintMode() {
// TODO Auto-generated method stub
@@ -222,19 +98,4 @@ public void copyArea(int x, int y, int width, int height, int dx, int dy) {
int y1 = g2d.getCanvasHeight() - (y + height);
gl.glCopyPixels(x1, y1, width, height, GL2GL3.GL_COLOR);
}
-
- protected static class ColorState {
- public Composite composite;
- public Color color;
- public Color background;
-
- @Override
- public ColorState clone() {
- ColorState c = new ColorState();
- c.composite = composite;
- c.color = color;
- c.background = background;
- return c;
- }
- }
}
diff --git a/src/main/java/glg2d/impl/shader/GL2ES2ColorHelper.java b/src/main/java/glg2d/impl/shader/GL2ES2ColorHelper.java
new file mode 100644
index 00000000..aaaf90ac
--- /dev/null
+++ b/src/main/java/glg2d/impl/shader/GL2ES2ColorHelper.java
@@ -0,0 +1,57 @@
+package glg2d.impl.shader;
+
+import glg2d.impl.AbstractColorHelper;
+
+import java.awt.AlphaComposite;
+import java.awt.Color;
+import java.awt.Composite;
+
+public class GL2ES2ColorHelper extends AbstractColorHelper {
+ protected float[] foregroundRGBA = new float[4];
+
+ @Override
+ public void setColorNoRespectComposite(Color c) {
+ foregroundRGBA[0] = c.getRed() / 255f;
+ foregroundRGBA[1] = c.getGreen() / 255f;
+ foregroundRGBA[2] = c.getBlue() / 255f;
+ foregroundRGBA[3] = c.getAlpha() / 255f;
+ }
+
+ @Override
+ public void setColorRespectComposite(Color c) {
+ float alpha = getCompositeAlpha();
+ foregroundRGBA[0] = c.getRed() / 255f;
+ foregroundRGBA[1] = c.getGreen() / 255f;
+ foregroundRGBA[2] = c.getBlue() / 255f;
+ foregroundRGBA[3] = (c.getAlpha() / 255f) * alpha;
+ }
+
+ @Override
+ public void setPaintMode() {
+ // not implemented yet
+ }
+
+ @Override
+ public void setXORMode(Color c) {
+ // not implemented yet
+ }
+
+ @Override
+ public void copyArea(int x, int y, int width, int height, int dx, int dy) {
+ // not implemented yet
+ }
+
+ public float[] getForegroundRGBA() {
+ return foregroundRGBA;
+ }
+
+ public float getCompositeAlpha() {
+ Composite composite = getComposite();
+ float alpha = 1;
+ if (composite instanceof AlphaComposite) {
+ alpha = ((AlphaComposite) composite).getAlpha();
+ }
+
+ return alpha;
+ }
+}
diff --git a/src/main/java/glg2d/impl/shader/GL2ES2ImageDrawer.java b/src/main/java/glg2d/impl/shader/GL2ES2ImageDrawer.java
index 0799840c..0d5271df 100644
--- a/src/main/java/glg2d/impl/shader/GL2ES2ImageDrawer.java
+++ b/src/main/java/glg2d/impl/shader/GL2ES2ImageDrawer.java
@@ -33,6 +33,8 @@ public class GL2ES2ImageDrawer extends AbstractImageHelper {
protected FloatBuffer buffer = Buffers.newDirectFloatBuffer(300);
protected GL2ES2ImagePipeline shader;
+ private float[] white = new float[] { 1, 1, 1, 1 };
+
public GL2ES2ImageDrawer(GL2ES2ImagePipeline shader) {
this.shader = shader;
}
@@ -66,8 +68,18 @@ protected void begin(Texture texture, AffineTransform xform, Color bgcolor) {
shader.use(gl, true);
- shader.setColor(gl, bgcolor == null ? Color.white : bgcolor);
- shader.setMatrix(gl, ((GL2ES2TransformHelper) g2d.getMatrixHelper()).getGLMatrixData(xform));
+ float[] rgba;
+ if (bgcolor == null) {
+ rgba = white;
+ rgba[3] = ((GL2ES2ColorHelper) g2d.getColorHelper()).getCompositeAlpha();
+ } else {
+ rgba = ((GL2ES2ColorHelper) g2d.getColorHelper()).getForegroundRGBA();
+ }
+
+ FloatBuffer matrixBuf = ((GL2ES2TransformHelper) g2d.getMatrixHelper()).getGLMatrixData(xform);
+
+ shader.setColor(gl, rgba);
+ shader.setMatrix(gl, matrixBuf);
shader.setTextureUnit(gl, 0);
}
diff --git a/src/main/java/glg2d/impl/shader/GL2ES2ImagePipeline.java b/src/main/java/glg2d/impl/shader/GL2ES2ImagePipeline.java
index e8111b0d..39c0c5ea 100644
--- a/src/main/java/glg2d/impl/shader/GL2ES2ImagePipeline.java
+++ b/src/main/java/glg2d/impl/shader/GL2ES2ImagePipeline.java
@@ -1,8 +1,5 @@
package glg2d.impl.shader;
-import static glg2d.GLG2DUtils.getGLColor;
-
-import java.awt.Color;
import java.nio.FloatBuffer;
import javax.media.opengl.GL;
@@ -25,10 +22,9 @@ public void setMatrix(GL2ES2 gl, FloatBuffer glMatrixData) {
}
}
- public void setColor(GL2ES2 gl, Color c) {
- float[] color = getGLColor(c);
+ public void setColor(GL2ES2 gl, float[] rgba) {
if (colorLocation >= 0) {
- gl.glUniform4fv(colorLocation, 1, color, 0);
+ gl.glUniform4fv(colorLocation, 1, rgba, 0);
}
}
@@ -39,14 +35,11 @@ public void setTextureUnit(GL2ES2 gl, int unit) {
}
public void bindVertCoords(GL2ES2 gl, FloatBuffer buffer) {
- vertArrayData = GLArrayDataServer.createGLSL("a_vertCoord", 2, GL.GL_FLOAT, false, buffer.limit() - buffer.position(),
- GL.GL_STATIC_DRAW);
vertArrayData.put(buffer);
vertArrayData.seal(gl, true);
}
public void bindTexCoords(GL2ES2 gl, FloatBuffer buffer) {
- texArrayData = GLArrayDataServer.createGLSL("a_texCoord", 2, GL.GL_FLOAT, false, buffer.limit() - buffer.position(), GL.GL_STATIC_DRAW);
texArrayData.put(buffer);
texArrayData.seal(gl, true);
}
@@ -58,6 +51,9 @@ public void createProgramAndAttach(GL2ES2 gl) {
transformLocation = gl.glGetUniformLocation(program.id(), "u_transform");
colorLocation = gl.glGetUniformLocation(program.id(), "u_color");
textureLocation = gl.glGetUniformLocation(program.id(), "u_tex");
+
+ vertArrayData = GLArrayDataServer.createGLSL("a_vertCoord", 2, GL.GL_FLOAT, false, 8, GL.GL_DYNAMIC_DRAW);
+ texArrayData = GLArrayDataServer.createGLSL("a_texCoord", 2, GL.GL_FLOAT, false, 8, GL.GL_DYNAMIC_DRAW);
}
@Override
diff --git a/src/main/java/glg2d/impl/shader/GL2ES2TransformHelper.java b/src/main/java/glg2d/impl/shader/GL2ES2TransformHelper.java
index 0b027a37..74321969 100644
--- a/src/main/java/glg2d/impl/shader/GL2ES2TransformHelper.java
+++ b/src/main/java/glg2d/impl/shader/GL2ES2TransformHelper.java
@@ -20,12 +20,18 @@ public class GL2ES2TransformHelper implements GLG2DTransformHelper {
protected boolean dirtyMatrixBuffer;
+ protected int[] viewportDimensions;
+
@Override
public void setG2D(GLGraphics2D g2d) {
this.g2d = g2d;
transformStack.clear();
transformStack.push(new AffineTransform());
dirtyMatrixBuffer = true;
+
+ viewportDimensions = new int[4];
+ GL gl = g2d.getGLContext().getGL();
+ gl.glGetIntegerv(GL.GL_VIEWPORT, viewportDimensions, 0);
}
@Override
@@ -132,26 +138,35 @@ public FloatBuffer getGLMatrixData(AffineTransform concat) {
}
protected void updateMatrix(AffineTransform xform, FloatBuffer buffer) {
- // we're going to add the GL->G2D coordinate transform inline here
- int[] viewportDimensions = new int[4];
- GL gl = g2d.getGLContext().getGL();
- gl.glGetIntegerv(GL.GL_VIEWPORT, viewportDimensions, 0);
- int canvasWidth = viewportDimensions[2];
- int canvasHeight = viewportDimensions[3];
+ // add the GL->G2D coordinate transform and perspective inline here
- float[] matrix = new float[16];
-
- matrix[0] = (float) (2 * xform.getScaleX() / canvasWidth);
- matrix[1] = (float) (-2 * xform.getShearY() / canvasHeight);
- matrix[4] = (float) (2 * xform.getShearX() / canvasWidth);
- matrix[5] = (float) (-2 * xform.getScaleY() / canvasHeight);
- matrix[10] = -1;
- matrix[12] = (float) (2 * xform.getTranslateX() / canvasWidth - 1);
- matrix[13] = (float) (1 - 2 * xform.getTranslateY() / canvasHeight);
- matrix[15] = 1;
+ int x1 = viewportDimensions[0];
+ int y1 = viewportDimensions[1];
+ int x2 = viewportDimensions[2];
+ int y2 = viewportDimensions[3];
buffer.rewind();
- buffer.put(matrix);
+
+ buffer.put((float) (2 * xform.getScaleX() / (x2 - x1)));
+ buffer.put((float) (-2 * xform.getShearY() / (y2 - y1)));
+ buffer.put(0);
+ buffer.put(0);
+
+ buffer.put((float) (2 * xform.getShearX() / (x2 - x1)));
+ buffer.put((float) (-2 * xform.getScaleY() / (y2 - y1)));
+ buffer.put(0);
+ buffer.put(0);
+
+ buffer.put(0);
+ buffer.put(0);
+ buffer.put(-1);
+ buffer.put(0);
+
+ buffer.put((float) (2 * xform.getTranslateX() / (x2 - x1) - 1));
+ buffer.put((float) (1 - 2 * xform.getTranslateY() / (y2 - y1)));
+ buffer.put(0);
+ buffer.put(1);
+
buffer.flip();
}
}
diff --git a/src/main/java/glg2d/impl/shader/GLShaderGraphics2D.java b/src/main/java/glg2d/impl/shader/GLShaderGraphics2D.java
index a662a2ed..999cca0e 100644
--- a/src/main/java/glg2d/impl/shader/GLShaderGraphics2D.java
+++ b/src/main/java/glg2d/impl/shader/GLShaderGraphics2D.java
@@ -16,27 +16,33 @@
package glg2d.impl.shader;
+import glg2d.GLG2DColorHelper;
import glg2d.GLG2DImageHelper;
import glg2d.GLG2DTransformHelper;
import glg2d.GLGraphics2D;
+import javax.media.opengl.DebugGL4bc;
import javax.media.opengl.GLAutoDrawable;
public class GLShaderGraphics2D extends GLGraphics2D {
-
@Override
protected void setCanvas(GLAutoDrawable drawable) {
// for debugging
-// drawable.setGL(new DebugGL4bc(drawable.getGL().getGL4bc()));
-
+ drawable.setGL(new DebugGL4bc(drawable.getGL().getGL4bc()));
+
super.setCanvas(drawable);
}
@Override
protected GLG2DImageHelper createImageHelper() {
- return new GL2ES2ImageDrawer(new GL2ES2ImagePipeline());
+ return new GL2ES2ImageDrawer(new GL2ES2ImagePipeline());
}
-
+
+ @Override
+ protected GLG2DColorHelper createColorHelper() {
+ return new GL2ES2ColorHelper();
+ }
+
@Override
protected GLG2DTransformHelper createTransformHelper() {
return new GL2ES2TransformHelper();
|
290343ed0276ade6737d6b2e7a2b701c3a70ce77
|
kotlin
|
refactoring--
|
p
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/state/JetTypeMapper.java b/compiler/backend/src/org/jetbrains/jet/codegen/state/JetTypeMapper.java
index 8720b44a3f13d..32e489b5b6965 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/state/JetTypeMapper.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/state/JetTypeMapper.java
@@ -776,10 +776,11 @@ private JvmMethodSignature mapConstructorSignature(ConstructorDescriptor descrip
if (closure != null) {
for (Map.Entry<DeclarationDescriptor, EnclosedValueDescriptor> entry : closure.getCaptureVariables().entrySet()) {
- if (entry.getKey() instanceof VariableDescriptor && !(entry.getKey() instanceof PropertyDescriptor)) {
- Type sharedVarType = getSharedVarType(entry.getKey());
+ DeclarationDescriptor variableDescriptor = entry.getKey();
+ if (variableDescriptor instanceof VariableDescriptor && !(variableDescriptor instanceof PropertyDescriptor)) {
+ Type sharedVarType = getSharedVarType(variableDescriptor);
if (sharedVarType == null) {
- sharedVarType = mapType(((VariableDescriptor) entry.getKey()).getType());
+ sharedVarType = mapType(((VariableDescriptor) variableDescriptor).getType());
}
signatureWriter.writeParameterType(JvmMethodParameterKind.SHARED_VAR);
signatureWriter.writeAsmType(sharedVarType, false);
|
d66956b1177df05de05644f53e33509d790b57bf
|
spring-framework
|
Changed use of AssertThrows to @Test(expected =- ...)--
|
p
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.testsuite/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterUtilsTests.java b/org.springframework.testsuite/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterUtilsTests.java
index ccecc08a64e4..16382eb95497 100644
--- a/org.springframework.testsuite/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterUtilsTests.java
+++ b/org.springframework.testsuite/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterUtilsTests.java
@@ -20,19 +20,20 @@
import java.util.HashMap;
import java.util.Map;
-import junit.framework.TestCase;
+import static org.junit.Assert.*;
+import org.junit.Test;
import org.springframework.dao.InvalidDataAccessApiUsageException;
-import org.springframework.test.AssertThrows;
/**
* @author Thomas Risberg
* @author Juergen Hoeller
* @author Rick Evans
*/
-public class NamedParameterUtilsTests extends TestCase {
+public class NamedParameterUtilsTests {
- public void testParseSql() {
+ @Test
+ public void parseSql() {
String sql = "xxx :a yyyy :b :c :a zzzzz";
ParsedSql psql = NamedParameterUtils.parseSqlStatement(sql);
assertEquals("xxx ? yyyy ? ? ? zzzzz", NamedParameterUtils.substituteNamedParameters(psql, null));
@@ -57,21 +58,24 @@ public void testParseSql() {
}
- public void testSubstituteNamedParameters() {
+ @Test
+ public void substituteNamedParameters() {
MapSqlParameterSource namedParams = new MapSqlParameterSource();
namedParams.addValue("a", "a").addValue("b", "b").addValue("c", "c");
assertEquals("xxx ? ? ?", NamedParameterUtils.substituteNamedParameters("xxx :a :b :c", namedParams));
- assertEquals("xxx ? ? ? xx ? ?", NamedParameterUtils.substituteNamedParameters("xxx :a :b :c xx :a :a", namedParams));
+ assertEquals("xxx ? ? ? xx ? ?",
+ NamedParameterUtils.substituteNamedParameters("xxx :a :b :c xx :a :a", namedParams));
}
- public void testConvertParamMapToArray() {
- Map paramMap = new HashMap();
+ @Test
+ public void convertParamMapToArray() {
+ Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("a", "a");
paramMap.put("b", "b");
paramMap.put("c", "c");
- assertTrue(3 == NamedParameterUtils.buildValueArray("xxx :a :b :c", paramMap).length);
- assertTrue(5 == NamedParameterUtils.buildValueArray("xxx :a :b :c xx :a :b", paramMap).length);
- assertTrue(5 == NamedParameterUtils.buildValueArray("xxx :a :a :a xx :a :a", paramMap).length);
+ assertSame(3, NamedParameterUtils.buildValueArray("xxx :a :b :c", paramMap).length);
+ assertSame(5, NamedParameterUtils.buildValueArray("xxx :a :b :c xx :a :b", paramMap).length);
+ assertSame(5, NamedParameterUtils.buildValueArray("xxx :a :a :a xx :a :a", paramMap).length);
assertEquals("b", NamedParameterUtils.buildValueArray("xxx :a :b :c xx :a :b", paramMap)[4]);
try {
NamedParameterUtils.buildValueArray("xxx :a :b ?", paramMap);
@@ -81,31 +85,35 @@ public void testConvertParamMapToArray() {
}
}
- public void testConvertTypeMapToArray() {
+ @Test
+ public void convertTypeMapToArray() {
MapSqlParameterSource namedParams = new MapSqlParameterSource();
namedParams.addValue("a", "a", 1).addValue("b", "b", 2).addValue("c", "c", 3);
- assertTrue(3 == NamedParameterUtils.buildSqlTypeArray(NamedParameterUtils.parseSqlStatement("xxx :a :b :c"), namedParams).length);
- assertTrue(5 == NamedParameterUtils.buildSqlTypeArray(NamedParameterUtils.parseSqlStatement("xxx :a :b :c xx :a :b"), namedParams).length);
- assertTrue(5 == NamedParameterUtils.buildSqlTypeArray(NamedParameterUtils.parseSqlStatement("xxx :a :a :a xx :a :a"), namedParams).length);
- assertEquals(2, NamedParameterUtils.buildSqlTypeArray(NamedParameterUtils.parseSqlStatement("xxx :a :b :c xx :a :b"), namedParams)[4]);
+ assertSame(3, NamedParameterUtils
+ .buildSqlTypeArray(NamedParameterUtils.parseSqlStatement("xxx :a :b :c"), namedParams).length);
+ assertSame(5, NamedParameterUtils
+ .buildSqlTypeArray(NamedParameterUtils.parseSqlStatement("xxx :a :b :c xx :a :b"), namedParams).length);
+ assertSame(5, NamedParameterUtils
+ .buildSqlTypeArray(NamedParameterUtils.parseSqlStatement("xxx :a :a :a xx :a :a"), namedParams).length);
+ assertEquals(2, NamedParameterUtils
+ .buildSqlTypeArray(NamedParameterUtils.parseSqlStatement("xxx :a :b :c xx :a :b"), namedParams)[4]);
}
- public void testBuildValueArrayWithMissingParameterValue() throws Exception {
- new AssertThrows(InvalidDataAccessApiUsageException.class) {
- public void test() throws Exception {
- String sql = "select count(0) from foo where id = :id";
- NamedParameterUtils.buildValueArray(sql, new HashMap());
- }
- }.runTest();
+ @Test(expected = InvalidDataAccessApiUsageException.class)
+ public void buildValueArrayWithMissingParameterValue() throws Exception {
+ String sql = "select count(0) from foo where id = :id";
+ NamedParameterUtils.buildValueArray(sql, new HashMap());
}
- public void testSubstituteNamedParametersWithStringContainingQuotes() throws Exception {
+ @Test
+ public void substituteNamedParametersWithStringContainingQuotes() throws Exception {
String expectedSql = "select 'first name' from artists where id = ? and quote = 'exsqueeze me?'";
String sql = "select 'first name' from artists where id = :id and quote = 'exsqueeze me?'";
String newSql = NamedParameterUtils.substituteNamedParameters(sql, new MapSqlParameterSource());
assertEquals(expectedSql, newSql);
}
+ @Test
public void testParseSqlStatementWithStringContainingQuotes() throws Exception {
String expectedSql = "select 'first name' from artists where id = ? and quote = 'exsqueeze me?'";
String sql = "select 'first name' from artists where id = :id and quote = 'exsqueeze me?'";
@@ -116,7 +124,8 @@ public void testParseSqlStatementWithStringContainingQuotes() throws Exception {
/*
* SPR-4789
*/
- public void testParseSqlContainingComments() {
+ @Test
+ public void parseSqlContainingComments() {
String sql1 = "/*+ HINT */ xxx /* comment ? */ :a yyyy :b :c :a zzzzz -- :xx XX\n";
ParsedSql psql1 = NamedParameterUtils.parseSqlStatement(sql1);
assertEquals("/*+ HINT */ xxx /* comment ? */ ? yyyy ? ? ? zzzzz -- :xx XX\n",
@@ -152,7 +161,8 @@ public void testParseSqlContainingComments() {
/*
* SPR-4612
*/
- public void testParseSqlStatementWithPostgresCasting() throws Exception {
+ @Test
+ public void parseSqlStatementWithPostgresCasting() throws Exception {
String expectedSql = "select 'first name' from artists where id = ? and birth_date=?::timestamp";
String sql = "select 'first name' from artists where id = :id and birth_date=:birthDate::timestamp";
ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql);
@@ -162,7 +172,8 @@ public void testParseSqlStatementWithPostgresCasting() throws Exception {
/*
* SPR-2544
*/
- public void testParseSqlStatementWithLogicalAnd() {
+ @Test
+ public void parseSqlStatementWithLogicalAnd() {
String expectedSql = "xxx & yyyy";
ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(expectedSql);
assertEquals(expectedSql, NamedParameterUtils.substituteNamedParameters(parsedSql, null));
@@ -171,7 +182,8 @@ public void testParseSqlStatementWithLogicalAnd() {
/*
* SPR-2544
*/
- public void testSubstituteNamedParametersWithLogicalAnd() throws Exception {
+ @Test
+ public void substituteNamedParametersWithLogicalAnd() throws Exception {
String expectedSql = "xxx & yyyy";
String newSql = NamedParameterUtils.substituteNamedParameters(expectedSql, new MapSqlParameterSource());
assertEquals(expectedSql, newSql);
@@ -180,7 +192,8 @@ public void testSubstituteNamedParametersWithLogicalAnd() throws Exception {
/*
* SPR-3173
*/
- public void testVariableAssignmentOperator() throws Exception {
+ @Test
+ public void variableAssignmentOperator() throws Exception {
String expectedSql = "x := 1";
String newSql = NamedParameterUtils.substituteNamedParameters(expectedSql, new MapSqlParameterSource());
assertEquals(expectedSql, newSql);
|
e9f46afa47e9b7c0d7aaf90568237d35a76e9535
|
Mylyn Reviews
|
Moved "tbr" to subfolder and added folders for other projects
|
p
|
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
|
diff --git a/framework/README.txt b/framework/README.txt
new file mode 100644
index 00000000..e69de29b
diff --git a/gerrit/README.txt b/gerrit/README.txt
new file mode 100644
index 00000000..e69de29b
diff --git a/tbr/org.eclipse.mylyn.reviews-site/.project b/tbr/org.eclipse.mylyn.reviews-site/.project
new file mode 100644
index 00000000..e7305348
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews-site/.project
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.mylyn.reviews-site</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.pde.UpdateSiteBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.UpdateSiteNature</nature>
+ </natures>
+</projectDescription>
diff --git a/tbr/org.eclipse.mylyn.reviews-site/site.xml b/tbr/org.eclipse.mylyn.reviews-site/site.xml
new file mode 100644
index 00000000..5ca060f2
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews-site/site.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<site>
+ <feature url="features/org.eclipse.mylyn.reviews_0.0.1.jar" id="org.eclipse.mylyn.reviews" version="0.0.1">
+ <category name="mylyn.reviews"/>
+ </feature>
+ <category-def name="mylyn.reviews" label="Mylyn Reviews (Incubation)"/>
+</site>
diff --git a/tbr/org.eclipse.mylyn.reviews.core/.classpath b/tbr/org.eclipse.mylyn.reviews.core/.classpath
new file mode 100644
index 00000000..121e527a
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/.classpath
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/tbr/org.eclipse.mylyn.reviews.core/.project b/tbr/org.eclipse.mylyn.reviews.core/.project
new file mode 100644
index 00000000..7b0cd529
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/.project
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.mylyn.reviews.core</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.api.tools.apiAnalysisBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ <nature>org.eclipse.pde.api.tools.apiAnalysisNature</nature>
+ </natures>
+</projectDescription>
diff --git a/tbr/org.eclipse.mylyn.reviews.core/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.reviews.core/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..b93a9fc9
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/META-INF/MANIFEST.MF
@@ -0,0 +1,18 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Mylyn Reviews Core (Incubation)
+Bundle-SymbolicName: org.eclipse.mylyn.reviews.core;singleton:=true
+Bundle-Version: 0.0.1
+Bundle-Activator: org.eclipse.mylyn.reviews.core.Activator
+Require-Bundle: org.eclipse.core.runtime,
+ org.eclipse.emf.edit;bundle-version="2.5.0",
+ org.eclipse.team.core;bundle-version="3.5.0",
+ org.eclipse.core.resources;bundle-version="3.5.1",
+ org.eclipse.mylyn.tasks.core;bundle-version="3.3.0",
+ org.eclipse.compare;bundle-version="3.5.0"
+Bundle-ActivationPolicy: lazy
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Export-Package: org.eclipse.mylyn.reviews.core,
+ org.eclipse.mylyn.reviews.core.model.review,
+ org.eclipse.mylyn.reviews.core.model.review.impl,
+ org.eclipse.mylyn.reviews.core.model.review.util
diff --git a/tbr/org.eclipse.mylyn.reviews.core/about.html b/tbr/org.eclipse.mylyn.reviews.core/about.html
new file mode 100644
index 00000000..c258ef55
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/about.html
@@ -0,0 +1,28 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
+<title>About</title>
+</head>
+<body lang="EN-US">
+<h2>About This Content</h2>
+
+<p>June 5, 2006</p>
+<h3>License</h3>
+
+<p>The Eclipse Foundation makes available all content in this plug-in ("Content"). Unless otherwise
+indicated below, the Content is provided to you under the terms and conditions of the
+Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is available
+at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>.
+For purposes of the EPL, "Program" will mean the Content.</p>
+
+<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is
+being redistributed by another party ("Redistributor") and different terms and conditions may
+apply to your use of any object code in the Content. Check the Redistributor's license that was
+provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise
+indicated below, the terms and conditions of the EPL still apply to any source code in the Content
+and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p>
+
+</body>
+</html>
\ No newline at end of file
diff --git a/tbr/org.eclipse.mylyn.reviews.core/build.properties b/tbr/org.eclipse.mylyn.reviews.core/build.properties
new file mode 100644
index 00000000..3022405d
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/build.properties
@@ -0,0 +1,16 @@
+###############################################################################
+# Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+# All rights reserved. This program and the accompanying materials
+# are made available under the terms of the Eclipse Public License v1.0
+# which accompanies this distribution, and is available at
+# http://www.eclipse.org/legal/epl-v10.html
+#
+# Contributors:
+# Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+###############################################################################
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+ .,\
+ plugin.xml
+jre.compilation.profile = J2SE-1.5
diff --git a/tbr/org.eclipse.mylyn.reviews.core/model/review.ecore b/tbr/org.eclipse.mylyn.reviews.core/model/review.ecore
new file mode 100644
index 00000000..f2d227e6
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/model/review.ecore
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ecore:EPackage xmi:version="2.0"
+ xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore" name="review"
+ nsURI="org.eclipse.mylyn.reviews" nsPrefix="">
+ <eClassifiers xsi:type="ecore:EClass" name="Review">
+ <eStructuralFeatures xsi:type="ecore:EReference" name="result" eType="#//ReviewResult"/>
+ <eStructuralFeatures xsi:type="ecore:EReference" name="scope" upperBound="-1"
+ eType="#//ScopeItem"/>
+ </eClassifiers>
+ <eClassifiers xsi:type="ecore:EClass" name="ReviewResult">
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="text" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="rating" eType="#//Rating"/>
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="reviewer" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
+ </eClassifiers>
+ <eClassifiers xsi:type="ecore:EClass" name="Patch" eSuperTypes="#//ScopeItem">
+ <eOperations name="parse" upperBound="-1" eType="#//IFilePatch2"/>
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="contents" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="creationDate" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EDate"/>
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="fileName" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
+ </eClassifiers>
+ <eClassifiers xsi:type="ecore:EEnum" name="Rating">
+ <eLiterals name="NONE"/>
+ <eLiterals name="PASSED"/>
+ <eLiterals name="WARNING"/>
+ <eLiterals name="FAILED"/>
+ </eClassifiers>
+ <eClassifiers xsi:type="ecore:EDataType" name="IFilePatch2" instanceClassName="org.eclipse.compare.patch.IFilePatch2"/>
+ <eClassifiers xsi:type="ecore:EDataType" name="IProgressMonitor" instanceClassName="org.eclipse.core.runtime.IProgressMonitor"/>
+ <eClassifiers xsi:type="ecore:EClass" name="ScopeItem">
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="author" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
+ </eClassifiers>
+</ecore:EPackage>
diff --git a/tbr/org.eclipse.mylyn.reviews.core/model/review.genmodel b/tbr/org.eclipse.mylyn.reviews.core/model/review.genmodel
new file mode 100644
index 00000000..c3b7f79e
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/model/review.genmodel
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<genmodel:GenModel xmi:version="2.0"
+ xmlns:xmi="http://www.omg.org/XMI" xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore"
+ xmlns:genmodel="http://www.eclipse.org/emf/2002/GenModel" modelDirectory="/org.eclipse.mylyn.reviews.core/src"
+ modelPluginID="org.eclipse.mylyn.reviews.core" modelName="Review" importerID="org.eclipse.emf.importer.ecore"
+ complianceLevel="5.0" copyrightFields="false">
+ <foreignModel>review.ecore</foreignModel>
+ <genPackages prefix="Review" basePackage="org.eclipse.mylyn.reviews.core.model"
+ disposableProviderFactory="true" ecorePackage="review.ecore#/">
+ <genEnums typeSafeEnumCompatible="false" ecoreEnum="review.ecore#//Rating">
+ <genEnumLiterals ecoreEnumLiteral="review.ecore#//Rating/NONE"/>
+ <genEnumLiterals ecoreEnumLiteral="review.ecore#//Rating/PASSED"/>
+ <genEnumLiterals ecoreEnumLiteral="review.ecore#//Rating/WARNING"/>
+ <genEnumLiterals ecoreEnumLiteral="review.ecore#//Rating/FAILED"/>
+ </genEnums>
+ <genDataTypes ecoreDataType="review.ecore#//IFilePatch2"/>
+ <genDataTypes ecoreDataType="review.ecore#//IProgressMonitor"/>
+ <genClasses ecoreClass="review.ecore#//Review">
+ <genFeatures notify="false" createChild="false" propertySortChoices="true" ecoreFeature="ecore:EReference review.ecore#//Review/result"/>
+ <genFeatures notify="false" createChild="false" propertySortChoices="true" ecoreFeature="ecore:EReference review.ecore#//Review/scope"/>
+ </genClasses>
+ <genClasses ecoreClass="review.ecore#//ReviewResult">
+ <genFeatures createChild="false" ecoreFeature="ecore:EAttribute review.ecore#//ReviewResult/text"/>
+ <genFeatures createChild="false" ecoreFeature="ecore:EAttribute review.ecore#//ReviewResult/rating"/>
+ <genFeatures createChild="false" ecoreFeature="ecore:EAttribute review.ecore#//ReviewResult/reviewer"/>
+ </genClasses>
+ <genClasses ecoreClass="review.ecore#//Patch">
+ <genFeatures createChild="false" ecoreFeature="ecore:EAttribute review.ecore#//Patch/contents"/>
+ <genFeatures createChild="false" ecoreFeature="ecore:EAttribute review.ecore#//Patch/creationDate"/>
+ <genFeatures createChild="false" ecoreFeature="ecore:EAttribute review.ecore#//Patch/fileName"/>
+ <genOperations ecoreOperation="review.ecore#//Patch/parse"/>
+ </genClasses>
+ <genClasses ecoreClass="review.ecore#//ScopeItem">
+ <genFeatures createChild="false" ecoreFeature="ecore:EAttribute review.ecore#//ScopeItem/author"/>
+ </genClasses>
+ </genPackages>
+</genmodel:GenModel>
diff --git a/tbr/org.eclipse.mylyn.reviews.core/plugin.properties b/tbr/org.eclipse.mylyn.reviews.core/plugin.properties
new file mode 100644
index 00000000..4041a812
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/plugin.properties
@@ -0,0 +1,42 @@
+###############################################################################
+# Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+# All rights reserved. This program and the accompanying materials
+# are made available under the terms of the Eclipse Public License v1.0
+# which accompanies this distribution, and is available at
+# http://www.eclipse.org/legal/epl-v10.html
+#
+# Contributors:
+# Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+###############################################################################
+
+pluginName = Review Edit Support
+providerName = www.example.org
+
+_UI_CreateChild_text = {0}
+_UI_CreateChild_text2 = {1} {0}
+_UI_CreateChild_text3 = {1}
+_UI_CreateChild_tooltip = Create New {0} Under {1} Feature
+_UI_CreateChild_description = Create a new child of type {0} for the {1} feature of the selected {2}.
+_UI_CreateSibling_description = Create a new sibling of type {0} for the selected {2}, under the {1} feature of their parent.
+
+_UI_PropertyDescriptor_description = The {0} of the {1}
+
+_UI_User_type = User
+_UI_Assignment_type = Assignment
+_UI_Period_type = Period
+_UI_Review_type = Review
+_UI_Unknown_type = Object
+
+_UI_Unknown_datatype= Value
+
+_UI_User_name_feature = Name
+_UI_Assignment_author_feature = Author
+_UI_Assignment_reviewer_feature = Reviewer
+_UI_Assignment_period_feature = Period
+_UI_Period_startDate_feature = Start Date
+_UI_Period_assignments_feature = Assignments
+_UI_Review_users_feature = Users
+_UI_Review_periods_feature = Periods
+_UI_Unknown_feature = Unspecified
+
+_UI_Review_content_type = Review File
diff --git a/tbr/org.eclipse.mylyn.reviews.core/plugin.xml b/tbr/org.eclipse.mylyn.reviews.core/plugin.xml
new file mode 100644
index 00000000..703ee688
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/plugin.xml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.4"?><!--
+ Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ All rights reserved. This program and the accompanying materials
+ are made available under the terms of the Eclipse Public License v1.0
+ which accompanies this distribution, and is available at
+ http://www.eclipse.org/legal/epl-v10.html
+
+ Contributors:
+ Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ -->
+
+<plugin>
+</plugin>
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/Activator.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/Activator.java
new file mode 100644
index 00000000..16999003
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/Activator.java
@@ -0,0 +1,67 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.core;
+
+import org.eclipse.core.runtime.Plugin;
+import org.osgi.framework.BundleContext;
+
+/**
+ * The activator class controls the plug-in life cycle
+ * @author Kilian Matt
+ */
+public class Activator extends Plugin {
+
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.mylyn.reviews.core"; //$NON-NLS-1$
+
+ // The shared instance
+ private static Activator plugin;
+
+ /**
+ * The constructor
+ */
+ public Activator() {
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.core.runtime.Plugins#start(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.core.runtime.Plugin#stop(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static Activator getDefault() {
+ return plugin;
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/GitPatchPathFindingStrategy.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/GitPatchPathFindingStrategy.java
new file mode 100644
index 00000000..4875e3ea
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/GitPatchPathFindingStrategy.java
@@ -0,0 +1,44 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.core;
+
+import java.io.InputStreamReader;
+import java.io.Reader;
+
+import org.eclipse.compare.patch.ReaderCreator;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+
+/**
+ * @author Kilian Matt
+ */
+public class GitPatchPathFindingStrategy implements ITargetPathStrategy {
+
+ public ReaderCreator get(IPath path) {
+ final IFile file = org.eclipse.core.resources.ResourcesPlugin
+ .getWorkspace().getRoot().getFile(path.removeFirstSegments(1));
+ return new ReaderCreator() {
+ @Override
+ public Reader createReader() throws CoreException {
+ return new InputStreamReader(file.getContents());
+ }
+ };
+ }
+
+ public boolean matches(IPath targetPath) {
+ final IFile file = org.eclipse.core.resources.ResourcesPlugin
+ .getWorkspace().getRoot().getFile(targetPath.removeFirstSegments(1));
+
+ return file.exists();
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ITargetPathStrategy.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ITargetPathStrategy.java
new file mode 100644
index 00000000..78f355cc
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ITargetPathStrategy.java
@@ -0,0 +1,23 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.core;
+
+import org.eclipse.compare.patch.ReaderCreator;
+import org.eclipse.core.runtime.IPath;
+
+/*
+ * @author Kilian Matt
+ */
+public interface ITargetPathStrategy {
+ boolean matches(IPath path);
+
+ ReaderCreator get(IPath path);
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewConstants.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewConstants.java
new file mode 100644
index 00000000..704be905
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewConstants.java
@@ -0,0 +1,25 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.core;
+
+/**
+ * @author Kilian Matt
+ */
+public class ReviewConstants {
+
+ public static final String REVIEW_DATA_CONTAINER = "review-data.zip";
+
+ public static final String REVIEW_DATA_FILE = "reviews-data.xml";
+
+ public static final String ATTR_CACHED_REVIEW = "review";
+
+ public static final String ATTR_REVIEW_FLAG = "isReview";
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewData.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewData.java
new file mode 100644
index 00000000..bcf8c548
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewData.java
@@ -0,0 +1,48 @@
+package org.eclipse.mylyn.reviews.core;
+
+import org.eclipse.mylyn.reviews.core.model.review.Review;
+import org.eclipse.mylyn.tasks.core.ITask;
+
+public class ReviewData {
+ private boolean outgoing;
+ private Review review;
+ private ITask task;
+ private boolean dirty;
+
+ public ReviewData(ITask task, Review review) {
+ this.task=task;
+ this.review = review;
+ }
+
+ public boolean isOutgoing() {
+ return outgoing;
+ }
+
+ public void setOutgoing() {
+ this.outgoing = true;
+ }
+
+ public void setOutgoing(boolean outgoing) {
+ this.outgoing = outgoing;
+ }
+
+ public ITask getTask() {
+ return task;
+ }
+
+ public Review getReview() {
+ return review;
+ }
+
+ public void setDirty(boolean isDirty) {
+ this.dirty=isDirty;
+ }
+
+ public void setDirty() {
+ setDirty(true);
+ }
+ public boolean isDirty() {
+ return this.dirty;
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataManager.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataManager.java
new file mode 100644
index 00000000..13ec95fd
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataManager.java
@@ -0,0 +1,90 @@
+package org.eclipse.mylyn.reviews.core;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.emf.common.notify.Adapter;
+import org.eclipse.emf.common.notify.Notification;
+import org.eclipse.emf.common.notify.Notifier;
+import org.eclipse.emf.common.notify.impl.AdapterImpl;
+import org.eclipse.mylyn.reviews.core.model.review.Review;
+import org.eclipse.mylyn.tasks.core.IRepositoryModel;
+import org.eclipse.mylyn.tasks.core.ITask;
+import org.eclipse.mylyn.tasks.core.data.ITaskDataManager;
+
+public class ReviewDataManager {
+ private Map<ITask, ReviewData> cached = new HashMap<ITask, ReviewData>();
+ private ReviewDataStore store;
+ private ITaskDataManager taskDataManager;
+ private IRepositoryModel repositoryModel;
+
+ public ReviewDataManager(ReviewDataStore store,
+ ITaskDataManager taskDataManager, IRepositoryModel repositoryModel) {
+ this.store = store;
+ this.taskDataManager = taskDataManager;
+ this.repositoryModel = repositoryModel;
+
+ }
+
+ public void storeOutgoingTask(ITask task, Review review) {
+ ReviewData reviewData = new ReviewData(task, review);
+ reviewData.setOutgoing();
+ cached.put(task, reviewData);
+ store.storeReviewData(task.getRepositoryUrl(), task.getTaskId(),
+ review, "review");
+ }
+
+ public ReviewData getReviewData(ITask task) {
+ if (task == null)
+ return null;
+ ReviewData reviewData = cached.get(task);
+ if (reviewData == null) {
+ reviewData = loadFromDiskAddCache(task);
+ }
+ if (reviewData == null) {
+ reviewData = loadFromTask(task);
+ }
+ return reviewData;
+ }
+
+ private ReviewData loadFromTask(ITask task) {
+ try {
+ List<Review> reviews = ReviewsUtil.getReviewAttachmentFromTask(
+ taskDataManager, repositoryModel, task);
+ storeTask(task, reviews.get(reviews.size() - 1));
+
+ return getReviewData(task);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ private ReviewData loadFromDiskAddCache(ITask task) {
+ List<Review> reviews = store.loadReviewData(task.getRepositoryUrl(),
+ task.getTaskId());
+ if (reviews.size() > 0) {
+ Review review = reviews.get(0);
+ storeTask(task, review);
+ return getReviewData(task);
+ }
+ return null;
+ }
+
+ public void storeTask(ITask task, Review review) {
+ final ReviewData reviewData = new ReviewData(task, review);
+ review.eAdapters().add(new AdapterImpl() {
+ public void notifyChanged(Notification notification) {
+ System.err.println("notification "+notification);
+ reviewData.setDirty(true);
+ }
+
+ });
+ cached.put(task, reviewData);
+ store.storeReviewData(task.getRepositoryUrl(), task.getTaskId(),
+ review, "review");
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataStore.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataStore.java
new file mode 100644
index 00000000..f24ad5a6
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataStore.java
@@ -0,0 +1,105 @@
+package org.eclipse.mylyn.reviews.core;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+import java.util.zip.ZipOutputStream;
+
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.resource.ResourceSet;
+import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
+import org.eclipse.mylyn.reviews.core.model.review.Review;
+import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
+
+public class ReviewDataStore {
+
+ private String storeRootDir;
+
+ public ReviewDataStore(String storeRootDir) {
+ this.storeRootDir = storeRootDir;
+ }
+
+ public void storeReviewData(String repositoryUrl, String taskId,
+ Review review, String id) {
+ try {
+
+ File file = getFile(repositoryUrl, taskId);
+ createDirectoriesIfNecessary(file);
+ if (!file.exists()) {
+ file.createNewFile();
+ ZipOutputStream outputStream = new ZipOutputStream(
+ new FileOutputStream(file));
+ ResourceSet resourceSet = new ResourceSetImpl();
+
+ Resource resource = resourceSet.createResource(URI
+ .createFileURI("")); //$NON-NLS-1$
+
+ resource.getContents().add(review);
+ resource.getContents().add(review.getScope().get(0));
+ if (review.getResult() != null)
+ resource.getContents().add(review.getResult());
+
+ outputStream.putNextEntry(new ZipEntry(id));
+ resource.save(outputStream, null);
+ outputStream.closeEntry();
+ outputStream.close();
+ } else {
+ // TODO append
+
+ }
+ } catch (Exception e) {
+ // TODO: handle exception
+ e.printStackTrace();
+ }
+ }
+
+ private void createDirectoriesIfNecessary(File file) {
+ File parent = file.getParentFile();
+ if(!parent.exists()) {
+ parent.mkdirs();
+ }
+ }
+
+ public List<Review> loadReviewData(String repositoryUrl, String taskId) {
+ List<Review> reviews = new ArrayList<Review>();
+ try {
+
+ File file = getFile(repositoryUrl, taskId);
+ if(!file.exists()) {
+ return reviews;
+ }
+ ZipInputStream inputStream = new ZipInputStream(
+ new FileInputStream(file));
+ inputStream.getNextEntry();
+ ResourceSet resourceSet = new ResourceSetImpl();
+ resourceSet.getPackageRegistry().put(ReviewPackage.eNS_URI,
+ ReviewPackage.eINSTANCE);
+ Resource resource = resourceSet.createResource(URI.createURI(""));
+ resource.load(inputStream, null);
+ for (EObject item : resource.getContents()) {
+ if (item instanceof Review) {
+ Review review = (Review) item;
+ reviews.add(review);
+ }
+ }
+ } catch (Exception e) {
+ // TODO: handle exception
+ e.printStackTrace();
+ }
+ return reviews;
+ }
+
+ private File getFile(String repositoryUrl, String taskId) {
+ File path = new File(storeRootDir + File.separator + "reviews"
+ + File.separator + URLEncoder.encode(repositoryUrl)
+ + File.separator);
+ return new File(path, taskId);
+ }
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewSubTask.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewSubTask.java
new file mode 100644
index 00000000..db2ba150
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewSubTask.java
@@ -0,0 +1,81 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.core;
+
+import java.util.Date;
+
+import org.eclipse.mylyn.reviews.core.model.review.Rating;
+import org.eclipse.mylyn.tasks.core.ITask;
+
+/**
+ * @author Kilian Matt
+ */
+public class ReviewSubTask {
+
+ private String comment;
+ private ITask task;
+ private Date creationDate;
+
+ public ReviewSubTask(String patchFile, Date creationDate, String author,
+ String reviewer, Rating result, String comment, ITask task) {
+ super();
+ this.patchFile = patchFile;
+ this.creationDate = new Date(creationDate.getTime());
+ this.author = author;
+ this.reviewer = reviewer;
+ this.result = result;
+ this.comment = comment;
+ this.task = task;
+ }
+
+ private String patchFile;
+ private String author;
+ private String reviewer;
+ private Rating result;
+
+ public String getPatchFile() {
+ return patchFile;
+ }
+
+ public Date getCreationDate() {
+ return creationDate;
+ }
+
+ public String getPatchDescription() {
+ return String.format("%s %s", patchFile, creationDate);
+ }
+
+ public String getAuthor() {
+ return author;
+ }
+
+ public String getReviewer() {
+ return reviewer;
+ }
+
+ public Rating getResult() {
+ return result;
+ }
+
+ public String getComment() {
+ return comment;
+ }
+
+ public ITask getTask() {
+ return task;
+ }
+
+ @Override
+ public String toString() {
+ return "Review Subtask " + patchFile + " by " + author + " revd by "
+ + reviewer + " rated as " + result;
+ }
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewsUtil.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewsUtil.java
new file mode 100644
index 00000000..2497d432
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewsUtil.java
@@ -0,0 +1,236 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.core;
+
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.zip.ZipInputStream;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.emf.common.util.EList;
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.resource.ResourceSet;
+import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
+import org.eclipse.mylyn.internal.tasks.core.RepositoryModel;
+import org.eclipse.mylyn.reviews.core.model.review.Patch;
+import org.eclipse.mylyn.reviews.core.model.review.Rating;
+import org.eclipse.mylyn.reviews.core.model.review.Review;
+import org.eclipse.mylyn.reviews.core.model.review.ReviewFactory;
+import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
+import org.eclipse.mylyn.reviews.core.model.review.ReviewResult;
+import org.eclipse.mylyn.reviews.core.model.review.ScopeItem;
+import org.eclipse.mylyn.tasks.core.IRepositoryModel;
+import org.eclipse.mylyn.tasks.core.ITask;
+import org.eclipse.mylyn.tasks.core.ITaskAttachment;
+import org.eclipse.mylyn.tasks.core.ITaskContainer;
+import org.eclipse.mylyn.tasks.core.data.ITaskDataManager;
+import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
+import org.eclipse.mylyn.tasks.core.data.TaskData;
+
+/**
+ * @author Kilian Matt
+ */
+public class ReviewsUtil {
+
+ public static List<ReviewSubTask> getReviewSubTasksFor(
+ ITaskContainer taskContainer, ITaskDataManager taskDataManager,
+ IRepositoryModel repositoryModel, IProgressMonitor monitor) {
+ List<ReviewSubTask> resultList = new ArrayList<ReviewSubTask>();
+ try {
+ for (ITask subTask : taskContainer.getChildren()) {
+ if (!ReviewsUtil.hasReviewMarker(subTask)) {
+ TaskData taskData = taskDataManager.getTaskData(subTask);
+ if (getReviewAttachments(repositoryModel, taskData).size() > 0) {
+ ReviewsUtil.markAsReview(subTask);
+ }
+ }
+
+ if (ReviewsUtil.isMarkedAsReview(subTask)) {//.getSummary().startsWith("Review")) { //$NON-NLS-1$
+ // change to review data manager
+ for (Review review : getReviewAttachmentFromTask(
+ taskDataManager, repositoryModel, subTask)) {
+ // TODO change to latest etc
+ ReviewResult result = review.getResult();
+ if (result == null) {
+ result = ReviewFactory.eINSTANCE
+ .createReviewResult();
+ result.setRating(Rating.NONE);
+ result.setText("");
+ }
+ resultList.add(new ReviewSubTask(getPatchFile(review
+ .getScope()), getPatchCreationDate(review
+ .getScope()),
+ getAuthorString(review.getScope()), subTask
+ .getOwner(), result.getRating(), result
+ .getText(), subTask));
+
+ }
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return resultList;
+
+ }
+
+ private static String getPatchFile(EList<ScopeItem> scope) {
+ if (scope.size() == 1 && scope.get(0) instanceof Patch) {
+ return ((Patch) scope.get(0)).getFileName();
+ } else {
+ return "";
+ }
+ }
+
+ private static Date getPatchCreationDate(EList<ScopeItem> scope) {
+ if (scope.size() == 1 && scope.get(0) instanceof Patch) {
+ return ((Patch) scope.get(0)).getCreationDate();
+ } else {
+ return null;
+ }
+ }
+
+ private static String getAuthorString(EList<ScopeItem> scope) {
+ if (scope.size() == 0) {
+ return "none";
+ } else if (scope.size() == 1) {
+ return scope.get(0).getAuthor();
+ } else if (scope.size() < 3) {
+ StringBuilder sb = new StringBuilder();
+ for (ScopeItem item : scope) {
+ sb.append(item.getAuthor());
+ sb.append(", ");
+ }
+ return sb.substring(0, sb.length() - 2);
+ } else {
+ return "Multiple Authors";
+ }
+ }
+
+ static List<Review> parseAttachments(TaskAttribute attribute,
+ IProgressMonitor monitor) {
+ List<Review> reviewList = new ArrayList<Review>();
+ try {
+ URL url = new URL(attribute.getMappedAttribute(
+ TaskAttribute.ATTACHMENT_URL).getValue());
+
+ ZipInputStream stream = new ZipInputStream(url.openStream());
+ while (!stream.getNextEntry().getName()
+ .equals(ReviewConstants.REVIEW_DATA_FILE)) {
+ }
+
+ ResourceSet resourceSet = new ResourceSetImpl();
+ resourceSet.getPackageRegistry().put(ReviewPackage.eNS_URI,
+ ReviewPackage.eINSTANCE);
+ Resource resource = resourceSet.createResource(URI.createURI(""));
+ resource.load(stream, null);
+ for (EObject item : resource.getContents()) {
+ if (item instanceof Review) {
+ Review review = (Review) item;
+ reviewList.add(review);
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return reviewList;
+ }
+
+ public static List<Review> getReviewAttachmentFromTask(
+ ITaskDataManager taskDataManager, IRepositoryModel repositoryModel,
+ ITask task) throws CoreException {
+
+ List<Review> reviews = new ArrayList<Review>();
+ TaskData taskData = taskDataManager.getTaskData(task);
+ if (taskData != null) {
+ List<TaskAttribute> attributesByType = taskData
+ .getAttributeMapper().getAttributesByType(taskData,
+ TaskAttribute.TYPE_ATTACHMENT);
+ ITaskAttachment lastReview = null;
+
+ for (TaskAttribute attribute : attributesByType) {
+ // TODO move RepositoryModel.createTaskAttachment to interface?
+ ITaskAttachment taskAttachment = ((RepositoryModel) repositoryModel)
+ .createTaskAttachment(attribute);
+ if (taskAttachment != null
+ && taskAttachment.getFileName().equals(
+ ReviewConstants.REVIEW_DATA_CONTAINER)) {
+
+ if (lastReview == null
+ || lastReview.getCreationDate().before(
+ taskAttachment.getCreationDate())) {
+ lastReview = taskAttachment;
+ }
+ }
+
+ }
+
+ if (lastReview != null) {
+ reviews.addAll(parseAttachments(lastReview.getTaskAttribute(),
+ new NullProgressMonitor()));
+ }
+
+ }
+ return reviews;
+ }
+
+ public static List<TaskAttribute> getReviewAttachments(
+ IRepositoryModel repositoryModel, TaskData taskData) {
+
+ List<TaskAttribute> matchingAttributes = new ArrayList<TaskAttribute>();
+ List<TaskAttribute> attributesByType = taskData.getAttributeMapper()
+ .getAttributesByType(taskData, TaskAttribute.TYPE_ATTACHMENT);
+ for (TaskAttribute attribute : attributesByType) {
+ // TODO move RepositoryModel.createTaskAttachment to interface?
+ ITaskAttachment taskAttachment = ((RepositoryModel) repositoryModel)
+ .createTaskAttachment(attribute);
+ if (taskAttachment != null
+ && taskAttachment.getFileName().equals(
+ ReviewConstants.REVIEW_DATA_CONTAINER)) {
+ matchingAttributes.add(attribute);
+ }
+ }
+ return matchingAttributes;
+ }
+
+ private static List<ITargetPathStrategy> strategies;
+ static {
+ strategies = new ArrayList<ITargetPathStrategy>();
+ strategies.add(new SimplePathFindingStrategy());
+ strategies.add(new GitPatchPathFindingStrategy());
+ }
+
+ public static List<? extends ITargetPathStrategy> getPathFindingStrategies() {
+ return strategies;
+ }
+
+ public static boolean isMarkedAsReview(ITask task) {
+ boolean isReview = Boolean.parseBoolean(task
+ .getAttribute(ReviewConstants.ATTR_REVIEW_FLAG));
+ return isReview;
+ }
+
+ public static void markAsReview(ITask task) {
+ task.setAttribute(ReviewConstants.ATTR_REVIEW_FLAG,
+ Boolean.TRUE.toString());
+ }
+
+ public static boolean hasReviewMarker(ITask task) {
+ return task.getAttribute(ReviewConstants.ATTR_REVIEW_FLAG) != null;
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/SimplePathFindingStrategy.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/SimplePathFindingStrategy.java
new file mode 100644
index 00000000..db3b871e
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/SimplePathFindingStrategy.java
@@ -0,0 +1,44 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.core;
+
+import java.io.InputStreamReader;
+import java.io.Reader;
+
+import org.eclipse.compare.patch.ReaderCreator;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+
+/**
+ * @author Kilian Matt
+ */
+public class SimplePathFindingStrategy implements ITargetPathStrategy {
+
+ public ReaderCreator get(IPath path) {
+ final IFile file = org.eclipse.core.resources.ResourcesPlugin
+ .getWorkspace().getRoot().getFile(path);
+ return new ReaderCreator() {
+ @Override
+ public Reader createReader() throws CoreException {
+ return new InputStreamReader(file.getContents());
+ }
+ };
+ }
+
+ public boolean matches(IPath targetPath) {
+ final IFile file = org.eclipse.core.resources.ResourcesPlugin
+ .getWorkspace().getRoot().getFile(targetPath);
+
+ return file.exists();
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Patch.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Patch.java
new file mode 100644
index 00000000..7521cb9f
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Patch.java
@@ -0,0 +1,124 @@
+/**
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ */
+package org.eclipse.mylyn.reviews.core.model.review;
+
+import java.util.Date;
+
+import org.eclipse.compare.patch.IFilePatch2;
+
+import org.eclipse.emf.common.util.EList;
+
+/**
+ * <!-- begin-user-doc -->
+ * A representation of the model object '<em><b>Patch</b></em>'.
+ * <!-- end-user-doc -->
+ *
+ * <p>
+ * The following features are supported:
+ * <ul>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.review.Patch#getContents <em>Contents</em>}</li>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.review.Patch#getCreationDate <em>Creation Date</em>}</li>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.review.Patch#getFileName <em>File Name</em>}</li>
+ * </ul>
+ * </p>
+ *
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getPatch()
+ * @model
+ * @generated
+ */
+public interface Patch extends ScopeItem {
+ /**
+ * Returns the value of the '<em><b>Contents</b></em>' attribute.
+ * <!-- begin-user-doc -->
+ * <p>
+ * If the meaning of the '<em>Contents</em>' attribute isn't clear,
+ * there really should be more of a description here...
+ * </p>
+ * <!-- end-user-doc -->
+ * @return the value of the '<em>Contents</em>' attribute.
+ * @see #setContents(String)
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getPatch_Contents()
+ * @model
+ * @generated
+ */
+ String getContents();
+
+ /**
+ * Sets the value of the '{@link org.eclipse.mylyn.reviews.core.model.review.Patch#getContents <em>Contents</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @param value the new value of the '<em>Contents</em>' attribute.
+ * @see #getContents()
+ * @generated
+ */
+ void setContents(String value);
+
+ /**
+ * Returns the value of the '<em><b>Creation Date</b></em>' attribute.
+ * <!-- begin-user-doc -->
+ * <p>
+ * If the meaning of the '<em>Creation Date</em>' attribute isn't clear,
+ * there really should be more of a description here...
+ * </p>
+ * <!-- end-user-doc -->
+ * @return the value of the '<em>Creation Date</em>' attribute.
+ * @see #setCreationDate(Date)
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getPatch_CreationDate()
+ * @model
+ * @generated
+ */
+ Date getCreationDate();
+
+ /**
+ * Sets the value of the '{@link org.eclipse.mylyn.reviews.core.model.review.Patch#getCreationDate <em>Creation Date</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @param value the new value of the '<em>Creation Date</em>' attribute.
+ * @see #getCreationDate()
+ * @generated
+ */
+ void setCreationDate(Date value);
+
+ /**
+ * Returns the value of the '<em><b>File Name</b></em>' attribute.
+ * <!-- begin-user-doc -->
+ * <p>
+ * If the meaning of the '<em>File Name</em>' attribute isn't clear,
+ * there really should be more of a description here...
+ * </p>
+ * <!-- end-user-doc -->
+ * @return the value of the '<em>File Name</em>' attribute.
+ * @see #setFileName(String)
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getPatch_FileName()
+ * @model
+ * @generated
+ */
+ String getFileName();
+
+ /**
+ * Sets the value of the '{@link org.eclipse.mylyn.reviews.core.model.review.Patch#getFileName <em>File Name</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @param value the new value of the '<em>File Name</em>' attribute.
+ * @see #getFileName()
+ * @generated
+ */
+ void setFileName(String value);
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @model dataType="org.eclipse.mylyn.reviews.core.model.review.IFilePatch2"
+ * @generated
+ */
+ EList<IFilePatch2> parse();
+
+} // Patch
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Rating.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Rating.java
new file mode 100644
index 00000000..c4a04335
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Rating.java
@@ -0,0 +1,267 @@
+/**
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ */
+package org.eclipse.mylyn.reviews.core.model.review;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import org.eclipse.emf.common.util.Enumerator;
+
+/**
+ * <!-- begin-user-doc -->
+ * A representation of the literals of the enumeration '<em><b>Rating</b></em>',
+ * and utility methods for working with them.
+ * <!-- end-user-doc -->
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getRating()
+ * @model
+ * @generated
+ */
+public enum Rating implements Enumerator {
+ /**
+ * The '<em><b>NONE</b></em>' literal object.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #NONE_VALUE
+ * @generated
+ * @ordered
+ */
+ NONE(0, "NONE", "NONE"),
+
+ /**
+ * The '<em><b>PASSED</b></em>' literal object.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #PASSED_VALUE
+ * @generated
+ * @ordered
+ */
+ PASSED(0, "PASSED", "PASSED"),
+
+ /**
+ * The '<em><b>WARNING</b></em>' literal object.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #WARNING_VALUE
+ * @generated
+ * @ordered
+ */
+ WARNING(0, "WARNING", "WARNING"),
+
+ /**
+ * The '<em><b>FAILED</b></em>' literal object.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #FAILED_VALUE
+ * @generated
+ * @ordered
+ */
+ FAILED(0, "FAILED", "FAILED");
+
+ /**
+ * The '<em><b>NONE</b></em>' literal value.
+ * <!-- begin-user-doc -->
+ * <p>
+ * If the meaning of '<em><b>NONE</b></em>' literal object isn't clear,
+ * there really should be more of a description here...
+ * </p>
+ * <!-- end-user-doc -->
+ * @see #NONE
+ * @model
+ * @generated
+ * @ordered
+ */
+ public static final int NONE_VALUE = 0;
+
+ /**
+ * The '<em><b>PASSED</b></em>' literal value.
+ * <!-- begin-user-doc -->
+ * <p>
+ * If the meaning of '<em><b>PASSED</b></em>' literal object isn't clear,
+ * there really should be more of a description here...
+ * </p>
+ * <!-- end-user-doc -->
+ * @see #PASSED
+ * @model
+ * @generated
+ * @ordered
+ */
+ public static final int PASSED_VALUE = 0;
+
+ /**
+ * The '<em><b>WARNING</b></em>' literal value.
+ * <!-- begin-user-doc -->
+ * <p>
+ * If the meaning of '<em><b>WARNING</b></em>' literal object isn't clear,
+ * there really should be more of a description here...
+ * </p>
+ * <!-- end-user-doc -->
+ * @see #WARNING
+ * @model
+ * @generated
+ * @ordered
+ */
+ public static final int WARNING_VALUE = 0;
+
+ /**
+ * The '<em><b>FAILED</b></em>' literal value.
+ * <!-- begin-user-doc -->
+ * <p>
+ * If the meaning of '<em><b>FAILED</b></em>' literal object isn't clear,
+ * there really should be more of a description here...
+ * </p>
+ * <!-- end-user-doc -->
+ * @see #FAILED
+ * @model
+ * @generated
+ * @ordered
+ */
+ public static final int FAILED_VALUE = 0;
+
+ /**
+ * An array of all the '<em><b>Rating</b></em>' enumerators.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ private static final Rating[] VALUES_ARRAY =
+ new Rating[] {
+ NONE,
+ PASSED,
+ WARNING,
+ FAILED,
+ };
+
+ /**
+ * A public read-only list of all the '<em><b>Rating</b></em>' enumerators.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public static final List<Rating> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
+
+ /**
+ * Returns the '<em><b>Rating</b></em>' literal with the specified literal value.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public static Rating get(String literal) {
+ for (int i = 0; i < VALUES_ARRAY.length; ++i) {
+ Rating result = VALUES_ARRAY[i];
+ if (result.toString().equals(literal)) {
+ return result;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns the '<em><b>Rating</b></em>' literal with the specified name.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public static Rating getByName(String name) {
+ for (int i = 0; i < VALUES_ARRAY.length; ++i) {
+ Rating result = VALUES_ARRAY[i];
+ if (result.getName().equals(name)) {
+ return result;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns the '<em><b>Rating</b></em>' literal with the specified integer value.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public static Rating get(int value) {
+ switch (value) {
+ case NONE_VALUE: return NONE;
+ }
+ return null;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ private final int value;
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ private final String name;
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ private final String literal;
+
+ /**
+ * Only this class can construct instances.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ private Rating(int value, String name, String literal) {
+ this.value = value;
+ this.name = name;
+ this.literal = literal;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public int getValue() {
+ return value;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public String getLiteral() {
+ return literal;
+ }
+
+ /**
+ * Returns the literal value of the enumerator, which is its string representation.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public String toString() {
+ return literal;
+ }
+
+} //Rating
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Review.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Review.java
new file mode 100644
index 00000000..5d3bf277
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Review.java
@@ -0,0 +1,76 @@
+/**
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ */
+package org.eclipse.mylyn.reviews.core.model.review;
+
+import org.eclipse.emf.common.util.EList;
+import org.eclipse.emf.ecore.EObject;
+
+/**
+ * <!-- begin-user-doc -->
+ * A representation of the model object '<em><b>Review</b></em>'.
+ * <!-- end-user-doc -->
+ *
+ * <p>
+ * The following features are supported:
+ * <ul>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.review.Review#getResult <em>Result</em>}</li>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.review.Review#getScope <em>Scope</em>}</li>
+ * </ul>
+ * </p>
+ *
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getReview()
+ * @model
+ * @generated
+ */
+public interface Review extends EObject {
+ /**
+ * Returns the value of the '<em><b>Result</b></em>' reference.
+ * <!-- begin-user-doc -->
+ * <p>
+ * If the meaning of the '<em>Result</em>' reference isn't clear,
+ * there really should be more of a description here...
+ * </p>
+ * <!-- end-user-doc -->
+ * @return the value of the '<em>Result</em>' reference.
+ * @see #setResult(ReviewResult)
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getReview_Result()
+ * @model
+ * @generated
+ */
+ ReviewResult getResult();
+
+ /**
+ * Sets the value of the '{@link org.eclipse.mylyn.reviews.core.model.review.Review#getResult <em>Result</em>}' reference.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @param value the new value of the '<em>Result</em>' reference.
+ * @see #getResult()
+ * @generated
+ */
+ void setResult(ReviewResult value);
+
+ /**
+ * Returns the value of the '<em><b>Scope</b></em>' reference list.
+ * The list contents are of type {@link org.eclipse.mylyn.reviews.core.model.review.ScopeItem}.
+ * <!-- begin-user-doc -->
+ * <p>
+ * If the meaning of the '<em>Scope</em>' reference list isn't clear,
+ * there really should be more of a description here...
+ * </p>
+ * <!-- end-user-doc -->
+ * @return the value of the '<em>Scope</em>' reference list.
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getReview_Scope()
+ * @model
+ * @generated
+ */
+ EList<ScopeItem> getScope();
+
+} // Review
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewFactory.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewFactory.java
new file mode 100644
index 00000000..288649cd
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewFactory.java
@@ -0,0 +1,77 @@
+/**
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ */
+package org.eclipse.mylyn.reviews.core.model.review;
+
+import org.eclipse.emf.ecore.EFactory;
+
+/**
+ * <!-- begin-user-doc -->
+ * The <b>Factory</b> for the model.
+ * It provides a create method for each non-abstract class of the model.
+ * <!-- end-user-doc -->
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage
+ * @generated
+ */
+public interface ReviewFactory extends EFactory {
+ /**
+ * The singleton instance of the factory.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ ReviewFactory eINSTANCE = org.eclipse.mylyn.reviews.core.model.review.impl.ReviewFactoryImpl.init();
+
+ /**
+ * Returns a new object of class '<em>Review</em>'.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return a new object of class '<em>Review</em>'.
+ * @generated
+ */
+ Review createReview();
+
+ /**
+ * Returns a new object of class '<em>Result</em>'.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return a new object of class '<em>Result</em>'.
+ * @generated
+ */
+ ReviewResult createReviewResult();
+
+ /**
+ * Returns a new object of class '<em>Patch</em>'.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return a new object of class '<em>Patch</em>'.
+ * @generated
+ */
+ Patch createPatch();
+
+ /**
+ * Returns a new object of class '<em>Scope Item</em>'.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return a new object of class '<em>Scope Item</em>'.
+ * @generated
+ */
+ ScopeItem createScopeItem();
+
+ /**
+ * Returns the package supported by this factory.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return the package supported by this factory.
+ * @generated
+ */
+ ReviewPackage getReviewPackage();
+
+} //ReviewFactory
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewPackage.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewPackage.java
new file mode 100644
index 00000000..20ed8ed5
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewPackage.java
@@ -0,0 +1,602 @@
+/**
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ */
+package org.eclipse.mylyn.reviews.core.model.review;
+
+import org.eclipse.emf.ecore.EAttribute;
+import org.eclipse.emf.ecore.EClass;
+import org.eclipse.emf.ecore.EDataType;
+import org.eclipse.emf.ecore.EEnum;
+import org.eclipse.emf.ecore.EPackage;
+import org.eclipse.emf.ecore.EReference;
+
+/**
+ * <!-- begin-user-doc -->
+ * The <b>Package</b> for the model.
+ * It contains accessors for the meta objects to represent
+ * <ul>
+ * <li>each class,</li>
+ * <li>each feature of each class,</li>
+ * <li>each enum,</li>
+ * <li>and each data type</li>
+ * </ul>
+ * <!-- end-user-doc -->
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewFactory
+ * @model kind="package"
+ * @generated
+ */
+public interface ReviewPackage extends EPackage {
+ /**
+ * The package name.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ String eNAME = "review";
+
+ /**
+ * The package namespace URI.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ String eNS_URI = "org.eclipse.mylyn.reviews";
+
+ /**
+ * The package namespace name.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ String eNS_PREFIX = "";
+
+ /**
+ * The singleton instance of the package.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ ReviewPackage eINSTANCE = org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl.init();
+
+ /**
+ * The meta object id for the '{@link org.eclipse.mylyn.reviews.core.model.review.impl.ReviewImpl <em>Review</em>}' class.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewImpl
+ * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getReview()
+ * @generated
+ */
+ int REVIEW = 0;
+
+ /**
+ * The feature id for the '<em><b>Result</b></em>' reference.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ * @ordered
+ */
+ int REVIEW__RESULT = 0;
+
+ /**
+ * The feature id for the '<em><b>Scope</b></em>' reference list.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ * @ordered
+ */
+ int REVIEW__SCOPE = 1;
+
+ /**
+ * The number of structural features of the '<em>Review</em>' class.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ * @ordered
+ */
+ int REVIEW_FEATURE_COUNT = 2;
+
+ /**
+ * The meta object id for the '{@link org.eclipse.mylyn.reviews.core.model.review.impl.ReviewResultImpl <em>Result</em>}' class.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewResultImpl
+ * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getReviewResult()
+ * @generated
+ */
+ int REVIEW_RESULT = 1;
+
+ /**
+ * The feature id for the '<em><b>Text</b></em>' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ * @ordered
+ */
+ int REVIEW_RESULT__TEXT = 0;
+
+ /**
+ * The feature id for the '<em><b>Rating</b></em>' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ * @ordered
+ */
+ int REVIEW_RESULT__RATING = 1;
+
+ /**
+ * The feature id for the '<em><b>Reviewer</b></em>' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ * @ordered
+ */
+ int REVIEW_RESULT__REVIEWER = 2;
+
+ /**
+ * The number of structural features of the '<em>Result</em>' class.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ * @ordered
+ */
+ int REVIEW_RESULT_FEATURE_COUNT = 3;
+
+ /**
+ * The meta object id for the '{@link org.eclipse.mylyn.reviews.core.model.review.impl.ScopeItemImpl <em>Scope Item</em>}' class.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see org.eclipse.mylyn.reviews.core.model.review.impl.ScopeItemImpl
+ * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getScopeItem()
+ * @generated
+ */
+ int SCOPE_ITEM = 3;
+
+ /**
+ * The feature id for the '<em><b>Author</b></em>' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ * @ordered
+ */
+ int SCOPE_ITEM__AUTHOR = 0;
+
+ /**
+ * The number of structural features of the '<em>Scope Item</em>' class.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ * @ordered
+ */
+ int SCOPE_ITEM_FEATURE_COUNT = 1;
+
+ /**
+ * The meta object id for the '{@link org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl <em>Patch</em>}' class.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl
+ * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getPatch()
+ * @generated
+ */
+ int PATCH = 2;
+
+ /**
+ * The feature id for the '<em><b>Author</b></em>' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ * @ordered
+ */
+ int PATCH__AUTHOR = SCOPE_ITEM__AUTHOR;
+
+ /**
+ * The feature id for the '<em><b>Contents</b></em>' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ * @ordered
+ */
+ int PATCH__CONTENTS = SCOPE_ITEM_FEATURE_COUNT + 0;
+
+ /**
+ * The feature id for the '<em><b>Creation Date</b></em>' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ * @ordered
+ */
+ int PATCH__CREATION_DATE = SCOPE_ITEM_FEATURE_COUNT + 1;
+
+ /**
+ * The feature id for the '<em><b>File Name</b></em>' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ * @ordered
+ */
+ int PATCH__FILE_NAME = SCOPE_ITEM_FEATURE_COUNT + 2;
+
+ /**
+ * The number of structural features of the '<em>Patch</em>' class.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ * @ordered
+ */
+ int PATCH_FEATURE_COUNT = SCOPE_ITEM_FEATURE_COUNT + 3;
+
+ /**
+ * The meta object id for the '{@link org.eclipse.mylyn.reviews.core.model.review.Rating <em>Rating</em>}' enum.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see org.eclipse.mylyn.reviews.core.model.review.Rating
+ * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getRating()
+ * @generated
+ */
+ int RATING = 4;
+
+ /**
+ * The meta object id for the '<em>IFile Patch2</em>' data type.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see org.eclipse.compare.patch.IFilePatch2
+ * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getIFilePatch2()
+ * @generated
+ */
+ int IFILE_PATCH2 = 5;
+
+ /**
+ * The meta object id for the '<em>IProgress Monitor</em>' data type.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see org.eclipse.core.runtime.IProgressMonitor
+ * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getIProgressMonitor()
+ * @generated
+ */
+ int IPROGRESS_MONITOR = 6;
+
+
+ /**
+ * Returns the meta object for class '{@link org.eclipse.mylyn.reviews.core.model.review.Review <em>Review</em>}'.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return the meta object for class '<em>Review</em>'.
+ * @see org.eclipse.mylyn.reviews.core.model.review.Review
+ * @generated
+ */
+ EClass getReview();
+
+ /**
+ * Returns the meta object for the reference '{@link org.eclipse.mylyn.reviews.core.model.review.Review#getResult <em>Result</em>}'.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return the meta object for the reference '<em>Result</em>'.
+ * @see org.eclipse.mylyn.reviews.core.model.review.Review#getResult()
+ * @see #getReview()
+ * @generated
+ */
+ EReference getReview_Result();
+
+ /**
+ * Returns the meta object for the reference list '{@link org.eclipse.mylyn.reviews.core.model.review.Review#getScope <em>Scope</em>}'.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return the meta object for the reference list '<em>Scope</em>'.
+ * @see org.eclipse.mylyn.reviews.core.model.review.Review#getScope()
+ * @see #getReview()
+ * @generated
+ */
+ EReference getReview_Scope();
+
+ /**
+ * Returns the meta object for class '{@link org.eclipse.mylyn.reviews.core.model.review.ReviewResult <em>Result</em>}'.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return the meta object for class '<em>Result</em>'.
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewResult
+ * @generated
+ */
+ EClass getReviewResult();
+
+ /**
+ * Returns the meta object for the attribute '{@link org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getText <em>Text</em>}'.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return the meta object for the attribute '<em>Text</em>'.
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getText()
+ * @see #getReviewResult()
+ * @generated
+ */
+ EAttribute getReviewResult_Text();
+
+ /**
+ * Returns the meta object for the attribute '{@link org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getRating <em>Rating</em>}'.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return the meta object for the attribute '<em>Rating</em>'.
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getRating()
+ * @see #getReviewResult()
+ * @generated
+ */
+ EAttribute getReviewResult_Rating();
+
+ /**
+ * Returns the meta object for the attribute '{@link org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getReviewer <em>Reviewer</em>}'.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return the meta object for the attribute '<em>Reviewer</em>'.
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getReviewer()
+ * @see #getReviewResult()
+ * @generated
+ */
+ EAttribute getReviewResult_Reviewer();
+
+ /**
+ * Returns the meta object for class '{@link org.eclipse.mylyn.reviews.core.model.review.Patch <em>Patch</em>}'.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return the meta object for class '<em>Patch</em>'.
+ * @see org.eclipse.mylyn.reviews.core.model.review.Patch
+ * @generated
+ */
+ EClass getPatch();
+
+ /**
+ * Returns the meta object for the attribute '{@link org.eclipse.mylyn.reviews.core.model.review.Patch#getContents <em>Contents</em>}'.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return the meta object for the attribute '<em>Contents</em>'.
+ * @see org.eclipse.mylyn.reviews.core.model.review.Patch#getContents()
+ * @see #getPatch()
+ * @generated
+ */
+ EAttribute getPatch_Contents();
+
+ /**
+ * Returns the meta object for the attribute '{@link org.eclipse.mylyn.reviews.core.model.review.Patch#getCreationDate <em>Creation Date</em>}'.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return the meta object for the attribute '<em>Creation Date</em>'.
+ * @see org.eclipse.mylyn.reviews.core.model.review.Patch#getCreationDate()
+ * @see #getPatch()
+ * @generated
+ */
+ EAttribute getPatch_CreationDate();
+
+ /**
+ * Returns the meta object for the attribute '{@link org.eclipse.mylyn.reviews.core.model.review.Patch#getFileName <em>File Name</em>}'.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return the meta object for the attribute '<em>File Name</em>'.
+ * @see org.eclipse.mylyn.reviews.core.model.review.Patch#getFileName()
+ * @see #getPatch()
+ * @generated
+ */
+ EAttribute getPatch_FileName();
+
+ /**
+ * Returns the meta object for class '{@link org.eclipse.mylyn.reviews.core.model.review.ScopeItem <em>Scope Item</em>}'.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return the meta object for class '<em>Scope Item</em>'.
+ * @see org.eclipse.mylyn.reviews.core.model.review.ScopeItem
+ * @generated
+ */
+ EClass getScopeItem();
+
+ /**
+ * Returns the meta object for the attribute '{@link org.eclipse.mylyn.reviews.core.model.review.ScopeItem#getAuthor <em>Author</em>}'.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return the meta object for the attribute '<em>Author</em>'.
+ * @see org.eclipse.mylyn.reviews.core.model.review.ScopeItem#getAuthor()
+ * @see #getScopeItem()
+ * @generated
+ */
+ EAttribute getScopeItem_Author();
+
+ /**
+ * Returns the meta object for enum '{@link org.eclipse.mylyn.reviews.core.model.review.Rating <em>Rating</em>}'.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return the meta object for enum '<em>Rating</em>'.
+ * @see org.eclipse.mylyn.reviews.core.model.review.Rating
+ * @generated
+ */
+ EEnum getRating();
+
+ /**
+ * Returns the meta object for data type '{@link org.eclipse.compare.patch.IFilePatch2 <em>IFile Patch2</em>}'.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return the meta object for data type '<em>IFile Patch2</em>'.
+ * @see org.eclipse.compare.patch.IFilePatch2
+ * @model instanceClass="org.eclipse.compare.patch.IFilePatch2"
+ * @generated
+ */
+ EDataType getIFilePatch2();
+
+ /**
+ * Returns the meta object for data type '{@link org.eclipse.core.runtime.IProgressMonitor <em>IProgress Monitor</em>}'.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return the meta object for data type '<em>IProgress Monitor</em>'.
+ * @see org.eclipse.core.runtime.IProgressMonitor
+ * @model instanceClass="org.eclipse.core.runtime.IProgressMonitor"
+ * @generated
+ */
+ EDataType getIProgressMonitor();
+
+ /**
+ * Returns the factory that creates the instances of the model.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return the factory that creates the instances of the model.
+ * @generated
+ */
+ ReviewFactory getReviewFactory();
+
+ /**
+ * <!-- begin-user-doc -->
+ * Defines literals for the meta objects that represent
+ * <ul>
+ * <li>each class,</li>
+ * <li>each feature of each class,</li>
+ * <li>each enum,</li>
+ * <li>and each data type</li>
+ * </ul>
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ interface Literals {
+ /**
+ * The meta object literal for the '{@link org.eclipse.mylyn.reviews.core.model.review.impl.ReviewImpl <em>Review</em>}' class.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewImpl
+ * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getReview()
+ * @generated
+ */
+ EClass REVIEW = eINSTANCE.getReview();
+
+ /**
+ * The meta object literal for the '<em><b>Result</b></em>' reference feature.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ EReference REVIEW__RESULT = eINSTANCE.getReview_Result();
+
+ /**
+ * The meta object literal for the '<em><b>Scope</b></em>' reference list feature.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ EReference REVIEW__SCOPE = eINSTANCE.getReview_Scope();
+
+ /**
+ * The meta object literal for the '{@link org.eclipse.mylyn.reviews.core.model.review.impl.ReviewResultImpl <em>Result</em>}' class.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewResultImpl
+ * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getReviewResult()
+ * @generated
+ */
+ EClass REVIEW_RESULT = eINSTANCE.getReviewResult();
+
+ /**
+ * The meta object literal for the '<em><b>Text</b></em>' attribute feature.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ EAttribute REVIEW_RESULT__TEXT = eINSTANCE.getReviewResult_Text();
+
+ /**
+ * The meta object literal for the '<em><b>Rating</b></em>' attribute feature.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ EAttribute REVIEW_RESULT__RATING = eINSTANCE.getReviewResult_Rating();
+
+ /**
+ * The meta object literal for the '<em><b>Reviewer</b></em>' attribute feature.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ EAttribute REVIEW_RESULT__REVIEWER = eINSTANCE.getReviewResult_Reviewer();
+
+ /**
+ * The meta object literal for the '{@link org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl <em>Patch</em>}' class.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl
+ * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getPatch()
+ * @generated
+ */
+ EClass PATCH = eINSTANCE.getPatch();
+
+ /**
+ * The meta object literal for the '<em><b>Contents</b></em>' attribute feature.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ EAttribute PATCH__CONTENTS = eINSTANCE.getPatch_Contents();
+
+ /**
+ * The meta object literal for the '<em><b>Creation Date</b></em>' attribute feature.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ EAttribute PATCH__CREATION_DATE = eINSTANCE.getPatch_CreationDate();
+
+ /**
+ * The meta object literal for the '<em><b>File Name</b></em>' attribute feature.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ EAttribute PATCH__FILE_NAME = eINSTANCE.getPatch_FileName();
+
+ /**
+ * The meta object literal for the '{@link org.eclipse.mylyn.reviews.core.model.review.impl.ScopeItemImpl <em>Scope Item</em>}' class.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see org.eclipse.mylyn.reviews.core.model.review.impl.ScopeItemImpl
+ * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getScopeItem()
+ * @generated
+ */
+ EClass SCOPE_ITEM = eINSTANCE.getScopeItem();
+
+ /**
+ * The meta object literal for the '<em><b>Author</b></em>' attribute feature.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ EAttribute SCOPE_ITEM__AUTHOR = eINSTANCE.getScopeItem_Author();
+
+ /**
+ * The meta object literal for the '{@link org.eclipse.mylyn.reviews.core.model.review.Rating <em>Rating</em>}' enum.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see org.eclipse.mylyn.reviews.core.model.review.Rating
+ * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getRating()
+ * @generated
+ */
+ EEnum RATING = eINSTANCE.getRating();
+
+ /**
+ * The meta object literal for the '<em>IFile Patch2</em>' data type.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see org.eclipse.compare.patch.IFilePatch2
+ * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getIFilePatch2()
+ * @generated
+ */
+ EDataType IFILE_PATCH2 = eINSTANCE.getIFilePatch2();
+
+ /**
+ * The meta object literal for the '<em>IProgress Monitor</em>' data type.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see org.eclipse.core.runtime.IProgressMonitor
+ * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getIProgressMonitor()
+ * @generated
+ */
+ EDataType IPROGRESS_MONITOR = eINSTANCE.getIProgressMonitor();
+
+ }
+
+} //ReviewPackage
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewResult.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewResult.java
new file mode 100644
index 00000000..59c089de
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewResult.java
@@ -0,0 +1,115 @@
+/**
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ */
+package org.eclipse.mylyn.reviews.core.model.review;
+
+import org.eclipse.emf.ecore.EObject;
+
+/**
+ * <!-- begin-user-doc -->
+ * A representation of the model object '<em><b>Result</b></em>'.
+ * <!-- end-user-doc -->
+ *
+ * <p>
+ * The following features are supported:
+ * <ul>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getText <em>Text</em>}</li>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getRating <em>Rating</em>}</li>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getReviewer <em>Reviewer</em>}</li>
+ * </ul>
+ * </p>
+ *
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getReviewResult()
+ * @model
+ * @generated
+ */
+public interface ReviewResult extends EObject {
+ /**
+ * Returns the value of the '<em><b>Text</b></em>' attribute.
+ * <!-- begin-user-doc -->
+ * <p>
+ * If the meaning of the '<em>Text</em>' attribute isn't clear,
+ * there really should be more of a description here...
+ * </p>
+ * <!-- end-user-doc -->
+ * @return the value of the '<em>Text</em>' attribute.
+ * @see #setText(String)
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getReviewResult_Text()
+ * @model
+ * @generated
+ */
+ String getText();
+
+ /**
+ * Sets the value of the '{@link org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getText <em>Text</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @param value the new value of the '<em>Text</em>' attribute.
+ * @see #getText()
+ * @generated
+ */
+ void setText(String value);
+
+ /**
+ * Returns the value of the '<em><b>Rating</b></em>' attribute.
+ * The literals are from the enumeration {@link org.eclipse.mylyn.reviews.core.model.review.Rating}.
+ * <!-- begin-user-doc -->
+ * <p>
+ * If the meaning of the '<em>Rating</em>' attribute isn't clear,
+ * there really should be more of a description here...
+ * </p>
+ * <!-- end-user-doc -->
+ * @return the value of the '<em>Rating</em>' attribute.
+ * @see org.eclipse.mylyn.reviews.core.model.review.Rating
+ * @see #setRating(Rating)
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getReviewResult_Rating()
+ * @model
+ * @generated
+ */
+ Rating getRating();
+
+ /**
+ * Sets the value of the '{@link org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getRating <em>Rating</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @param value the new value of the '<em>Rating</em>' attribute.
+ * @see org.eclipse.mylyn.reviews.core.model.review.Rating
+ * @see #getRating()
+ * @generated
+ */
+ void setRating(Rating value);
+
+ /**
+ * Returns the value of the '<em><b>Reviewer</b></em>' attribute.
+ * <!-- begin-user-doc -->
+ * <p>
+ * If the meaning of the '<em>Reviewer</em>' attribute isn't clear,
+ * there really should be more of a description here...
+ * </p>
+ * <!-- end-user-doc -->
+ * @return the value of the '<em>Reviewer</em>' attribute.
+ * @see #setReviewer(String)
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getReviewResult_Reviewer()
+ * @model
+ * @generated
+ */
+ String getReviewer();
+
+ /**
+ * Sets the value of the '{@link org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getReviewer <em>Reviewer</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @param value the new value of the '<em>Reviewer</em>' attribute.
+ * @see #getReviewer()
+ * @generated
+ */
+ void setReviewer(String value);
+
+} // ReviewResult
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ScopeItem.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ScopeItem.java
new file mode 100644
index 00000000..252a01a1
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ScopeItem.java
@@ -0,0 +1,58 @@
+/**
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ */
+package org.eclipse.mylyn.reviews.core.model.review;
+
+import org.eclipse.emf.ecore.EObject;
+
+/**
+ * <!-- begin-user-doc -->
+ * A representation of the model object '<em><b>Scope Item</b></em>'.
+ * <!-- end-user-doc -->
+ *
+ * <p>
+ * The following features are supported:
+ * <ul>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.review.ScopeItem#getAuthor <em>Author</em>}</li>
+ * </ul>
+ * </p>
+ *
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getScopeItem()
+ * @model
+ * @generated
+ */
+public interface ScopeItem extends EObject {
+ /**
+ * Returns the value of the '<em><b>Author</b></em>' attribute.
+ * <!-- begin-user-doc -->
+ * <p>
+ * If the meaning of the '<em>Author</em>' attribute isn't clear,
+ * there really should be more of a description here...
+ * </p>
+ * <!-- end-user-doc -->
+ * @return the value of the '<em>Author</em>' attribute.
+ * @see #setAuthor(String)
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getScopeItem_Author()
+ * @model
+ * @generated
+ */
+ String getAuthor();
+
+ /**
+ * Sets the value of the '{@link org.eclipse.mylyn.reviews.core.model.review.ScopeItem#getAuthor <em>Author</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @param value the new value of the '<em>Author</em>' attribute.
+ * @see #getAuthor()
+ * @generated
+ */
+ void setAuthor(String value);
+
+} // ScopeItem
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/PatchImpl.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/PatchImpl.java
new file mode 100644
index 00000000..15f58c54
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/PatchImpl.java
@@ -0,0 +1,299 @@
+/**
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ */
+package org.eclipse.mylyn.reviews.core.model.review.impl;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.util.Date;
+
+import org.eclipse.compare.patch.IFilePatch2;
+import org.eclipse.emf.common.notify.Notification;
+import org.eclipse.compare.patch.PatchParser;
+import org.eclipse.compare.patch.ReaderCreator;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.emf.common.util.BasicEList;
+import org.eclipse.emf.common.util.EList;
+import org.eclipse.emf.ecore.EClass;
+import org.eclipse.emf.ecore.impl.ENotificationImpl;
+import org.eclipse.mylyn.reviews.core.model.review.Patch;
+import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
+
+/**
+ * <!-- begin-user-doc --> An implementation of the model object '
+ * <em><b>Patch</b></em>'. <!-- end-user-doc -->
+ * <p>
+ * The following features are implemented:
+ * <ul>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl#getContents <em>Contents</em>}</li>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl#getCreationDate <em>Creation Date</em>}</li>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl#getFileName <em>File Name</em>}</li>
+ * </ul>
+ * </p>
+ *
+ * @generated
+ */
+public class PatchImpl extends ScopeItemImpl implements Patch {
+ /**
+ * The default value of the '{@link #getContents() <em>Contents</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getContents()
+ * @generated
+ * @ordered
+ */
+ protected static final String CONTENTS_EDEFAULT = null;
+ /**
+ * The cached value of the '{@link #getContents() <em>Contents</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getContents()
+ * @generated
+ * @ordered
+ */
+ protected String contents = CONTENTS_EDEFAULT;
+ /**
+ * The default value of the '{@link #getCreationDate() <em>Creation Date</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getCreationDate()
+ * @generated
+ * @ordered
+ */
+ protected static final Date CREATION_DATE_EDEFAULT = null;
+ /**
+ * The cached value of the '{@link #getCreationDate() <em>Creation Date</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getCreationDate()
+ * @generated
+ * @ordered
+ */
+ protected Date creationDate = CREATION_DATE_EDEFAULT;
+ /**
+ * The default value of the '{@link #getFileName() <em>File Name</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getFileName()
+ * @generated
+ * @ordered
+ */
+ protected static final String FILE_NAME_EDEFAULT = null;
+ /**
+ * The cached value of the '{@link #getFileName() <em>File Name</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getFileName()
+ * @generated
+ * @ordered
+ */
+ protected String fileName = FILE_NAME_EDEFAULT;
+
+ /*
+ * owner* <!-- begin-user-doc --> <!-- end-user-doc -->
+ *
+ * @generated
+ */
+ protected PatchImpl() {
+ super();
+ }
+
+ /**
+ * <!-- begin-user-doc --> <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ protected EClass eStaticClass() {
+ return ReviewPackage.Literals.PATCH;
+ }
+
+ /**
+ * <!-- begin-user-doc --> <!-- end-user-doc -->
+ * @generated
+ */
+ public String getContents() {
+ return contents;
+ }
+
+ /**
+ * <!-- begin-user-doc --> <!-- end-user-doc -->
+ * @generated
+ */
+ public void setContents(String newContents) {
+ String oldContents = contents;
+ contents = newContents;
+ if (eNotificationRequired())
+ eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.PATCH__CONTENTS, oldContents, contents));
+ }
+
+ /**
+ * <!-- begin-user-doc --> <!-- end-user-doc -->
+ * @generated
+ */
+ public Date getCreationDate() {
+ return creationDate;
+ }
+
+ /**
+ * <!-- begin-user-doc --> <!-- end-user-doc -->
+ * @generated
+ */
+ public void setCreationDate(Date newCreationDate) {
+ Date oldCreationDate = creationDate;
+ creationDate = newCreationDate;
+ if (eNotificationRequired())
+ eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.PATCH__CREATION_DATE, oldCreationDate, creationDate));
+ }
+
+ /**
+ * <!-- begin-user-doc --> <!-- end-user-doc -->
+ * @generated
+ */
+ public String getFileName() {
+ return fileName;
+ }
+
+ /**
+ * <!-- begin-user-doc --> <!-- end-user-doc -->
+ * @generated
+ */
+ public void setFileName(String newFileName) {
+ String oldFileName = fileName;
+ fileName = newFileName;
+ if (eNotificationRequired())
+ eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.PATCH__FILE_NAME, oldFileName, fileName));
+ }
+
+ /**
+ * <!-- begin-user-doc --> <!-- end-user-doc -->
+ */
+ public EList<IFilePatch2> parse() {
+ try {
+ IFilePatch2[] patches = PatchParser.parsePatch(new ReaderCreator() {
+ @Override
+ public Reader createReader() throws CoreException {
+ return new InputStreamReader(new ByteArrayInputStream(
+ getContents().getBytes()));
+ }
+ });
+
+ EList<IFilePatch2> list = new BasicEList<IFilePatch2>();
+
+ for (IFilePatch2 patch : patches) {
+ list.add(patch);
+ }
+ return list;
+ } catch (Exception ex) {
+ // TODO
+ ex.printStackTrace();
+ throw new RuntimeException(ex);
+ }
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public Object eGet(int featureID, boolean resolve, boolean coreType) {
+ switch (featureID) {
+ case ReviewPackage.PATCH__CONTENTS:
+ return getContents();
+ case ReviewPackage.PATCH__CREATION_DATE:
+ return getCreationDate();
+ case ReviewPackage.PATCH__FILE_NAME:
+ return getFileName();
+ }
+ return super.eGet(featureID, resolve, coreType);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public void eSet(int featureID, Object newValue) {
+ switch (featureID) {
+ case ReviewPackage.PATCH__CONTENTS:
+ setContents((String)newValue);
+ return;
+ case ReviewPackage.PATCH__CREATION_DATE:
+ setCreationDate((Date)newValue);
+ return;
+ case ReviewPackage.PATCH__FILE_NAME:
+ setFileName((String)newValue);
+ return;
+ }
+ super.eSet(featureID, newValue);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public void eUnset(int featureID) {
+ switch (featureID) {
+ case ReviewPackage.PATCH__CONTENTS:
+ setContents(CONTENTS_EDEFAULT);
+ return;
+ case ReviewPackage.PATCH__CREATION_DATE:
+ setCreationDate(CREATION_DATE_EDEFAULT);
+ return;
+ case ReviewPackage.PATCH__FILE_NAME:
+ setFileName(FILE_NAME_EDEFAULT);
+ return;
+ }
+ super.eUnset(featureID);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public boolean eIsSet(int featureID) {
+ switch (featureID) {
+ case ReviewPackage.PATCH__CONTENTS:
+ return CONTENTS_EDEFAULT == null ? contents != null : !CONTENTS_EDEFAULT.equals(contents);
+ case ReviewPackage.PATCH__CREATION_DATE:
+ return CREATION_DATE_EDEFAULT == null ? creationDate != null : !CREATION_DATE_EDEFAULT.equals(creationDate);
+ case ReviewPackage.PATCH__FILE_NAME:
+ return FILE_NAME_EDEFAULT == null ? fileName != null : !FILE_NAME_EDEFAULT.equals(fileName);
+ }
+ return super.eIsSet(featureID);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public String toString() {
+ if (eIsProxy()) return super.toString();
+
+ StringBuffer result = new StringBuffer(super.toString());
+ result.append(" (contents: ");
+ result.append(contents);
+ result.append(", creationDate: ");
+ result.append(creationDate);
+ result.append(", fileName: ");
+ result.append(fileName);
+ result.append(')');
+ return result.toString();
+ }
+
+} // PatchImpl
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewFactoryImpl.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewFactoryImpl.java
new file mode 100644
index 00000000..0ef56ca2
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewFactoryImpl.java
@@ -0,0 +1,235 @@
+/**
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ */
+package org.eclipse.mylyn.reviews.core.model.review.impl;
+
+import org.eclipse.compare.patch.IFilePatch2;
+
+import org.eclipse.core.runtime.IProgressMonitor;
+
+import org.eclipse.emf.ecore.EClass;
+import org.eclipse.emf.ecore.EDataType;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EPackage;
+
+import org.eclipse.emf.ecore.impl.EFactoryImpl;
+
+import org.eclipse.emf.ecore.plugin.EcorePlugin;
+
+import org.eclipse.mylyn.reviews.core.model.review.*;
+
+/**
+ * <!-- begin-user-doc -->
+ * An implementation of the model <b>Factory</b>.
+ * <!-- end-user-doc -->
+ * @generated
+ */
+public class ReviewFactoryImpl extends EFactoryImpl implements ReviewFactory {
+ /**
+ * Creates the default factory implementation.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public static ReviewFactory init() {
+ try {
+ ReviewFactory theReviewFactory = (ReviewFactory)EPackage.Registry.INSTANCE.getEFactory("org.eclipse.mylyn.reviews");
+ if (theReviewFactory != null) {
+ return theReviewFactory;
+ }
+ }
+ catch (Exception exception) {
+ EcorePlugin.INSTANCE.log(exception);
+ }
+ return new ReviewFactoryImpl();
+ }
+
+ /**
+ * Creates an instance of the factory.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public ReviewFactoryImpl() {
+ super();
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public EObject create(EClass eClass) {
+ switch (eClass.getClassifierID()) {
+ case ReviewPackage.REVIEW: return createReview();
+ case ReviewPackage.REVIEW_RESULT: return createReviewResult();
+ case ReviewPackage.PATCH: return createPatch();
+ case ReviewPackage.SCOPE_ITEM: return createScopeItem();
+ default:
+ throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
+ }
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public Object createFromString(EDataType eDataType, String initialValue) {
+ switch (eDataType.getClassifierID()) {
+ case ReviewPackage.RATING:
+ return createRatingFromString(eDataType, initialValue);
+ case ReviewPackage.IFILE_PATCH2:
+ return createIFilePatch2FromString(eDataType, initialValue);
+ case ReviewPackage.IPROGRESS_MONITOR:
+ return createIProgressMonitorFromString(eDataType, initialValue);
+ default:
+ throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
+ }
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public String convertToString(EDataType eDataType, Object instanceValue) {
+ switch (eDataType.getClassifierID()) {
+ case ReviewPackage.RATING:
+ return convertRatingToString(eDataType, instanceValue);
+ case ReviewPackage.IFILE_PATCH2:
+ return convertIFilePatch2ToString(eDataType, instanceValue);
+ case ReviewPackage.IPROGRESS_MONITOR:
+ return convertIProgressMonitorToString(eDataType, instanceValue);
+ default:
+ throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
+ }
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public Review createReview() {
+ ReviewImpl review = new ReviewImpl();
+ return review;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public ReviewResult createReviewResult() {
+ ReviewResultImpl reviewResult = new ReviewResultImpl();
+ return reviewResult;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public Patch createPatch() {
+ PatchImpl patch = new PatchImpl();
+ return patch;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public ScopeItem createScopeItem() {
+ ScopeItemImpl scopeItem = new ScopeItemImpl();
+ return scopeItem;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public Rating createRatingFromString(EDataType eDataType, String initialValue) {
+ Rating result = Rating.get(initialValue);
+ if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
+ return result;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public String convertRatingToString(EDataType eDataType, Object instanceValue) {
+ return instanceValue == null ? null : instanceValue.toString();
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public IFilePatch2 createIFilePatch2FromString(EDataType eDataType, String initialValue) {
+ return (IFilePatch2)super.createFromString(eDataType, initialValue);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public String convertIFilePatch2ToString(EDataType eDataType, Object instanceValue) {
+ return super.convertToString(eDataType, instanceValue);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public IProgressMonitor createIProgressMonitorFromString(EDataType eDataType, String initialValue) {
+ return (IProgressMonitor)super.createFromString(eDataType, initialValue);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public String convertIProgressMonitorToString(EDataType eDataType, Object instanceValue) {
+ return super.convertToString(eDataType, instanceValue);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public ReviewPackage getReviewPackage() {
+ return (ReviewPackage)getEPackage();
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @deprecated
+ * @generated
+ */
+ @Deprecated
+ public static ReviewPackage getPackage() {
+ return ReviewPackage.eINSTANCE;
+ }
+
+} //ReviewFactoryImpl
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewImpl.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewImpl.java
new file mode 100644
index 00000000..4cebc515
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewImpl.java
@@ -0,0 +1,204 @@
+/**
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ */
+package org.eclipse.mylyn.reviews.core.model.review.impl;
+
+import java.util.Collection;
+import org.eclipse.emf.common.notify.Notification;
+import org.eclipse.emf.common.util.EList;
+
+import org.eclipse.emf.ecore.EClass;
+
+import org.eclipse.emf.ecore.InternalEObject;
+import org.eclipse.emf.ecore.impl.ENotificationImpl;
+import org.eclipse.emf.ecore.impl.EObjectImpl;
+import org.eclipse.emf.ecore.util.EObjectResolvingEList;
+
+import org.eclipse.mylyn.reviews.core.model.review.Review;
+import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
+import org.eclipse.mylyn.reviews.core.model.review.ReviewResult;
+import org.eclipse.mylyn.reviews.core.model.review.ScopeItem;
+
+/**
+ * <!-- begin-user-doc -->
+ * An implementation of the model object '<em><b>Review</b></em>'.
+ * <!-- end-user-doc -->
+ * <p>
+ * The following features are implemented:
+ * <ul>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.ReviewImpl#getResult <em>Result</em>}</li>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.ReviewImpl#getScope <em>Scope</em>}</li>
+ * </ul>
+ * </p>
+ *
+ * @generated
+ */
+public class ReviewImpl extends EObjectImpl implements Review {
+ /**
+ * The cached value of the '{@link #getResult() <em>Result</em>}' reference.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getResult()
+ * @generated
+ * @ordered
+ */
+ protected ReviewResult result;
+ /**
+ * The cached value of the '{@link #getScope() <em>Scope</em>}' reference list.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getScope()
+ * @generated
+ * @ordered
+ */
+ protected EList<ScopeItem> scope;
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ protected ReviewImpl() {
+ super();
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ protected EClass eStaticClass() {
+ return ReviewPackage.Literals.REVIEW;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public ReviewResult getResult() {
+ if (result != null && result.eIsProxy()) {
+ InternalEObject oldResult = (InternalEObject)result;
+ result = (ReviewResult)eResolveProxy(oldResult);
+ if (result != oldResult) {
+ if (eNotificationRequired())
+ eNotify(new ENotificationImpl(this, Notification.RESOLVE, ReviewPackage.REVIEW__RESULT, oldResult, result));
+ }
+ }
+ return result;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public ReviewResult basicGetResult() {
+ return result;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public void setResult(ReviewResult newResult) {
+ ReviewResult oldResult = result;
+ result = newResult;
+ if (eNotificationRequired())
+ eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.REVIEW__RESULT, oldResult, result));
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @SuppressWarnings("unchecked")
+ public EList<ScopeItem> getScope() {
+ if (scope == null) {
+ scope = new EObjectResolvingEList<ScopeItem>(ScopeItem.class, this, ReviewPackage.REVIEW__SCOPE);
+ }
+ return scope;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public Object eGet(int featureID, boolean resolve, boolean coreType) {
+ switch (featureID) {
+ case ReviewPackage.REVIEW__RESULT:
+ if (resolve) return getResult();
+ return basicGetResult();
+ case ReviewPackage.REVIEW__SCOPE:
+ return getScope();
+ }
+ return super.eGet(featureID, resolve, coreType);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @SuppressWarnings("unchecked")
+ @Override
+ public void eSet(int featureID, Object newValue) {
+ switch (featureID) {
+ case ReviewPackage.REVIEW__RESULT:
+ setResult((ReviewResult)newValue);
+ return;
+ case ReviewPackage.REVIEW__SCOPE:
+ getScope().clear();
+ getScope().addAll((Collection<? extends ScopeItem>)newValue);
+ return;
+ }
+ super.eSet(featureID, newValue);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public void eUnset(int featureID) {
+ switch (featureID) {
+ case ReviewPackage.REVIEW__RESULT:
+ setResult((ReviewResult)null);
+ return;
+ case ReviewPackage.REVIEW__SCOPE:
+ getScope().clear();
+ return;
+ }
+ super.eUnset(featureID);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public boolean eIsSet(int featureID) {
+ switch (featureID) {
+ case ReviewPackage.REVIEW__RESULT:
+ return result != null;
+ case ReviewPackage.REVIEW__SCOPE:
+ return scope != null && !scope.isEmpty();
+ }
+ return super.eIsSet(featureID);
+ }
+
+} //ReviewImpl
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewPackageImpl.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewPackageImpl.java
new file mode 100644
index 00000000..0b2e5332
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewPackageImpl.java
@@ -0,0 +1,413 @@
+/**
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ */
+package org.eclipse.mylyn.reviews.core.model.review.impl;
+
+import org.eclipse.compare.patch.IFilePatch2;
+
+import org.eclipse.core.runtime.IProgressMonitor;
+
+import org.eclipse.emf.ecore.EAttribute;
+import org.eclipse.emf.ecore.EClass;
+import org.eclipse.emf.ecore.EDataType;
+import org.eclipse.emf.ecore.EEnum;
+import org.eclipse.emf.ecore.EPackage;
+import org.eclipse.emf.ecore.EReference;
+
+import org.eclipse.emf.ecore.impl.EPackageImpl;
+
+import org.eclipse.mylyn.reviews.core.model.review.Patch;
+import org.eclipse.mylyn.reviews.core.model.review.Rating;
+import org.eclipse.mylyn.reviews.core.model.review.Review;
+import org.eclipse.mylyn.reviews.core.model.review.ReviewFactory;
+import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
+import org.eclipse.mylyn.reviews.core.model.review.ReviewResult;
+import org.eclipse.mylyn.reviews.core.model.review.ScopeItem;
+
+/**
+ * <!-- begin-user-doc -->
+ * An implementation of the model <b>Package</b>.
+ * <!-- end-user-doc -->
+ * @generated
+ */
+public class ReviewPackageImpl extends EPackageImpl implements ReviewPackage {
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ private EClass reviewEClass = null;
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ private EClass reviewResultEClass = null;
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ private EClass patchEClass = null;
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ private EClass scopeItemEClass = null;
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ private EEnum ratingEEnum = null;
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ private EDataType iFilePatch2EDataType = null;
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ private EDataType iProgressMonitorEDataType = null;
+
+ /**
+ * Creates an instance of the model <b>Package</b>, registered with
+ * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package
+ * package URI value.
+ * <p>Note: the correct way to create the package is via the static
+ * factory method {@link #init init()}, which also performs
+ * initialization of the package, or returns the registered package,
+ * if one already exists.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see org.eclipse.emf.ecore.EPackage.Registry
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#eNS_URI
+ * @see #init()
+ * @generated
+ */
+ private ReviewPackageImpl() {
+ super(eNS_URI, ReviewFactory.eINSTANCE);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ private static boolean isInited = false;
+
+ /**
+ * Creates, registers, and initializes the <b>Package</b> for this model, and for any others upon which it depends.
+ *
+ * <p>This method is used to initialize {@link ReviewPackage#eINSTANCE} when that field is accessed.
+ * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #eNS_URI
+ * @see #createPackageContents()
+ * @see #initializePackageContents()
+ * @generated
+ */
+ public static ReviewPackage init() {
+ if (isInited) return (ReviewPackage)EPackage.Registry.INSTANCE.getEPackage(ReviewPackage.eNS_URI);
+
+ // Obtain or create and register package
+ ReviewPackageImpl theReviewPackage = (ReviewPackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof ReviewPackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new ReviewPackageImpl());
+
+ isInited = true;
+
+ // Create package meta-data objects
+ theReviewPackage.createPackageContents();
+
+ // Initialize created meta-data
+ theReviewPackage.initializePackageContents();
+
+ // Mark meta-data to indicate it can't be changed
+ theReviewPackage.freeze();
+
+
+ // Update the registry and return the package
+ EPackage.Registry.INSTANCE.put(ReviewPackage.eNS_URI, theReviewPackage);
+ return theReviewPackage;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public EClass getReview() {
+ return reviewEClass;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public EReference getReview_Result() {
+ return (EReference)reviewEClass.getEStructuralFeatures().get(0);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public EReference getReview_Scope() {
+ return (EReference)reviewEClass.getEStructuralFeatures().get(1);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public EClass getReviewResult() {
+ return reviewResultEClass;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public EAttribute getReviewResult_Text() {
+ return (EAttribute)reviewResultEClass.getEStructuralFeatures().get(0);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public EAttribute getReviewResult_Rating() {
+ return (EAttribute)reviewResultEClass.getEStructuralFeatures().get(1);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public EAttribute getReviewResult_Reviewer() {
+ return (EAttribute)reviewResultEClass.getEStructuralFeatures().get(2);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public EClass getPatch() {
+ return patchEClass;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public EAttribute getPatch_Contents() {
+ return (EAttribute)patchEClass.getEStructuralFeatures().get(0);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public EAttribute getPatch_CreationDate() {
+ return (EAttribute)patchEClass.getEStructuralFeatures().get(1);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public EAttribute getPatch_FileName() {
+ return (EAttribute)patchEClass.getEStructuralFeatures().get(2);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public EClass getScopeItem() {
+ return scopeItemEClass;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public EAttribute getScopeItem_Author() {
+ return (EAttribute)scopeItemEClass.getEStructuralFeatures().get(0);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public EEnum getRating() {
+ return ratingEEnum;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public EDataType getIFilePatch2() {
+ return iFilePatch2EDataType;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public EDataType getIProgressMonitor() {
+ return iProgressMonitorEDataType;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public ReviewFactory getReviewFactory() {
+ return (ReviewFactory)getEFactoryInstance();
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ private boolean isCreated = false;
+
+ /**
+ * Creates the meta-model objects for the package. This method is
+ * guarded to have no affect on any invocation but its first.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public void createPackageContents() {
+ if (isCreated) return;
+ isCreated = true;
+
+ // Create classes and their features
+ reviewEClass = createEClass(REVIEW);
+ createEReference(reviewEClass, REVIEW__RESULT);
+ createEReference(reviewEClass, REVIEW__SCOPE);
+
+ reviewResultEClass = createEClass(REVIEW_RESULT);
+ createEAttribute(reviewResultEClass, REVIEW_RESULT__TEXT);
+ createEAttribute(reviewResultEClass, REVIEW_RESULT__RATING);
+ createEAttribute(reviewResultEClass, REVIEW_RESULT__REVIEWER);
+
+ patchEClass = createEClass(PATCH);
+ createEAttribute(patchEClass, PATCH__CONTENTS);
+ createEAttribute(patchEClass, PATCH__CREATION_DATE);
+ createEAttribute(patchEClass, PATCH__FILE_NAME);
+
+ scopeItemEClass = createEClass(SCOPE_ITEM);
+ createEAttribute(scopeItemEClass, SCOPE_ITEM__AUTHOR);
+
+ // Create enums
+ ratingEEnum = createEEnum(RATING);
+
+ // Create data types
+ iFilePatch2EDataType = createEDataType(IFILE_PATCH2);
+ iProgressMonitorEDataType = createEDataType(IPROGRESS_MONITOR);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ private boolean isInitialized = false;
+
+ /**
+ * Complete the initialization of the package and its meta-model. This
+ * method is guarded to have no affect on any invocation but its first.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public void initializePackageContents() {
+ if (isInitialized) return;
+ isInitialized = true;
+
+ // Initialize package
+ setName(eNAME);
+ setNsPrefix(eNS_PREFIX);
+ setNsURI(eNS_URI);
+
+ // Create type parameters
+
+ // Set bounds for type parameters
+
+ // Add supertypes to classes
+ patchEClass.getESuperTypes().add(this.getScopeItem());
+
+ // Initialize classes and features; add operations and parameters
+ initEClass(reviewEClass, Review.class, "Review", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
+ initEReference(getReview_Result(), this.getReviewResult(), null, "result", null, 0, 1, Review.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
+ initEReference(getReview_Scope(), this.getScopeItem(), null, "scope", null, 0, -1, Review.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
+
+ initEClass(reviewResultEClass, ReviewResult.class, "ReviewResult", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
+ initEAttribute(getReviewResult_Text(), ecorePackage.getEString(), "text", null, 0, 1, ReviewResult.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
+ initEAttribute(getReviewResult_Rating(), this.getRating(), "rating", null, 0, 1, ReviewResult.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
+ initEAttribute(getReviewResult_Reviewer(), ecorePackage.getEString(), "reviewer", null, 0, 1, ReviewResult.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
+
+ initEClass(patchEClass, Patch.class, "Patch", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
+ initEAttribute(getPatch_Contents(), ecorePackage.getEString(), "contents", null, 0, 1, Patch.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
+ initEAttribute(getPatch_CreationDate(), ecorePackage.getEDate(), "creationDate", null, 0, 1, Patch.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
+ initEAttribute(getPatch_FileName(), ecorePackage.getEString(), "fileName", null, 0, 1, Patch.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
+
+ addEOperation(patchEClass, this.getIFilePatch2(), "parse", 0, -1, IS_UNIQUE, IS_ORDERED);
+
+ initEClass(scopeItemEClass, ScopeItem.class, "ScopeItem", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
+ initEAttribute(getScopeItem_Author(), ecorePackage.getEString(), "author", null, 0, 1, ScopeItem.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
+
+ // Initialize enums and add enum literals
+ initEEnum(ratingEEnum, Rating.class, "Rating");
+ addEEnumLiteral(ratingEEnum, Rating.NONE);
+ addEEnumLiteral(ratingEEnum, Rating.PASSED);
+ addEEnumLiteral(ratingEEnum, Rating.WARNING);
+ addEEnumLiteral(ratingEEnum, Rating.FAILED);
+
+ // Initialize data types
+ initEDataType(iFilePatch2EDataType, IFilePatch2.class, "IFilePatch2", IS_SERIALIZABLE, !IS_GENERATED_INSTANCE_CLASS);
+ initEDataType(iProgressMonitorEDataType, IProgressMonitor.class, "IProgressMonitor", IS_SERIALIZABLE, !IS_GENERATED_INSTANCE_CLASS);
+
+ // Create resource
+ createResource(eNS_URI);
+ }
+
+} //ReviewPackageImpl
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewResultImpl.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewResultImpl.java
new file mode 100644
index 00000000..1619866d
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewResultImpl.java
@@ -0,0 +1,272 @@
+/**
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ */
+package org.eclipse.mylyn.reviews.core.model.review.impl;
+
+import org.eclipse.emf.common.notify.Notification;
+import org.eclipse.emf.ecore.EClass;
+import org.eclipse.emf.ecore.impl.ENotificationImpl;
+import org.eclipse.emf.ecore.impl.EObjectImpl;
+import org.eclipse.mylyn.reviews.core.model.review.Rating;
+import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
+import org.eclipse.mylyn.reviews.core.model.review.ReviewResult;
+
+/**
+ * <!-- begin-user-doc -->
+ * An implementation of the model object '<em><b>Result</b></em>'.
+ * <!-- end-user-doc -->
+ * <p>
+ * The following features are implemented:
+ * <ul>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.ReviewResultImpl#getText <em>Text</em>}</li>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.ReviewResultImpl#getRating <em>Rating</em>}</li>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.ReviewResultImpl#getReviewer <em>Reviewer</em>}</li>
+ * </ul>
+ * </p>
+ *
+ * @generated
+ */
+public class ReviewResultImpl extends EObjectImpl implements ReviewResult {
+ /**
+ * The default value of the '{@link #getText() <em>Text</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getText()
+ * @generated
+ * @ordered
+ */
+ protected static final String TEXT_EDEFAULT = null;
+ /**
+ * The cached value of the '{@link #getText() <em>Text</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getText()
+ * @generated
+ * @ordered
+ */
+ protected String text = TEXT_EDEFAULT;
+ /**
+ * The default value of the '{@link #getRating() <em>Rating</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getRating()
+ * @generated
+ * @ordered
+ */
+ protected static final Rating RATING_EDEFAULT = Rating.NONE;
+ /**
+ * The cached value of the '{@link #getRating() <em>Rating</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getRating()
+ * @generated
+ * @ordered
+ */
+ protected Rating rating = RATING_EDEFAULT;
+ /**
+ * The default value of the '{@link #getReviewer() <em>Reviewer</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getReviewer()
+ * @generated
+ * @ordered
+ */
+ protected static final String REVIEWER_EDEFAULT = null;
+ /**
+ * The cached value of the '{@link #getReviewer() <em>Reviewer</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getReviewer()
+ * @generated
+ * @ordered
+ */
+ protected String reviewer = REVIEWER_EDEFAULT;
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ protected ReviewResultImpl() {
+ super();
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ protected EClass eStaticClass() {
+ return ReviewPackage.Literals.REVIEW_RESULT;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public String getText() {
+ return text;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public void setText(String newText) {
+ String oldText = text;
+ text = newText;
+ if (eNotificationRequired())
+ eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.REVIEW_RESULT__TEXT, oldText, text));
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public Rating getRating() {
+ return rating;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public void setRating(Rating newRating) {
+ Rating oldRating = rating;
+ rating = newRating == null ? RATING_EDEFAULT : newRating;
+ if (eNotificationRequired())
+ eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.REVIEW_RESULT__RATING, oldRating, rating));
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public String getReviewer() {
+ return reviewer;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public void setReviewer(String newReviewer) {
+ String oldReviewer = reviewer;
+ reviewer = newReviewer;
+ if (eNotificationRequired())
+ eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.REVIEW_RESULT__REVIEWER, oldReviewer, reviewer));
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public Object eGet(int featureID, boolean resolve, boolean coreType) {
+ switch (featureID) {
+ case ReviewPackage.REVIEW_RESULT__TEXT:
+ return getText();
+ case ReviewPackage.REVIEW_RESULT__RATING:
+ return getRating();
+ case ReviewPackage.REVIEW_RESULT__REVIEWER:
+ return getReviewer();
+ }
+ return super.eGet(featureID, resolve, coreType);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public void eSet(int featureID, Object newValue) {
+ switch (featureID) {
+ case ReviewPackage.REVIEW_RESULT__TEXT:
+ setText((String)newValue);
+ return;
+ case ReviewPackage.REVIEW_RESULT__RATING:
+ setRating((Rating)newValue);
+ return;
+ case ReviewPackage.REVIEW_RESULT__REVIEWER:
+ setReviewer((String)newValue);
+ return;
+ }
+ super.eSet(featureID, newValue);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public void eUnset(int featureID) {
+ switch (featureID) {
+ case ReviewPackage.REVIEW_RESULT__TEXT:
+ setText(TEXT_EDEFAULT);
+ return;
+ case ReviewPackage.REVIEW_RESULT__RATING:
+ setRating(RATING_EDEFAULT);
+ return;
+ case ReviewPackage.REVIEW_RESULT__REVIEWER:
+ setReviewer(REVIEWER_EDEFAULT);
+ return;
+ }
+ super.eUnset(featureID);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public boolean eIsSet(int featureID) {
+ switch (featureID) {
+ case ReviewPackage.REVIEW_RESULT__TEXT:
+ return TEXT_EDEFAULT == null ? text != null : !TEXT_EDEFAULT.equals(text);
+ case ReviewPackage.REVIEW_RESULT__RATING:
+ return rating != RATING_EDEFAULT;
+ case ReviewPackage.REVIEW_RESULT__REVIEWER:
+ return REVIEWER_EDEFAULT == null ? reviewer != null : !REVIEWER_EDEFAULT.equals(reviewer);
+ }
+ return super.eIsSet(featureID);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public String toString() {
+ if (eIsProxy()) return super.toString();
+
+ StringBuffer result = new StringBuffer(super.toString());
+ result.append(" (text: ");
+ result.append(text);
+ result.append(", rating: ");
+ result.append(rating);
+ result.append(", reviewer: ");
+ result.append(reviewer);
+ result.append(')');
+ return result.toString();
+ }
+
+} //ReviewResultImpl
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ScopeItemImpl.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ScopeItemImpl.java
new file mode 100644
index 00000000..cad5f6f7
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ScopeItemImpl.java
@@ -0,0 +1,167 @@
+/**
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ */
+package org.eclipse.mylyn.reviews.core.model.review.impl;
+
+import org.eclipse.emf.common.notify.Notification;
+import org.eclipse.emf.ecore.EClass;
+import org.eclipse.emf.ecore.impl.ENotificationImpl;
+import org.eclipse.emf.ecore.impl.EObjectImpl;
+import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
+import org.eclipse.mylyn.reviews.core.model.review.ScopeItem;
+
+/**
+ * <!-- begin-user-doc -->
+ * An implementation of the model object '<em><b>Scope Item</b></em>'.
+ * <!-- end-user-doc -->
+ * <p>
+ * The following features are implemented:
+ * <ul>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.ScopeItemImpl#getAuthor <em>Author</em>}</li>
+ * </ul>
+ * </p>
+ *
+ * @generated
+ */
+public class ScopeItemImpl extends EObjectImpl implements ScopeItem {
+ /**
+ * The default value of the '{@link #getAuthor() <em>Author</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getAuthor()
+ * @generated
+ * @ordered
+ */
+ protected static final String AUTHOR_EDEFAULT = null;
+ /**
+ * The cached value of the '{@link #getAuthor() <em>Author</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getAuthor()
+ * @generated
+ * @ordered
+ */
+ protected String author = AUTHOR_EDEFAULT;
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ protected ScopeItemImpl() {
+ super();
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ protected EClass eStaticClass() {
+ return ReviewPackage.Literals.SCOPE_ITEM;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public String getAuthor() {
+ return author;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public void setAuthor(String newAuthor) {
+ String oldAuthor = author;
+ author = newAuthor;
+ if (eNotificationRequired())
+ eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.SCOPE_ITEM__AUTHOR, oldAuthor, author));
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public Object eGet(int featureID, boolean resolve, boolean coreType) {
+ switch (featureID) {
+ case ReviewPackage.SCOPE_ITEM__AUTHOR:
+ return getAuthor();
+ }
+ return super.eGet(featureID, resolve, coreType);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public void eSet(int featureID, Object newValue) {
+ switch (featureID) {
+ case ReviewPackage.SCOPE_ITEM__AUTHOR:
+ setAuthor((String)newValue);
+ return;
+ }
+ super.eSet(featureID, newValue);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public void eUnset(int featureID) {
+ switch (featureID) {
+ case ReviewPackage.SCOPE_ITEM__AUTHOR:
+ setAuthor(AUTHOR_EDEFAULT);
+ return;
+ }
+ super.eUnset(featureID);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public boolean eIsSet(int featureID) {
+ switch (featureID) {
+ case ReviewPackage.SCOPE_ITEM__AUTHOR:
+ return AUTHOR_EDEFAULT == null ? author != null : !AUTHOR_EDEFAULT.equals(author);
+ }
+ return super.eIsSet(featureID);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public String toString() {
+ if (eIsProxy()) return super.toString();
+
+ StringBuffer result = new StringBuffer(super.toString());
+ result.append(" (author: ");
+ result.append(author);
+ result.append(')');
+ return result.toString();
+ }
+
+} //ScopeItemImpl
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewAdapterFactory.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewAdapterFactory.java
new file mode 100644
index 00000000..73e096eb
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewAdapterFactory.java
@@ -0,0 +1,182 @@
+/**
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ */
+package org.eclipse.mylyn.reviews.core.model.review.util;
+
+import org.eclipse.emf.common.notify.Adapter;
+import org.eclipse.emf.common.notify.Notifier;
+import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.mylyn.reviews.core.model.review.*;
+import org.eclipse.mylyn.reviews.core.model.review.Patch;
+import org.eclipse.mylyn.reviews.core.model.review.Review;
+import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
+import org.eclipse.mylyn.reviews.core.model.review.ReviewResult;
+import org.eclipse.mylyn.reviews.core.model.review.ScopeItem;
+
+/**
+ * <!-- begin-user-doc --> The <b>Adapter Factory</b> for the model. It provides
+ * an adapter <code>createXXX</code> method for each class of the model. <!--
+ * end-user-doc -->
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage
+ * @generated
+ */
+public class ReviewAdapterFactory extends AdapterFactoryImpl {
+ /**
+ * The cached model package.
+ * <!-- begin-user-doc --> <!-- end-user-doc -->
+ * @generated
+ */
+ protected static ReviewPackage modelPackage;
+
+ /**
+ * Creates an instance of the adapter factory.
+ * <!-- begin-user-doc --> <!--
+ * end-user-doc -->
+ * @generated
+ */
+ public ReviewAdapterFactory() {
+ if (modelPackage == null) {
+ modelPackage = ReviewPackage.eINSTANCE;
+ }
+ }
+
+ /**
+ * Returns whether this factory is applicable for the type of the object.
+ * <!-- begin-user-doc --> This implementation returns <code>true</code> if
+ * the object is either the model's package or is an instance object of the
+ * model. <!-- end-user-doc -->
+ * @return whether this factory is applicable for the type of the object.
+ * @generated
+ */
+ @Override
+ public boolean isFactoryForType(Object object) {
+ if (object == modelPackage) {
+ return true;
+ }
+ if (object instanceof EObject) {
+ return ((EObject)object).eClass().getEPackage() == modelPackage;
+ }
+ return false;
+ }
+
+ /**
+ * The switch that delegates to the <code>createXXX</code> methods. <!--
+ * begin-user-doc --> <!-- end-user-doc -->
+ *
+ * @generated
+ */
+ protected ReviewSwitch<Adapter> modelSwitch = new ReviewSwitch<Adapter>() {
+ @Override
+ public Adapter caseReview(Review object) {
+ return createReviewAdapter();
+ }
+ @Override
+ public Adapter caseReviewResult(ReviewResult object) {
+ return createReviewResultAdapter();
+ }
+ @Override
+ public Adapter casePatch(Patch object) {
+ return createPatchAdapter();
+ }
+ @Override
+ public Adapter caseScopeItem(ScopeItem object) {
+ return createScopeItemAdapter();
+ }
+ @Override
+ public Adapter defaultCase(EObject object) {
+ return createEObjectAdapter();
+ }
+ };
+
+ /**
+ * Creates an adapter for the <code>target</code>.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @param target the object to adapt.
+ * @return the adapter for the <code>target</code>.
+ * @generated
+ */
+ @Override
+ public Adapter createAdapter(Notifier target) {
+ return modelSwitch.doSwitch((EObject)target);
+ }
+
+ /**
+ * Creates a new adapter for an object of class '
+ * {@link org.eclipse.mylyn.reviews.core.model.review.Review
+ * <em>Review</em>}'. <!-- begin-user-doc --> This default implementation
+ * returns null so that we can easily ignore cases; it's useful to ignore a
+ * case when inheritance will catch all the cases anyway. <!-- end-user-doc
+ * -->
+ *
+ * @return the new adapter.
+ * @see org.eclipse.mylyn.reviews.core.model.review.Review
+ * @generated
+ */
+ public Adapter createReviewAdapter() {
+ return null;
+ }
+
+ /**
+ * Creates a new adapter for an object of class '
+ * {@link org.eclipse.mylyn.reviews.core.model.review.ReviewResult
+ * <em>Result</em>}'. <!-- begin-user-doc --> This default implementation
+ * returns null so that we can easily ignore cases; it's useful to ignore a
+ * case when inheritance will catch all the cases anyway. <!-- end-user-doc
+ * -->
+ *
+ * @return the new adapter.
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewResult
+ * @generated
+ */
+ public Adapter createReviewResultAdapter() {
+ return null;
+ }
+
+ /**
+ * Creates a new adapter for an object of class '{@link org.eclipse.mylyn.reviews.core.model.review.Patch <em>Patch</em>}'.
+ * <!-- begin-user-doc --> This default implementation returns null so
+ * that we can easily ignore cases; it's useful to ignore a case when
+ * inheritance will catch all the cases anyway. <!-- end-user-doc -->
+ * @return the new adapter.
+ * @see org.eclipse.mylyn.reviews.core.model.review.Patch
+ * @generated
+ */
+ public Adapter createPatchAdapter() {
+ return null;
+ }
+
+ /**
+ * Creates a new adapter for an object of class '{@link org.eclipse.mylyn.reviews.core.model.review.ScopeItem <em>Scope Item</em>}'.
+ * <!-- begin-user-doc --> This default
+ * implementation returns null so that we can easily ignore cases; it's
+ * useful to ignore a case when inheritance will catch all the cases anyway.
+ * <!-- end-user-doc -->
+ * @return the new adapter.
+ * @see org.eclipse.mylyn.reviews.core.model.review.ScopeItem
+ * @generated
+ */
+ public Adapter createScopeItemAdapter() {
+ return null;
+ }
+
+ /**
+ * Creates a new adapter for the default case.
+ * <!-- begin-user-doc --> This
+ * default implementation returns null. <!-- end-user-doc -->
+ * @return the new adapter.
+ * @generated
+ */
+ public Adapter createEObjectAdapter() {
+ return null;
+ }
+
+} // ReviewAdapterFactory
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewSwitch.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewSwitch.java
new file mode 100644
index 00000000..3ab3388d
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewSwitch.java
@@ -0,0 +1,193 @@
+/**
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ */
+package org.eclipse.mylyn.reviews.core.model.review.util;
+
+import java.util.List;
+
+import org.eclipse.emf.ecore.EClass;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.mylyn.reviews.core.model.review.*;
+import org.eclipse.mylyn.reviews.core.model.review.Patch;
+import org.eclipse.mylyn.reviews.core.model.review.Review;
+import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
+import org.eclipse.mylyn.reviews.core.model.review.ReviewResult;
+import org.eclipse.mylyn.reviews.core.model.review.ScopeItem;
+
+/**
+ * <!-- begin-user-doc --> The <b>Switch</b> for the model's inheritance
+ * hierarchy. It supports the call {@link #doSwitch(EObject) doSwitch(object)}
+ * to invoke the <code>caseXXX</code> method for each class of the model,
+ * starting with the actual class of the object and proceeding up the
+ * inheritance hierarchy until a non-null result is returned, which is the
+ * result of the switch. <!-- end-user-doc -->
+ * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage
+ * @generated
+ */
+public class ReviewSwitch<T> {
+ /**
+ * The cached model package
+ * <!-- begin-user-doc --> <!-- end-user-doc -->
+ * @generated
+ */
+ protected static ReviewPackage modelPackage;
+
+ /**
+ * Creates an instance of the switch.
+ * <!-- begin-user-doc --> <!--
+ * end-user-doc -->
+ * @generated
+ */
+ public ReviewSwitch() {
+ if (modelPackage == null) {
+ modelPackage = ReviewPackage.eINSTANCE;
+ }
+ }
+
+ /**
+ * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
+ * <!-- begin-user-doc --> <!--
+ * end-user-doc -->
+ * @return the first non-null result returned by a <code>caseXXX</code> call.
+ * @generated
+ */
+ public T doSwitch(EObject theEObject) {
+ return doSwitch(theEObject.eClass(), theEObject);
+ }
+
+ /**
+ * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
+ * <!-- begin-user-doc --> <!--
+ * end-user-doc -->
+ * @return the first non-null result returned by a <code>caseXXX</code> call.
+ * @generated
+ */
+ protected T doSwitch(EClass theEClass, EObject theEObject) {
+ if (theEClass.eContainer() == modelPackage) {
+ return doSwitch(theEClass.getClassifierID(), theEObject);
+ }
+ else {
+ List<EClass> eSuperTypes = theEClass.getESuperTypes();
+ return
+ eSuperTypes.isEmpty() ?
+ defaultCase(theEObject) :
+ doSwitch(eSuperTypes.get(0), theEObject);
+ }
+ }
+
+ /**
+ * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
+ * <!-- begin-user-doc --> <!--
+ * end-user-doc -->
+ * @return the first non-null result returned by a <code>caseXXX</code> call.
+ * @generated
+ */
+ protected T doSwitch(int classifierID, EObject theEObject) {
+ switch (classifierID) {
+ case ReviewPackage.REVIEW: {
+ Review review = (Review)theEObject;
+ T result = caseReview(review);
+ if (result == null) result = defaultCase(theEObject);
+ return result;
+ }
+ case ReviewPackage.REVIEW_RESULT: {
+ ReviewResult reviewResult = (ReviewResult)theEObject;
+ T result = caseReviewResult(reviewResult);
+ if (result == null) result = defaultCase(theEObject);
+ return result;
+ }
+ case ReviewPackage.PATCH: {
+ Patch patch = (Patch)theEObject;
+ T result = casePatch(patch);
+ if (result == null) result = caseScopeItem(patch);
+ if (result == null) result = defaultCase(theEObject);
+ return result;
+ }
+ case ReviewPackage.SCOPE_ITEM: {
+ ScopeItem scopeItem = (ScopeItem)theEObject;
+ T result = caseScopeItem(scopeItem);
+ if (result == null) result = defaultCase(theEObject);
+ return result;
+ }
+ default: return defaultCase(theEObject);
+ }
+ }
+
+ /**
+ * Returns the result of interpreting the object as an instance of '<em>Review</em>'.
+ * <!-- begin-user-doc --> This implementation returns
+ * null; returning a non-null result will terminate the switch. <!--
+ * end-user-doc -->
+ * @param object the target of the switch.
+ * @return the result of interpreting the object as an instance of '<em>Review</em>'.
+ * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
+ * @generated
+ */
+ public T caseReview(Review object) {
+ return null;
+ }
+
+ /**
+ * Returns the result of interpreting the object as an instance of '<em>Result</em>'.
+ * <!-- begin-user-doc --> This implementation returns
+ * null; returning a non-null result will terminate the switch. <!--
+ * end-user-doc -->
+ * @param object the target of the switch.
+ * @return the result of interpreting the object as an instance of '<em>Result</em>'.
+ * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
+ * @generated
+ */
+ public T caseReviewResult(ReviewResult object) {
+ return null;
+ }
+
+ /**
+ * Returns the result of interpreting the object as an instance of '<em>Patch</em>'.
+ * <!-- begin-user-doc --> This implementation returns
+ * null; returning a non-null result will terminate the switch. <!--
+ * end-user-doc -->
+ * @param object the target of the switch.
+ * @return the result of interpreting the object as an instance of '<em>Patch</em>'.
+ * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
+ * @generated
+ */
+ public T casePatch(Patch object) {
+ return null;
+ }
+
+ /**
+ * Returns the result of interpreting the object as an instance of '<em>Scope Item</em>'.
+ * <!-- begin-user-doc --> This implementation returns
+ * null; returning a non-null result will terminate the switch. <!--
+ * end-user-doc -->
+ * @param object the target of the switch.
+ * @return the result of interpreting the object as an instance of '<em>Scope Item</em>'.
+ * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
+ * @generated
+ */
+ public T caseScopeItem(ScopeItem object) {
+ return null;
+ }
+
+ /**
+ * Returns the result of interpreting the object as an instance of '<em>EObject</em>'.
+ * <!-- begin-user-doc --> This implementation returns
+ * null; returning a non-null result will terminate the switch, but this is
+ * the last case anyway. <!-- end-user-doc -->
+ * @param object the target of the switch.
+ * @return the result of interpreting the object as an instance of '<em>EObject</em>'.
+ * @see #doSwitch(org.eclipse.emf.ecore.EObject)
+ * @generated
+ */
+ public T defaultCase(EObject object) {
+ return null;
+ }
+
+} // ReviewSwitch
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/.classpath b/tbr/org.eclipse.mylyn.reviews.ui/.classpath
new file mode 100644
index 00000000..ad32c83a
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/.classpath
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/.project b/tbr/org.eclipse.mylyn.reviews.ui/.project
new file mode 100644
index 00000000..8d039bc9
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/.project
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.mylyn.reviews.ui</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.api.tools.apiAnalysisBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ <nature>org.eclipse.pde.api.tools.apiAnalysisNature</nature>
+ </natures>
+</projectDescription>
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.reviews.ui/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..cf178a13
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/META-INF/MANIFEST.MF
@@ -0,0 +1,20 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Mylyn Reviews UI (Incubation)
+Bundle-SymbolicName: org.eclipse.mylyn.reviews.ui;singleton:=true
+Bundle-Version: 0.0.1
+Bundle-Activator: org.eclipse.mylyn.reviews.ui.ReviewsUiPlugin
+Require-Bundle: org.eclipse.ui,
+ org.eclipse.core.runtime,
+ org.eclipse.mylyn.tasks.ui;bundle-version="3.5.0",
+ org.eclipse.ui.forms;bundle-version="3.4.1",
+ org.eclipse.mylyn.tasks.core;bundle-version="3.3.0",
+ org.eclipse.compare;bundle-version="3.5.0",
+ org.eclipse.mylyn.reviews.core;bundle-version="0.0.1",
+ org.eclipse.emf.ecore.change;bundle-version="2.5.0",
+ org.eclipse.mylyn.bugzilla.ui;bundle-version="3.4.0",
+ org.eclipse.core.resources;bundle-version="3.6.0"
+Bundle-ActivationPolicy: lazy
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Export-Package: org.eclipse.mylyn.reviews.ui,
+ org.eclipse.mylyn.reviews.ui.editors
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/about.html b/tbr/org.eclipse.mylyn.reviews.ui/about.html
new file mode 100644
index 00000000..d677c21a
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/about.html
@@ -0,0 +1,60 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
+<title>About</title>
+</head>
+<body lang="EN-US">
+<h2>About This Content</h2>
+
+<p>June 1, 2010</p>
+<h3>License</h3>
+
+<p>The Eclipse Foundation makes available all content in this plug-in ("Content"). Unless otherwise
+indicated below, the Content is provided to you under the terms and conditions of the
+Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is available
+at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>.
+For purposes of the EPL, "Program" will mean the Content.</p>
+
+<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is
+being redistributed by another party ("Redistributor") and different terms and conditions may
+apply to your use of any object code in the Content. Check the Redistributor's license that was
+provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise
+indicated below, the terms and conditions of the EPL still apply to any source code in the Content
+and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p>
+
+
+ <h3>Third Party Content</h3>
+ <p>The Content includes items that have been sourced from third parties as set out below. If you
+ did not receive this Content directly from the Eclipse Foundation, the following is provided
+ for informational purposes only, and you should look to the Redistributor's license for
+ terms and conditions of use.</p>
+ <p>
+ <br/><br/>
+
+ <strong>Silk icon set 1.3</strong>
+ <br/><br/>
+
+ <p>The plug-in includes one Icon from the Silk Icon Set made by Mark James.
+ This icon is licensed under the <a href="http://creativecommons.org/licenses/by/2.5/">Creative Commons Attribution 2.5 License</a> (<a href="about_files/CreativeCommons-Attribution2.5-Legalcode.html">local copy</a>).
+ The original icons are available from <a href="http://www.famfamfam.com/lab/icons/silk/">http://www.famfamfam.com/lab/icons/silk/</a>.
+ The following files are included:</p>
+
+ <pre>
+ icons/review_none.png: renamed from delete.png
+ </pre>
+
+
+ </p>
+
+
+</body>
+</html>
+
+
+
+
+
+</body>
+</html>
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/about_files/CreativeCommons-Attribution2.5-Legalcode.html b/tbr/org.eclipse.mylyn.reviews.ui/about_files/CreativeCommons-Attribution2.5-Legalcode.html
new file mode 100644
index 00000000..7a9185d7
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/about_files/CreativeCommons-Attribution2.5-Legalcode.html
@@ -0,0 +1,203 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
+<html>
+<head>
+<title>Creative Commons Legal Code</title>
+<link rel="stylesheet" type="text/css" href="http://creativecommons.org/includes/deeds.css" />
+<style type="text/css">
+
+li {
+margin-bottom:12px;
+}
+
+</style>
+</head>
+
+<body>
+
+<p align="center"><a href="http://creativecommons.org/">Creative Commons</a></p>
+
+
+
+<div id="deed">
+<div align="center"><img src="http://creativecommons.org/images/deed/logo_code.gif" alt="Creative Commons Legal Code" width="280" height="79" vspace="14" border="0" /></div>
+
+
+<p align="center"><b>Attribution 2.5</b></p>
+
+
+<div class="text">
+
+
+<div class="fineprint" style="background:none;">
+CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL
+SERVICES. DISTRIBUTION OF THIS LICENSE DOES NOT CREATE AN
+ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON
+AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE
+INFORMATION PROVIDED, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
+ITS USE.</div>
+
+
+
+
+<p><em>License</em> </p>
+
+<p>THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. </p>
+
+<p>BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. </p>
+
+
+<p><strong>1. Definitions</strong> </p>
+
+<ol type="a">
+<li>
+<strong>"Collective Work"</strong> means a work, such as a periodical issue, anthology or encyclopedia, in which the Work in its entirety in unmodified form, along with a number of other contributions, constituting separate and independent works in themselves, are assembled into a collective whole. A work that constitutes a Collective Work will not be considered a Derivative Work (as defined below) for the purposes of this License.
+</li>
+
+<li>
+<strong>"Derivative Work"</strong> means a work based upon the Work or upon the Work and other pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which the Work may be recast, transformed, or adapted, except that a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this License. For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered a Derivative Work for the purpose of this License.</li>
+
+<li>
+<strong>"Licensor"</strong> means the individual or entity that offers the Work under the terms of this License.
+</li>
+
+<li>
+<strong>"Original Author"</strong> means the individual or entity who created the Work.
+</li>
+
+<li>
+<strong>"Work"</strong> means the copyrightable work of authorship offered under the terms of this License.
+</li>
+
+<li>
+<strong>"You"</strong> means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation.
+</li>
+</ol>
+
+<p><strong>2. Fair Use Rights.</strong> Nothing in this license is intended to reduce, limit, or restrict any rights arising from fair use, first sale or other limitations on the exclusive rights of the copyright owner under copyright law or other applicable laws. </p>
+
+
+<p><strong>3. License Grant.</strong> Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below: </p>
+
+
+<ol type="a">
+<li>
+to reproduce the Work, to incorporate the Work into one or more Collective Works, and to reproduce the Work as incorporated in the Collective Works;
+</li>
+
+<li>
+to create and reproduce Derivative Works;
+</li>
+
+<li>
+to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission the Work including as incorporated in Collective Works;
+
+</li>
+
+<li>
+to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission Derivative Works.
+</li>
+
+<li><p>For the avoidance of doubt, where the work is a musical composition:</p>
+
+<ol type="i">
+<li><strong>Performance Royalties Under Blanket Licenses</strong>. Licensor waives the exclusive right to collect, whether individually or via a performance rights society (e.g. ASCAP, BMI, SESAC), royalties for the public performance or public digital performance (e.g. webcast) of the Work.</li>
+
+<li><strong>Mechanical Rights and Statutory Royalties</strong>. Licensor waives the exclusive right to collect, whether individually or via a music rights agency or designated agent (e.g. Harry Fox Agency), royalties for any phonorecord You create from the Work ("cover version") and distribute, subject to the compulsory license created by 17 USC Section 115 of the US Copyright Act (or the equivalent in other jurisdictions).</li></ol></li>
+
+<li><strong>Webcasting Rights and Statutory Royalties</strong>. For the avoidance of doubt, where the Work is a sound recording, Licensor waives the exclusive right to collect, whether individually or via a performance-rights society (e.g. SoundExchange), royalties for the public digital performance (e.g. webcast) of the Work, subject to the compulsory license created by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions).</li>
+
+</ol>
+
+
+<p>The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. All rights not expressly granted by Licensor are hereby reserved.</p>
+
+<p><strong>4. Restrictions.</strong>The license granted in Section 3 above is expressly made subject to and limited by the following restrictions: </p>
+
+
+<ol type="a">
+<li>
+You may distribute, publicly display, publicly perform, or publicly digitally perform the Work only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy or phonorecord of the Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Work that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Work itself to be made subject to the terms of this License. If You create a Collective Work, upon notice from any Licensor You must, to the extent practicable, remove from the Collective Work any credit as required by clause 4(b), as requested. If You create a Derivative Work, upon notice from any Licensor You must, to the extent practicable, remove from the Derivative Work any credit as required by clause 4(b), as requested.
+</li>
+
+
+<li>
+If you distribute, publicly display, publicly perform, or publicly digitally perform the Work or any Derivative Works or Collective Works, You must keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or (ii) if the Original Author and/or Licensor designate another party or parties (e.g. a sponsor institute, publishing entity, journal) for attribution in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; the title of the Work if supplied; to the extent reasonably practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and in the case of a Derivative Work, a credit identifying the use of the Work in the Derivative Work (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). Such credit may be implemented in any reasonable manner; provided, however, that in the case of a Derivative Work or Collective Work, at a minimum such credit will appear where any other comparable authorship credit appears and in a manner at least as prominent as such other comparable authorship credit.
+</li>
+
+</ol>
+
+
+
+
+
+
+<p><strong>5. Representations, Warranties and Disclaimer</strong></p>
+
+<p>UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.</p>
+
+
+<p><strong>6. Limitation on Liability.</strong> EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. </p>
+
+<p><strong>7. Termination</strong> </p>
+
+<ol type="a">
+
+<li>
+This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Derivative Works or Collective Works from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License.
+</li>
+
+<li>
+Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above.
+</li>
+</ol>
+
+<p><strong>8. Miscellaneous</strong> </p>
+
+<ol type="a">
+
+<li>
+Each time You distribute or publicly digitally perform the Work or a Collective Work, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License.
+</li>
+
+<li>
+Each time You distribute or publicly digitally perform a Derivative Work, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License.
+</li>
+
+<li>
+If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
+</li>
+
+<li>
+No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent.
+</li>
+
+<li>
+This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You.
+</li>
+</ol>
+
+
+<!-- BREAKOUT FOR CC NOTICE. NOT A PART OF THE LICENSE -->
+<div class="fineprint" >
+
+
+<p>Creative Commons is not a party to this License, and makes no warranty whatsoever in connection with the Work. Creative Commons will not be liable to You or any party on any legal theory for any damages whatsoever, including without limitation any general, special, incidental or consequential damages arising in connection to this license. Notwithstanding the foregoing two (2) sentences, if Creative Commons has expressly identified itself as the Licensor hereunder, it shall have all rights and obligations of Licensor. </p>
+
+
+<p>Except for the limited purpose of indicating to the public that the Work is licensed under the CCPL, neither party will use the trademark "Creative Commons" or any related trademark or logo of Creative Commons without the prior written consent of Creative Commons. Any permitted use will be in compliance with Creative Commons' then-current trademark usage guidelines, as may be published on its website or otherwise made available upon request from time to time.</p>
+
+
+<p>Creative Commons may be contacted at <a href="http://creativecommons.org">http://creativecommons.org/</a>.</p>
+
+
+</div>
+<!-- END CC NOTICE -->
+
+
+</div>
+
+
+<div align="right" style="margin-bottom: 10px;"><a href="./" class="fulltext">« Back to Commons Deed</a></div>
+
+</div>
+</body></html>
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/build.properties b/tbr/org.eclipse.mylyn.reviews.ui/build.properties
new file mode 100644
index 00000000..fa2ca109
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/build.properties
@@ -0,0 +1,18 @@
+###############################################################################
+# Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+# All rights reserved. This program and the accompanying materials
+# are made available under the terms of the Eclipse Public License v1.0
+# which accompanies this distribution, and is available at
+# http://www.eclipse.org/legal/epl-v10.html
+#
+# Contributors:
+# Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+###############################################################################
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+ .,\
+ plugin.xml
+p2.gathering=true
+p2.compress=true
+jre.compilation.profile = J2SE-1.5
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/icons/addition.gif b/tbr/org.eclipse.mylyn.reviews.ui/icons/addition.gif
new file mode 100644
index 00000000..05a9f5a6
Binary files /dev/null and b/tbr/org.eclipse.mylyn.reviews.ui/icons/addition.gif differ
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/icons/maximize.png b/tbr/org.eclipse.mylyn.reviews.ui/icons/maximize.png
new file mode 100644
index 00000000..f300b7c6
Binary files /dev/null and b/tbr/org.eclipse.mylyn.reviews.ui/icons/maximize.png differ
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/icons/obstructed.gif b/tbr/org.eclipse.mylyn.reviews.ui/icons/obstructed.gif
new file mode 100644
index 00000000..3f43a29d
Binary files /dev/null and b/tbr/org.eclipse.mylyn.reviews.ui/icons/obstructed.gif differ
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/icons/review_failed.png b/tbr/org.eclipse.mylyn.reviews.ui/icons/review_failed.png
new file mode 100644
index 00000000..08f24936
Binary files /dev/null and b/tbr/org.eclipse.mylyn.reviews.ui/icons/review_failed.png differ
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/icons/review_none.png b/tbr/org.eclipse.mylyn.reviews.ui/icons/review_none.png
new file mode 100644
index 00000000..6fcec88c
Binary files /dev/null and b/tbr/org.eclipse.mylyn.reviews.ui/icons/review_none.png differ
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/icons/review_passed.png b/tbr/org.eclipse.mylyn.reviews.ui/icons/review_passed.png
new file mode 100644
index 00000000..89c8129a
Binary files /dev/null and b/tbr/org.eclipse.mylyn.reviews.ui/icons/review_passed.png differ
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/icons/review_warning.png b/tbr/org.eclipse.mylyn.reviews.ui/icons/review_warning.png
new file mode 100644
index 00000000..0473c8e8
Binary files /dev/null and b/tbr/org.eclipse.mylyn.reviews.ui/icons/review_warning.png differ
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/icons/reviews16.gif b/tbr/org.eclipse.mylyn.reviews.ui/icons/reviews16.gif
new file mode 100644
index 00000000..d054f8d5
Binary files /dev/null and b/tbr/org.eclipse.mylyn.reviews.ui/icons/reviews16.gif differ
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/icons/reviews24.gif b/tbr/org.eclipse.mylyn.reviews.ui/icons/reviews24.gif
new file mode 100644
index 00000000..819460a2
Binary files /dev/null and b/tbr/org.eclipse.mylyn.reviews.ui/icons/reviews24.gif differ
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/icons/reviews32.gif b/tbr/org.eclipse.mylyn.reviews.ui/icons/reviews32.gif
new file mode 100644
index 00000000..41307e3a
Binary files /dev/null and b/tbr/org.eclipse.mylyn.reviews.ui/icons/reviews32.gif differ
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/plugin.xml b/tbr/org.eclipse.mylyn.reviews.ui/plugin.xml
new file mode 100644
index 00000000..61482a16
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/plugin.xml
@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.4"?><!--
+ Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ All rights reserved. This program and the accompanying materials
+ are made available under the terms of the Eclipse Public License v1.0
+ which accompanies this distribution, and is available at
+ http://www.eclipse.org/legal/epl-v10.html
+
+ Contributors:
+ Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ -->
+
+<plugin>
+ <extension
+ point="org.eclipse.ui.editors">
+ <editor
+ class="org.eclipse.mylyn.reviews.ui.editors.ReviewEditor"
+ icon="icons/reviews32.gif"
+ id="org.eclipse.mylyn.reviews.ui.editors.ReviewEditor"
+ name="Mylyn Reviews Editor">
+ </editor>
+ </extension>
+ <extension
+ point="org.eclipse.ui.popupMenus">
+ <objectContribution
+ adaptable="false"
+ id="org.eclipse.mylyn.reviews.ui.objectContribution1"
+ objectClass="org.eclipse.mylyn.tasks.core.ITaskAttachment">
+ <action
+ class="org.eclipse.mylyn.reviews.ui.CreateReviewAction"
+ enablesFor="*"
+ id="org.eclipse.mylyn.reviews.ui.create_review_from_attachment"
+ label="Create Review from Attachment"
+ tooltip="Create a new review from this attachment">
+ </action>
+ </objectContribution>
+ </extension>
+ <extension
+ point="org.eclipse.mylyn.tasks.ui.taskEditorPageContribution">
+ <partAdvisor
+ class="org.eclipse.mylyn.reviews.ui.editors.ReviewTaskEditorPartAdvisor"
+ id="org.eclipse.mylyn.reviews.ui.reviewPart">
+ </partAdvisor>
+ <partAdvisor
+ class="org.eclipse.mylyn.reviews.ui.editors.ReviewSummaryPartConfigurer"
+ id="org.eclipse.mylyn.reviews.ui.reviewSummaryPart">
+ </partAdvisor>
+ </extension>
+
+</plugin>
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/CompareItem.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/CompareItem.java
new file mode 100644
index 00000000..9c50c24c
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/CompareItem.java
@@ -0,0 +1,58 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.ui;
+
+import java.io.InputStream;
+
+import org.eclipse.compare.IStreamContentAccessor;
+import org.eclipse.compare.ITypedElement;
+import org.eclipse.compare.patch.IFilePatchResult;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.swt.graphics.Image;
+
+// TODO move to core?
+/*
+ * @author Kilian Matt
+ */
+public class CompareItem implements IStreamContentAccessor, ITypedElement {
+ public enum Kind {
+ ORIGINAL, PATCHED
+ };
+
+ private IFilePatchResult result;
+ private Kind kind;
+ private String filename;
+
+ public CompareItem(IFilePatchResult result, Kind kind, String filename) {
+ this.result = result;
+ this.kind = kind;
+ this.filename = filename;
+ if(result == null || filename==null)
+ throw new NullPointerException();
+ }
+
+ public InputStream getContents() throws CoreException {
+ return kind == Kind.ORIGINAL ? result.getOriginalContents() : result
+ .getPatchedContents();
+ }
+
+ public Image getImage() {
+ return null;
+ }
+
+ public String getName() {
+ return filename;
+ }
+
+ public String getType() {
+ return ITypedElement.TEXT_TYPE;
+ }
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/CreateReviewAction.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/CreateReviewAction.java
new file mode 100644
index 00000000..242ceda5
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/CreateReviewAction.java
@@ -0,0 +1,98 @@
+package org.eclipse.mylyn.reviews.ui;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
+import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal;
+import org.eclipse.mylyn.reviews.core.ReviewConstants;
+import org.eclipse.mylyn.reviews.core.ReviewsUtil;
+import org.eclipse.mylyn.reviews.core.model.review.Review;
+import org.eclipse.mylyn.reviews.core.model.review.ReviewFactory;
+import org.eclipse.mylyn.reviews.core.model.review.ScopeItem;
+import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
+import org.eclipse.mylyn.tasks.core.ITask;
+import org.eclipse.mylyn.tasks.core.ITaskAttachment;
+import org.eclipse.mylyn.tasks.core.TaskRepository;
+import org.eclipse.mylyn.tasks.core.data.ITaskDataWorkingCopy;
+import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
+import org.eclipse.mylyn.tasks.core.data.TaskData;
+import org.eclipse.mylyn.tasks.core.data.TaskDataModel;
+import org.eclipse.mylyn.tasks.core.data.TaskMapper;
+import org.eclipse.mylyn.tasks.ui.TasksUiUtil;
+import org.eclipse.ui.IActionDelegate;
+
+public class CreateReviewAction extends Action implements IActionDelegate {
+
+ private ITaskAttachment attachment;
+
+ public void run(IAction action) {
+ if (attachment != null) {
+ try {
+ ITaskDataWorkingCopy taskDataState = TasksUiPlugin
+ .getTaskDataManager().getWorkingCopy(
+ attachment.getTask());
+ TaskDataModel model = new TaskDataModel(
+ attachment.getTaskRepository(), attachment.getTask(),
+ taskDataState);
+
+ performFinish(model, new PatchCreator(attachment.getTaskAttribute()).create());
+ } catch (CoreException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ }
+
+ public void selectionChanged(IAction action, ISelection selection) {
+ action.setEnabled(false);
+ if (selection instanceof IStructuredSelection) {
+ IStructuredSelection structuredSelection = (IStructuredSelection) selection;
+ if (structuredSelection.size() == 1) {
+ attachment = (ITaskAttachment) structuredSelection
+ .getFirstElement();
+ if (attachment.isPatch()) {
+ action.setEnabled(true);
+ }
+ }
+ }
+ }
+
+
+ public boolean performFinish(TaskDataModel model,ScopeItem scope) {
+ String reviewer=model.getTaskRepository().getUserName();
+ try {
+ Review review = ReviewFactory.eINSTANCE.createReview();
+ review.getScope().add(scope);
+ TaskRepository taskRepository=model.getTaskRepository();
+ ITask newTask = TasksUiUtil.createOutgoingNewTask(taskRepository.getConnectorKind(), taskRepository.getRepositoryUrl());
+
+ ReviewsUtil.markAsReview(newTask);
+ TaskMapper initializationData=new TaskMapper(model.getTaskData());
+ TaskData taskData = TasksUiInternal.createTaskData(taskRepository, initializationData, null,
+ new NullProgressMonitor());
+ AbstractRepositoryConnector connector=TasksUiPlugin.getConnector(taskRepository.getConnectorKind());
+ connector.getTaskDataHandler().initializeSubTaskData(
+ taskRepository, taskData, model.getTaskData(),
+ new NullProgressMonitor());
+
+
+ taskData.getRoot().getMappedAttribute(TaskAttribute.SUMMARY).setValue("Review of " + model.getTask().getSummary());
+ taskData.getRoot().getMappedAttribute(TaskAttribute.USER_ASSIGNED).setValue(reviewer);
+ taskData.getRoot().getMappedAttribute(TaskAttribute.DESCRIPTION).setValue("Review of " + model.getTask().getSummary() );
+
+ ReviewsUiPlugin.getDataManager().storeOutgoingTask(newTask, review);
+
+
+ TasksUiInternal.createAndOpenNewTask(newTask, taskData);
+ } catch (CoreException e1) {
+ throw new RuntimeException(e1);
+ }
+
+ return true;
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/CreateTask.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/CreateTask.java
new file mode 100644
index 00000000..fda72779
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/CreateTask.java
@@ -0,0 +1,179 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.ui;
+
+import java.io.ByteArrayOutputStream;
+import java.util.TreeSet;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.Job;
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.resource.ResourceSet;
+import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
+import org.eclipse.mylyn.internal.tasks.ui.editors.TaskMigrator;
+import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal;
+import org.eclipse.mylyn.reviews.core.ReviewConstants;
+import org.eclipse.mylyn.reviews.core.model.review.Review;
+import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
+import org.eclipse.mylyn.tasks.core.ITask;
+import org.eclipse.mylyn.tasks.core.TaskRepository;
+import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
+import org.eclipse.mylyn.tasks.core.data.TaskAttributeMapper;
+import org.eclipse.mylyn.tasks.core.data.TaskData;
+import org.eclipse.mylyn.tasks.core.data.TaskDataModel;
+import org.eclipse.mylyn.tasks.core.sync.SubmitJob;
+import org.eclipse.mylyn.tasks.ui.TasksUi;
+import org.eclipse.mylyn.tasks.ui.TasksUiUtil;
+
+/*
+ * @author Kilian Matt
+ */
+public class CreateTask extends Job {
+
+ private TaskDataModel model;
+ private Review review;
+ private TaskRepository taskRepository;
+ private AbstractRepositoryConnector connector;
+ private String reviewer;
+
+ public CreateTask(TaskDataModel model, Review review, String reviewer) {
+ super(Messages.CreateTask_Title);
+ this.model = model;
+ this.review = review;
+
+ this.taskRepository = model.getTaskRepository();
+
+ this.connector = TasksUi.getRepositoryConnector(taskRepository
+ .getConnectorKind());
+ this.reviewer = reviewer;
+ }
+
+ @Override
+ protected IStatus run(final IProgressMonitor monitor) {
+ try {
+
+ final ITask newLocalTask = TasksUiUtil.createOutgoingNewTask(
+ taskRepository.getConnectorKind(),
+ taskRepository.getRepositoryUrl());
+
+ TaskAttributeMapper mapper = connector.getTaskDataHandler()
+ .getAttributeMapper(taskRepository);
+
+ final TaskData data = new TaskData(mapper,
+ taskRepository.getConnectorKind(),
+ taskRepository.getRepositoryUrl(), ""); //$NON-NLS-1$
+
+ connector.getTaskDataHandler().initializeSubTaskData(
+ taskRepository, data, model.getTaskData(),
+ new NullProgressMonitor());
+
+ if (reviewer != null && reviewer.isEmpty()) {
+ createAttribute(data,TaskAttribute.USER_ASSIGNED,reviewer);
+ }
+
+ createAttribute(data,TaskAttribute.SUMMARY,
+ "Review of " + model.getTask().getTaskKey() + " " + model.getTask().getSummary()); //$NON-NLS-1$ //$NON-NLS-2$
+
+ createAttribute(data,TaskAttribute.COMPONENT,
+ model.getTaskData()
+ .getRoot()
+ .getMappedAttribute(TaskAttribute.COMPONENT)
+ .getValue());
+ createAttribute(data,TaskAttribute.STATUS, "NEW"); //$NON-NLS-1$
+ createAttribute(data,TaskAttribute.VERSION,
+ model.getTaskData().getRoot()
+ .getMappedAttribute(TaskAttribute.VERSION)
+ .getValue());
+ createAttribute(data,TaskAttribute.PRODUCT,
+ model.getTaskData().getRoot()
+ .getMappedAttribute(TaskAttribute.PRODUCT)
+ .getValue());
+
+ final byte[] attachmentBytes = createAttachment(model, review);
+
+ final SubmitJob submitJob = TasksUiInternal.getJobFactory()
+ .createSubmitTaskJob(connector, taskRepository,
+ newLocalTask, data, new TreeSet<TaskAttribute>());
+ submitJob.schedule();
+ submitJob.join();
+
+ if (submitJob.getStatus() == null) {
+ ITask newRepoTask = submitJob.getTask();
+
+ TaskMigrator migrator = new TaskMigrator(newLocalTask);
+ migrator.setDelete(true);
+ migrator.execute(newRepoTask);
+
+ TaskAttribute attachmentAttribute = data.getAttributeMapper()
+ .createTaskAttachment(data);
+ try {
+ ReviewCommentTaskAttachmentSource attachment = new ReviewCommentTaskAttachmentSource(
+ attachmentBytes);
+
+ monitor.subTask(Messages.CreateTask_UploadingAttachment);
+ connector.getTaskAttachmentHandler().postContent(
+ taskRepository, newRepoTask, attachment,
+ "review result", //$NON-NLS-1$
+ attachmentAttribute, monitor);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+
+ return new ReviewStatus(Messages.CreateTask_Success,
+ newRepoTask);
+ }
+ return new Status(IStatus.WARNING, ReviewsUiPlugin.PLUGIN_ID, "");
+ } catch (Exception e) {
+ return new Status(IStatus.ERROR, ReviewsUiPlugin.PLUGIN_ID,
+ e.getMessage());
+ }
+ }
+ private TaskAttribute createAttribute( TaskData taskData, String mappedAttributeName, String value) {
+ TaskAttribute attribute = taskData.getRoot().createMappedAttribute(mappedAttributeName);
+ attribute.setValue(value);
+ return attribute;
+ }
+
+ private byte[] createAttachment(TaskDataModel model, Review review) {
+ try {
+ ResourceSet resourceSet = new ResourceSetImpl();
+
+ Resource resource = resourceSet.createResource(URI
+ .createFileURI("")); //$NON-NLS-1$
+
+ resource.getContents().add(review);
+ resource.getContents().add(review.getScope().get(0));
+ if(review.getResult()!=null)
+ resource.getContents().add(review.getResult());
+ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+ ZipOutputStream outputStream = new ZipOutputStream(
+ byteArrayOutputStream);
+ outputStream.putNextEntry(new ZipEntry(
+ ReviewConstants.REVIEW_DATA_FILE));
+ resource.save(outputStream, null);
+ outputStream.closeEntry();
+ outputStream.close();
+ return byteArrayOutputStream.toByteArray();
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new RuntimeException(e);
+ }
+
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/IPatchCreator.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/IPatchCreator.java
new file mode 100644
index 00000000..390692ed
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/IPatchCreator.java
@@ -0,0 +1,31 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.ui;
+
+import java.util.Date;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.mylyn.reviews.core.model.review.Patch;
+
+/*
+ * @author Kilian Matt
+ */
+public interface IPatchCreator {
+
+ public abstract Patch create() throws CoreException;
+
+ public abstract String getFileName();
+
+ public abstract String getAuthor();
+
+ public abstract Date getCreationDate();
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/Images.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/Images.java
new file mode 100644
index 00000000..f6cae175
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/Images.java
@@ -0,0 +1,92 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Christoph Mayerhofer (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.ui;
+
+import java.net.URL;
+
+import org.eclipse.core.runtime.FileLocator;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.resource.ImageRegistry;
+import org.eclipse.swt.graphics.Image;
+
+/**
+ * Image helper class which contains all application images.
+ *
+ * @author Christoph Mayerhofer
+ */
+public class Images {
+
+ protected final static ImageRegistry PLUGIN_REGISTRY = ReviewsUiPlugin
+ .getDefault().getImageRegistry();
+
+ // icons path
+ public final static String ICONS_PATH = "icons/"; //$NON-NLS-1$
+
+ public static final ImageDescriptor SMALL_ICON = create(ICONS_PATH,
+ "reviews16.gif"); //$NON-NLS-1$
+
+ public static final ImageDescriptor ICON = create(ICONS_PATH,
+ "reviews24.gif"); //$NON-NLS-1$
+ public static final ImageDescriptor BIG_ICON = create(ICONS_PATH,
+ "reviews32.gif"); //$NON-NLS-1$
+
+ public static final ImageDescriptor REVIEW_RESULT_FAILED = create(
+ ICONS_PATH, "review_failed.png"); //$NON-NLS-1$
+ public static final ImageDescriptor REVIEW_RESULT_WARNING = create(
+ ICONS_PATH, "review_warning.png"); //$NON-NLS-1$
+ public static final ImageDescriptor REVIEW_RESULT_PASSED = create(
+ ICONS_PATH, "review_passed.png"); //$NON-NLS-1$
+ public static final ImageDescriptor REVIEW_RESULT_NONE = create(ICONS_PATH,
+ "review_none.png"); //$NON-NLS-1$
+ public static final ImageDescriptor OVERLAY_ADDITION = create(ICONS_PATH,
+ "addition.gif"); //$NON-NLS-1$
+ public static final ImageDescriptor OVERLAY_OBSTRUCTED = create(ICONS_PATH,
+ "obstructed.gif"); //$NON-NLS-1$
+ public static final ImageDescriptor MAXIMIZE = create(ICONS_PATH,
+ "maximize.png"); //$NON-NLS-1$
+
+ protected static ImageDescriptor create(String prefix, String name) {
+ return ImageDescriptor.createFromURL(makeIconURL(prefix, name));
+ }
+
+ /**
+ * Get the image for the specified key from the registry.
+ *
+ * @param key
+ * The key for the image.
+ * @return The image, or <code>null</code> if none.
+ */
+ public static Image get(String key) {
+ return PLUGIN_REGISTRY.get(key);
+ }
+
+ private static URL makeIconURL(String prefix, String name) {
+ String path = "$nl$/" + prefix + name; //$NON-NLS-1$
+ return FileLocator.find(ReviewsUiPlugin.getDefault().getBundle(),
+ new Path(path), null);
+ }
+
+ /**
+ * Puts the image with the specified key to the image registry.
+ *
+ * @param key
+ * The key for the image.
+ * @param desc
+ * The ImageDescriptor for which the image is created.
+ * @return The image which has been added to the registry.
+ */
+ public static Image manage(String key, ImageDescriptor desc) {
+ Image image = desc.createImage();
+ PLUGIN_REGISTRY.put(key, image);
+ return image;
+ }
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/Messages.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/Messages.java
new file mode 100644
index 00000000..56a075c8
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/Messages.java
@@ -0,0 +1,33 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.ui;
+
+import org.eclipse.osgi.util.NLS;
+
+/*
+ * @author Kilian Matt
+ */
+public class Messages extends NLS {
+ private static final String BUNDLE_NAME = "org.eclipse.mylyn.reviews.ui.messages"; //$NON-NLS-1$
+ public static String CreateTask_Success;
+ public static String CreateTask_Title;
+ public static String CreateTask_UploadingAttachment;
+ public static String PatchCreator_ReaderCreationFailed;
+ public static String ReviewCommentTaskAttachmentSource_Description;
+ public static String ReviewTaskEditorPageFactory_PageTitle;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
+
+ private Messages() {
+ }
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/PatchCreator.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/PatchCreator.java
new file mode 100644
index 00000000..5fc79751
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/PatchCreator.java
@@ -0,0 +1,135 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.ui;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.util.Date;
+import java.util.logging.Logger;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.mylyn.internal.tasks.core.RepositoryModel;
+import org.eclipse.mylyn.reviews.core.model.review.Patch;
+import org.eclipse.mylyn.reviews.core.model.review.ReviewFactory;
+import org.eclipse.mylyn.tasks.core.ITaskAttachment;
+import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
+import org.eclipse.mylyn.tasks.ui.TasksUi;
+
+/**
+ * @author Kilian Matt
+ */
+public class PatchCreator implements IPatchCreator {
+
+ private static final Logger log = Logger.getAnonymousLogger();
+ private TaskAttribute attribute;
+
+ public PatchCreator(TaskAttribute attribute) {
+ this.attribute = attribute;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.mylyn.reviews.ui.IPatchCreator#create()
+ */
+ public Patch create() throws CoreException {
+ try {
+ ITaskAttachment taskAttachment = getTaskAttachment();
+ URL url = new URL(attribute.getMappedAttribute(
+ TaskAttribute.ATTACHMENT_URL).getValue());
+ Patch patch = ReviewFactory.eINSTANCE.createPatch();
+ patch.setAuthor(taskAttachment.getAuthor().getName());
+ patch.setCreationDate(taskAttachment.getCreationDate());
+ patch.setContents(readContents(url));
+ patch.setFileName(taskAttachment.getFileName());
+ return patch;
+ } catch (Exception e) {
+ e.printStackTrace();
+ log.warning(e.toString());
+ throw new CoreException(new Status(IStatus.ERROR,
+ ReviewsUiPlugin.PLUGIN_ID,
+ Messages.PatchCreator_ReaderCreationFailed, e));
+ }
+ }
+
+ private ITaskAttachment taskAttachment;
+
+ private ITaskAttachment getTaskAttachment() {
+ if (taskAttachment == null) {
+ // TODO move RepositoryModel.createTaskAttachment to interface?
+ taskAttachment = ((RepositoryModel) TasksUi.getRepositoryModel())
+ .createTaskAttachment(attribute);
+ // new TaskAttachment(repository, task, attribute);
+ // attributeMapper.updateTaskAttachment(taskAttachment, attribute);
+ }
+ return taskAttachment;
+ }
+
+ private String readContents(URL url) throws IOException {
+ InputStream stream = null;
+ try {
+ stream = url.openStream();
+ InputStreamReader reader = new InputStreamReader(stream);
+ char[] buffer = new char[256];
+ int readChars = 0;
+ StringBuilder sb = new StringBuilder();
+ while ((readChars = reader.read(buffer)) > 0) {
+ sb.append(buffer, 0, readChars);
+ }
+ return sb.toString();
+ } finally {
+ if (stream != null)
+ try {
+ stream.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ }
+
+ @Override
+ public String toString() {
+ return attribute.getMappedAttribute(TaskAttribute.ATTACHMENT_FILENAME)
+ .getValue();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.mylyn.reviews.ui.IPatchCreator#getFileName()
+ */
+ public String getFileName() {
+ return getTaskAttachment().getFileName();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.mylyn.reviews.ui.IPatchCreator#getAuthor()
+ */
+ public String getAuthor() {
+ return getTaskAttachment().getAuthor().getName();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.mylyn.reviews.ui.IPatchCreator#getCreationDate()
+ */
+ public Date getCreationDate() {
+ return getTaskAttachment().getCreationDate();
+ }
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewCommentTaskAttachmentSource.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewCommentTaskAttachmentSource.java
new file mode 100644
index 00000000..d3fdbe0f
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewCommentTaskAttachmentSource.java
@@ -0,0 +1,64 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.ui;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.mylyn.reviews.core.ReviewConstants;
+import org.eclipse.mylyn.tasks.core.data.AbstractTaskAttachmentSource;
+
+/*
+ * @author Kilian Matt
+ */
+public class ReviewCommentTaskAttachmentSource extends
+ AbstractTaskAttachmentSource {
+
+ private byte[] source;
+
+ public ReviewCommentTaskAttachmentSource(byte[] source) {
+ this.source = source;
+ }
+
+ @Override
+ public InputStream createInputStream(IProgressMonitor monitor)
+ throws CoreException {
+ return new ByteArrayInputStream(source);
+ }
+
+ @Override
+ public String getContentType() {
+ return "application/octet-stream"; //$NON-NLS-1$
+ }
+
+ @Override
+ public String getDescription() {
+ return Messages.ReviewCommentTaskAttachmentSource_Description;
+ }
+
+ @Override
+ public long getLength() {
+ return source.length;
+ }
+
+ @Override
+ public String getName() {
+ return ReviewConstants.REVIEW_DATA_CONTAINER;
+ }
+
+ @Override
+ public boolean isLocal() {
+ return true;
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewDiffModel.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewDiffModel.java
new file mode 100644
index 00000000..7626eeb5
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewDiffModel.java
@@ -0,0 +1,136 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.ui;
+
+import java.io.CharArrayReader;
+import java.io.Reader;
+
+import org.eclipse.compare.CompareConfiguration;
+import org.eclipse.compare.patch.IFilePatch2;
+import org.eclipse.compare.patch.IFilePatchResult;
+import org.eclipse.compare.patch.IHunk;
+import org.eclipse.compare.patch.PatchConfiguration;
+import org.eclipse.compare.patch.ReaderCreator;
+import org.eclipse.compare.structuremergeviewer.DiffNode;
+import org.eclipse.compare.structuremergeviewer.Differencer;
+import org.eclipse.compare.structuremergeviewer.ICompareInput;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.mylyn.reviews.core.ITargetPathStrategy;
+import org.eclipse.mylyn.reviews.core.ReviewsUtil;
+
+/**
+ * @author Kilian Matt
+ */
+public class ReviewDiffModel {
+
+ private IFilePatch2 patch;
+ private PatchConfiguration configuration;
+ private ICompareInput compareInput;
+ private IFilePatchResult compareEditorInput = null;
+
+ public ReviewDiffModel(IFilePatch2 currentPatch,
+ PatchConfiguration configuration) {
+ patch = currentPatch;
+ this.configuration = configuration;
+ }
+
+ @Override
+ public String toString() {
+ return getFileName();
+ }
+
+ public String getFileName() {
+ String string = patch.getTargetPath(configuration).lastSegment();
+ return string;
+ }
+
+ public ICompareInput getCompareInput() {
+ if (compareInput == null) {
+ IFilePatchResult patchResult = getCompareEditorInput();
+ ICompareInput ci = new DiffNode(Differencer.CHANGE, null,
+ new CompareItem(patchResult, CompareItem.Kind.ORIGINAL,
+ toString()), new CompareItem(patchResult,
+ CompareItem.Kind.PATCHED, toString()));
+ compareInput = ci;
+ }
+ return compareInput;
+
+ }
+
+ public IFilePatchResult getCompareEditorInput() {
+ if (compareEditorInput == null) {
+ IPath targetPath = patch.getTargetPath(configuration);
+
+ for (ITargetPathStrategy strategy : ReviewsUtil
+ .getPathFindingStrategies()) {
+
+ if (strategy.matches(targetPath)) {
+ CompareConfiguration config = new CompareConfiguration();
+ config.setRightEditable(false);
+ config.setLeftEditable(false);
+
+ ReaderCreator rc = strategy.get(targetPath);
+ NullProgressMonitor monitor = new NullProgressMonitor();
+ IFilePatchResult result = patch.apply(rc, configuration,
+ monitor);
+
+ return compareEditorInput = result;
+ }
+ }
+ if (patchAddsFile()) {
+ ReaderCreator rc = new ReaderCreator() {
+
+ @Override
+ public Reader createReader() throws CoreException {
+ return new CharArrayReader(new char[0]);
+ }
+ };
+ NullProgressMonitor monitor = new NullProgressMonitor();
+ compareEditorInput = patch.apply(rc, configuration, monitor);
+ }
+ }
+ return compareEditorInput;
+ }
+
+ private boolean patchAddsFile() {
+ for (IHunk hunk : patch.getHunks()) {
+ for (String line : hunk.getUnifiedLines()) {
+ if (!line.startsWith("+")) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ public boolean sourceFileExists() {
+ IPath targetPath = patch.getTargetPath(configuration);
+
+ for (ITargetPathStrategy strategy : ReviewsUtil
+ .getPathFindingStrategies()) {
+
+ if (strategy.matches(targetPath)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ public boolean canReview() {
+ return sourceFileExists() || patchAddsFile();
+ }
+
+ public boolean isNewFile() {
+ return patchAddsFile();
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewStatus.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewStatus.java
new file mode 100644
index 00000000..e2f5c433
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewStatus.java
@@ -0,0 +1,19 @@
+package org.eclipse.mylyn.reviews.ui;
+
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.mylyn.tasks.core.ITask;
+
+public class ReviewStatus extends Status {
+ private ITask task;
+
+ public ReviewStatus(String message, ITask task) {
+ super(IStatus.OK, ReviewsUiPlugin.PLUGIN_ID, message);
+ this.task = task;
+ }
+
+ public ITask getTask() {
+ return task;
+ }
+
+}
\ No newline at end of file
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewsUiPlugin.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewsUiPlugin.java
new file mode 100644
index 00000000..64343541
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewsUiPlugin.java
@@ -0,0 +1,92 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.ui;
+
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.mylyn.internal.tasks.ui.ITasksUiPreferenceConstants;
+import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
+import org.eclipse.mylyn.reviews.core.ReviewDataManager;
+import org.eclipse.mylyn.reviews.core.ReviewDataStore;
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
+/**
+ * The activator class controls the plug-in life cycle
+ *
+ * @author Kilian Matt
+ */
+public class ReviewsUiPlugin extends AbstractUIPlugin {
+
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.mylyn.reviews.ui"; //$NON-NLS-1$
+
+ // The shared instance
+ private static ReviewsUiPlugin plugin;
+
+ private static ReviewDataManager reviewDataManager;
+
+ /**
+ * The constructor
+ */
+ public ReviewsUiPlugin() {
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
+ * )
+ */
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+
+ String DIRECTORY_METADATA = ".metadata"; //$NON-NLS-1$
+
+ String NAME_DATA_DIR = ".mylyn"; //$NON-NLS-1$
+ String storeDir = ResourcesPlugin.getWorkspace().getRoot()
+ .getLocation().toString()
+ + '/' + DIRECTORY_METADATA + '/' + NAME_DATA_DIR;
+ ReviewDataStore store = new ReviewDataStore(storeDir);
+ reviewDataManager = new ReviewDataManager(store,
+ TasksUiPlugin.getTaskDataManager(),
+ TasksUiPlugin.getRepositoryModel());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
+ * )
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static ReviewsUiPlugin getDefault() {
+ return plugin;
+ }
+
+ public static ReviewDataManager getDataManager() {
+ return reviewDataManager;
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/Messages.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/Messages.java
new file mode 100644
index 00000000..288a7ee0
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/Messages.java
@@ -0,0 +1,61 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.ui.editors;
+
+import org.eclipse.osgi.util.NLS;
+
+/*
+ * @author Kilian Matt
+ */
+public class Messages extends NLS {
+ private static final String BUNDLE_NAME = "org.eclipse.mylyn.reviews.ui.editors.messages"; //$NON-NLS-1$
+ public static String CreateReviewTaskEditorPageFactory_Reviews;
+ public static String CreateReviewTaskEditorPart_Patches;
+ public static String CreateReviewTaskEditorPart_Create_Review;
+ public static String CreateReviewTaskEditorPart_Header_Author;
+ public static String CreateReviewTaskEditorPart_Header_Date;
+ public static String CreateReviewTaskEditorPart_Header_Filename;
+ public static String EditorSupport_Original;
+ public static String EditorSupport_Patched;
+ public static String NewReviewTaskEditorInput_ReviewPrefix;
+ public static String NewReviewTaskEditorInput_Tooltip;
+ public static String ReviewEditor_Assigned_to;
+ public static String ReviewEditor_Comment;
+ public static String ReviewEditor_Create_delegated_Review;
+ public static String ReviewEditor_Diff;
+ public static String ReviewEditor_Files;
+ public static String ReviewEditor_New_Patch_based_Review;
+ public static String ReviewEditor_Rating;
+ public static String ReviewEditor_Review;
+ public static String ReviewEditor_Submit;
+ public static String ReviewSummaryTaskEditorPart_Header_Author;
+ public static String ReviewSummaryTaskEditorPart_Header_Comment;
+ public static String ReviewSummaryTaskEditorPart_Header_Scope;
+ public static String ReviewSummaryTaskEditorPart_Header_Result;
+ public static String ReviewSummaryTaskEditorPart_Header_Reviewer;
+ public static String ReviewSummaryTaskEditorPart_Header_ReviewId;
+ public static String ReviewSummaryTaskEditorPart_Partname;
+ public static String ReviewTaskEditorInput_New_Review;
+ public static String TaskEditorPatchReviewPart_Diff;
+ public static String TaskEditorPatchReviewPart_Files;
+ public static String TaskEditorPatchReviewPart_Name;
+ public static String TaskEditorPatchReviewPart_Patches;
+ public static String TaskEditorPatchReviewPart_Rating;
+ public static String TaskEditorPatchReviewPart_Review;
+ public static String UpdateReviewTask_Title;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
+
+ private Messages() {
+ }
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/NewReviewTaskEditorInput.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/NewReviewTaskEditorInput.java
new file mode 100644
index 00000000..9356bf7c
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/NewReviewTaskEditorInput.java
@@ -0,0 +1,39 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.ui.editors;
+
+import org.eclipse.mylyn.reviews.core.model.review.Patch;
+import org.eclipse.mylyn.reviews.core.model.review.ReviewFactory;
+import org.eclipse.mylyn.tasks.core.data.TaskDataModel;
+
+/*
+ * @author Kilian Matt
+ */
+public class NewReviewTaskEditorInput extends ReviewTaskEditorInput {
+
+ private TaskDataModel model;
+
+ public NewReviewTaskEditorInput(TaskDataModel model, Patch patch) {
+ super(ReviewFactory.eINSTANCE.createReview());
+ this.model = model;
+ getReview().getScope().add(patch);
+ }
+
+ @Override
+ public String getName() {
+ return Messages.NewReviewTaskEditorInput_ReviewPrefix + model.getTask().getTaskKey() + " " //$NON-NLS-2$
+ + model.getTask().toString();
+ }
+
+ public TaskDataModel getModel() {
+ return model;
+ }
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewSubmitHandler.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewSubmitHandler.java
new file mode 100644
index 00000000..f037b64a
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewSubmitHandler.java
@@ -0,0 +1,20 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.ui.editors;
+
+/*
+ * @author Kilian Matt
+ */
+public interface ReviewSubmitHandler {
+
+ void doSubmit(ReviewTaskEditorInput editorInput);
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewSummaryPartConfigurer.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewSummaryPartConfigurer.java
new file mode 100644
index 00000000..bd1127c1
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewSummaryPartConfigurer.java
@@ -0,0 +1,78 @@
+package org.eclipse.mylyn.reviews.ui.editors;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.eclipse.mylyn.internal.tasks.core.RepositoryModel;
+import org.eclipse.mylyn.tasks.core.IRepositoryModel;
+import org.eclipse.mylyn.tasks.core.ITask;
+import org.eclipse.mylyn.tasks.core.ITaskAttachment;
+import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
+import org.eclipse.mylyn.tasks.core.data.TaskData;
+import org.eclipse.mylyn.tasks.ui.TasksUi;
+import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart;
+import org.eclipse.mylyn.tasks.ui.editors.ITaskEditorPartDescriptorAdvisor;
+import org.eclipse.mylyn.tasks.ui.editors.TaskEditorPartDescriptor;
+
+public class ReviewSummaryPartConfigurer implements
+ ITaskEditorPartDescriptorAdvisor {
+
+ public boolean canCustomize(ITask task) {
+ try {
+
+ // TODO change to detecting review sub tasks!
+
+ TaskData taskData = TasksUi.getTaskDataManager().getTaskData(task);
+ IRepositoryModel repositoryModel = TasksUi.getRepositoryModel();
+ if (taskData != null) {
+ List<TaskAttribute> attributesByType = taskData
+ .getAttributeMapper().getAttributesByType(taskData,
+ TaskAttribute.TYPE_ATTACHMENT);
+ for (TaskAttribute attribute : attributesByType) {
+ // TODO move RepositoryModel.createTaskAttachment to
+ // interface?
+ ITaskAttachment taskAttachment = ((RepositoryModel) repositoryModel)
+ .createTaskAttachment(attribute);
+ if (taskAttachment.isPatch())
+ return true;
+
+ }
+ }
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ return false;
+ }
+
+ public Set<String> getBlockingIds(ITask task) {
+ return Collections.emptySet();
+ }
+
+ public Set<String> getBlockingPaths(ITask task) {
+ return Collections.emptySet();
+ }
+
+ public Set<TaskEditorPartDescriptor> getPartContributions(ITask task) {
+ Set<TaskEditorPartDescriptor> descriptors = new HashSet<TaskEditorPartDescriptor>();
+ descriptors.add(new TaskEditorPartDescriptor(
+ ReviewSummaryTaskEditorPart.ID_PART_REVIEWSUMMARY) {
+
+ @Override
+ public AbstractTaskEditorPart createPart() {
+ return new ReviewSummaryTaskEditorPart();
+ }
+ });
+ return descriptors;
+ }
+
+ public void afterSubmit(ITask task) {
+ }
+
+ public void prepareSubmit(ITask task) {
+ }
+
+ public void taskMigration(ITask oldTask, ITask newTask) {
+ }
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewSummaryTaskEditorPart.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewSummaryTaskEditorPart.java
new file mode 100644
index 00000000..48900dd4
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewSummaryTaskEditorPart.java
@@ -0,0 +1,220 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.ui.editors;
+
+import java.util.List;
+
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.jface.viewers.DoubleClickEvent;
+import org.eclipse.jface.viewers.IDoubleClickListener;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.TableViewerColumn;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.mylyn.reviews.core.ReviewSubTask;
+import org.eclipse.mylyn.reviews.core.ReviewsUtil;
+import org.eclipse.mylyn.reviews.core.model.review.Rating;
+import org.eclipse.mylyn.reviews.ui.Images;
+import org.eclipse.mylyn.tasks.core.ITask;
+import org.eclipse.mylyn.tasks.core.ITaskContainer;
+import org.eclipse.mylyn.tasks.ui.TasksUi;
+import org.eclipse.mylyn.tasks.ui.TasksUiUtil;
+import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.layout.FillLayout;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.ui.forms.widgets.ExpandableComposite;
+import org.eclipse.ui.forms.widgets.FormToolkit;
+import org.eclipse.ui.forms.widgets.Section;
+
+/*
+ * @author Kilian Matt
+ */
+public class ReviewSummaryTaskEditorPart extends AbstractTaskEditorPart {
+
+ public static final String ID_PART_REVIEWSUMMARY = "org.eclipse.mylyn.reviews.ui.editors.parts.reviewsummary"; //$NON-NLS-1$
+ private Section summarySection;
+
+ public ReviewSummaryTaskEditorPart() {
+ setPartName(Messages.ReviewSummaryTaskEditorPart_Partname);
+ }
+
+ @Override
+ public void createControl(final Composite parent, FormToolkit toolkit) {
+ summarySection = createSection(parent, toolkit,
+ ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE
+ | ExpandableComposite.EXPANDED);
+ summarySection.setLayout(new FillLayout(SWT.HORIZONTAL));
+ summarySection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
+ true));
+ // summarySection.setText(Messages.ReviewSummaryTaskEditorPart_Partname);
+ Composite reviewResultsComposite = toolkit
+ .createComposite(summarySection);
+ toolkit.paintBordersFor(reviewResultsComposite);
+ reviewResultsComposite.setLayout(new GridLayout(1, false));
+
+ TableViewer reviewResults = createResultsTableViewer(
+ reviewResultsComposite, toolkit);
+ reviewResults.getControl().setLayoutData(
+ new GridData(SWT.FILL, SWT.FILL, true, true));
+
+ summarySection.setClient(reviewResultsComposite);
+ }
+
+ private TableViewerColumn createColumn(TableViewer parent,
+ String columnTitle) {
+ TableViewerColumn column = new TableViewerColumn(parent, SWT.LEFT);
+ column.getColumn().setText(columnTitle);
+ column.getColumn().setWidth(100);
+ column.getColumn().setResizable(true);
+ return column;
+ }
+
+ private TableViewer createResultsTableViewer(
+ Composite reviewResultsComposite, FormToolkit toolkit) {
+ Table table = toolkit.createTable(reviewResultsComposite, SWT.SINGLE
+ | SWT.FULL_SELECTION);
+ table.setHeaderVisible(true);
+ table.setLinesVisible(true);
+ table.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TREE_BORDER);
+
+ TableViewer reviewResults = new TableViewer(table);
+ createColumn(reviewResults,
+ Messages.ReviewSummaryTaskEditorPart_Header_ReviewId);
+ createColumn(reviewResults,
+ Messages.ReviewSummaryTaskEditorPart_Header_Scope);
+ createColumn(reviewResults,
+ Messages.ReviewSummaryTaskEditorPart_Header_Author);
+ createColumn(reviewResults,
+ Messages.ReviewSummaryTaskEditorPart_Header_Reviewer);
+ createColumn(reviewResults,
+ Messages.ReviewSummaryTaskEditorPart_Header_Result);
+
+ createColumn(reviewResults,
+ Messages.ReviewSummaryTaskEditorPart_Header_Comment);
+
+ reviewResults.setContentProvider(new IStructuredContentProvider() {
+
+ public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
+ }
+
+ public void dispose() {
+ }
+
+ public Object[] getElements(Object inputElement) {
+ if (inputElement instanceof ITaskContainer) {
+ ITaskContainer taskContainer = (ITaskContainer) inputElement;
+ List<ReviewSubTask> reviewSubTasks = ReviewsUtil
+ .getReviewSubTasksFor(taskContainer,
+ TasksUi.getTaskDataManager(),
+ TasksUi.getRepositoryModel(),
+ new NullProgressMonitor());
+ int passedCount = 0;
+ int warningCount = 0;
+ int failedCount = 0;
+ int noResultCount = 0;
+ for (ReviewSubTask subtask : reviewSubTasks) {
+ switch (subtask.getResult()) {
+ case PASSED:
+ passedCount++;
+ break;
+ case WARNING:
+ warningCount++;
+ break;
+ case FAILED:
+ failedCount++;
+ break;
+ case NONE:
+ noResultCount++;
+ break;
+
+ }
+ }
+
+ summarySection.setText(String
+ .format("Review Summary (PASSED: %s / WARNING: %s / FAILED: %s / ?: %s)",
+ passedCount, warningCount, failedCount,
+ noResultCount));
+ return reviewSubTasks
+ .toArray(new ReviewSubTask[reviewSubTasks.size()]);
+ }
+ return null;
+ }
+ });
+
+ reviewResults.setLabelProvider(new TableLabelProvider() {
+ private static final int COLUMN_ID = 0;
+ private static final int COLUMN_PATCHFILE = 1;
+ private static final int COLUMN_AUTHOR = 2;
+ private static final int COLUMN_REVIEWER = 3;
+ private static final int COLUMN_RESULT = 4;
+ private static final int COLUMN_COMMENT = 5;
+
+ public Image getColumnImage(Object element, int columnIndex) {
+ if (columnIndex == COLUMN_RESULT) {
+ ReviewSubTask subtask = (ReviewSubTask) element;
+ switch (subtask.getResult()) {
+ case FAILED:
+ return Images.REVIEW_RESULT_FAILED.createImage();
+ case WARNING:
+ return Images.REVIEW_RESULT_WARNING.createImage();
+ case PASSED:
+ return Images.REVIEW_RESULT_PASSED.createImage();
+ case NONE:
+ return Images.REVIEW_RESULT_NONE.createImage();
+
+ }
+ }
+ return null;
+ }
+
+ public String getColumnText(Object element, int columnIndex) {
+
+ ReviewSubTask subtask = (ReviewSubTask) element;
+ switch (columnIndex) {
+ case COLUMN_ID:
+ return subtask.getTask().getTaskId();
+ case COLUMN_PATCHFILE:
+ return subtask.getPatchDescription();
+ case COLUMN_AUTHOR:
+ return subtask.getAuthor();
+ case COLUMN_REVIEWER:
+ return subtask.getReviewer();
+ case COLUMN_RESULT:
+ return subtask.getResult().getName();
+ case COLUMN_COMMENT:
+ return subtask.getComment();
+ default:
+ return null;
+ }
+ }
+
+ });
+ reviewResults.setInput(getModel().getTask());
+ reviewResults.addDoubleClickListener(new IDoubleClickListener() {
+
+ public void doubleClick(DoubleClickEvent event) {
+ if (!event.getSelection().isEmpty()) {
+ ITask task = ((ReviewSubTask) ((IStructuredSelection) event
+ .getSelection()).getFirstElement()).getTask();
+ TasksUiUtil.openTask(task);
+ }
+ }
+ });
+ return reviewResults;
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorInput.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorInput.java
new file mode 100644
index 00000000..c9020428
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorInput.java
@@ -0,0 +1,100 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.ui.editors;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.compare.patch.IFilePatch2;
+import org.eclipse.compare.patch.PatchConfiguration;
+import org.eclipse.compare.patch.PatchParser;
+import org.eclipse.compare.patch.ReaderCreator;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.mylyn.reviews.core.model.review.Patch;
+import org.eclipse.mylyn.reviews.core.model.review.Review;
+import org.eclipse.mylyn.reviews.ui.Images;
+import org.eclipse.mylyn.reviews.ui.ReviewDiffModel;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IPersistableElement;
+
+/*
+ * @author Kilian Matt
+ */
+public class ReviewTaskEditorInput implements IEditorInput {
+
+ private Review review;
+
+ public ReviewTaskEditorInput(Review review) {
+ this.review = review;
+ }
+
+ public Review getReview() {
+ return review;
+ }
+
+ public boolean exists() {
+ return false;
+ }
+
+ public ImageDescriptor getImageDescriptor() {
+ return Images.SMALL_ICON;
+ }
+
+ public String getName() {
+ // TODO
+ return Messages.ReviewTaskEditorInput_New_Review;//"Review of" + model.getTask().getTaskKey() + " " +
+ // model.getTask().toString();
+ }
+
+ public IPersistableElement getPersistable() {
+ return null;
+ }
+
+ public String getToolTipText() {
+ return Messages.NewReviewTaskEditorInput_Tooltip;
+ }
+
+ @SuppressWarnings("rawtypes")
+ public Object getAdapter(Class adapter) {
+ return null;
+ }
+
+ public List<ReviewDiffModel> getScope() {
+ try {
+
+ IFilePatch2[] patches = PatchParser.parsePatch(new ReaderCreator() {
+
+ @Override
+ public Reader createReader() throws CoreException {
+ return new InputStreamReader(new ByteArrayInputStream(
+ ((Patch) review.getScope().get(0)).getContents()
+ .getBytes()));
+ }
+ });
+ List<ReviewDiffModel> model = new ArrayList<ReviewDiffModel>();
+ for (int i = 0; i < patches.length; i++) {
+ final PatchConfiguration configuration = new PatchConfiguration();
+
+ final IFilePatch2 currentPatch = patches[i];
+ model.add(new ReviewDiffModel(currentPatch, configuration));
+ }
+ return model;
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ throw new RuntimeException(ex);
+ }
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java
new file mode 100644
index 00000000..d0279cfa
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java
@@ -0,0 +1,425 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.ui.editors;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.List;
+
+import org.eclipse.compare.CompareConfiguration;
+import org.eclipse.compare.CompareEditorInput;
+import org.eclipse.compare.CompareUI;
+import org.eclipse.compare.patch.IFilePatch2;
+import org.eclipse.compare.patch.PatchConfiguration;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.jface.action.ToolBarManager;
+import org.eclipse.jface.resource.CompositeImageDescriptor;
+import org.eclipse.jface.viewers.ArrayContentProvider;
+import org.eclipse.jface.viewers.ColumnWeightData;
+import org.eclipse.jface.viewers.ComboViewer;
+import org.eclipse.jface.viewers.DoubleClickEvent;
+import org.eclipse.jface.viewers.IDoubleClickListener;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.jface.viewers.TableLayout;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.TableViewerColumn;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.mylyn.reviews.core.ReviewData;
+import org.eclipse.mylyn.reviews.core.ReviewsUtil;
+import org.eclipse.mylyn.reviews.core.model.review.Patch;
+import org.eclipse.mylyn.reviews.core.model.review.Rating;
+import org.eclipse.mylyn.reviews.core.model.review.Review;
+import org.eclipse.mylyn.reviews.core.model.review.ReviewFactory;
+import org.eclipse.mylyn.reviews.ui.Images;
+import org.eclipse.mylyn.reviews.ui.ReviewDiffModel;
+import org.eclipse.mylyn.reviews.ui.ReviewsUiPlugin;
+import org.eclipse.mylyn.tasks.core.data.TaskDataModel;
+import org.eclipse.mylyn.tasks.ui.TasksUi;
+import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.CCombo;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.ImageData;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.ui.ISharedImages;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.forms.IFormColors;
+import org.eclipse.ui.forms.widgets.FormToolkit;
+import org.eclipse.ui.forms.widgets.Section;
+
+/*
+ * @author Kilian Matt
+ */
+public class ReviewTaskEditorPart extends AbstractTaskEditorPart {
+ public static final String ID_PART_REVIEW = "org.eclipse.mylyn.reviews.ui.editors.ReviewTaskEditorPart"; //$NON-NLS-1$
+ private TableViewer fileList;
+ private Composite composite;
+
+ public ReviewTaskEditorPart() {
+ setPartName("Review ");
+ setExpandVertically(true);
+ }
+
+ @Override
+ public void createControl(Composite parent, FormToolkit toolkit) {
+ Section section = createSection(parent, toolkit, true);
+ GridLayout gl = new GridLayout(1, false);
+ gl.marginBottom = 16;
+ GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+ gd.horizontalSpan = 4;
+ section.setLayout(gl);
+ section.setLayoutData(gd);
+
+ composite = toolkit.createComposite(section);
+
+ composite.setLayout(new GridLayout(1, true));
+
+ fileList = new TableViewer(composite);
+
+ fileList.getControl().setLayoutData(
+ new GridData(SWT.FILL, SWT.FILL, true, true));
+
+ TableViewerColumn column = new TableViewerColumn(fileList, SWT.LEFT);
+ column.getColumn().setText("Filename");
+ column.getColumn().setWidth(100);
+ column.getColumn().setResizable(true);
+
+ TableLayout tableLayout = new TableLayout();
+ tableLayout.addColumnData(new ColumnWeightData(100, true));
+ fileList.getTable().setLayout(tableLayout);
+
+ fileList.setLabelProvider(new TableLabelProvider() {
+ private final int COLUMN_FILE = 0;
+
+ @Override
+ public String getColumnText(Object element, int columnIndex) {
+ if (columnIndex == COLUMN_FILE) {
+ if (element instanceof ReviewDiffModel) {
+ ReviewDiffModel diffModel = ((ReviewDiffModel) element);
+
+ return diffModel.getFileName();
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public Image getColumnImage(Object element, int columnIndex) {
+ if (columnIndex == COLUMN_FILE) {
+ ISharedImages sharedImages = PlatformUI.getWorkbench()
+ .getSharedImages();
+ if (element instanceof ReviewDiffModel) {
+ ReviewDiffModel diffModel = ((ReviewDiffModel) element);
+ if (diffModel.isNewFile()) {
+ return new NewFile().createImage();
+ }
+ if (!diffModel.canReview()) {
+ return new MissingFile().createImage();
+ }
+ }
+
+ return sharedImages.getImage(ISharedImages.IMG_OBJ_FILE);
+ }
+ return null;
+ }
+ });
+
+ fileList.setContentProvider(new IStructuredContentProvider() {
+
+ public void inputChanged(Viewer viewer, Object oldInput,
+ Object newInput) {
+ }
+
+ public void dispose() {
+ }
+
+ public Object[] getElements(Object inputElement) {
+ // parse the patch and create our model for the table
+ Patch patch = (Patch) inputElement;
+ List<IFilePatch2> patches = patch.parse();
+ ReviewDiffModel[] model = new ReviewDiffModel[patches.size()];
+ int index = 0;
+ for (IFilePatch2 currentPatch : patches) {
+ final PatchConfiguration configuration = new PatchConfiguration();
+ currentPatch.getTargetPath(configuration);
+ model[index++] = new ReviewDiffModel(currentPatch,
+ configuration);
+
+ }
+ return model;
+ }
+ });
+ fileList.addDoubleClickListener(new IDoubleClickListener() {
+
+ public void doubleClick(DoubleClickEvent event) {
+ ISelection selection = event.getSelection();
+ if (selection instanceof IStructuredSelection) {
+ IStructuredSelection sel = (IStructuredSelection) selection;
+ if (sel.getFirstElement() instanceof ReviewDiffModel) {
+ final ReviewDiffModel diffModel = ((ReviewDiffModel) sel
+ .getFirstElement());
+ if (diffModel.canReview()) {
+ CompareConfiguration configuration = new CompareConfiguration();
+ configuration.setLeftEditable(false);
+ configuration.setRightEditable(false);
+ configuration
+ .setLeftLabel(Messages.EditorSupport_Original);
+ configuration
+ .setRightLabel(Messages.EditorSupport_Patched);
+ configuration.setProperty(
+ CompareConfiguration.IGNORE_WHITESPACE,
+ false);
+ configuration
+ .setProperty(
+ CompareConfiguration.USE_OUTLINE_VIEW,
+ true);
+ CompareUI.openCompareEditor(new CompareEditorInput(
+ configuration) {
+
+ @Override
+ protected Object prepareInput(
+ IProgressMonitor monitor)
+ throws InvocationTargetException,
+ InterruptedException {
+ return diffModel.getCompareInput();
+ }
+ }, true);
+ }
+ }
+ }
+ }
+ });
+ setInput();
+
+ createResultFields(composite, toolkit);
+
+ section.setClient(composite);
+
+ // Depends on 288171
+ // getSashComposite().setData(EditorUtil.KEY_TOGGLE_TO_MAXIMIZE_ACTION,
+ // getMaximizePartAction());
+ // if (getSashComposite() instanceof Composite) {
+ // for (Control control : ((Composite)
+ // getSashComposite()).getChildren()) {
+ // control.setData(EditorUtil.KEY_TOGGLE_TO_MAXIMIZE_ACTION,
+ // getMaximizePartAction());
+ // }
+ // }
+
+ setSection(toolkit, section);
+
+ }
+
+ private void createResultFields(Composite composite, FormToolkit toolkit) {
+
+ final Review review;
+ final ReviewData rd = ReviewsUiPlugin.getDataManager().getReviewData(
+ getModel().getTask());
+ if (rd != null) {
+ review = rd.getReview();
+ } else {
+ review = parseFromAttachments();
+ if (review != null) {
+ ReviewsUiPlugin.getDataManager().storeTask(
+ getModel().getTask(), review);
+ }
+ }
+
+ Composite resultComposite = toolkit.createComposite(composite);
+ toolkit.paintBordersFor(resultComposite);
+ resultComposite.setLayoutData(new GridData(SWT.FILL, SWT.DEFAULT, true,
+ false));
+ resultComposite.setLayout(new GridLayout(2, false));
+
+ toolkit.createLabel(resultComposite, "Rating:").setForeground(
+ toolkit.getColors().getColor(IFormColors.TITLE));
+ CCombo ratingsCombo = new CCombo(resultComposite, SWT.READ_ONLY
+ | SWT.FLAT);
+ ratingsCombo.setData(FormToolkit.KEY_DRAW_BORDER,
+ FormToolkit.TREE_BORDER);
+ toolkit.adapt(ratingsCombo, false, false);
+
+ final ComboViewer ratingList = new ComboViewer(ratingsCombo);
+
+ ratingList.setContentProvider(ArrayContentProvider.getInstance());
+ ratingList.setLabelProvider(new LabelProvider() {
+ @Override
+ public String getText(Object element) {
+ // TODO externalize string
+ return ((Rating) element).getName();
+ }
+
+ @Override
+ public Image getImage(Object element) {
+ Rating rating = ((Rating) element);
+ switch (rating) {
+ case FAILED:
+ return Images.REVIEW_RESULT_FAILED.createImage();
+ case NONE:
+ return Images.REVIEW_RESULT_NONE.createImage();
+ case PASSED:
+ return Images.REVIEW_RESULT_PASSED.createImage();
+ case WARNING:
+ return Images.REVIEW_RESULT_WARNING.createImage();
+ }
+ return super.getImage(element);
+ }
+ });
+ ratingList.setInput(Rating.VALUES);
+ ratingList.getControl().setLayoutData(
+ new GridData(SWT.LEFT, SWT.TOP, false, false));
+
+ toolkit.createLabel(resultComposite, "Rating comment:").setForeground(
+ toolkit.getColors().getColor(IFormColors.TITLE));
+ final Text commentText = toolkit.createText(resultComposite, "", SWT.MULTI);
+
+ GridData gd = new GridData(SWT.FILL, SWT.DEFAULT, true, false);
+ gd.heightHint = 100;
+ commentText.setLayoutData(gd);
+
+ if (review.getResult() != null) {
+ Rating rating = review.getResult().getRating();
+ ratingList.setSelection(new StructuredSelection(rating));
+ String comment = review.getResult().getText();
+ commentText.setText(comment != null ? comment : "");
+ }
+ commentText.addModifyListener(new ModifyListener() {
+
+ public void modifyText(ModifyEvent e) {
+ if (review.getResult() == null) {
+ review.setResult(ReviewFactory.eINSTANCE
+ .createReviewResult());
+ }
+ review.getResult().setText(commentText.getText());
+ rd.setDirty();
+ }
+ });
+ ratingList.addSelectionChangedListener(new ISelectionChangedListener() {
+
+ public void selectionChanged(SelectionChangedEvent event) {
+ Rating rating = (Rating) ((IStructuredSelection) event
+ .getSelection()).getFirstElement();
+ if (review.getResult() == null) {
+ review.setResult(ReviewFactory.eINSTANCE
+ .createReviewResult());
+ }
+ review.getResult().setRating(rating);
+ rd.setDirty();
+ }
+ });
+
+ }
+
+ private Review parseFromAttachments() {
+ try {
+ final TaskDataModel model = getModel();
+ List<Review> reviews = ReviewsUtil.getReviewAttachmentFromTask(
+ TasksUi.getTaskDataManager(), TasksUi.getRepositoryModel(),
+ model.getTask());
+
+ if (reviews.size() > 0) {
+ return reviews.get(0);
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ return null;
+ }
+
+ /**
+ * Retrieves the review from the review data manager and fills the left
+ * table with the files.
+ */
+ private void setInput() {
+ ReviewData rd = ReviewsUiPlugin.getDataManager().getReviewData(
+ getModel().getTask());
+ if (rd != null) {
+ fileList.setInput((rd.getReview().getScope().get(0)));
+ }
+ }
+
+ private static class MissingFile extends CompositeImageDescriptor {
+ ISharedImages sharedImages = PlatformUI.getWorkbench()
+ .getSharedImages();
+
+ @Override
+ protected void drawCompositeImage(int width, int height) {
+ drawImage(getBaseImageData(), 0, 0);
+ drawImage(Images.OVERLAY_OBSTRUCTED.getImageData(), 7, 3);
+ }
+
+ @Override
+ protected Point getSize() {
+ ImageData img = getBaseImageData();
+ return new Point(img.width, img.height);
+ }
+
+ private ImageData baseImage;
+
+ private ImageData getBaseImageData() {
+ if (baseImage == null) {
+ baseImage = sharedImages.getImageDescriptor(
+ ISharedImages.IMG_OBJ_FILE).getImageData();
+ }
+ return baseImage;
+ }
+
+ }
+
+ private static class NewFile extends CompositeImageDescriptor {
+ ISharedImages sharedImages = PlatformUI.getWorkbench()
+ .getSharedImages();
+
+ @Override
+ protected void drawCompositeImage(int width, int height) {
+ drawImage(getBaseImageData(), 0, 0);
+ drawImage(Images.OVERLAY_ADDITION.getImageData(), 7, 5);
+ }
+
+ @Override
+ protected Point getSize() {
+
+ ImageData img = getBaseImageData();
+ return new Point(img.width, img.height);
+ }
+
+ private ImageData baseImage;
+
+ private ImageData getBaseImageData() {
+ if (baseImage == null) {
+ baseImage = sharedImages.getImageDescriptor(
+ ISharedImages.IMG_OBJ_FILE).getImageData();
+ }
+ return baseImage;
+ }
+
+ }
+
+ @Override
+ protected void fillToolBar(ToolBarManager manager) {
+ // Depends on 288171
+ // manager.add(getMaximizePartAction());
+ super.fillToolBar(manager);
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java
new file mode 100644
index 00000000..2e4b4ddb
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java
@@ -0,0 +1,160 @@
+package org.eclipse.mylyn.reviews.ui.editors;
+
+import java.io.ByteArrayOutputStream;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.resource.ResourceSet;
+import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
+import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
+import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal;
+import org.eclipse.mylyn.reviews.core.ReviewConstants;
+import org.eclipse.mylyn.reviews.core.ReviewData;
+import org.eclipse.mylyn.reviews.core.ReviewDataManager;
+import org.eclipse.mylyn.reviews.core.ReviewsUtil;
+import org.eclipse.mylyn.reviews.core.model.review.Review;
+import org.eclipse.mylyn.reviews.ui.ReviewCommentTaskAttachmentSource;
+import org.eclipse.mylyn.reviews.ui.ReviewsUiPlugin;
+import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
+import org.eclipse.mylyn.tasks.core.IRepositoryModel;
+import org.eclipse.mylyn.tasks.core.ITask;
+import org.eclipse.mylyn.tasks.core.TaskRepository;
+import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
+import org.eclipse.mylyn.tasks.core.data.TaskData;
+import org.eclipse.mylyn.tasks.ui.TasksUi;
+import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPage;
+import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart;
+import org.eclipse.mylyn.tasks.ui.editors.ITaskEditorPartDescriptorAdvisor;
+import org.eclipse.mylyn.tasks.ui.editors.TaskEditorPartDescriptor;
+
+public class ReviewTaskEditorPartAdvisor implements
+ ITaskEditorPartDescriptorAdvisor {
+
+ public boolean canCustomize(ITask task) {
+ if (!ReviewsUtil.hasReviewMarker(task)) {
+ try {
+ IRepositoryModel repositoryModel = TasksUi.getRepositoryModel();
+ TaskData taskData = TasksUiPlugin.getTaskDataManager()
+ .getTaskData(task);
+ if (ReviewsUtil.getReviewAttachments(repositoryModel, taskData)
+ .size() > 0) {
+ ReviewsUtil.markAsReview(task);
+ }
+ } catch (CoreException e) {
+ // FIXME
+ e.printStackTrace();
+ }
+ }
+
+ boolean isReview = ReviewsUtil.isMarkedAsReview(task);
+ return isReview;
+ }
+
+ public Set<String> getBlockingIds(ITask task) {
+ return Collections.emptySet();
+ }
+
+ public Set<String> getBlockingPaths(ITask task) {
+ Set<String> blockedPaths = new HashSet<String>();
+ blockedPaths.add(AbstractTaskEditorPage.PATH_ATTRIBUTES);
+ blockedPaths.add(AbstractTaskEditorPage.PATH_ATTACHMENTS);
+ blockedPaths.add(AbstractTaskEditorPage.PATH_PLANNING);
+
+ return blockedPaths;
+ }
+
+ public Set<TaskEditorPartDescriptor> getPartContributions(ITask task) {
+ Set<TaskEditorPartDescriptor> parts = new HashSet<TaskEditorPartDescriptor>();
+ parts.add(new TaskEditorPartDescriptor(
+ ReviewTaskEditorPart.ID_PART_REVIEW) {
+
+ @Override
+ public AbstractTaskEditorPart createPart() {
+ return new ReviewTaskEditorPart();
+ }
+ }.setPath(AbstractTaskEditorPage.PATH_ATTRIBUTES));
+ return parts;
+ }
+
+ public void taskMigration(ITask oldTask, ITask newTask) {
+ ReviewDataManager dataManager = ReviewsUiPlugin.getDataManager();
+ Review review = dataManager.getReviewData(oldTask).getReview();
+ dataManager.storeOutgoingTask(newTask, review);
+ ReviewsUtil.markAsReview(newTask);
+ }
+
+ public void afterSubmit(ITask task) {
+ try {
+ ReviewData reviewData = ReviewsUiPlugin.getDataManager()
+ .getReviewData(task);
+ Review review = reviewData.getReview();
+
+ if (reviewData.isOutgoing() || reviewData.isDirty()) {
+ reviewData.setDirty(false);
+ TaskRepository taskRepository = TasksUiPlugin
+ .getRepositoryManager().getRepository(
+ task.getRepositoryUrl());
+ TaskData taskData = TasksUiPlugin.getTaskDataManager()
+ .getTaskData(task);
+ // todo get which attachments have to be submitted
+ TaskAttribute attachmentAttribute = taskData
+ .getAttributeMapper().createTaskAttachment(taskData);
+ byte[] attachmentBytes = createAttachment(review);
+
+ ReviewCommentTaskAttachmentSource attachment = new ReviewCommentTaskAttachmentSource(
+ attachmentBytes);
+
+ AbstractRepositoryConnector connector = TasksUi
+ .getRepositoryConnector(taskRepository
+ .getConnectorKind());
+ connector.getTaskAttachmentHandler().postContent(
+ taskRepository, task, attachment, "review result", //$NON-NLS-1$
+ attachmentAttribute, new NullProgressMonitor());
+
+ TasksUiInternal.closeTaskEditorInAllPages(task, false);
+ TasksUiInternal.synchronizeTask(connector, task, false, null);
+ TasksUiInternal.openTaskInBackground(task, true);
+ }
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void prepareSubmit(ITask task) {
+ }
+
+ private byte[] createAttachment(Review review) {
+ try {
+ ResourceSet resourceSet = new ResourceSetImpl();
+
+ Resource resource = resourceSet.createResource(URI
+ .createFileURI("")); //$NON-NLS-1$
+
+ resource.getContents().add(review);
+ resource.getContents().add(review.getScope().get(0));
+ if (review.getResult() != null)
+ resource.getContents().add(review.getResult());
+ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+ ZipOutputStream outputStream = new ZipOutputStream(
+ byteArrayOutputStream);
+ outputStream.putNextEntry(new ZipEntry(
+ ReviewConstants.REVIEW_DATA_FILE));
+ resource.save(outputStream, null);
+ outputStream.closeEntry();
+ outputStream.close();
+ return byteArrayOutputStream.toByteArray();
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new RuntimeException(e);
+ }
+
+ }
+
+}
\ No newline at end of file
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/TableLabelProvider.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/TableLabelProvider.java
new file mode 100644
index 00000000..22d00865
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/TableLabelProvider.java
@@ -0,0 +1,27 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Christoph Mayerhofer (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.ui.editors;
+
+import org.eclipse.jface.viewers.ITableLabelProvider;
+import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.swt.graphics.Image;
+
+/**
+ * @author Christoph Mayerhofer
+ */
+public abstract class TableLabelProvider extends LabelProvider implements
+ ITableLabelProvider {
+
+ public abstract Image getColumnImage(Object element, int columnIndex);
+
+ public abstract String getColumnText(Object element, int columnIndex);
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/UpdateReviewTask.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/UpdateReviewTask.java
new file mode 100644
index 00000000..f51af485
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/UpdateReviewTask.java
@@ -0,0 +1,117 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.ui.editors;
+
+import java.io.ByteArrayOutputStream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.Job;
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.resource.ResourceSet;
+import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
+import org.eclipse.mylyn.reviews.core.ReviewConstants;
+import org.eclipse.mylyn.reviews.core.model.review.Review;
+import org.eclipse.mylyn.reviews.ui.editors.Messages;
+import org.eclipse.mylyn.reviews.ui.ReviewCommentTaskAttachmentSource;
+import org.eclipse.mylyn.reviews.ui.ReviewsUiPlugin;
+import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
+import org.eclipse.mylyn.tasks.core.TaskRepository;
+import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
+import org.eclipse.mylyn.tasks.core.data.TaskDataModel;
+import org.eclipse.mylyn.tasks.ui.TasksUi;
+
+/*
+ * @author Kilian Matt
+ */
+public class UpdateReviewTask extends Job {
+
+
+
+ private TaskDataModel model;
+ private Review review;
+ private TaskRepository taskRepository;
+ private AbstractRepositoryConnector connector;
+
+ public UpdateReviewTask(TaskDataModel model, Review review) {
+ super(Messages.UpdateReviewTask_Title);
+ this.model = model;
+ this.review = review;
+
+ this.taskRepository = model.getTaskRepository();
+
+ this.connector = TasksUi.getRepositoryConnector(taskRepository
+ .getConnectorKind());
+ }
+
+ @Override
+ protected IStatus run(final IProgressMonitor monitor) {
+ try {
+
+
+ final byte[] attachmentBytes = createAttachment(model, review);
+
+ TaskAttribute attachmentAttribute = model.getTaskData().getAttributeMapper()
+ .createTaskAttachment( model.getTaskData());
+ try {
+ ReviewCommentTaskAttachmentSource attachment = new ReviewCommentTaskAttachmentSource(
+ attachmentBytes);
+
+ monitor.subTask(org.eclipse.mylyn.reviews.ui.Messages.CreateTask_UploadingAttachment);
+ connector.getTaskAttachmentHandler().postContent(
+ taskRepository, model.getTask(), attachment,
+ "review result", //$NON-NLS-1$
+ attachmentAttribute, monitor);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+
+
+ return new Status(IStatus.OK, ReviewsUiPlugin.PLUGIN_ID,
+ org.eclipse.mylyn.reviews.ui.Messages.CreateTask_Success);
+ } catch (Exception e) {
+ return new Status(IStatus.ERROR, ReviewsUiPlugin.PLUGIN_ID, e
+ .getMessage());
+ }
+ }
+
+ private byte[] createAttachment(TaskDataModel model, Review review) {
+ try {
+ ResourceSet resourceSet = new ResourceSetImpl();
+
+ Resource resource = resourceSet.createResource(URI
+ .createFileURI("")); //$NON-NLS-1$
+
+ resource.getContents().add(review);
+ resource.getContents().add(review.getScope().get(0));
+ resource.getContents().add(review.getResult());
+ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+ ZipOutputStream outputStream = new ZipOutputStream(
+ byteArrayOutputStream);
+ outputStream.putNextEntry(new ZipEntry(
+ ReviewConstants.REVIEW_DATA_FILE));
+ resource.save(outputStream, null);
+ outputStream.closeEntry();
+ outputStream.close();
+ return byteArrayOutputStream.toByteArray();
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new RuntimeException(e);
+ }
+
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/messages.properties b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/messages.properties
new file mode 100644
index 00000000..7eb450b0
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/messages.properties
@@ -0,0 +1,44 @@
+###############################################################################
+# Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+# All rights reserved. This program and the accompanying materials
+# are made available under the terms of the Eclipse Public License v1.0
+# which accompanies this distribution, and is available at
+# http://www.eclipse.org/legal/epl-v10.html
+#
+# Contributors:
+# Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+###############################################################################
+CreateReviewTaskEditorPageFactory_Reviews=Reviews
+CreateReviewTaskEditorPart_Patches=Patches
+CreateReviewTaskEditorPart_Create_Review=Create review
+CreateReviewTaskEditorPart_Header_Author=Author
+CreateReviewTaskEditorPart_Header_Date=Date
+CreateReviewTaskEditorPart_Header_Filename=Filename
+EditorSupport_Original=Original
+EditorSupport_Patched=Patched
+NewReviewTaskEditorInput_ReviewPrefix=Review of
+NewReviewTaskEditorInput_Tooltip=Review input
+ReviewEditor_Assigned_to=Assigned to
+ReviewEditor_Comment=Comment
+ReviewEditor_Create_delegated_Review=Create delegated review
+ReviewEditor_Diff=Differences
+ReviewEditor_Files=Files
+ReviewEditor_New_Patch_based_Review=New patch-based Review
+ReviewEditor_Rating=Rating
+ReviewEditor_Review=Review
+ReviewEditor_Submit=Submit
+ReviewSummaryTaskEditorPart_Header_Author=Author
+ReviewSummaryTaskEditorPart_Header_Comment=Rating Comment
+ReviewSummaryTaskEditorPart_Header_Scope=Scope
+ReviewSummaryTaskEditorPart_Header_Result=Rating
+ReviewSummaryTaskEditorPart_Header_Reviewer=Reviewer
+ReviewSummaryTaskEditorPart_Header_ReviewId=Review Task
+ReviewSummaryTaskEditorPart_Partname=Review Summary
+ReviewTaskEditorInput_New_Review=New Review
+TaskEditorPatchReviewPart_Diff=Differences
+TaskEditorPatchReviewPart_Files=Files
+TaskEditorPatchReviewPart_Name=Reviews
+TaskEditorPatchReviewPart_Patches=Patches
+TaskEditorPatchReviewPart_Rating=Rating
+TaskEditorPatchReviewPart_Review=Review
+UpdateReviewTask_Title=Updating review task
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/messages.properties b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/messages.properties
new file mode 100644
index 00000000..022d1d92
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/messages.properties
@@ -0,0 +1,6 @@
+CreateTask_Success=Successfully created task
+CreateTask_Title=Creating new Mylyn Reviews task
+CreateTask_UploadingAttachment=Uploading attachment
+PatchCreator_ReaderCreationFailed=ReviewPatchFile.createReader failed
+ReviewCommentTaskAttachmentSource_Description=Mylyn Review Result
+ReviewTaskEditorPageFactory_PageTitle=Reviews
diff --git a/tbr/org.eclipse.mylyn.reviews/.project b/tbr/org.eclipse.mylyn.reviews/.project
new file mode 100644
index 00000000..005dafcc
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews/.project
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.mylyn.reviews</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.pde.FeatureBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.FeatureNature</nature>
+ </natures>
+</projectDescription>
diff --git a/tbr/org.eclipse.mylyn.reviews/build.properties b/tbr/org.eclipse.mylyn.reviews/build.properties
new file mode 100644
index 00000000..64f93a9f
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews/build.properties
@@ -0,0 +1 @@
+bin.includes = feature.xml
diff --git a/tbr/org.eclipse.mylyn.reviews/feature.xml b/tbr/org.eclipse.mylyn.reviews/feature.xml
new file mode 100644
index 00000000..1bcecf9a
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews/feature.xml
@@ -0,0 +1,84 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<feature
+ id="org.eclipse.mylyn.reviews"
+ label="Mylyn Reviews (Incubation)"
+ version="0.0.1"
+ provider-name="Mylyn Reviews Team">
+
+ <description url="http://www.eclipse.org/reviews">
+ Provides Review functionality for Mylyn
+ </description>
+
+ <copyright>
+ Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology and others. All rights reserved.
+ </copyright>
+
+ <license url="http://www.eclipse.org/legal/epl/notice.php">
+ Eclipse Foundation Software User Agreement
+
+April 14, 2010
+Usage Of Content
+
+THE ECLIPSE FOUNDATION MAKES AVAILABLE SOFTWARE, DOCUMENTATION, INFORMATION AND/OR OTHER MATERIALS FOR OPEN SOURCE PROJECTS (COLLECTIVELY "CONTENT"). USE OF THE CONTENT IS GOVERNED BY THE TERMS AND CONDITIONS OF THIS AGREEMENT AND/OR THE TERMS AND CONDITIONS OF LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW. BY USING THE CONTENT, YOU AGREE THAT YOUR USE OF THE CONTENT IS GOVERNED BY THIS AGREEMENT AND/OR THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW. IF YOU DO NOT AGREE TO THE TERMS AND CONDITIONS OF THIS AGREEMENT AND THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW, THEN YOU MAY NOT USE THE CONTENT.
+Applicable Licenses
+
+Unless otherwise indicated, all Content made available by the Eclipse Foundation is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is provided with this Content and is also available at http://www.eclipse.org/legal/epl-v10.html. For purposes of the EPL, "Program" will mean the Content.
+
+Content includes, but is not limited to, source code, object code, documentation and other files maintained in the Eclipse Foundation source code repository ("Repository") in software modules ("Modules") and made available as downloadable archives ("Downloads").
+
+ * Content may be structured and packaged into modules to facilitate delivering, extending, and upgrading the Content. Typical modules may include plug-ins ("Plug-ins"), plug-in fragments ("Fragments"), and features ("Features").
+ * Each Plug-in or Fragment may be packaged as a sub-directory or JAR (Java™ ARchive) in a directory named "plugins".
+ * A Feature is a bundle of one or more Plug-ins and/or Fragments and associated material. Each Feature may be packaged as a sub-directory in a directory named "features". Within a Feature, files named "feature.xml" may contain a list of the names and version numbers of the Plug-ins and/or Fragments associated with that Feature.
+ * Features may also include other Features ("Included Features"). Within a Feature, files named "feature.xml" may contain a list of the names and version numbers of Included Features.
+
+The terms and conditions governing Plug-ins and Fragments should be contained in files named "about.html" ("Abouts"). The terms and conditions governing Features and Included Features should be contained in files named "license.html" ("Feature Licenses"). Abouts and Feature Licenses may be located in any directory of a Download or Module including, but not limited to the following locations:
+
+ * The top-level (root) directory
+ * Plug-in and Fragment directories
+ * Inside Plug-ins and Fragments packaged as JARs
+ * Sub-directories of the directory named "src" of certain Plug-ins
+ * Feature directories
+
+Note: if a Feature made available by the Eclipse Foundation is installed using the Provisioning Technology (as defined below), you must agree to a license ("Feature Update License") during the installation process. If the Feature contains Included Features, the Feature Update License should either provide you with the terms and conditions governing the Included Features or inform you where you can locate them. Feature Update Licenses may be found in the "license" property of files named "feature.properties" found within a Feature. Such Abouts, Feature Licenses, and Feature Update Licenses contain the terms and conditions (or references to such terms and conditions) that govern your use of the associated Content in that directory.
+
+THE ABOUTS, FEATURE LICENSES, AND FEATURE UPDATE LICENSES MAY REFER TO THE EPL OR OTHER LICENSE AGREEMENTS, NOTICES OR TERMS AND CONDITIONS. SOME OF THESE OTHER LICENSE AGREEMENTS MAY INCLUDE (BUT ARE NOT LIMITED TO):
+
+ * Common Public License Version 1.0 (available at http://www.eclipse.org/legal/cpl-v10.html)
+ * Apache Software License 1.1 (available at http://www.apache.org/licenses/LICENSE)
+ * Apache Software License 2.0 (available at http://www.apache.org/licenses/LICENSE-2.0)
+ * Metro Link Public License 1.00 (available at http://www.opengroup.org/openmotif/supporters/metrolink/license.html)
+ * Mozilla Public License Version 1.1 (available at http://www.mozilla.org/MPL/MPL-1.1.html)
+
+IT IS YOUR OBLIGATION TO READ AND ACCEPT ALL SUCH TERMS AND CONDITIONS PRIOR TO USE OF THE CONTENT. If no About, Feature License, or Feature Update License is provided, please contact the Eclipse Foundation to determine what terms and conditions govern that particular Content.
+Use of Provisioning Technology
+
+The Eclipse Foundation makes available provisioning software, examples of which include, but are not limited to, p2 and the Eclipse Update Manager ("Provisioning Technology") for the purpose of allowing users to install software, documentation, information and/or other materials (collectively "Installable Software"). This capability is provided with the intent of allowing such users to install, extend and update Eclipse-based products. Information about packaging Installable Software is available at http://eclipse.org/equinox/p2/repository_packaging.html ("Specification").
+
+You may use Provisioning Technology to allow other parties to install Installable Software. You shall be responsible for enabling the applicable license agreements relating to the Installable Software to be presented to, and accepted by, the users of the Provisioning Technology in accordance with the Specification. By using Provisioning Technology in such a manner and making it available in accordance with the Specification, you further acknowledge your agreement to, and the acquisition of all necessary rights to permit the following:
+
+ 1. A series of actions may occur ("Provisioning Process") in which a user may execute the Provisioning Technology on a machine ("Target Machine") with the intent of installing, extending or updating the functionality of an Eclipse-based product.
+ 2. During the Provisioning Process, the Provisioning Technology may cause third party Installable Software or a portion thereof to be accessed and copied to the Target Machine.
+ 3. Pursuant to the Specification, you will provide to the user the terms and conditions that govern the use of the Installable Software ("Installable Software Agreement") and such Installable Software Agreement shall be accessed from the Target Machine in accordance with the Specification. Such Installable Software Agreement must inform the user of the terms and conditions that govern the Installable Software and must solicit acceptance by the end user in the manner prescribed in such Installable Software Agreement. Upon such indication of agreement by the user, the provisioning Technology will complete installation of the Installable Software.
+
+Cryptography
+
+Content may contain encryption software. The country in which you are currently may have restrictions on the import, possession, and use, and/or re-export to another country, of encryption software. BEFORE using any encryption software, please check the country's laws, regulations and policies concerning the import, possession, or use, and re-export of encryption software, to see if this is permitted.
+
+Java and all Java-based trademarks are trademarks of Oracle Corporation in the United States, other countries, or both.
+ </license>
+
+ <plugin
+ id="org.eclipse.mylyn.reviews.core"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"
+ unpack="false"/>
+
+ <plugin
+ id="org.eclipse.mylyn.reviews.ui"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"
+ unpack="false"/>
+
+</feature>
|
a0b240db548102de8ecaf7e7ee27cd0010557b7d
|
hbase
|
HBASE-9287 TestCatalogTracker depends on the- execution order--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1516292 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/hbase
|
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/catalog/TestCatalogTracker.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/catalog/TestCatalogTracker.java
index 8163ea8a3b49..558549836808 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/catalog/TestCatalogTracker.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/catalog/TestCatalogTracker.java
@@ -103,6 +103,17 @@ public boolean isAborted() {
}
@After public void after() {
+ try {
+ // Clean out meta location or later tests will be confused... they presume
+ // start fresh in zk.
+ MetaRegionTracker.deleteMetaLocation(this.watcher);
+ } catch (KeeperException e) {
+ LOG.warn("Unable to delete META location", e);
+ }
+
+ // Clear out our doctored connection or could mess up subsequent tests.
+ HConnectionManager.deleteConnection(UTIL.getConfiguration());
+
this.watcher.close();
}
@@ -124,14 +135,9 @@ private CatalogTracker constructAndStartCatalogTracker(final HConnection c)
throws IOException, InterruptedException, KeeperException {
HConnection connection = Mockito.mock(HConnection.class);
constructAndStartCatalogTracker(connection);
- try {
- MetaRegionTracker.setMetaLocation(this.watcher,
- new ServerName("example.com", 1234, System.currentTimeMillis()));
- } finally {
- // Clean out meta location or later tests will be confused... they presume
- // start fresh in zk.
- MetaRegionTracker.deleteMetaLocation(this.watcher);
- }
+
+ MetaRegionTracker.setMetaLocation(this.watcher,
+ new ServerName("example.com", 1234, System.currentTimeMillis()));
}
/**
@@ -145,33 +151,30 @@ private CatalogTracker constructAndStartCatalogTracker(final HConnection c)
final ClientProtos.ClientService.BlockingInterface client =
Mockito.mock(ClientProtos.ClientService.BlockingInterface.class);
HConnection connection = mockConnection(null, client);
- try {
- Mockito.when(client.get((RpcController)Mockito.any(), (GetRequest)Mockito.any())).
- thenReturn(GetResponse.newBuilder().build());
- final CatalogTracker ct = constructAndStartCatalogTracker(connection);
- ServerName meta = ct.getMetaLocation();
- Assert.assertNull(meta);
- Thread t = new Thread() {
- @Override
- public void run() {
- try {
- ct.waitForMeta();
- } catch (InterruptedException e) {
- throw new RuntimeException("Interrupted", e);
- }
+
+ Mockito.when(client.get((RpcController)Mockito.any(), (GetRequest)Mockito.any())).
+ thenReturn(GetResponse.newBuilder().build());
+ final CatalogTracker ct = constructAndStartCatalogTracker(connection);
+ ServerName meta = ct.getMetaLocation();
+ Assert.assertNull(meta);
+ Thread t = new Thread() {
+ @Override
+ public void run() {
+ try {
+ ct.waitForMeta();
+ } catch (InterruptedException e) {
+ throw new RuntimeException("Interrupted", e);
}
- };
- t.start();
- while (!t.isAlive())
- Threads.sleep(1);
+ }
+ };
+ t.start();
+ while (!t.isAlive())
Threads.sleep(1);
- assertTrue(t.isAlive());
- ct.stop();
- // Join the thread... should exit shortly.
- t.join();
- } finally {
- HConnectionManager.deleteConnection(UTIL.getConfiguration());
- }
+ Threads.sleep(1);
+ assertTrue(t.isAlive());
+ ct.stop();
+ // Join the thread... should exit shortly.
+ t.join();
}
private void testVerifyMetaRegionLocationWithException(Exception ex)
@@ -180,26 +183,17 @@ private void testVerifyMetaRegionLocationWithException(Exception ex)
final ClientProtos.ClientService.BlockingInterface implementation =
Mockito.mock(ClientProtos.ClientService.BlockingInterface.class);
HConnection connection = mockConnection(null, implementation);
- try {
- // If a 'get' is called on mocked interface, throw connection refused.
- Mockito.when(implementation.get((RpcController) Mockito.any(), (GetRequest) Mockito.any())).
- thenThrow(new ServiceException(ex));
- // Now start up the catalogtracker with our doctored Connection.
- final CatalogTracker ct = constructAndStartCatalogTracker(connection);
- try {
- MetaRegionTracker.setMetaLocation(this.watcher, SN);
- long timeout = UTIL.getConfiguration().
- getLong("hbase.catalog.verification.timeout", 1000);
- Assert.assertFalse(ct.verifyMetaRegionLocation(timeout));
- } finally {
- // Clean out meta location or later tests will be confused... they
- // presume start fresh in zk.
- MetaRegionTracker.deleteMetaLocation(this.watcher);
- }
- } finally {
- // Clear out our doctored connection or could mess up subsequent tests.
- HConnectionManager.deleteConnection(UTIL.getConfiguration());
- }
+
+ // If a 'get' is called on mocked interface, throw connection refused.
+ Mockito.when(implementation.get((RpcController) Mockito.any(), (GetRequest) Mockito.any())).
+ thenThrow(new ServiceException(ex));
+ // Now start up the catalogtracker with our doctored Connection.
+ final CatalogTracker ct = constructAndStartCatalogTracker(connection);
+
+ MetaRegionTracker.setMetaLocation(this.watcher, SN);
+ long timeout = UTIL.getConfiguration().
+ getLong("hbase.catalog.verification.timeout", 1000);
+ Assert.assertFalse(ct.verifyMetaRegionLocation(timeout));
}
/**
@@ -255,15 +249,10 @@ public void testVerifyMetaRegionLocationFails()
Mockito.when(connection.getAdmin(Mockito.any(ServerName.class), Mockito.anyBoolean())).
thenReturn(implementation);
final CatalogTracker ct = constructAndStartCatalogTracker(connection);
- try {
- MetaRegionTracker.setMetaLocation(this.watcher,
- new ServerName("example.com", 1234, System.currentTimeMillis()));
- Assert.assertFalse(ct.verifyMetaRegionLocation(100));
- } finally {
- // Clean out meta location or later tests will be confused... they presume
- // start fresh in zk.
- MetaRegionTracker.deleteMetaLocation(this.watcher);
- }
+
+ MetaRegionTracker.setMetaLocation(this.watcher,
+ new ServerName("example.com", 1234, System.currentTimeMillis()));
+ Assert.assertFalse(ct.verifyMetaRegionLocation(100));
}
@Test (expected = NotAllMetaRegionsOnlineException.class)
|
28174744a74e08cc974a54041e304dc4aafa5334
|
spring-framework
|
Fix race when flushing messages--The use of an AtomicBoolean and no lock meant that it was possible-for a message to be queued and then never be flushed and sent to the-broker:--1. On t1
|
c
|
https://github.com/spring-projects/spring-framework
|
diff --git a/spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompRelayPubSubMessageHandler.java b/spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompRelayPubSubMessageHandler.java
index 2337814fcadc..ae8df8f91a2c 100644
--- a/spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompRelayPubSubMessageHandler.java
+++ b/spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompRelayPubSubMessageHandler.java
@@ -24,7 +24,6 @@
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.atomic.AtomicBoolean;
import org.springframework.http.MediaType;
import org.springframework.messaging.Message;
@@ -171,10 +170,11 @@ private final class RelaySession {
private final Promise<TcpConnection<String, String>> promise;
- private final AtomicBoolean isConnected = new AtomicBoolean(false);
-
private final BlockingQueue<M> messageQueue = new LinkedBlockingQueue<M>(50);
+ private final Object monitor = new Object();
+
+ private boolean isConnected = false;
public RelaySession(final M message, final StompHeaders stompHeaders) {
@@ -224,8 +224,10 @@ private void readStompFrame(String stompFrame) {
StompHeaders headers = StompHeaders.fromMessageHeaders(message.getHeaders());
if (StompCommand.CONNECTED == headers.getStompCommand()) {
- this.isConnected.set(true);
- flushMessages(promise.get());
+ synchronized(this.monitor) {
+ this.isConnected = true;
+ flushMessages(promise.get());
+ }
return;
}
if (StompCommand.ERROR == headers.getStompCommand()) {
@@ -248,14 +250,14 @@ private void sendError(String sessionId, String errorText) {
public void forward(M message, StompHeaders headers) {
- if (!this.isConnected.get()) {
- @SuppressWarnings("unchecked")
- M m = (M) MessageBuilder.fromPayloadAndHeaders(message.getPayload(), headers.toMessageHeaders()).build();
- if (logger.isTraceEnabled()) {
- logger.trace("Adding to queue message " + m + ", queue size=" + this.messageQueue.size());
+ synchronized(this.monitor) {
+ if (!this.isConnected) {
+ if (logger.isTraceEnabled()) {
+ logger.trace("Adding to queue message " + message + ", queue size=" + this.messageQueue.size());
+ }
+ this.messageQueue.add(message);
+ return;
}
- this.messageQueue.add(m);
- return;
}
TcpConnection<String, String> connection = this.promise.get();
|
09c3edcbc7b12c62280eeba8bb3dea0f06775367
|
kotlin
|
'hasSyntaxErrors' check moved from Diagnostic to- PositioningStrategy--This makes possible to mark diagnostic errors when syntax error are present (by overriding isValid in PositioningStrategy subclasses).-
|
a
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AbstractDiagnostic.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AbstractDiagnostic.java
index 22f5a8fbb944d..ab26aa0d0ea02 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AbstractDiagnostic.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AbstractDiagnostic.java
@@ -71,20 +71,7 @@ public List<TextRange> getTextRanges() {
@Override
public boolean isValid() {
if (!getFactory().isValid(this)) return false;
- if (hasSyntaxErrors(psiElement)) return false;
if (psiElement.getNode().findChildByType(JetNodeTypes.IDE_TEMPLATE_EXPRESSION) != null) return false;
return true;
}
-
- private static boolean hasSyntaxErrors(@NotNull PsiElement psiElement) {
- if (psiElement instanceof PsiErrorElement) return true;
-
- PsiElement lastChild = psiElement.getLastChild();
- if (lastChild != null && hasSyntaxErrors(lastChild)) return true;
-
- PsiElement[] children = psiElement.getChildren();
- if (children.length > 0 && hasSyntaxErrors(children[children.length - 1])) return true;
-
- return false;
- }
}
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/PositioningStrategies.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/PositioningStrategies.java
index d49d8a2daad25..d7abf9cf9cb36 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/PositioningStrategies.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/PositioningStrategies.java
@@ -139,7 +139,7 @@ else if (element instanceof JetClass) {
}
@Override
public boolean isValid(@NotNull PsiNameIdentifierOwner element) {
- return element.getNameIdentifier() != null;
+ return element.getNameIdentifier() != null && super.isValid(element);
}
};
@@ -299,6 +299,8 @@ public List<TextRange> mark(@NotNull JetDeclarationWithBody element) {
@Override
public boolean isValid(@NotNull JetDeclarationWithBody element) {
+ if (!super.isValid(element)) return false;
+
JetExpression bodyExpression = element.getBodyExpression();
if (!(bodyExpression instanceof JetBlockExpression)) return false;
if (((JetBlockExpression) bodyExpression).getLastBracketRange() == null) return false;
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/PositioningStrategy.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/PositioningStrategy.java
index f2dcf999f6b4f..4e54884790a93 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/PositioningStrategy.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/PositioningStrategy.java
@@ -32,7 +32,7 @@ public List<TextRange> mark(@NotNull E element) {
}
public boolean isValid(@NotNull E element) {
- return true;
+ return !hasSyntaxErrors(element);
}
@NotNull
@@ -49,4 +49,16 @@ protected static List<TextRange> markNode(@NotNull ASTNode node) {
protected static List<TextRange> markRange(@NotNull TextRange range) {
return Collections.singletonList(range);
}
+
+ protected static boolean hasSyntaxErrors(@NotNull PsiElement psiElement) {
+ if (psiElement instanceof PsiErrorElement) return true;
+
+ PsiElement lastChild = psiElement.getLastChild();
+ if (lastChild != null && hasSyntaxErrors(lastChild)) return true;
+
+ PsiElement[] children = psiElement.getChildren();
+ if (children.length > 0 && hasSyntaxErrors(children[children.length - 1])) return true;
+
+ return false;
+ }
}
|
b2b67bd48d228d919db25ca3afd26b70ebf58897
|
camel
|
CAMEL-6013 fixed the issue that Validator- component fails on XSD with indirect relative import--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1438352 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/camel
|
diff --git a/camel-core/src/main/java/org/apache/camel/component/validator/DefaultLSResourceResolver.java b/camel-core/src/main/java/org/apache/camel/component/validator/DefaultLSResourceResolver.java
index bb4831950f1a7..842b20f2213b1 100644
--- a/camel-core/src/main/java/org/apache/camel/component/validator/DefaultLSResourceResolver.java
+++ b/camel-core/src/main/java/org/apache/camel/component/validator/DefaultLSResourceResolver.java
@@ -36,12 +36,21 @@ public class DefaultLSResourceResolver implements LSResourceResolver {
private final CamelContext camelContext;
private final String resourceUri;
private final String resourcePath;
+ private String relatedURI;
public DefaultLSResourceResolver(CamelContext camelContext, String resourceUri) {
this.camelContext = camelContext;
this.resourceUri = resourceUri;
this.resourcePath = FileUtil.onlyPath(resourceUri);
}
+
+ private String getUri(String systemId) {
+ if (resourcePath != null) {
+ return FileUtil.onlyPath(resourceUri) + "/" + systemId;
+ } else {
+ return systemId;
+ }
+ }
@Override
public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
@@ -50,7 +59,13 @@ public LSInput resolveResource(String type, String namespaceURI, String publicId
throw new IllegalArgumentException(String.format("Resource: %s refers an invalid resource without SystemId."
+ " Invalid resource has type: %s, namespaceURI: %s, publicId: %s, systemId: %s, baseURI: %s", resourceUri, type, namespaceURI, publicId, systemId, baseURI));
}
- return new DefaultLSInput(publicId, systemId, baseURI);
+ // Build up the relative path for using
+ if (baseURI == null) {
+ relatedURI = getUri(systemId);
+ } else {
+ relatedURI = FileUtil.onlyPath(relatedURI) + "/" + systemId;
+ }
+ return new DefaultLSInput(publicId, systemId, baseURI, relatedURI);
}
private final class DefaultLSInput implements LSInput {
@@ -58,23 +73,25 @@ private final class DefaultLSInput implements LSInput {
private final String publicId;
private final String systemId;
private final String baseURI;
+ private final String relatedURI;
private final String uri;
+
- private DefaultLSInput(String publicId, String systemId, String baseURI) {
+ private DefaultLSInput(String publicId, String systemId, String basedURI, String relatedURI) {
this.publicId = publicId;
this.systemId = systemId;
- this.baseURI = baseURI;
+ this.baseURI = basedURI;
+ this.relatedURI = relatedURI;
this.uri = getInputUri();
}
private String getInputUri() {
// find the xsd with relative path
- if (ObjectHelper.isNotEmpty(baseURI)) {
- String inputUri = getUri(getRelativePath(baseURI));
+ if (ObjectHelper.isNotEmpty(relatedURI)) {
try {
- ResourceHelper.resolveMandatoryResourceAsInputStream(camelContext.getClassResolver(), inputUri);
- return inputUri;
+ ResourceHelper.resolveMandatoryResourceAsInputStream(camelContext.getClassResolver(), relatedURI);
+ return relatedURI;
} catch (IOException e) {
// ignore the exception
}
@@ -83,28 +100,6 @@ private String getInputUri() {
return getUri("");
}
- private String getRelativePath(String base) {
- String userDir = "";
- String answer = "";
- if (ObjectHelper.isNotEmpty(base)) {
- try {
- userDir = FileUtil.getUserDir().toURI().toASCIIString();
- } catch (Exception ex) {
- // do nothing here
- }
- // get the relative path from the userdir
- if (ObjectHelper.isNotEmpty(base) && base.startsWith("file://") && userDir.startsWith("file:")) {
- // skip the protocol part
- base = base.substring(7);
- userDir = userDir.substring(5);
- if (base.startsWith(userDir)) {
- answer = FileUtil.onlyPath(base.substring(userDir.length())) + "/";
- }
- }
- }
- return answer;
- }
-
private String getUri(String relativePath) {
if (resourcePath != null) {
return FileUtil.onlyPath(resourceUri) + "/" + relativePath + systemId;
diff --git a/tests/camel-itest/src/test/java/org/apache/camel/itest/validator/ValidatorSchemaImportTest.java b/tests/camel-itest/src/test/java/org/apache/camel/itest/validator/ValidatorSchemaImportTest.java
index 0c5dfd6aa979c..caed57ed5c9ef 100644
--- a/tests/camel-itest/src/test/java/org/apache/camel/itest/validator/ValidatorSchemaImportTest.java
+++ b/tests/camel-itest/src/test/java/org/apache/camel/itest/validator/ValidatorSchemaImportTest.java
@@ -113,6 +113,35 @@ public void configure() throws Exception {
MockEndpoint.assertIsSatisfied(validEndpoint, invalidEndpoint, finallyEndpoint);
}
+
+ /**
+ * Test for the valid schema location relative to a path other than the validating schema
+ * @throws Exception
+ */
+ @Test
+ public void testChildParentUncleSchemaImport() throws Exception {
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+ from("direct:start")
+ .doTry()
+ .to("validator:org/apache/camel/component/validator/childparentuncle/child/child.xsd")
+ .to("mock:valid")
+ .doCatch(ValidationException.class)
+ .to("mock:invalid")
+ .doFinally()
+ .to("mock:finally")
+ .end();
+ }
+ });
+ validEndpoint.expectedMessageCount(1);
+ finallyEndpoint.expectedMessageCount(1);
+
+ template.sendBody("direct:start",
+ "<childuser xmlns='http://foo.com/bar'><user><id>1</id><username>Test User</username></user></childuser>");
+
+ MockEndpoint.assertIsSatisfied(validEndpoint, invalidEndpoint, finallyEndpoint);
+ }
@Override
@Before
diff --git a/tests/camel-itest/src/test/resources/org/apache/camel/component/validator/childparentuncle/child/child.xsd b/tests/camel-itest/src/test/resources/org/apache/camel/component/validator/childparentuncle/child/child.xsd
new file mode 100644
index 0000000000000..3cf6b48cf1c21
--- /dev/null
+++ b/tests/camel-itest/src/test/resources/org/apache/camel/component/validator/childparentuncle/child/child.xsd
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!--
+ 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.
+-->
+<xs:schema elementFormDefault="qualified" version="1.0"
+ targetNamespace="http://foo.com/bar"
+ xmlns:tns="http://foo.com/bar"
+ xmlns:xs="http://www.w3.org/2001/XMLSchema">
+
+ <xs:include schemaLocation="../deeper/parent/parent.xsd"/>
+ <xs:element name="childuser">
+ <xs:complexType>
+ <xs:sequence>
+ <xs:element ref="tns:user" />
+ </xs:sequence>
+ </xs:complexType>
+ </xs:element>
+
+</xs:schema>
+
diff --git a/tests/camel-itest/src/test/resources/org/apache/camel/component/validator/childparentuncle/deeper/parent/parent.xsd b/tests/camel-itest/src/test/resources/org/apache/camel/component/validator/childparentuncle/deeper/parent/parent.xsd
new file mode 100644
index 0000000000000..01aec8e42ce1a
--- /dev/null
+++ b/tests/camel-itest/src/test/resources/org/apache/camel/component/validator/childparentuncle/deeper/parent/parent.xsd
@@ -0,0 +1,17 @@
+<xs:schema elementFormDefault="qualified" version="1.0"
+ targetNamespace="http://foo.com/bar"
+ xmlns:tns="http://foo.com/bar"
+ xmlns:xs="http://www.w3.org/2001/XMLSchema">
+
+<xs:include schemaLocation="../uncle/uncle.xsd"/>
+<xs:element name="parent">
+ <xs:complexType>
+ <xs:sequence>
+ <xs:element name="id" type="xs:int"/>
+ <xs:element name="username" type="xs:string"/>
+ </xs:sequence>
+ </xs:complexType>
+ </xs:element>
+
+</xs:schema>
+
diff --git a/tests/camel-itest/src/test/resources/org/apache/camel/component/validator/childparentuncle/deeper/uncle/uncle.xsd b/tests/camel-itest/src/test/resources/org/apache/camel/component/validator/childparentuncle/deeper/uncle/uncle.xsd
new file mode 100644
index 0000000000000..8f708d8ecdc9f
--- /dev/null
+++ b/tests/camel-itest/src/test/resources/org/apache/camel/component/validator/childparentuncle/deeper/uncle/uncle.xsd
@@ -0,0 +1,17 @@
+<xs:schema elementFormDefault="qualified" version="1.0"
+ targetNamespace="http://foo.com/bar"
+ xmlns:tns="http://foo.com/bar"
+ xmlns:xs="http://www.w3.org/2001/XMLSchema">
+
+
+ <xs:element name="user">
+ <xs:complexType>
+ <xs:sequence>
+ <xs:element name="id" type="xs:int"/>
+ <xs:element name="username" type="xs:string"/>
+ </xs:sequence>
+ </xs:complexType>
+ </xs:element>
+
+</xs:schema>
+
|
6be649b286d7b3e2a1193cbe808f8a46fa1ae4c4
|
internetarchive$heritrix3
|
[HER-1783] BloomFilter64bit bit-length bug prevents full bitfield from being used; premature saturation
* BloomFilter64bit.java
include the split-to-subarrays (for larger bitfields) and round-up-to-power-of-2 (for performance) options previously in largely-redundant classes
fit a number of problems with int/long overflow and bitwise ops
add methods for reporting/testing
* BloomFilter.java
add methods for reporting/testing
* BloomFilterTest.java, BloomFilter64bitTest.java
more extensive tests, including two lengthy tests of default/oversized blooms usually disabled by renaming
* BloomFilter32bit.java, BloomFilter32bitSplit.java, BloomFilter32bp2.java, BloomFilter32bp2Split.java
deleted as buggy or redundant
* BenchmarkBlooms.java
move to test source dir
* BloomUriUniqFilter.java
change to accept filter instance (rather than parameters) for added configuration flexibility
fix comments
* BloomUriUniqFilterTest.java
supply filter not paramters
|
p
|
https://github.com/internetarchive/heritrix3
|
diff --git a/commons/src/main/java/org/archive/util/BloomFilter.java b/commons/src/main/java/org/archive/util/BloomFilter.java
index c83fbc5e7..17de30d2d 100644
--- a/commons/src/main/java/org/archive/util/BloomFilter.java
+++ b/commons/src/main/java/org/archive/util/BloomFilter.java
@@ -1,15 +1,11 @@
/* BloomFilter
*
-* $Id$
-*
-* Created on Jun 30, 2005
-*
-* Copyright (C) 2005 Internet Archive; an adaptation of
+* Copyright (C) 2010 Internet Archive; an adaptation of
* LGPL work (C) Sebastiano Vigna
*
* This file is part of the Heritrix web crawler (crawler.archive.org).
*
-* Heritrix is free software; you can redistribute it and/or modify
+* This class is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* any later version.
@@ -27,13 +23,13 @@
package org.archive.util;
/**
- * Common interface for different Bloom filter
- * implementations
+ * Common interface for different Bloom filter implementations
*
* @author Gordon Mohr
*/
public interface BloomFilter {
- /** The number of character sequences in the filter.
+ /** The number of character sequences in the filter (considered to be the
+ * number of add()s that returned 'true')
*
* @return the number of character sequences in the filter (but see {@link #contains(CharSequence)}).
*/
@@ -67,4 +63,23 @@ public interface BloomFilter {
* @return memory used by bloom bitfield, in bytes
*/
public abstract long getSizeBytes();
+
+ /**
+ * Report the number of expected inserts used at instantiation time to
+ * calculate the bitfield size.
+ *
+ * @return long number of inserts expected at instantiation
+ */
+ public abstract long getExpectedInserts();
+
+ /**
+ * Report the number of internal independent hash function (and thus the
+ * number of bits set/checked for each item presented).
+ *
+ * @return long count of hash functions
+ */
+ public abstract long getHashCount();
+
+ // public for white-box unit testing
+ public boolean getBit(long bitIndex);
}
\ No newline at end of file
diff --git a/commons/src/main/java/org/archive/util/BloomFilter32bit.java b/commons/src/main/java/org/archive/util/BloomFilter32bit.java
deleted file mode 100644
index 7a52ce392..000000000
--- a/commons/src/main/java/org/archive/util/BloomFilter32bit.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/* BloomFilter32bit
-*
-* $Id$
-*
-* Created on Jun 21, 2005
-*
-* Copyright (C) 2005 Internet Archive; a slight adaptation of
-* LGPL work (C) Sebastiano Vigna
-*
-* This file is part of the Heritrix web crawler (crawler.archive.org).
-*
-* Heritrix is free software; you can redistribute it and/or modify
-* it under the terms of the GNU Lesser Public License as published by
-* the Free Software Foundation; either version 2.1 of the License, or
-* any later version.
-*
-* Heritrix 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 Public License for more details.
-*
-* You should have received a copy of the GNU Lesser Public License
-* along with Heritrix; if not, write to the Free Software
-* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-*/
-
-package org.archive.util;
-
-import java.io.Serializable;
-import java.security.SecureRandom;
-
-/** A Bloom filter.
- *
- * SLIGHTLY ADAPTED VERSION OF MG4J it.unimi.dsi.mg4j.util.BloomFilter
- *
- * <p>KEY CHANGES:
- *
- * <ul>
- * <li>Adapted to use 32bit ops as much as possible... may be slightly
- * faster on 32bit hardware/OS</li>
- * <li>NUMBER_OF_WEIGHTS is 2083, to better avoid collisions between
- * similar strings</li>
- * <li>Removed dependence on cern.colt MersenneTwister (replaced with
- * SecureRandom) and QuickBitVector (replaced with local methods).</li>
- * </ul>
- *
- * <hr>
- *
- * <P>Instances of this class represent a set of character sequences (with false positives)
- * using a Bloom filter. Because of the way Bloom filters work,
- * you cannot remove elements.
- *
- * <P>Bloom filters have an expected error rate, depending on the number
- * of hash functions used, on the filter size and on the number of elements in the filter. This implementation
- * uses a variable optimal number of hash functions, depending on the expected
- * number of elements. More precisely, a Bloom
- * filter for <var>n</var> character sequences with <var>d</var> hash functions will use
- * ln 2 <var>d</var><var>n</var> ≈ 1.44 <var>d</var><var>n</var> bits;
- * false positives will happen with probability 2<sup>-<var>d</var></sup>.
- *
- * <P>Hash functions are generated at creation time using universal hashing. Each hash function
- * uses {@link #NUMBER_OF_WEIGHTS} random integers, which are cyclically multiplied by
- * the character codes in a character sequence. The resulting integers are XOR-ed together.
- *
- * <P>This class exports access methods that are very similar to those of {@link java.util.Set},
- * but it does not implement that interface, as too many non-optional methods
- * would be unimplementable (e.g., iterators).
- *
- * @author Sebastiano Vigna
- */
-public class BloomFilter32bit implements Serializable, BloomFilter {
-
- private static final long serialVersionUID = -1567837798979475689L;
-
- /** The number of weights used to create hash functions. */
- final public static int NUMBER_OF_WEIGHTS = 2083; // CHANGED FROM 16
- /** The number of bits in this filter. */
- final public long m;
- /** The number of hash functions used by this filter. */
- final public int d;
- /** The underlying bit vectorS. */
- final private int[] bits;
- /** The random integers used to generate the hash functions. */
- final private int[][] weight;
-
- /** The number of elements currently in the filter. It may be
- * smaller than the actual number of additions of distinct character
- * sequences because of false positives.
- */
- private int size;
-
- /** The natural logarithm of 2, used in the computation of the number of bits. */
- private final static double NATURAL_LOG_OF_2 = Math.log( 2 );
-
- private final static boolean DEBUG = false;
-
- /** Creates a new Bloom filter with given number of hash functions and expected number of elements.
- *
- * @param n the expected number of elements.
- * @param d the number of hash functions; if the filter add not more than <code>n</code> elements,
- * false positives will happen with probability 2<sup>-<var>d</var></sup>.
- */
- public BloomFilter32bit( final int n, final int d ) {
- this.d = d;
- int len =
- (int)Math.ceil( ( (long)n * (long)d / NATURAL_LOG_OF_2 ) / 32 );
- this.m = len*32L;
- if ( m >= 1L<<32 ) {
- throw new IllegalArgumentException( "This filter would require " + m + " bits" );
- }
- bits = new int[ len ];
-
- if ( DEBUG ) System.err.println( "Number of bits: " + m );
-
- // seeded for reproduceable behavior in repeated runs; BUT:
- // SecureRandom's default implementation (as of 1.5)
- // seems to mix in its own seeding.
- final SecureRandom random = new SecureRandom(new byte[] {19,96});
- weight = new int[ d ][];
- for( int i = 0; i < d; i++ ) {
- weight[ i ] = new int[ NUMBER_OF_WEIGHTS ];
- for( int j = 0; j < NUMBER_OF_WEIGHTS; j++ )
- weight[ i ][ j ] = random.nextInt();
- }
- }
-
- /** The number of character sequences in the filter.
- *
- * @return the number of character sequences in the filter (but see {@link #contains(CharSequence)}).
- */
-
- public int size() {
- return size;
- }
-
- /** Hashes the given sequence with the given hash function.
- *
- * @param s a character sequence.
- * @param l the length of <code>s</code>.
- * @param k a hash function index (smaller than {@link #d}).
- * @return the position in the filter corresponding to <code>s</code> for the hash function <code>k</code>.
- */
- private long hash( final CharSequence s, final int l, final int k ) {
- final int[] w = weight[ k ];
- int h = 0, i = l;
- while( i-- != 0 ) h ^= s.charAt( i ) * w[ i % NUMBER_OF_WEIGHTS ];
- return ((long)h-Integer.MIN_VALUE) % m;
- }
-
- /** Checks whether the given character sequence is in this filter.
- *
- * <P>Note that this method may return true on a character sequence that is has
- * not been added to the filter. This will happen with probability 2<sub>-<var>d</var></sub>,
- * where <var>d</var> is the number of hash functions specified at creation time, if
- * the number of the elements in the filter is less than <var>n</var>, the number
- * of expected elements specified at creation time.
- *
- * @param s a character sequence.
- * @return true if the sequence is in the filter (or if a sequence with the
- * same hash sequence is in the filter).
- */
-
- public boolean contains( final CharSequence s ) {
- int i = d, l = s.length();
- while( i-- != 0 ) if ( ! getBit( hash( s, l, i ) ) ) return false;
- return true;
- }
-
- /** Adds a character sequence to the filter.
- *
- * @param s a character sequence.
- * @return true if the character sequence was not in the filter (but see {@link #contains(CharSequence)}).
- */
-
- public boolean add( final CharSequence s ) {
- boolean result = false;
- int i = d, l = s.length();
- long h;
- while( i-- != 0 ) {
- h = hash( s, l, i );
- if ( ! getBit( h ) ) result = true;
- setBit( h );
- }
- if ( result ) size++;
- return result;
- }
-
- protected final static long ADDRESS_BITS_PER_UNIT = 5; // 32=2^5
- protected final static long BIT_INDEX_MASK = 31; // = BITS_PER_UNIT - 1;
-
- /**
- * Returns from the local bitvector the value of the bit with
- * the specified index. The value is <tt>true</tt> if the bit
- * with the index <tt>bitIndex</tt> is currently set; otherwise,
- * returns <tt>false</tt>.
- *
- * (adapted from cern.colt.bitvector.QuickBitVector)
- *
- * @param bitIndex the bit index.
- * @return the value of the bit with the specified index.
- */
- protected boolean getBit(long bitIndex) {
- return ((bits[(int)(bitIndex >> ADDRESS_BITS_PER_UNIT)] & (1 << (bitIndex & BIT_INDEX_MASK))) != 0);
- }
-
- /**
- * Changes the bit with index <tt>bitIndex</tt> in local bitvector.
- *
- * (adapted from cern.colt.bitvector.QuickBitVector)
- *
- * @param bitIndex the index of the bit to be set.
- */
- protected void setBit(long bitIndex) {
- bits[(int)(bitIndex >> ADDRESS_BITS_PER_UNIT)] |= 1 << (bitIndex & BIT_INDEX_MASK);
- }
-
- /* (non-Javadoc)
- * @see org.archive.util.BloomFilter#getSizeBytes()
- */
- public long getSizeBytes() {
- return bits.length*4;
- }
-}
diff --git a/commons/src/main/java/org/archive/util/BloomFilter32bitSplit.java b/commons/src/main/java/org/archive/util/BloomFilter32bitSplit.java
deleted file mode 100644
index fd71c8847..000000000
--- a/commons/src/main/java/org/archive/util/BloomFilter32bitSplit.java
+++ /dev/null
@@ -1,251 +0,0 @@
-/* BloomFilter32bit
-*
-* $Id$
-*
-* Created on Jun 21, 2005
-*
-* Copyright (C) 2005 Internet Archive; a slight adaptation of
-* LGPL work (C) Sebastiano Vigna
-*
-* This file is part of the Heritrix web crawler (crawler.archive.org).
-*
-* Heritrix is free software; you can redistribute it and/or modify
-* it under the terms of the GNU Lesser Public License as published by
-* the Free Software Foundation; either version 2.1 of the License, or
-* any later version.
-*
-* Heritrix 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 Public License for more details.
-*
-* You should have received a copy of the GNU Lesser Public License
-* along with Heritrix; if not, write to the Free Software
-* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-*/
-
-package org.archive.util;
-
-import java.io.Serializable;
-import java.security.SecureRandom;
-
-/** A Bloom filter.
- *
- * SLIGHTLY ADAPTED VERSION OF MG4J it.unimi.dsi.mg4j.util.BloomFilter
- *
- * <p>KEY CHANGES:
- *
- * <ul>
- * <li>Adapted to use 32bit ops as much as possible... may be slightly
- * faster on 32bit hardware/OS</li>
- * <li>NUMBER_OF_WEIGHTS is 2083, to better avoid collisions between
- * similar strings</li>
- * <li>Removed dependence on cern.colt MersenneTwister (replaced with
- * SecureRandom) and QuickBitVector (replaced with local methods).</li>
- * </ul>
- *
- * <hr>
- *
- * <P>Instances of this class represent a set of character sequences (with false positives)
- * using a Bloom filter. Because of the way Bloom filters work,
- * you cannot remove elements.
- *
- * <P>Bloom filters have an expected error rate, depending on the number
- * of hash functions used, on the filter size and on the number of elements in the filter. This implementation
- * uses a variable optimal number of hash functions, depending on the expected
- * number of elements. More precisely, a Bloom
- * filter for <var>n</var> character sequences with <var>d</var> hash functions will use
- * ln 2 <var>d</var><var>n</var> ≈ 1.44 <var>d</var><var>n</var> bits;
- * false positives will happen with probability 2<sup>-<var>d</var></sup>.
- *
- * <P>Hash functions are generated at creation time using universal hashing. Each hash function
- * uses {@link #NUMBER_OF_WEIGHTS} random integers, which are cyclically multiplied by
- * the character codes in a character sequence. The resulting integers are XOR-ed together.
- *
- * <P>This class exports access methods that are very similar to those of {@link java.util.Set},
- * but it does not implement that interface, as too many non-optional methods
- * would be unimplementable (e.g., iterators).
- *
- * @author Sebastiano Vigna
- */
-public class BloomFilter32bitSplit implements Serializable, BloomFilter {
-
- private static final long serialVersionUID = -164106965277863971L;
-
- /** The number of weights used to create hash functions. */
- final public static int NUMBER_OF_WEIGHTS = 2083; // CHANGED FROM 16
- /** The number of bits in this filter. */
- final public long m;
- /** The number of hash functions used by this filter. */
- final public int d;
- /** The underlying bit vectorS. */
-// final private int[] bits;
- final private int[][] bits;
- /** The random integers used to generate the hash functions. */
- final private int[][] weight;
-
- /** The number of elements currently in the filter. It may be
- * smaller than the actual number of additions of distinct character
- * sequences because of false positives.
- */
- private int size;
-
- /** The natural logarithm of 2, used in the computation of the number of bits. */
- private final static double NATURAL_LOG_OF_2 = Math.log( 2 );
-
- /** number of ints in 1MB. */
- private final static int ONE_MB_INTS = 1 << 18; //
-
- private final static boolean DEBUG = false;
-
- /** Creates a new Bloom filter with given number of hash functions and expected number of elements.
- *
- * @param n the expected number of elements.
- * @param d the number of hash functions; if the filter add not more than <code>n</code> elements,
- * false positives will happen with probability 2<sup>-<var>d</var></sup>.
- */
- public BloomFilter32bitSplit( final int n, final int d ) {
- this.d = d;
- int len =
- (int)Math.ceil( ( (long)n * (long)d / NATURAL_LOG_OF_2 ) / 32 );
- // round up to ensure divisible into 1MiB chunks
- len = ((len / ONE_MB_INTS)+1)*ONE_MB_INTS;
- this.m = len*32L;
- if ( m >= 1L<<54 ) {
- throw new IllegalArgumentException( "This filter would require " + m + " bits" );
- }
-// bits = new int[ len ];
- bits = new int[ len/ONE_MB_INTS ][ONE_MB_INTS];
-
- if ( DEBUG ) System.err.println( "Number of bits: " + m );
-
- // seeded for reproduceable behavior in repeated runs; BUT:
- // SecureRandom's default implementation (as of 1.5)
- // seems to mix in its own seeding.
- final SecureRandom random = new SecureRandom(new byte[] {19,96});
- weight = new int[ d ][];
- for( int i = 0; i < d; i++ ) {
- weight[ i ] = new int[ NUMBER_OF_WEIGHTS ];
- for( int j = 0; j < NUMBER_OF_WEIGHTS; j++ )
- weight[ i ][ j ] = random.nextInt();
- }
- }
-
- /** The number of character sequences in the filter.
- *
- * @return the number of character sequences in the filter (but see {@link #contains(CharSequence)}).
- */
-
- public int size() {
- return size;
- }
-
- /** Hashes the given sequence with the given hash function.
- *
- * @param s a character sequence.
- * @param l the length of <code>s</code>.
- * @param k a hash function index (smaller than {@link #d}).
- * @return the position in the filter corresponding to <code>s</code> for the hash function <code>k</code>.
- */
- private long hash( final CharSequence s, final int l, final int k ) {
- final int[] w = weight[ k ];
- int h = 0, i = l;
- while( i-- != 0 ) h ^= s.charAt( i ) * w[ i % NUMBER_OF_WEIGHTS ];
- return ((long)h-Integer.MIN_VALUE) % m;
- }
-
- /** Checks whether the given character sequence is in this filter.
- *
- * <P>Note that this method may return true on a character sequence that is has
- * not been added to the filter. This will happen with probability 2<sub>-<var>d</var></sub>,
- * where <var>d</var> is the number of hash functions specified at creation time, if
- * the number of the elements in the filter is less than <var>n</var>, the number
- * of expected elements specified at creation time.
- *
- * @param s a character sequence.
- * @return true if the sequence is in the filter (or if a sequence with the
- * same hash sequence is in the filter).
- */
-
- public boolean contains( final CharSequence s ) {
- int i = d, l = s.length();
- while( i-- != 0 ) if ( ! getBit( hash( s, l, i ) ) ) return false;
- return true;
- }
-
- /** Adds a character sequence to the filter.
- *
- * @param s a character sequence.
- * @return true if the character sequence was not in the filter (but see {@link #contains(CharSequence)}).
- */
-
- public boolean add( final CharSequence s ) {
- boolean result = false;
- int i = d, l = s.length();
- long h;
- while( i-- != 0 ) {
- h = hash( s, l, i );
- if ( ! setGetBit( h ) ) result = true;
- }
- if ( result ) size++;
- return result;
- }
-
- protected final static long ADDRESS_BITS_PER_UNIT = 5; // 32=2^5
- protected final static long BIT_INDEX_MASK = 31; // = BITS_PER_UNIT - 1;
-
- /**
- * Returns from the local bitvector the value of the bit with
- * the specified index. The value is <tt>true</tt> if the bit
- * with the index <tt>bitIndex</tt> is currently set; otherwise,
- * returns <tt>false</tt>.
- *
- * (adapted from cern.colt.bitvector.QuickBitVector)
- *
- * @param bitIndex the bit index.
- * @return the value of the bit with the specified index.
- */
- protected boolean getBit(long bitIndex) {
- long intIndex = (bitIndex >>> ADDRESS_BITS_PER_UNIT);
- return ((bits[(int)(intIndex / ONE_MB_INTS)][(int)(intIndex % ONE_MB_INTS)]
- & (1 << (bitIndex & BIT_INDEX_MASK))) != 0);
- }
-
- /**
- * Changes the bit with index <tt>bitIndex</tt> in local bitvector.
- *
- * (adapted from cern.colt.bitvector.QuickBitVector)
- *
- * @param bitIndex the index of the bit to be set.
- */
- protected void setBit(long bitIndex) {
- long intIndex = (bitIndex >>> ADDRESS_BITS_PER_UNIT);
- bits[(int)(intIndex / ONE_MB_INTS)][(int)(intIndex % ONE_MB_INTS)]
- |= 1 << (bitIndex & BIT_INDEX_MASK);
- }
-
- /**
- * Sets the bit with index <tt>bitIndex</tt> in local bitvector --
- * returning the old value.
- *
- * (adapted from cern.colt.bitvector.QuickBitVector)
- *
- * @param bitIndex the index of the bit to be set.
- */
- protected boolean setGetBit(long bitIndex) {
- long intIndex = (int) (bitIndex >>> ADDRESS_BITS_PER_UNIT);
- int a = (int)(intIndex / ONE_MB_INTS);
- int b = (int)(intIndex % ONE_MB_INTS);
- int mask = 1 << (bitIndex & BIT_INDEX_MASK);
- boolean ret = ((bits[a][b] & (mask)) != 0);
- bits[a][b] |= mask;
- return ret;
- }
-
- /* (non-Javadoc)
- * @see org.archive.util.BloomFilter#getSizeBytes()
- */
- public long getSizeBytes() {
- return bits.length*bits[0].length*4;
- }
-}
diff --git a/commons/src/main/java/org/archive/util/BloomFilter32bp2.java b/commons/src/main/java/org/archive/util/BloomFilter32bp2.java
deleted file mode 100644
index ffa64d667..000000000
--- a/commons/src/main/java/org/archive/util/BloomFilter32bp2.java
+++ /dev/null
@@ -1,235 +0,0 @@
-/* BloomFilter
-*
-* $Id$
-*
-* Created on Jun 21, 2005
-*
-* Copyright (C) 2005 Internet Archive; a slight adaptation of
-* LGPL work (C) Sebastiano Vigna
-*
-* This file is part of the Heritrix web crawler (crawler.archive.org).
-*
-* Heritrix is free software; you can redistribute it and/or modify
-* it under the terms of the GNU Lesser Public License as published by
-* the Free Software Foundation; either version 2.1 of the License, or
-* any later version.
-*
-* Heritrix 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 Public License for more details.
-*
-* You should have received a copy of the GNU Lesser Public License
-* along with Heritrix; if not, write to the Free Software
-* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-*/
-
-package org.archive.util;
-
-import java.io.Serializable;
-import java.security.SecureRandom;
-
-/** A Bloom filter.
- *
- * SLIGHTLY ADAPTED VERSION OF MG4J it.unimi.dsi.mg4j.util.BloomFilter
- *
- * <p>KEY CHANGES:
- *
- * <ul>
- * <li>Adapted to use 32bit ops as much as possible... may be slightly
- * faster on 32bit hardware/OS</li>
- * <li>Changed to use bitfield that is a power-of-two in size, allowing
- * hash() to use bitshifting rather than modulus... may be slightly
- * faster</li>
- * <li>NUMBER_OF_WEIGHTS is 2083, to better avoid collisions between
- * similar strings</li>
- * <li>Removed dependence on cern.colt MersenneTwister (replaced with
- * SecureRandom) and QuickBitVector (replaced with local methods).</li>
- * </ul>
- *
- * <hr>
- *
- * <P>Instances of this class represent a set of character sequences (with false positives)
- * using a Bloom filter. Because of the way Bloom filters work,
- * you cannot remove elements.
- *
- * <P>Bloom filters have an expected error rate, depending on the number
- * of hash functions used, on the filter size and on the number of elements in the filter. This implementation
- * uses a variable optimal number of hash functions, depending on the expected
- * number of elements. More precisely, a Bloom
- * filter for <var>n</var> character sequences with <var>d</var> hash functions will use
- * ln 2 <var>d</var><var>n</var> ≈ 1.44 <var>d</var><var>n</var> bits;
- * false positives will happen with probability 2<sup>-<var>d</var></sup>.
- *
- * <P>Hash functions are generated at creation time using universal hashing. Each hash function
- * uses {@link #NUMBER_OF_WEIGHTS} random integers, which are cyclically multiplied by
- * the character codes in a character sequence. The resulting integers are XOR-ed together.
- *
- * <P>This class exports access methods that are very similar to those of {@link java.util.Set},
- * but it does not implement that interface, as too many non-optional methods
- * would be unimplementable (e.g., iterators).
- *
- * @author Sebastiano Vigna
- */
-public class BloomFilter32bp2 implements Serializable, BloomFilter {
-
- private static final long serialVersionUID = -2292902803681146635L;
-
- /** The number of weights used to create hash functions. */
- final public static int NUMBER_OF_WEIGHTS = 2083; // CHANGED FROM 16
- /** The number of bits in this filter. */
- final public long m;
- /** the power-of-two that m is */
- final public long power; // 1<<power == m
- /** The number of hash functions used by this filter. */
- final public int d;
- /** The underlying bit vectorS. */
- final private int[] bits;
- /** The random integers used to generate the hash functions. */
- final private int[][] weight;
-
- /** The number of elements currently in the filter. It may be
- * smaller than the actual number of additions of distinct character
- * sequences because of false positives.
- */
- private int size;
-
- /** The natural logarithm of 2, used in the computation of the number of bits. */
- private final static double NATURAL_LOG_OF_2 = Math.log( 2 );
-
- private final static boolean DEBUG = false;
-
- /** Creates a new Bloom filter with given number of hash functions and expected number of elements.
- *
- * @param n the expected number of elements.
- * @param d the number of hash functions; if the filter add not more than <code>n</code> elements,
- * false positives will happen with probability 2<sup>-<var>d</var></sup>.
- */
- public BloomFilter32bp2( final int n, final int d ) {
- this.d = d;
- long minBits = (long) ((long)n * (long)d / NATURAL_LOG_OF_2);
- long pow = 0;
- while((1L<<pow) < minBits) {
- pow++;
- }
- this.power = pow;
- this.m = 1L<<pow;
- int len = (int) (m / 32);
- if ( m > 1L<<32 ) {
- throw new IllegalArgumentException( "This filter would require " + m + " bits" );
- }
- System.out.println("power "+power+" bits "+m+" len "+len);
-
- bits = new int[ len ];
-
- if ( DEBUG ) System.err.println( "Number of bits: " + m );
-
- // seeded for reproduceable behavior in repeated runs; BUT:
- // SecureRandom's default implementation (as of 1.5)
- // seems to mix in its own seeding.
- final SecureRandom random = new SecureRandom(new byte[] {19,96});
- weight = new int[ d ][];
- for( int i = 0; i < d; i++ ) {
- weight[ i ] = new int[ NUMBER_OF_WEIGHTS ];
- for( int j = 0; j < NUMBER_OF_WEIGHTS; j++ )
- weight[ i ][ j ] = random.nextInt();
- }
- }
-
- /** The number of character sequences in the filter.
- *
- * @return the number of character sequences in the filter (but see {@link #contains(CharSequence)}).
- */
-
- public int size() {
- return size;
- }
-
- /** Hashes the given sequence with the given hash function.
- *
- * @param s a character sequence.
- * @param l the length of <code>s</code>.
- * @param k a hash function index (smaller than {@link #d}).
- * @return the position in the filter corresponding to <code>s</code> for the hash function <code>k</code>.
- */
- private int hash( final CharSequence s, final int l, final int k ) {
- final int[] w = weight[ k ];
- int h = 0, i = l;
- while( i-- != 0 ) h ^= s.charAt( i ) * w[ i % NUMBER_OF_WEIGHTS ];
- return h >>> (32-power);
- }
-
- /** Checks whether the given character sequence is in this filter.
- *
- * <P>Note that this method may return true on a character sequence that is has
- * not been added to the filter. This will happen with probability 2<sub>-<var>d</var></sub>,
- * where <var>d</var> is the number of hash functions specified at creation time, if
- * the number of the elements in the filter is less than <var>n</var>, the number
- * of expected elements specified at creation time.
- *
- * @param s a character sequence.
- * @return true if the sequence is in the filter (or if a sequence with the
- * same hash sequence is in the filter).
- */
-
- public boolean contains( final CharSequence s ) {
- int i = d, l = s.length();
- while( i-- != 0 ) if ( ! getBit( hash( s, l, i ) ) ) return false;
- return true;
- }
-
- /** Adds a character sequence to the filter.
- *
- * @param s a character sequence.
- * @return true if the character sequence was not in the filter (but see {@link #contains(CharSequence)}).
- */
-
- public boolean add( final CharSequence s ) {
- boolean result = false;
- int i = d, l = s.length();
- int h;
- while( i-- != 0 ) {
- h = hash( s, l, i );
- if ( ! getBit( h ) ) result = true;
- setBit( h );
- }
- if ( result ) size++;
- return result;
- }
-
- protected final static int ADDRESS_BITS_PER_UNIT = 5; // 32=2^5
- protected final static int BIT_INDEX_MASK = 31; // = BITS_PER_UNIT - 1;
-
- /**
- * Returns from the local bitvector the value of the bit with
- * the specified index. The value is <tt>true</tt> if the bit
- * with the index <tt>bitIndex</tt> is currently set; otherwise,
- * returns <tt>false</tt>.
- *
- * (adapted from cern.colt.bitvector.QuickBitVector)
- *
- * @param bitIndex the bit index.
- * @return the value of the bit with the specified index.
- */
- protected boolean getBit(int bitIndex) {
- return ((bits[(int)(bitIndex >>> ADDRESS_BITS_PER_UNIT)] & (1 << (bitIndex & BIT_INDEX_MASK))) != 0);
- }
-
- /**
- * Changes the bit with index <tt>bitIndex</tt> in local bitvector.
- *
- * (adapted from cern.colt.bitvector.QuickBitVector)
- *
- * @param bitIndex the index of the bit to be set.
- */
- protected void setBit(int bitIndex) {
- bits[(int)(bitIndex >>> ADDRESS_BITS_PER_UNIT)] |= 1 << (bitIndex & BIT_INDEX_MASK);
- }
-
- /* (non-Javadoc)
- * @see org.archive.util.BloomFilter#getSizeBytes()
- */
- public long getSizeBytes() {
- return bits.length*4;
- }
-}
diff --git a/commons/src/main/java/org/archive/util/BloomFilter32bp2Split.java b/commons/src/main/java/org/archive/util/BloomFilter32bp2Split.java
deleted file mode 100644
index aba45f75f..000000000
--- a/commons/src/main/java/org/archive/util/BloomFilter32bp2Split.java
+++ /dev/null
@@ -1,262 +0,0 @@
-/* BloomFilter
-*
-* $Id$
-*
-* Created on Jun 21, 2005
-*
-* Copyright (C) 2005 Internet Archive; a slight adaptation of
-* LGPL work (C) Sebastiano Vigna
-*
-* This file is part of the Heritrix web crawler (crawler.archive.org).
-*
-* Heritrix is free software; you can redistribute it and/or modify
-* it under the terms of the GNU Lesser Public License as published by
-* the Free Software Foundation; either version 2.1 of the License, or
-* any later version.
-*
-* Heritrix 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 Public License for more details.
-*
-* You should have received a copy of the GNU Lesser Public License
-* along with Heritrix; if not, write to the Free Software
-* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-*/
-
-package org.archive.util;
-
-import java.io.Serializable;
-import java.security.SecureRandom;
-
-/** A Bloom filter.
- *
- * SLIGHTLY ADAPTED VERSION OF MG4J it.unimi.dsi.mg4j.util.BloomFilter
- *
- * <p>KEY CHANGES:
- *
- * <ul>
- * <li>Adapted to use 32bit ops as much as possible... may be slightly
- * faster on 32bit hardware/OS</li>
- * <li>Changed to use bitfield that is a power-of-two in size, allowing
- * hash() to use bitshifting rather than modulus... may be slightly
- * faster</li>
- * <li>NUMBER_OF_WEIGHTS is 2083, to better avoid collisions between
- * similar strings</li>
- * <li>Removed dependence on cern.colt MersenneTwister (replaced with
- * SecureRandom) and QuickBitVector (replaced with local methods).</li>
- * </ul>
- *
- * <hr>
- *
- * <P>Instances of this class represent a set of character sequences (with false positives)
- * using a Bloom filter. Because of the way Bloom filters work,
- * you cannot remove elements.
- *
- * <P>Bloom filters have an expected error rate, depending on the number
- * of hash functions used, on the filter size and on the number of elements in the filter. This implementation
- * uses a variable optimal number of hash functions, depending on the expected
- * number of elements. More precisely, a Bloom
- * filter for <var>n</var> character sequences with <var>d</var> hash functions will use
- * ln 2 <var>d</var><var>n</var> ≈ 1.44 <var>d</var><var>n</var> bits;
- * false positives will happen with probability 2<sup>-<var>d</var></sup>.
- *
- * <P>Hash functions are generated at creation time using universal hashing. Each hash function
- * uses {@link #NUMBER_OF_WEIGHTS} random integers, which are cyclically multiplied by
- * the character codes in a character sequence. The resulting integers are XOR-ed together.
- *
- * <P>This class exports access methods that are very similar to those of {@link java.util.Set},
- * but it does not implement that interface, as too many non-optional methods
- * would be unimplementable (e.g., iterators).
- *
- * @author Sebastiano Vigna
- */
-public class BloomFilter32bp2Split implements Serializable, BloomFilter {
-
- private static final long serialVersionUID = -1504889954381695129L;
-
- /** The number of weights used to create hash functions. */
- final public static int NUMBER_OF_WEIGHTS = 2083; // CHANGED FROM 16
- /** The number of bits in this filter. */
- final public long m;
- /** the power-of-two that m is */
- final public long power; // 1<<power == m
- /** The number of hash functions used by this filter. */
- final public int d;
- /** The underlying bit vectorS. */
- final private int[][] bits;
- /** Bitshift to get first index */
- final private int aShift;
- /** Mask to get second index */
- final private int bMask;
- /** The random integers used to generate the hash functions. */
- final private int[][] weight;
-
- /** The number of elements currently in the filter. It may be
- * smaller than the actual number of additions of distinct character
- * sequences because of false positives.
- */
- private int size;
-
- /** The natural logarithm of 2, used in the computation of the number of bits. */
- private final static double NATURAL_LOG_OF_2 = Math.log( 2 );
-
- private final static boolean DEBUG = false;
-
- /** Creates a new Bloom filter with given number of hash functions and expected number of elements.
- *
- * @param n the expected number of elements.
- * @param d the number of hash functions; if the filter add not more than <code>n</code> elements,
- * false positives will happen with probability 2<sup>-<var>d</var></sup>.
- */
- public BloomFilter32bp2Split( final int n, final int d ) {
- this.d = d;
- long minBits = (long) ((long)n * (long)d / NATURAL_LOG_OF_2);
- long pow = 0;
- while((1L<<pow) < minBits) {
- pow++;
- }
- this.power = pow;
- this.m = 1L<<pow;
- int len = (int) (m / 32);
- if ( m > 1L<<32 ) {
- throw new IllegalArgumentException( "This filter would require " + m + " bits" );
- }
-
- aShift = (int) (pow - ADDRESS_BITS_PER_UNIT - 8);
- bMask = (1<<aShift) - 1;
- bits = new int[256][ 1<<aShift ];
-
- System.out.println("power "+power+" bits "+m+" len "+len);
- System.out.println("aShift "+aShift+" bMask "+bMask);
-
- if ( DEBUG ) System.err.println( "Number of bits: " + m );
-
- // seeded for reproduceable behavior in repeated runs; BUT:
- // SecureRandom's default implementation (as of 1.5)
- // seems to mix in its own seeding.
- final SecureRandom random = new SecureRandom(new byte[] {19,96});
- weight = new int[ d ][];
- for( int i = 0; i < d; i++ ) {
- weight[ i ] = new int[ NUMBER_OF_WEIGHTS ];
- for( int j = 0; j < NUMBER_OF_WEIGHTS; j++ )
- weight[ i ][ j ] = random.nextInt();
- }
- }
-
- /** The number of character sequences in the filter.
- *
- * @return the number of character sequences in the filter (but see {@link #contains(CharSequence)}).
- */
-
- public int size() {
- return size;
- }
-
- /** Hashes the given sequence with the given hash function.
- *
- * @param s a character sequence.
- * @param l the length of <code>s</code>.
- * @param k a hash function index (smaller than {@link #d}).
- * @return the position in the filter corresponding to <code>s</code> for the hash function <code>k</code>.
- */
- private int hash( final CharSequence s, final int l, final int k ) {
- final int[] w = weight[ k ];
- int h = 0, i = l;
- while( i-- != 0 ) h ^= s.charAt( i ) * w[ i % NUMBER_OF_WEIGHTS ];
- return h >>> (32-power);
- }
-
- /** Checks whether the given character sequence is in this filter.
- *
- * <P>Note that this method may return true on a character sequence that is has
- * not been added to the filter. This will happen with probability 2<sub>-<var>d</var></sub>,
- * where <var>d</var> is the number of hash functions specified at creation time, if
- * the number of the elements in the filter is less than <var>n</var>, the number
- * of expected elements specified at creation time.
- *
- * @param s a character sequence.
- * @return true if the sequence is in the filter (or if a sequence with the
- * same hash sequence is in the filter).
- */
-
- public boolean contains( final CharSequence s ) {
- int i = d, l = s.length();
- while( i-- != 0 ) if ( ! getBit( hash( s, l, i ) ) ) return false;
- return true;
- }
-
- /** Adds a character sequence to the filter.
- *
- * @param s a character sequence.
- * @return true if the character sequence was not in the filter (but see {@link #contains(CharSequence)}).
- */
-
- public boolean add( final CharSequence s ) {
- boolean result = false;
- int i = d, l = s.length();
- int h;
- while( i-- != 0 ) {
- h = hash( s, l, i );
- if ( ! setGetBit( h ) ) result = true;
- }
- if ( result ) size++;
- return result;
- }
-
- protected final static int ADDRESS_BITS_PER_UNIT = 5; // 32=2^5
- protected final static int BIT_INDEX_MASK = 31; // = BITS_PER_UNIT - 1;
-
- /**
- * Returns from the local bitvector the value of the bit with
- * the specified index. The value is <tt>true</tt> if the bit
- * with the index <tt>bitIndex</tt> is currently set; otherwise,
- * returns <tt>false</tt>.
- *
- * (adapted from cern.colt.bitvector.QuickBitVector)
- *
- * @param bitIndex the bit index.
- * @return the value of the bit with the specified index.
- */
- protected boolean getBit(int bitIndex) {
- int intIndex = (int)(bitIndex >>> ADDRESS_BITS_PER_UNIT);
- return ((bits[intIndex>>>aShift][intIndex&bMask] & (1 << (bitIndex & BIT_INDEX_MASK))) != 0);
- }
-
- /**
- * Changes the bit with index <tt>bitIndex</tt> in local bitvector.
- *
- * (adapted from cern.colt.bitvector.QuickBitVector)
- *
- * @param bitIndex the index of the bit to be set.
- */
- protected void setBit(int bitIndex) {
- int intIndex = (int)(bitIndex >>> ADDRESS_BITS_PER_UNIT);
- bits[intIndex>>>aShift][intIndex&bMask] |= 1 << (bitIndex & BIT_INDEX_MASK);
- }
-
- /**
- * Sets the bit with index <tt>bitIndex</tt> in local bitvector --
- * returning the old value.
- *
- * (adapted from cern.colt.bitvector.QuickBitVector)
- *
- * @param bitIndex the index of the bit to be set.
- */
- protected boolean setGetBit(int bitIndex) {
- int intIndex = (int)(bitIndex >>> ADDRESS_BITS_PER_UNIT);
- int a = intIndex>>>aShift;
- int b = intIndex&bMask;
- int mask = 1 << (bitIndex & BIT_INDEX_MASK);
- boolean ret = ((bits[a][b] & (mask)) != 0);
- bits[a][b] |= mask;
- return ret;
- }
-
- /* (non-Javadoc)
- * @see org.archive.util.BloomFilter#getSizeBytes()
- */
- public long getSizeBytes() {
- return bits.length*bits[0].length*4;
- }
-}
diff --git a/commons/src/main/java/org/archive/util/BloomFilter64bit.java b/commons/src/main/java/org/archive/util/BloomFilter64bit.java
index 97b0d06e1..aeca26ed2 100644
--- a/commons/src/main/java/org/archive/util/BloomFilter64bit.java
+++ b/commons/src/main/java/org/archive/util/BloomFilter64bit.java
@@ -28,104 +28,165 @@
import java.io.Serializable;
import java.security.SecureRandom;
+import java.util.Random;
/** A Bloom filter.
*
- * SLIGHTLY ADAPTED VERSION OF MG4J it.unimi.dsi.mg4j.util.BloomFilter
+ * ADAPTED/IMPROVED VERSION OF MG4J it.unimi.dsi.mg4j.util.BloomFilter
*
* <p>KEY CHANGES:
*
* <ul>
* <li>NUMBER_OF_WEIGHTS is 2083, to better avoid collisions between
- * similar strings</li>
+ * similar strings (common in the domain of URIs)</li>
+ *
* <li>Removed dependence on cern.colt MersenneTwister (replaced with
* SecureRandom) and QuickBitVector (replaced with local methods).</li>
- * <li>Adapted to allow long bit indices so long as the index/64 (used
- * an array index in bit vector) fits within Integer.MAX_VALUE. (Thus
- * it supports filters up to 64*Integer.MAX_VALUE bits in size, or
- * 16GiB.)</li>
+ *
+ * <li>Adapted to allow long bit indices</li>
+ *
+ * <li>Stores bitfield in an array of up to 2^22 arrays of 2^26 longs. Thus,
+ * bitfield may grow to 2^48 longs in size -- 2PiB, 2*54 bitfield indexes.
+ * (I expect this will outstrip available RAM for the next few years.)</li>
* </ul>
*
* <hr>
*
- * <P>Instances of this class represent a set of character sequences (with false positives)
- * using a Bloom filter. Because of the way Bloom filters work,
+ * <P>Instances of this class represent a set of character sequences (with
+ * false positives) using a Bloom filter. Because of the way Bloom filters work,
* you cannot remove elements.
*
* <P>Bloom filters have an expected error rate, depending on the number
- * of hash functions used, on the filter size and on the number of elements in the filter. This implementation
- * uses a variable optimal number of hash functions, depending on the expected
- * number of elements. More precisely, a Bloom
- * filter for <var>n</var> character sequences with <var>d</var> hash functions will use
- * ln 2 <var>d</var><var>n</var> ≈ 1.44 <var>d</var><var>n</var> bits;
- * false positives will happen with probability 2<sup>-<var>d</var></sup>.
+ * of hash functions used, on the filter size and on the number of elements in
+ * the filter. This implementation uses a variable optimal number of hash
+ * functions, depending on the expected number of elements. More precisely, a
+ * Bloom filter for <var>n</var> character sequences with <var>d</var> hash
+ * functions will use ln 2 <var>d</var><var>n</var> ≈
+ * 1.44 <var>d</var><var>n</var> bits; false positives will happen with
+ * probability 2<sup>-<var>d</var></sup>.
*
- * <P>Hash functions are generated at creation time using universal hashing. Each hash function
- * uses {@link #NUMBER_OF_WEIGHTS} random integers, which are cyclically multiplied by
- * the character codes in a character sequence. The resulting integers are XOR-ed together.
+ * <P>Hash functions are generated at creation time using universal hashing.
+ * Each hash function uses {@link #NUMBER_OF_WEIGHTS} random integers, which
+ * are cyclically multiplied by the character codes in a character sequence.
+ * The resulting integers are XOR-ed together.
*
- * <P>This class exports access methods that are very similar to those of {@link java.util.Set},
- * but it does not implement that interface, as too many non-optional methods
- * would be unimplementable (e.g., iterators).
+ * <P>This class exports access methods that are very similar to those of
+ * {@link java.util.Set}, but it does not implement that interface, as too
+ * many non-optional methods would be unimplementable (e.g., iterators).
*
* @author Sebastiano Vigna
+ * @contributor Gordon Mohr
*/
public class BloomFilter64bit implements Serializable, BloomFilter {
-
- private static final long serialVersionUID = 2317000663009608403L;
+ private static final long serialVersionUID = 2L;
/** The number of weights used to create hash functions. */
- final public static int NUMBER_OF_WEIGHTS = 2083; // CHANGED FROM 16
+ final static int NUMBER_OF_WEIGHTS = 2083; // CHANGED FROM 16
/** The number of bits in this filter. */
- final public long m;
+ final protected long m;
+ /** if bitfield is an exact power of 2 in length, it is this power */
+ protected int power = -1;
+ /** The expected number of inserts; determines calculated size */
+ final protected long expectedInserts;
/** The number of hash functions used by this filter. */
- final public int d;
- /** The underlying bit vector. package access for testing */
- final long[] bits;
+ final protected int d;
+ /** The underlying bit vector */
+ final protected long[][] bits;
/** The random integers used to generate the hash functions. */
- final long[][] weight;
+ final protected long[][] weight;
/** The number of elements currently in the filter. It may be
* smaller than the actual number of additions of distinct character
* sequences because of false positives.
*/
- private int size;
+ int size;
/** The natural logarithm of 2, used in the computation of the number of bits. */
- private final static double NATURAL_LOG_OF_2 = Math.log( 2 );
+ final static double NATURAL_LOG_OF_2 = Math.log( 2 );
+
+ /** power-of-two to use as maximum size of bitfield subarrays */
+ protected final static int SUBARRAY_POWER_OF_TWO = 26; // 512MiB of longs
+ /** number of longs in one subarray */
+ protected final static int SUBARRAY_LENGTH_IN_LONGS = 1 << SUBARRAY_POWER_OF_TWO;
+ /** mask for lowest SUBARRAY_POWER_OF_TWO bits */
+ protected final static int SUBARRAY_MASK = SUBARRAY_LENGTH_IN_LONGS - 1; //0x0FFFFFFF
- private final static boolean DEBUG = false;
+ final static boolean DEBUG = false;
- /** Creates a new Bloom filter with given number of hash functions and expected number of elements.
+ /** Creates a new Bloom filter with given number of hash functions and
+ * expected number of elements.
+ *
+ * @param n the expected number of elements.
+ * @param d the number of hash functions; if the filter add not more
+ * than <code>n</code> elements, false positives will happen with
+ * probability 2<sup>-<var>d</var></sup>.
+ */
+ public BloomFilter64bit( final long n, final int d) {
+ this(n,d, new SecureRandom(), false);
+ }
+
+ public BloomFilter64bit( final long n, final int d, boolean roundUp) {
+ this(n,d, new SecureRandom(), roundUp);
+ }
+
+ /** Creates a new Bloom filter with given number of hash functions and
+ * expected number of elements.
*
* @param n the expected number of elements.
- * @param d the number of hash functions; if the filter add not more than <code>n</code> elements,
- * false positives will happen with probability 2<sup>-<var>d</var></sup>.
+ * @param d the number of hash functions; if the filter add not more
+ * than <code>n</code> elements, false positives will happen with
+ * probability 2<sup>-<var>d</var></sup>.
+ * @param Random weightsGenerator may provide a seeded Random for reproducible
+ * internal universal hash function weighting
+ * @param roundUp if true, round bit size up to next-nearest-power-of-2
*/
- public BloomFilter64bit( final int n, final int d ) {
+ public BloomFilter64bit( final long n, final int d, Random weightsGenerator, boolean roundUp ) {
+ this.expectedInserts = n;
this.d = d;
- int len = (int)Math.ceil( ( (long)n * (long)d / NATURAL_LOG_OF_2 ) / 64L );
- if ( len/64 > Integer.MAX_VALUE ) throw new IllegalArgumentException( "This filter would require " + len * 64L + " bits" );
- bits = new long[ len ];
- m = bits.length * 64L;
+ long lenInLongs = (long)Math.ceil( ( (long)n * (long)d / NATURAL_LOG_OF_2 ) / 64L );
+ if ( lenInLongs > (1L<<48) ) {
+ throw new IllegalArgumentException(
+ "This filter would require " + lenInLongs + " longs, " +
+ "greater than this classes maximum of 2^48 longs (2PiB)." );
+ }
+ long lenInBits = lenInLongs * 64L;
+
+ if(roundUp) {
+ int pow = 0;
+ while((1L<<pow) < lenInBits) {
+ pow++;
+ }
+ this.power = pow;
+ this.m = 1L<<pow;
+ lenInLongs = m/64L;
+ } else {
+ this.m = lenInBits;
+ }
+
+
+ int arrayOfArraysLength = (int)((lenInLongs+SUBARRAY_LENGTH_IN_LONGS-1)/SUBARRAY_LENGTH_IN_LONGS);
+ bits = new long[ (int)(arrayOfArraysLength) ][];
+ // ensure last subarray is no longer than necessary
+ long lenInLongsRemaining = lenInLongs;
+ for(int i = 0; i < bits.length; i++) {
+ bits[i] = new long[(int)Math.min(lenInLongsRemaining,SUBARRAY_LENGTH_IN_LONGS)];
+ lenInLongsRemaining -= bits[i].length;
+ }
if ( DEBUG ) System.err.println( "Number of bits: " + m );
- // seeded for reproduceable behavior in repeated runs; BUT:
- // SecureRandom's default implementation (as of 1.5)
- // seems to mix in its own seeding.
- final SecureRandom random = new SecureRandom(new byte[] {19,96});
weight = new long[ d ][];
for( int i = 0; i < d; i++ ) {
weight[ i ] = new long[ NUMBER_OF_WEIGHTS ];
for( int j = 0; j < NUMBER_OF_WEIGHTS; j++ )
- weight[ i ][ j ] = random.nextLong();
+ weight[ i ][ j ] = weightsGenerator.nextLong();
}
}
/** The number of character sequences in the filter.
*
- * @return the number of character sequences in the filter (but see {@link #contains(CharSequence)}).
+ * @return the number of character sequences in the filter (but
+ * see {@link #contains(CharSequence)}).
*/
public int size() {
@@ -139,15 +200,29 @@ public int size() {
* @param k a hash function index (smaller than {@link #d}).
* @return the position in the filter corresponding to <code>s</code> for the hash function <code>k</code>.
*/
-
- private long hash( final CharSequence s, final int l, final int k ) {
+ protected long hash( final CharSequence s, final int l, final int k ) {
final long[] w = weight[ k ];
long h = 0;
int i = l;
while( i-- != 0 ) h ^= s.charAt( i ) * w[ i % NUMBER_OF_WEIGHTS ];
- return ( h & 0x7FFFFFFFFFFFFFFFL ) % m;
+ long retVal;
+ if(power>0) {
+ retVal = h >>> (64-power);
+ } else {
+ // ####----####----
+ retVal = ( h & 0x7FFFFFFFFFFFFFFFL ) % m;
+ }
+ return retVal;
}
-
+
+ public long[] bitIndexesFor(CharSequence s) {
+ long[] ret = new long[d];
+ for(int i = 0; i < d; i++) {
+ ret[i] = hash(s,s.length(),i);
+ }
+ return ret;
+ }
+
/** Checks whether the given character sequence is in this filter.
*
* <P>Note that this method may return true on a character sequence that is has
@@ -179,9 +254,8 @@ public boolean add( final CharSequence s ) {
long h;
while( i-- != 0 ) {
h = hash( s, l, i );
- if ( ! getBit( h ) ) {
+ if ( ! setGetBit( h ) ) {
result = true;
- setBit( h );
}
}
if ( result ) size++;
@@ -189,7 +263,7 @@ public boolean add( final CharSequence s ) {
}
protected final static long ADDRESS_BITS_PER_UNIT = 6; // 64=2^6
- protected final static long BIT_INDEX_MASK = 63; // = BITS_PER_UNIT - 1;
+ protected final static long BIT_INDEX_MASK = (1<<6)-1; // = 63 = 2^BITS_PER_UNIT - 1;
/**
* Returns from the local bitvector the value of the bit with
@@ -202,8 +276,11 @@ public boolean add( final CharSequence s ) {
* @param bitIndex the bit index.
* @return the value of the bit with the specified index.
*/
- protected boolean getBit(long bitIndex) {
- return ((bits[(int)(bitIndex >> ADDRESS_BITS_PER_UNIT)] & (1L << (bitIndex & BIT_INDEX_MASK))) != 0);
+ public boolean getBit(long bitIndex) {
+ long longIndex = bitIndex >>> ADDRESS_BITS_PER_UNIT;
+ int arrayIndex = (int) (longIndex >>> SUBARRAY_POWER_OF_TWO);
+ int subarrayIndex = (int) (longIndex & SUBARRAY_MASK);
+ return ((bits[arrayIndex][subarrayIndex] & (1L << (bitIndex & BIT_INDEX_MASK))) != 0);
}
/**
@@ -214,13 +291,45 @@ protected boolean getBit(long bitIndex) {
* @param bitIndex the index of the bit to be set.
*/
protected void setBit( long bitIndex) {
- bits[(int)(bitIndex >> ADDRESS_BITS_PER_UNIT)] |= 1L << (bitIndex & BIT_INDEX_MASK);
+ long longIndex = bitIndex >>> ADDRESS_BITS_PER_UNIT;
+ int arrayIndex = (int) (longIndex >>> SUBARRAY_POWER_OF_TWO);
+ int subarrayIndex = (int) (longIndex & SUBARRAY_MASK);
+ bits[arrayIndex][subarrayIndex] |= (1L << (bitIndex & BIT_INDEX_MASK));
+ }
+
+ /**
+ * Sets the bit with index <tt>bitIndex</tt> in local bitvector --
+ * returning the old value.
+ *
+ * (adapted from cern.colt.bitvector.QuickBitVector)
+ *
+ * @param bitIndex the index of the bit to be set.
+ */
+ protected boolean setGetBit( long bitIndex) {
+ long longIndex = bitIndex >>> ADDRESS_BITS_PER_UNIT;
+ int arrayIndex = (int) (longIndex >>> SUBARRAY_POWER_OF_TWO);
+ int subarrayIndex = (int) (longIndex & SUBARRAY_MASK);
+ long mask = 1L << (bitIndex & BIT_INDEX_MASK);
+ boolean ret = (bits[arrayIndex][subarrayIndex] & mask)!=0;
+ bits[arrayIndex][subarrayIndex] |= mask;
+ return ret;
}
/* (non-Javadoc)
* @see org.archive.util.BloomFilter#getSizeBytes()
*/
public long getSizeBytes() {
- return bits.length*8;
+ // account for ragged-sized last array
+ return 8*(((bits.length-1)*bits[0].length)+bits[bits.length-1].length);
}
+
+ @Override
+ public long getExpectedInserts() {
+ return expectedInserts;
+ }
+
+ @Override
+ public long getHashCount() {
+ return d;
+ }
}
diff --git a/commons/src/main/java/org/archive/util/BenchmarkBlooms.java b/commons/src/test/java/org/archive/util/BenchmarkBlooms.java
similarity index 55%
rename from commons/src/main/java/org/archive/util/BenchmarkBlooms.java
rename to commons/src/test/java/org/archive/util/BenchmarkBlooms.java
index 535564f9a..b3f206787 100644
--- a/commons/src/main/java/org/archive/util/BenchmarkBlooms.java
+++ b/commons/src/test/java/org/archive/util/BenchmarkBlooms.java
@@ -49,35 +49,34 @@ public void instanceMain(String[] args) {
int d_hashes =
(args.length > 2) ? Integer.parseInt(args[2]) : 22;
int adds =
- (args.length > 3) ? Integer.parseInt(args[3]) : 5000000;
+ (args.length > 3) ? Integer.parseInt(args[3]) : 10000000;
+ int contains =
+ (args.length > 4) ? Integer.parseInt(args[4]) : 8000000;
String prefix =
- (args.length > 4) ? args[4] : "http://www.archive.org/";
+ (args.length > 5) ? args[5] : "http://www.archive.org/";
System.out.println(
"reps="+reps+" n_expected="+n_expected+
- " d_hashes="+d_hashes+" adds="+adds+" prefix="+prefix);
+ " d_hashes="+d_hashes+" adds="+adds+
+ " contains="+contains+" prefix="+prefix);
- BloomFilter bloom64;
- BloomFilter bloom32;
- BloomFilter bloom32split;
- BloomFilter bloom32p2;
- BloomFilter bloom32p2split;
+ BloomFilter64bit bloom64;
+// BloomFilter bloom32;
+// BloomFilter bloom32split;
for (int r=0;r<reps;r++) {
- bloom32 = new BloomFilter32bit(n_expected,d_hashes);
- testBloom(bloom32,adds,prefix);
- bloom32=null;
- bloom32split = new BloomFilter32bitSplit(n_expected,d_hashes);
- testBloom(bloom32split,adds,prefix);
- bloom32split=null;
- bloom64 = new BloomFilter64bit(n_expected,d_hashes);
- testBloom(bloom64,adds,prefix);
- bloom64=null;
- bloom32p2 = new BloomFilter32bp2(n_expected,d_hashes);
- testBloom(bloom32p2,adds,prefix);
- bloom32p2=null;
- bloom32p2split = new BloomFilter32bp2Split(n_expected,d_hashes);
- testBloom(bloom32p2split,adds,prefix);
- bloom32p2split=null;
+// bloom32 = new BloomFilter32bit(n_expected,d_hashes);
+// testBloom(bloom32,adds,contains,prefix);
+// bloom32=null;
+// bloom32split = new BloomFilter32bitSplit(n_expected,d_hashes);
+// testBloom(bloom32split,adds,contains,prefix);
+// bloom32split=null;
+ bloom64 = new BloomFilter64bit(n_expected,d_hashes);
+ testBloom(null, bloom64,adds,contains,prefix);
+ bloom64=null;
+ // rounded up to power-of-2 bits size
+ bloom64 = new BloomFilter64bit(n_expected,d_hashes,true);
+ testBloom("bitsize rounded up",bloom64,adds,contains,prefix);
+ bloom64=null;
}
}
@@ -87,19 +86,29 @@ public void instanceMain(String[] args) {
* @param adds
* @param d_hashes
*/
- private void testBloom(BloomFilter bloom, int adds, String prefix) {
+ private void testBloom(String note, BloomFilter bloom, int adds, int contains, String prefix) {
System.gc();
long startTime = System.currentTimeMillis();
- long falsePositives = 0;
- for(int i = 0; i<adds; i++) {
+ long falsePositivesAdds = 0;
+ int i = 0;
+ for(; i<adds; i++) {
if(!bloom.add(prefix+Integer.toString(i))) {
- falsePositives++;
+ falsePositivesAdds++;
}
}
+ long falsPositivesContains = 0;
+ for(; i<(adds+contains); i++) {
+ if(bloom.contains(prefix+Integer.toString(i))) {
+ falsPositivesContains++;
+ }
+ }
long finishTime = System.currentTimeMillis();
- System.out.println(bloom.getClass().getName()+": "
+ System.out.println(bloom.getClass().getName()
+ +((note!=null)?" ("+note+")" : "")
+ +":\n "
+(finishTime-startTime)+"ms "
+bloom.getSizeBytes()+"bytes "
- +falsePositives+"false");
+ +falsePositivesAdds+" falseDuringAdds "
+ +falsPositivesContains+" falseDuringContains ");
}
}
diff --git a/commons/src/test/java/org/archive/util/BloomFilter64bitTest.java b/commons/src/test/java/org/archive/util/BloomFilter64bitTest.java
index e3ba2f5ae..35b0a64ab 100644
--- a/commons/src/test/java/org/archive/util/BloomFilter64bitTest.java
+++ b/commons/src/test/java/org/archive/util/BloomFilter64bitTest.java
@@ -19,7 +19,7 @@
package org.archive.util;
-
+import java.util.Random;
/**
* BloomFilter64 tests
@@ -28,32 +28,8 @@
* @version $Date: 2009-11-19 14:39:53 -0800 (Thu, 19 Nov 2009) $, $Revision: 6674 $
*/
public class BloomFilter64bitTest extends BloomFilterTest {
-
- protected void setUp() throws Exception {
- // test at default size of BloomUriUniqFilter -- but don't depend on that
- // 'engine'-subproject class for values
- bloom = new BloomFilter64bit(125000000,22);
- }
-
- public void testDistributionOfSetBits() {
- // prelaod
- testBasics();
-
- BloomFilter64bit bloom64 = (BloomFilter64bit)bloom;
- for(int i = 0; i<bloom64.bits.length; i++) {
- // verify that first set bit is in first 20% of bitfield
- if(bloom64.bits[i]>0) {
- assertTrue("set bits not as expected in early positions",(i/(double)bloom64.bits.length)<0.2d);
- break;
- }
- }
- for(int i = bloom64.bits.length-1; i>=0; i--) {
- // verify that first set bit is in first 20% of bitfield
- if(bloom64.bits[i]>0) {
- assertTrue("set bits not as expected in late positions",(i/(double)bloom64.bits.length)>0.8d);
- break;
- }
- }
-
+ @Override
+ BloomFilter createBloom(long n, int d, Random weightsGenerator) {
+ return new BloomFilter64bit(n, d, weightsGenerator, false);
}
}
diff --git a/commons/src/test/java/org/archive/util/BloomFilterTest.java b/commons/src/test/java/org/archive/util/BloomFilterTest.java
index d61ecfaef..769b8cefe 100644
--- a/commons/src/test/java/org/archive/util/BloomFilterTest.java
+++ b/commons/src/test/java/org/archive/util/BloomFilterTest.java
@@ -19,39 +19,155 @@
package org.archive.util;
+import java.security.SecureRandom;
+import java.util.Random;
+
import junit.framework.TestCase;
/**
- * BloomFilter tests
+ * BloomFilter tests.
*
* @contributor gojomo
* @version $Date: 2009-11-19 14:39:53 -0800 (Thu, 19 Nov 2009) $, $Revision: 6674 $
*/
public abstract class BloomFilterTest extends TestCase {
- protected BloomFilter bloom;
-
- protected abstract void setUp() throws Exception;
- public void testBasics() {
- // require initial additions to return 'true' (for 'added')
- assertTrue(bloom.add("abracadabra"));
- assertTrue(bloom.add("foobar"));
- assertTrue(bloom.add("rumplestiltskin"));
- assertTrue(bloom.add("buckaroobanzai"));
- assertTrue(bloom.add("scheherazade"));
+ abstract BloomFilter createBloom(long n, int d, Random random);
+
+ protected void trialWithParameters(long targetSize, int hashCount, long addCount, long containsCount) {
+ BloomFilter bloom = createBloom(targetSize,hashCount,new Random(1996L));
+
+ int addFalsePositives = checkAdds(bloom,addCount);
+ checkDistribution(bloom);
+ // this is a *very* rough and *very* lenient upper bound for adds <= targetSize
+ long maxTolerableDuringAdds = addCount / (1<<hashCount);
+ assertTrue(
+ "excessive false positives ("+addFalsePositives+">"+maxTolerableDuringAdds+") during adds",
+ addFalsePositives<10);
- // require readdition to return 'false' (not added because already present)
- assertFalse(bloom.add("abracadabra"));
- assertFalse(bloom.add("foobar"));
- assertFalse(bloom.add("rumplestiltskin"));
- assertFalse(bloom.add("buckaroobanzai"));
- assertFalse(bloom.add("scheherazade"));
+ if(containsCount==0) {
+ return;
+ }
+ int containsFalsePositives = checkContains(bloom,containsCount);
+ // expect at least 0 if bloom wasn't saturated in add phase
+ // if was saturated, expect at least 1/4th of the theoretical 1-in-every-(2<<hashCount)
+ long minTolerableDuringContains = (addCount < targetSize) ? 0 : containsCount / ((1<<hashCount) * 4);
+ // expect no more than 4 times the theoretical-at-saturation
+ long maxTolerableDuringContains = containsCount * 4 / (1<<hashCount);
+ assertTrue(
+ "excessive false positives ("+containsFalsePositives+">"+maxTolerableDuringContains+") during contains",
+ containsFalsePositives<=maxTolerableDuringContains); // no more than double expected 1-in-4mil
+ assertTrue(
+ "missing false positives ("+containsFalsePositives+"<"+minTolerableDuringContains+") during contains",
+ containsFalsePositives>=minTolerableDuringContains); // should be at least a couple
+ }
+
+ /**
+ * Test very-large (almost 800MB, spanning more than Integer.MAX_VALUE bit
+ * indexes) bloom at saturation for expected behavior and level of
+ * false-positives.
+ *
+ * Renamed to non-'test' name so not automatically run, because can
+ * take 15+ minutes to complete.
+ */
+ public void testOversized() {
+ trialWithParameters(200000000,22,200000000,32000000);
+ }
+
+ /**
+ * Test large (495MB), default-sized bloom at saturation for
+ * expected behavior and level of false-positives.
+ *
+ * Renamed to non-'test' name so not automatically run, because can
+ * take 15+ minutes to complete.
+ */
+ public void testDefaultFull() {
+ trialWithParameters(125000000,22,125000000,34000000);
+ }
+
+ public void testDefaultAbbreviated() {
+ trialWithParameters(125000000,22,17000000,0);
+ }
+
+ public void testSmall() {
+ trialWithParameters(10000000, 20, 10000000, 10000000);
+ }
+
+ /**
+ * Check that the given filter behaves properly as a large number of
+ * constructed unique strings are added: responding positively to
+ * contains, and negatively to redundant adds. Assuming that the filter
+ * was empty before it was called, any add()s that report the string was
+ * already present are false-positives; report the total of same so the
+ * caller can evaluate if that level was suspiciously out of the expected
+ * error rate.
+ *
+ * @param bloom BloomFilter to check
+ * @param count int number of unique strings to check
+ * @return
+ */
+ protected int checkAdds(BloomFilter bloom, long count) {
+ int falsePositives = 0;
+ for(int i = 0; i < count; i++) {
+ String str = "add"+Integer.toString(i);
+ if(!bloom.add(str)) {
+ falsePositives++;
+ }
+ assertTrue(bloom.contains(str));
+ assertFalse(str+" not present on re-add",bloom.add(str));
+ }
+ return falsePositives;
+ }
+
+ /**
+ * Check if the given filter contains any of the given constructed
+ * strings. Since the previously-added strings (of checkAdds) were
+ * different from these, *any* positive contains results are
+ * false-positives. Return the total count so that the calling method
+ * can determine if the false-positive rate is outside the expected
+ * range.
+ *
+ * @param bloom BloomFilter to check
+ * @param count int number of unique strings to check
+ * @return
+ */
+ protected int checkContains(BloomFilter bloom, long count) {
+ int falsePositives = 0;
+ for(int i = 0; i < count; i++) {
+ String str = "contains"+Integer.toString(i);
+ if(bloom.contains(str)) {
+ falsePositives++;
+ }
+ }
+ return falsePositives;
}
- @Override
- protected void tearDown() throws Exception {
- super.tearDown();
- bloom = null;
+ /**
+ * Check that the given bloom filter, assumed to have already had a
+ * significant number of items added, has bits set in the lower and upper
+ * 10% of its bit field.
+ *
+ * (This would have caught previous int/long bugs in the filter hashing
+ * or conversion of bit indexes into array indexes and bit masks.)
+ *
+ * @param bloom BloomFilter to check
+ */
+ public void checkDistribution(BloomFilter bloom) {
+ long bitLength = bloom.getSizeBytes() * 8L;
+ for(long i = 0; i<bitLength; i++) {
+ // verify that first set bit is in first 20% of bitfield
+ if(bloom.getBit(i)) {
+ assertTrue("set bits not as expected in early positions",(i/(double)bitLength)<0.1d);
+ break;
+ }
+ }
+ for(long i = bitLength-1; i>=0; i--) {
+ // verify that first set bit is in first 20% of bitfield
+ if(bloom.getBit(i)) {
+ assertTrue("set bits not as expected in late positions",(i/(double)bitLength)>0.1d);
+ break;
+ }
+ }
}
}
diff --git a/engine/src/main/java/org/archive/crawler/util/BloomUriUniqFilter.java b/engine/src/main/java/org/archive/crawler/util/BloomUriUniqFilter.java
index 2b15f5d2d..98120a6e9 100644
--- a/engine/src/main/java/org/archive/crawler/util/BloomUriUniqFilter.java
+++ b/engine/src/main/java/org/archive/crawler/util/BloomUriUniqFilter.java
@@ -47,25 +47,8 @@
* through 125 million unique inserts, which creates a filter structure
* about 495MB in size.
*
- * You may use the following system properties to tune the size and
- * false-positive rate of the bloom filter structure used by this class:
- *
- * org.archive.crawler.util.BloomUriUniqFilter.expected-size (default 125000000)
- * org.archive.crawler.util.BloomUriUniqFilter.hash-count (default 22)
- *
- * The resulting filter will take up approximately...
- *
- * 1.44 * expected-size * hash-count / 8
- *
- * ...bytes.
- *
- * The BloomFilter64bit implementation class supports filters up to
- * 16GiB in size.
- *
- * (If you only need a filter up to 512MiB in size, the
- * BloomFilter32bitSplit *might* offer better performance, on 32bit
- * JVMs or with respect to heap-handling of giant arrays. The only
- * current way to swap in this class is by editing the source.)
+ * You may swap in an differently-configured BloomFilter class to alter
+ * these tradeoffs.
*
* @author gojomo
* @version $Date$, $Revision$
@@ -78,28 +61,13 @@ public class BloomUriUniqFilter extends SetBasedUriUniqFilter
Logger.getLogger(BloomUriUniqFilter.class.getName());
BloomFilter bloom; // package access for testing convenience
-
- // these defaults create a bloom filter that is
- // 1.44*125mil*22/8 ~= 495MB in size, and at full
- // capacity will give a false contained indication
- // 1/(2^22) ~= 1 in every 4 million probes
- protected int expectedInserts= 125000000; // default 125 million;
- public int getExpectedInserts() {
- return expectedInserts;
+ public BloomFilter getBloomFilter() {
+ return bloom;
}
- public void setExpectedInserts(int expectedInserts) {
- this.expectedInserts = expectedInserts;
+ public void setBloomFilter(BloomFilter filter) {
+ bloom = filter;
}
- protected int hashCount = 22; // 1 in 4 million false pos
- public int getHashCount() {
- return hashCount;
- }
- public void setHashCount(int hashCount) {
- this.hashCount = hashCount;
- }
-
-
/**
* Default constructor
*/
@@ -109,14 +77,17 @@ public BloomUriUniqFilter() {
/**
* Initializer.
- *
- * @param n the expected number of elements.
- * @param d the number of hash functions; if the filter adds not more
- * than <code>n</code> elements, false positives will happen with
- * probability 2<sup>-<var>d</var></sup>.
*/
public void afterPropertiesSet() {
- bloom = new BloomFilter64bit(expectedInserts,hashCount);
+ if(bloom==null) {
+ // configure default bloom filter if operator hasn't already
+
+ // these defaults create a bloom filter that is
+ // 1.44*125mil*22/8 ~= 495MB in size, and at full
+ // capacity will give a false contained indication
+ // 1/(2^22) ~= 1 in every 4 million probes
+ bloom = new BloomFilter64bit(125000000,22);
+ }
}
public void forget(String canonical, CrawlURI item) {
@@ -128,8 +99,11 @@ protected boolean setAdd(CharSequence uri) {
boolean added = bloom.add(uri);
// warn if bloom has reached its expected size (and its false-pos
// rate will now exceed the theoretical/designed level)
- if( added && (count() == expectedInserts)) {
- LOGGER.warning("Bloom has reached expected limit "+expectedInserts);
+ if( added && (count() == bloom.getExpectedInserts())) {
+ LOGGER.warning(
+ "Bloom has reached expected limit "+bloom.getExpectedInserts()+
+ "; false-positive rate will now rise above goal of "+
+ "1-in-(2^"+bloom.getHashCount());
}
return added;
}
diff --git a/engine/src/test/java/org/archive/crawler/util/BloomUriUniqFilterTest.java b/engine/src/test/java/org/archive/crawler/util/BloomUriUniqFilterTest.java
index e00511e46..28390704e 100644
--- a/engine/src/test/java/org/archive/crawler/util/BloomUriUniqFilterTest.java
+++ b/engine/src/test/java/org/archive/crawler/util/BloomUriUniqFilterTest.java
@@ -32,6 +32,7 @@
import org.archive.modules.CrawlURI;
import org.archive.net.UURI;
import org.archive.net.UURIFactory;
+import org.archive.util.BloomFilter64bit;
/**
@@ -53,8 +54,7 @@ public class BloomUriUniqFilterTest extends TestCase
protected void setUp() throws Exception {
super.setUp();
this.filter = new BloomUriUniqFilter();
- this.filter.setExpectedInserts(2000);
- this.filter.setHashCount(24);
+ this.filter.setBloomFilter(new BloomFilter64bit(2000, 24));
this.filter.afterPropertiesSet();
this.filter.setDestination(this);
}
|
d52a7d799c2ab73dbc38de272d173bbe9cf08797
|
orientdb
|
Fixed issue reported by Steven about TX- congruency with nested records. The bug was reported in rollback.--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java
index 6f4d86d0df7..b873860ec1c 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java
@@ -795,11 +795,18 @@ public long createRecord(final ORecordId iRid, final byte[] iContent, final byte
ORecordCallback<Long> iCallback) {
checkOpeness();
- iRid.clusterPosition = createRecord(getClusterById(iRid.clusterId), iContent, iRecordType);
+ final OCluster cluster = getClusterById(iRid.clusterId);
+
+ if (txManager.isCommitting())
+ iRid.clusterPosition = txManager
+ .createRecord(txManager.getCurrentTransaction().getId(), cluster, iRid, iContent, iRecordType);
+ else
+ iRid.clusterPosition = createRecord(cluster, iContent, iRecordType);
return iRid.clusterPosition;
}
- public ORawBuffer readRecord(final ORecordId iRid, final String iFetchPlan, boolean iIgnoreCache, ORecordCallback<ORawBuffer> iCallback) {
+ public ORawBuffer readRecord(final ORecordId iRid, final String iFetchPlan, boolean iIgnoreCache,
+ ORecordCallback<ORawBuffer> iCallback) {
checkOpeness();
return readRecord(getClusterById(iRid.clusterId), iRid, true);
}
@@ -807,12 +814,24 @@ public ORawBuffer readRecord(final ORecordId iRid, final String iFetchPlan, bool
public int updateRecord(final ORecordId iRid, final byte[] iContent, final int iVersion, final byte iRecordType, final int iMode,
ORecordCallback<Integer> iCallback) {
checkOpeness();
- return updateRecord(getClusterById(iRid.clusterId), iRid, iContent, iVersion, iRecordType);
+
+ final OCluster cluster = getClusterById(iRid.clusterId);
+
+ if (txManager.isCommitting())
+ return txManager.updateRecord(txManager.getCurrentTransaction().getId(), cluster, iRid, iContent, iVersion, iRecordType);
+ else
+ return updateRecord(cluster, iRid, iContent, iVersion, iRecordType);
}
public boolean deleteRecord(final ORecordId iRid, final int iVersion, final int iMode, ORecordCallback<Boolean> iCallback) {
checkOpeness();
- return deleteRecord(getClusterById(iRid.clusterId), iRid, iVersion);
+
+ final OCluster cluster = getClusterById(iRid.clusterId);
+
+ if (txManager.isCommitting())
+ return txManager.deleteRecord(txManager.getCurrentTransaction().getId(), cluster, iRid.clusterPosition, iVersion);
+ else
+ return deleteRecord(cluster, iRid, iVersion);
}
public Set<String> getClusterNames() {
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java
index 79b7258e7d9..346cfa3307e 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java
@@ -37,6 +37,7 @@
public class OStorageLocalTxExecuter {
private final OStorageLocal storage;
private final OTxSegment txSegment;
+ private OTransaction currentTransaction;
public OStorageLocalTxExecuter(final OStorageLocal iStorage, final OStorageTxConfiguration iConfig) throws IOException {
storage = iStorage;
@@ -59,7 +60,7 @@ public void close() throws IOException {
}
protected long createRecord(final int iTxId, final OCluster iClusterSegment, final ORecordId iRid, final byte[] iContent,
- final byte iRecordType) throws IOException {
+ final byte iRecordType) {
iRid.clusterPosition = -1;
try {
@@ -108,7 +109,7 @@ protected int updateRecord(final int iTxId, final OCluster iClusterSegment, fina
return -1;
}
- protected void deleteRecord(final int iTxId, final OCluster iClusterSegment, final long iPosition, final int iVersion) {
+ protected boolean deleteRecord(final int iTxId, final OCluster iClusterSegment, final long iPosition, final int iVersion) {
try {
final ORecordId rid = new ORecordId(iClusterSegment.getId(), iPosition);
@@ -119,13 +120,14 @@ protected void deleteRecord(final int iTxId, final OCluster iClusterSegment, fin
txSegment.addLog(OTxSegment.OPERATION_DELETE, iTxId, iClusterSegment.getId(), iPosition, buffer.recordType, buffer.version,
buffer.buffer);
- storage.deleteRecord(iClusterSegment, rid, iVersion);
+ return storage.deleteRecord(iClusterSegment, rid, iVersion);
} catch (IOException e) {
OLogManager.instance().error(this, "Error on deleting entry #" + iPosition + " in log segment: " + iClusterSegment, e,
OTransactionException.class);
}
+ return false;
}
public OTxSegment getTxSegment() {
@@ -133,25 +135,30 @@ public OTxSegment getTxSegment() {
}
public void commitAllPendingRecords(final OTransaction iTx) throws IOException {
- // COPY ALL THE ENTRIES IN SEPARATE COLLECTION SINCE DURING THE COMMIT PHASE SOME NEW ENTRIES COULD BE CREATED AND
- // CONCURRENT-EXCEPTION MAY OCCURS
- final List<ORecordOperation> tmpEntries = new ArrayList<ORecordOperation>();
+ currentTransaction = iTx;
+ try {
+ // COPY ALL THE ENTRIES IN SEPARATE COLLECTION SINCE DURING THE COMMIT PHASE SOME NEW ENTRIES COULD BE CREATED AND
+ // CONCURRENT-EXCEPTION MAY OCCURS
+ final List<ORecordOperation> tmpEntries = new ArrayList<ORecordOperation>();
- while (iTx.getCurrentRecordEntries().iterator().hasNext()) {
- for (ORecordOperation txEntry : iTx.getCurrentRecordEntries())
- tmpEntries.add(txEntry);
+ while (iTx.getCurrentRecordEntries().iterator().hasNext()) {
+ for (ORecordOperation txEntry : iTx.getCurrentRecordEntries())
+ tmpEntries.add(txEntry);
- iTx.clearRecordEntries();
+ iTx.clearRecordEntries();
- if (!tmpEntries.isEmpty()) {
- for (ORecordOperation txEntry : tmpEntries)
- // COMMIT ALL THE SINGLE ENTRIES ONE BY ONE
- commitEntry(iTx, txEntry, iTx.isUsingLog());
+ if (!tmpEntries.isEmpty()) {
+ for (ORecordOperation txEntry : tmpEntries)
+ // COMMIT ALL THE SINGLE ENTRIES ONE BY ONE
+ commitEntry(iTx, txEntry, iTx.isUsingLog());
+ }
}
- }
- // UPDATE THE CACHE ONLY IF THE ITERATOR ALLOWS IT
- OTransactionAbstract.updateCacheFromEntries(storage, iTx, iTx.getAllRecordEntries(), true);
+ // UPDATE THE CACHE ONLY IF THE ITERATOR ALLOWS IT
+ OTransactionAbstract.updateCacheFromEntries(storage, iTx, iTx.getAllRecordEntries(), true);
+ } finally {
+ currentTransaction = null;
+ }
}
public void clearLogEntries(final OTransaction iTx) throws IOException {
@@ -273,4 +280,12 @@ private void commitEntry(final OTransaction iTx, final ORecordOperation txEntry,
if (txEntry.getRecord() instanceof OTxListener)
((OTxListener) txEntry.getRecord()).onEvent(txEntry, OTxListener.EVENT.AFTER_COMMIT);
}
+
+ public boolean isCommitting() {
+ return currentTransaction != null;
+ }
+
+ public OTransaction getCurrentTransaction() {
+ return currentTransaction;
+ }
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java
index 4d7f1c98259..0e88e90e161 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java
@@ -151,8 +151,8 @@ private void addRecord(final ORecordInternal<?> iRecord, final byte iStatus, fin
// && iRecord.getIdentity().isValid() && allEntries.containsKey(iRecord.getIdentity())) {
// if ((OStorage.CLUSTER_INDEX_NAME.equals(iClusterName) || iRecord.getIdentity().getClusterId() == database.getStorage()
// .getClusterIdByName(OStorage.CLUSTER_INDEX_NAME)) && database.getStorage() instanceof OStorageEmbedded) {
+
// I'M COMMITTING: BYPASS LOCAL BUFFER
-
switch (iStatus) {
case ORecordOperation.CREATED:
case ORecordOperation.UPDATED:
diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TransactionConsistencyTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TransactionConsistencyTest.java
index 0a88593ad2b..88786d54fd1 100644
--- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TransactionConsistencyTest.java
+++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TransactionConsistencyTest.java
@@ -21,6 +21,8 @@
import java.util.Vector;
import org.testng.Assert;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
@@ -32,6 +34,7 @@
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;
+import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.orientechnologies.orient.core.storage.OStorage;
import com.orientechnologies.orient.core.tx.OTransaction.TXTYPE;
@@ -53,10 +56,17 @@ public class TransactionConsistencyTest {
// }
@Parameters(value = "url")
- public TransactionConsistencyTest(String iURL) throws IOException {
+ public TransactionConsistencyTest(@Optional(value = "memory:test") String iURL) throws IOException {
url = iURL;
}
+ @BeforeClass
+ public void init() {
+ ODatabaseDocumentTx database = new ODatabaseDocumentTx(url);
+ if ("memory:test".equals(database.getURL()))
+ database.create();
+ }
+
@Test
public void test1RollbackOnConcurrentException() throws IOException {
database1 = new ODatabaseDocumentTx(url).open("admin", "admin");
@@ -625,6 +635,7 @@ public void deletesWithinTransactionArentWorking() throws IOException {
db.close();
}
}
+
//
// @SuppressWarnings("unchecked")
// @Test
@@ -674,4 +685,109 @@ public void deletesWithinTransactionArentWorking() throws IOException {
// db.close();
// System.out.println("************ end testTransactionPopulatePartialDelete *******************");
// }
+
+ public void TransactionRollbackConstistencyTest() {
+ System.out.println("**************************TransactionRollbackConsistencyTest***************************************");
+ ODatabaseDocumentTx db = new ODatabaseDocumentTx(url);
+ db.open("admin", "admin");
+ OClass vertexClass = db.getMetadata().getSchema().createClass("TRVertex");
+ OClass edgeClass = db.getMetadata().getSchema().createClass("TREdge");
+ vertexClass.createProperty("in", OType.LINKSET, edgeClass);
+ vertexClass.createProperty("out", OType.LINKSET, edgeClass);
+ edgeClass.createProperty("in", OType.LINK, vertexClass);
+ edgeClass.createProperty("out", OType.LINK, vertexClass);
+
+ OClass personClass = db.getMetadata().getSchema().createClass("TRPerson", vertexClass);
+ personClass.createProperty("name", OType.STRING).createIndex(OClass.INDEX_TYPE.UNIQUE);
+ personClass.createProperty("surname", OType.STRING).createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
+ personClass.createProperty("version", OType.INTEGER);
+
+ db.getMetadata().getSchema().save();
+ db.close();
+
+ final int cnt = 4;
+
+ db.open("admin", "admin");
+ db.begin();
+ Vector inserted = new Vector();
+
+ for (int i = 0; i < cnt; i++) {
+ ODocument person = new ODocument("TRPerson");
+ person.field("name", Character.toString((char) ('A' + i)));
+ person.field("surname", Character.toString((char) ('A' + (i % 3))));
+ person.field("myversion", 0);
+ person.field("in", new HashSet<ODocument>());
+ person.field("out", new HashSet<ODocument>());
+
+ if (i >= 1) {
+ ODocument edge = new ODocument("TREdge");
+ edge.field("in", person.getIdentity());
+ edge.field("out", inserted.elementAt(i - 1));
+ ((HashSet<ODocument>) person.field("out")).add(edge);
+ ((HashSet<ODocument>) ((ODocument) inserted.elementAt(i - 1)).field("in")).add(edge);
+ edge.save();
+ }
+ inserted.add(person);
+ person.save();
+ }
+ db.commit();
+
+ final List<ODocument> result1 = db.command(new OCommandSQL("select from TRPerson")).execute();
+ Assert.assertNotNull(result1);
+ Assert.assertEquals(result1.size(), 4);
+ System.out.println("Before transaction commit");
+ for (ODocument d : result1)
+ System.out.println(d);
+
+ try {
+ db.begin();
+ Vector inserted2 = new Vector();
+
+ for (int i = 0; i < cnt; i++) {
+ ODocument person = new ODocument("TRPerson");
+ person.field("name", Character.toString((char) ('a' + i)));
+ person.field("surname", Character.toString((char) ('a' + (i % 3))));
+ person.field("myversion", 0);
+ person.field("in", new HashSet<ODocument>());
+ person.field("out", new HashSet<ODocument>());
+
+ if (i >= 1) {
+ ODocument edge = new ODocument("TREdge");
+ edge.field("in", person.getIdentity());
+ edge.field("out", inserted2.elementAt(i - 1));
+ ((HashSet<ODocument>) person.field("out")).add(edge);
+ ((HashSet<ODocument>) ((ODocument) inserted2.elementAt(i - 1)).field("in")).add(edge);
+ edge.save();
+ }
+ inserted2.add(person);
+ person.save();
+ }
+
+ for (int i = 0; i < cnt; i++) {
+ if (i != cnt - 1) {
+ ((ODocument) inserted.elementAt(i)).field("myversion", 2);
+ ((ODocument) inserted.elementAt(i)).save();
+ }
+ }
+
+ ((ODocument) inserted.elementAt(cnt - 1)).delete();
+ ((ODocument) inserted.elementAt(cnt - 2)).setVersion(0);
+ ((ODocument) inserted.elementAt(cnt - 2)).save();
+ db.commit();
+ Assert.assertTrue(false);
+ } catch (OConcurrentModificationException e) {
+ Assert.assertTrue(true);
+ db.rollback();
+ }
+
+ final List<ODocument> result2 = db.command(new OCommandSQL("select from TRPerson")).execute();
+ Assert.assertNotNull(result2);
+ System.out.println("After transaction commit failure/rollback");
+ for (ODocument d : result2)
+ System.out.println(d);
+ Assert.assertEquals(result2.size(), 4);
+
+ db.close();
+ System.out.println("**************************TransactionRollbackConstistencyTest***************************************");
+ }
}
|
0561123a987b538aa9658dae42bd416b28a7e297
|
Valadoc
|
gtkdoc-importer: Add support for informaltable
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/src/libvaladoc/documentation/gtkdoccommentparser.vala b/src/libvaladoc/documentation/gtkdoccommentparser.vala
index 91d395bb1e..23e421bb06 100644
--- a/src/libvaladoc/documentation/gtkdoccommentparser.vala
+++ b/src/libvaladoc/documentation/gtkdoccommentparser.vala
@@ -362,7 +362,7 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
}
private bool check_xml_open_tag (string tagname) {
- if (current.type == TokenType.XML_OPEN && current.content != tagname) {
+ if ((current.type == TokenType.XML_OPEN && current.content != tagname) || current.type != TokenType.XML_OPEN) {
return false;
}
@@ -371,7 +371,7 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
}
private bool check_xml_close_tag (string tagname) {
- if (current.type == TokenType.XML_CLOSE && current.content != tagname) {
+ if ((current.type == TokenType.XML_CLOSE && current.content != tagname) || current.type != TokenType.XML_CLOSE) {
return false;
}
@@ -1063,6 +1063,164 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
}
}
+ private TableRow? parse_docbook_thead () {
+ if (!check_xml_open_tag ("thead")) {
+ this.report_unexpected_token (current, "<thead>");
+ return null;
+ }
+ next ();
+
+ parse_docbook_spaces ();
+ TableRow? row = parse_docbook_row (Run.Style.BOLD);
+ parse_docbook_spaces ();
+
+ if (!check_xml_close_tag ("thead")) {
+ this.report_unexpected_token (current, "</thead>");
+ return row;
+ }
+
+ next ();
+ return row;
+ }
+
+ private TableCell? parse_docbook_entry (Run.Style default_style = Run.Style.NONE) {
+ if (!check_xml_open_tag ("entry")) {
+ this.report_unexpected_token (current, "<entry>");
+ return null;
+ }
+ next ();
+
+ TableCell cell = factory.create_table_cell ();
+ Run run = factory.create_run (default_style);
+ run.content.add (parse_inline_content ());
+ cell.content.add (run);
+
+ if (!check_xml_close_tag ("entry")) {
+ this.report_unexpected_token (current, "</entry>");
+ return cell;
+ }
+
+ next ();
+ return cell;
+ }
+
+ private TableRow? parse_docbook_row (Run.Style default_style = Run.Style.NONE) {
+ if (!check_xml_open_tag ("row")) {
+ this.report_unexpected_token (current, "<row>");
+ return null;
+ }
+ next ();
+
+ TableRow row = factory.create_table_row ();
+ parse_docbook_spaces ();
+
+ while (current.type == TokenType.XML_OPEN && current.content == "entry") {
+ TableCell? table_cell = parse_docbook_entry (default_style);
+ if (table_cell == null) {
+ break;
+ }
+
+ row.cells.add (table_cell);
+ parse_docbook_spaces ();
+ }
+
+ if (!check_xml_close_tag ("row")) {
+ this.report_unexpected_token (current, "</row>");
+ return row;
+ }
+
+ next ();
+ return row;
+ }
+
+ private LinkedList<TableRow>? parse_docbook_tbody () {
+ if (!check_xml_open_tag ("tbody")) {
+ this.report_unexpected_token (current, "<tbody>");
+ return null;
+ }
+ next ();
+
+ parse_docbook_spaces ();
+
+ LinkedList<TableRow> rows = new LinkedList<TableRow> ();
+ while (current.type == TokenType.XML_OPEN && current.content == "row") {
+ TableRow? row = parse_docbook_row ();
+ if (row == null) {
+ break;
+ }
+
+ parse_docbook_spaces ();
+ rows.add (row);
+ }
+
+
+ if (!check_xml_close_tag ("tbody")) {
+ this.report_unexpected_token (current, "</tbody>");
+ return rows;
+ }
+
+ next ();
+ return rows;
+ }
+
+ private Table? parse_docbook_tgroup () {
+ if (!check_xml_open_tag ("tgroup")) {
+ this.report_unexpected_token (current, "<tgroup>");
+ return null;
+ }
+ next ();
+
+ Table table = factory.create_table ();
+ parse_docbook_spaces ();
+
+ if (current.type == TokenType.XML_OPEN && current.content == "thead") {
+ TableRow? row = parse_docbook_thead ();
+ if (row != null) {
+ parse_docbook_spaces ();
+ table.rows.add (row);
+ }
+
+ parse_docbook_spaces ();
+ }
+
+ if (current.type == TokenType.XML_OPEN && current.content == "tbody") {
+ LinkedList<TableRow>? rows = parse_docbook_tbody ();
+ if (rows != null) {
+ table.rows.add_all (rows);
+ }
+
+ parse_docbook_spaces ();
+ }
+
+ if (!check_xml_close_tag ("tgroup")) {
+ this.report_unexpected_token (current, "</tgroup>");
+ return table;
+ }
+
+ next ();
+ return table;
+ }
+
+ private Table? parse_docbook_informaltable () {
+ if (!check_xml_open_tag ("informaltable")) {
+ this.report_unexpected_token (current, "<informaltable>");
+ return null;
+ }
+ next ();
+
+ parse_docbook_spaces ();
+ Table? table = this.parse_docbook_tgroup ();
+ parse_docbook_spaces ();
+
+ if (!check_xml_close_tag ("informaltable")) {
+ this.report_unexpected_token (current, "</informaltable>");
+ return table;
+ }
+
+ next ();
+ return table;
+ }
+
private LinkedList<Block> parse_block_content () {
LinkedList<Block> content = new LinkedList<Block> ();
@@ -1071,6 +1229,8 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
if (current.type == TokenType.XML_OPEN && current.content == "itemizedlist") {
this.append_block_content_not_null (content, parse_docbook_itemizedlist ());
+ } else if (current.type == TokenType.XML_OPEN && current.content == "informaltable") {
+ this.append_block_content_not_null (content, parse_docbook_informaltable ());
} else if (current.type == TokenType.XML_OPEN && current.content == "programlisting") {
this.append_block_content_not_null (content, parse_docbook_programlisting ());
} else if (current.type == TokenType.XML_OPEN && current.content == "para") {
|
e8db1654df89d3c60a6620a68fc5b85137e05b42
|
orientdb
|
Renamed everywhere OTreeMap in OMVRBTree as the- new name of the algorithm: OMVRBTree--
|
p
|
https://github.com/orientechnologies/orientdb
|
diff --git a/commons/src/main/java/com/orientechnologies/common/collection/AbstractEntryIterator.java b/commons/src/main/java/com/orientechnologies/common/collection/AbstractEntryIterator.java
index b30c3731226..70fedb1e5ae 100644
--- a/commons/src/main/java/com/orientechnologies/common/collection/AbstractEntryIterator.java
+++ b/commons/src/main/java/com/orientechnologies/common/collection/AbstractEntryIterator.java
@@ -20,15 +20,15 @@
import java.util.NoSuchElementException;
/**
- * Base class for OTreeMap Iterators
+ * Base class for OMVRBTree Iterators
*/
abstract class AbstractEntryIterator<K, V, T> implements Iterator<T> {
- OTreeMap<K, V> tree;
- OTreeMapEntry<K, V> next;
- OTreeMapEntry<K, V> lastReturned;
+ OMVRBTree<K, V> tree;
+ OMVRBTreeEntry<K, V> next;
+ OMVRBTreeEntry<K, V> lastReturned;
int expectedModCount;
- AbstractEntryIterator(OTreeMapEntry<K, V> first) {
+ AbstractEntryIterator(OMVRBTreeEntry<K, V> first) {
if (first == null)
// IN CASE OF ABSTRACTMAP.HASHCODE()
return;
@@ -41,10 +41,10 @@ abstract class AbstractEntryIterator<K, V, T> implements Iterator<T> {
}
public final boolean hasNext() {
- return next != null && (OTreeMap.successor(next) != null || tree.pageIndex < next.getSize() - 1);
+ return next != null && (OMVRBTree.successor(next) != null || tree.pageIndex < next.getSize() - 1);
}
- final OTreeMapEntry<K, V> nextEntry() {
+ final OMVRBTreeEntry<K, V> nextEntry() {
if (next == null)
throw new NoSuchElementException();
@@ -57,20 +57,20 @@ final OTreeMapEntry<K, V> nextEntry() {
throw new ConcurrentModificationException();
tree.pageIndex = 0;
- next = OTreeMap.successor(next);
+ next = OMVRBTree.successor(next);
lastReturned = next;
}
return next;
}
- final OTreeMapEntry<K, V> prevEntry() {
- OTreeMapEntry<K, V> e = next;
+ final OMVRBTreeEntry<K, V> prevEntry() {
+ OMVRBTreeEntry<K, V> e = next;
if (e == null)
throw new NoSuchElementException();
if (tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
- next = OTreeMap.predecessor(e);
+ next = OMVRBTree.predecessor(e);
lastReturned = e;
return e;
}
diff --git a/commons/src/main/java/com/orientechnologies/common/collection/OTreeMap.java b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTree.java
similarity index 80%
rename from commons/src/main/java/com/orientechnologies/common/collection/OTreeMap.java
rename to commons/src/main/java/com/orientechnologies/common/collection/OMVRBTree.java
index d326af052f1..10403e270c1 100644
--- a/commons/src/main/java/com/orientechnologies/common/collection/OTreeMap.java
+++ b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTree.java
@@ -1,3 +1,18 @@
+/*
+ * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com)
+ *
+ * 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.orientechnologies.common.collection;
import java.io.IOException;
@@ -18,9 +33,19 @@
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.profiler.OProfiler;
+/**
+ * Base abstract class of MVRB-Tree algorithm.
+ *
+ * @author Luca Garulli (l.garulli--at--orientechnologies.com)
+ *
+ * @param <K>
+ * Key type
+ * @param <V>
+ * Value type
+ */
@SuppressWarnings("unchecked")
-public abstract class OTreeMap<K, V> extends AbstractMap<K, V> implements ONavigableMap<K, V>, Cloneable, java.io.Serializable {
- protected OTreeMapEventListener<K, V> listener;
+public abstract class OMVRBTree<K, V> extends AbstractMap<K, V> implements ONavigableMap<K, V>, Cloneable, java.io.Serializable {
+ protected OMVRBTreeEventListener<K, V> listener;
boolean pageItemFound = false;
int pageItemComparator = 0;
protected volatile int pageIndex = -1;
@@ -41,7 +66,7 @@ public abstract class OTreeMap<K, V> extends AbstractMap<K, V> implements ONavig
*/
private final Comparator<? super K> comparator;
- protected transient OTreeMapEntry<K, V> root = null;
+ protected transient OMVRBTreeEntry<K, V> root = null;
/**
* The number of structural modifications to the tree.
@@ -50,14 +75,14 @@ public abstract class OTreeMap<K, V> extends AbstractMap<K, V> implements ONavig
transient boolean runtimeCheckEnabled = false;
- public OTreeMap(final int iSize, final float iLoadFactor) {
+ public OMVRBTree(final int iSize, final float iLoadFactor) {
lastPageSize = iSize;
pageLoadFactor = iLoadFactor;
comparator = null;
init();
}
- public OTreeMap(final OTreeMapEventListener<K, V> iListener) {
+ public OMVRBTree(final OMVRBTreeEventListener<K, V> iListener) {
init();
comparator = null;
listener = iListener;
@@ -70,7 +95,7 @@ public OTreeMap(final OTreeMapEventListener<K, V> iListener) {
* the map that violates this constraint (for example, the user attempts to put a string key into a map whose keys are integers),
* the <tt>put(Object key, Object value)</tt> call will throw a <tt>ClassCastException</tt>.
*/
- public OTreeMap() {
+ public OMVRBTree() {
init();
comparator = null;
}
@@ -86,7 +111,7 @@ public OTreeMap() {
* the comparator that will be used to order this map. If <tt>null</tt>, the {@linkplain Comparable natural ordering} of
* the keys will be used.
*/
- public OTreeMap(final Comparator<? super K> comparator) {
+ public OMVRBTree(final Comparator<? super K> comparator) {
init();
this.comparator = comparator;
}
@@ -104,7 +129,7 @@ public OTreeMap(final Comparator<? super K> comparator) {
* @throws NullPointerException
* if the specified map is null
*/
- public OTreeMap(final Map<? extends K, ? extends V> m) {
+ public OMVRBTree(final Map<? extends K, ? extends V> m) {
init();
comparator = null;
putAll(m);
@@ -119,7 +144,7 @@ public OTreeMap(final Map<? extends K, ? extends V> m) {
* @throws NullPointerException
* if the specified map is null
*/
- public OTreeMap(final SortedMap<K, ? extends V> m) {
+ public OMVRBTree(final SortedMap<K, ? extends V> m) {
init();
comparator = m.comparator();
try {
@@ -132,17 +157,17 @@ public OTreeMap(final SortedMap<K, ? extends V> m) {
/**
* Create a new entry with the first key/value to handle.
*/
- protected abstract OTreeMapEntry<K, V> createEntry(final K key, final V value);
+ protected abstract OMVRBTreeEntry<K, V> createEntry(final K key, final V value);
/**
* Create a new node with the same parent of the node is splitting.
*/
- protected abstract OTreeMapEntry<K, V> createEntry(final OTreeMapEntry<K, V> parent);
+ protected abstract OMVRBTreeEntry<K, V> createEntry(final OMVRBTreeEntry<K, V> parent);
public int getNodes() {
int counter = -1;
- OTreeMapEntry<K, V> entry = getFirstEntry();
+ OMVRBTreeEntry<K, V> entry = getFirstEntry();
while (entry != null) {
entry = successor(entry);
counter++;
@@ -174,7 +199,7 @@ public int size() {
*/
@Override
public boolean containsKey(final Object key) {
- OTreeMapEntry<K, V> entry = getEntry(key);
+ OMVRBTreeEntry<K, V> entry = getEntry(key);
return entry != null;
}
@@ -191,7 +216,7 @@ public boolean containsKey(final Object key) {
*/
@Override
public boolean containsValue(final Object value) {
- for (OTreeMapEntry<K, V> e = getFirstEntry(); e != null; e = successor(e))
+ for (OMVRBTreeEntry<K, V> e = getFirstEntry(); e != null; e = successor(e))
if (valEquals(value, e.getValue()))
return true;
return false;
@@ -220,7 +245,7 @@ public V get(final Object key) {
if (size == 0)
return null;
- OTreeMapEntry<K, V> entry = getEntry(key);
+ OMVRBTreeEntry<K, V> entry = getEntry(key);
return entry == null ? null : entry.getValue();
}
@@ -282,11 +307,11 @@ public void putAll(final Map<? extends K, ? extends V> map) {
* @throws NullPointerException
* if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
*/
- final OTreeMapEntry<K, V> getEntry(final Object key) {
+ final OMVRBTreeEntry<K, V> getEntry(final Object key) {
return getEntry(key, false);
}
- final OTreeMapEntry<K, V> getEntry(final Object key, final boolean iGetContainer) {
+ final OMVRBTreeEntry<K, V> getEntry(final Object key, final boolean iGetContainer) {
if (key == null)
return null;
@@ -296,7 +321,7 @@ final OTreeMapEntry<K, V> getEntry(final Object key, final boolean iGetContainer
if (comparator != null)
return getEntryUsingComparator(key, iGetContainer);
- OTreeMapEntry<K, V> p = getBestEntryPoint(key);
+ OMVRBTreeEntry<K, V> p = getBestEntryPoint(key);
// System.out.println("Best entry point for key " + key + " is: "+p);
@@ -305,9 +330,9 @@ final OTreeMapEntry<K, V> getEntry(final Object key, final boolean iGetContainer
if (p == null)
return null;
- OTreeMapEntry<K, V> lastNode = p;
- OTreeMapEntry<K, V> prevNode = null;
- OTreeMapEntry<K, V> tmpNode;
+ OMVRBTreeEntry<K, V> lastNode = p;
+ OMVRBTreeEntry<K, V> prevNode = null;
+ OMVRBTreeEntry<K, V> tmpNode;
int beginKey = -1;
int steps = -1;
final Comparable<? super K> k = (Comparable<? super K>) key;
@@ -375,7 +400,7 @@ final OTreeMapEntry<K, V> getEntry(final Object key, final boolean iGetContainer
} finally {
checkTreeStructure(p);
- OProfiler.getInstance().updateStat("[OTreeMap.getEntry] Steps of search", steps);
+ OProfiler.getInstance().updateStat("[OMVRBTree.getEntry] Steps of search", steps);
}
return null;
@@ -384,15 +409,15 @@ final OTreeMapEntry<K, V> getEntry(final Object key, final boolean iGetContainer
/**
* Basic implementation that returns the root node.
*/
- protected OTreeMapEntry<K, V> getBestEntryPoint(final Object key) {
+ protected OMVRBTreeEntry<K, V> getBestEntryPoint(final Object key) {
return root;
}
- public OTreeMapEventListener<K, V> getListener() {
+ public OMVRBTreeEventListener<K, V> getListener() {
return listener;
}
- public void setListener(final OTreeMapEventListener<K, V> listener) {
+ public void setListener(final OMVRBTreeEventListener<K, V> listener) {
this.listener = listener;
}
@@ -402,12 +427,12 @@ public void setListener(final OTreeMapEventListener<K, V> listener) {
*
* @param iGetContainer
*/
- final OTreeMapEntry<K, V> getEntryUsingComparator(final Object key, final boolean iGetContainer) {
+ final OMVRBTreeEntry<K, V> getEntryUsingComparator(final Object key, final boolean iGetContainer) {
K k = (K) key;
Comparator<? super K> cpr = comparator;
if (cpr != null) {
- OTreeMapEntry<K, V> p = root;
- OTreeMapEntry<K, V> lastNode = null;
+ OMVRBTreeEntry<K, V> p = root;
+ OMVRBTreeEntry<K, V> lastNode = null;
while (p != null) {
lastNode = p;
@@ -451,8 +476,8 @@ else if (beginKey > 0) {
* the specified key; if no such entry exists (i.e., the greatest key in the Tree is less than the specified key), returns
* <tt>null</tt>.
*/
- final OTreeMapEntry<K, V> getCeilingEntry(final K key) {
- OTreeMapEntry<K, V> p = root;
+ final OMVRBTreeEntry<K, V> getCeilingEntry(final K key) {
+ OMVRBTreeEntry<K, V> p = root;
while (p != null) {
int cmp = compare(key, p.getKey());
if (cmp < 0) {
@@ -464,7 +489,7 @@ final OTreeMapEntry<K, V> getCeilingEntry(final K key) {
if (p.getRight() != null) {
p = p.getRight();
} else {
- OTreeMapEntry<K, V> parent = p.getParent();
+ OMVRBTreeEntry<K, V> parent = p.getParent();
Entry<K, V> ch = p;
while (parent != null && ch == parent.getRight()) {
ch = parent;
@@ -482,8 +507,8 @@ final OTreeMapEntry<K, V> getCeilingEntry(final K key) {
* Gets the entry corresponding to the specified key; if no such entry exists, returns the entry for the greatest key less than
* the specified key; if no such entry exists, returns <tt>null</tt>.
*/
- final OTreeMapEntry<K, V> getFloorEntry(final K key) {
- OTreeMapEntry<K, V> p = root;
+ final OMVRBTreeEntry<K, V> getFloorEntry(final K key) {
+ OMVRBTreeEntry<K, V> p = root;
while (p != null) {
int cmp = compare(key, p.getKey());
if (cmp > 0) {
@@ -495,7 +520,7 @@ final OTreeMapEntry<K, V> getFloorEntry(final K key) {
if (p.getLeft() != null) {
p = p.getLeft();
} else {
- OTreeMapEntry<K, V> parent = p.getParent();
+ OMVRBTreeEntry<K, V> parent = p.getParent();
Entry<K, V> ch = p;
while (parent != null && ch == parent.getLeft()) {
ch = parent;
@@ -514,8 +539,8 @@ final OTreeMapEntry<K, V> getFloorEntry(final K key) {
* Gets the entry for the least key greater than the specified key; if no such entry exists, returns the entry for the least key
* greater than the specified key; if no such entry exists returns <tt>null</tt>.
*/
- final OTreeMapEntry<K, V> getHigherEntry(final K key) {
- OTreeMapEntry<K, V> p = root;
+ final OMVRBTreeEntry<K, V> getHigherEntry(final K key) {
+ OMVRBTreeEntry<K, V> p = root;
while (p != null) {
int cmp = compare(key, p.getKey());
if (cmp < 0) {
@@ -527,7 +552,7 @@ final OTreeMapEntry<K, V> getHigherEntry(final K key) {
if (p.getRight() != null) {
p = p.getRight();
} else {
- OTreeMapEntry<K, V> parent = p.getParent();
+ OMVRBTreeEntry<K, V> parent = p.getParent();
Entry<K, V> ch = p;
while (parent != null && ch == parent.getRight()) {
ch = parent;
@@ -544,8 +569,8 @@ final OTreeMapEntry<K, V> getHigherEntry(final K key) {
* Returns the entry for the greatest key less than the specified key; if no such entry exists (i.e., the least key in the Tree is
* greater than the specified key), returns <tt>null</tt>.
*/
- final OTreeMapEntry<K, V> getLowerEntry(final K key) {
- OTreeMapEntry<K, V> p = root;
+ final OMVRBTreeEntry<K, V> getLowerEntry(final K key) {
+ OMVRBTreeEntry<K, V> p = root;
while (p != null) {
int cmp = compare(key, p.getKey());
if (cmp > 0) {
@@ -557,7 +582,7 @@ final OTreeMapEntry<K, V> getLowerEntry(final K key) {
if (p.getLeft() != null) {
p = p.getLeft();
} else {
- OTreeMapEntry<K, V> parent = p.getParent();
+ OMVRBTreeEntry<K, V> parent = p.getParent();
Entry<K, V> ch = p;
while (parent != null && ch == parent.getLeft()) {
ch = parent;
@@ -588,7 +613,7 @@ final OTreeMapEntry<K, V> getLowerEntry(final K key) {
*/
@Override
public V put(final K key, final V value) {
- OTreeMapEntry<K, V> parentNode = null;
+ OMVRBTreeEntry<K, V> parentNode = null;
try {
if (root == null) {
@@ -625,7 +650,7 @@ public V put(final K key, final V value) {
parentNode.insert(pageIndex, key, value);
} else {
// CREATE NEW NODE AND COPY HALF OF VALUES FROM THE ORIGIN TO THE NEW ONE IN ORDER TO GET VALUES BALANCED
- final OTreeMapEntry<K, V> newNode = createEntry(parentNode);
+ final OMVRBTreeEntry<K, V> newNode = createEntry(parentNode);
// System.out.println("Created new entry: " + newEntry+ ", insert the key as index="+pageIndex);
@@ -636,7 +661,7 @@ public V put(final K key, final V value) {
// INSERT IN THE NEW NODE
newNode.insert(pageIndex - parentNode.getPageSplitItems(), key, value);
- final OTreeMapEntry<K, V> prevNode = parentNode.getRight();
+ final OMVRBTreeEntry<K, V> prevNode = parentNode.getRight();
// REPLACE THE RIGHT ONE WITH THE NEW NODE
parentNode.setRight(newNode);
@@ -667,7 +692,7 @@ public V put(final K key, final V value) {
}
/**
- * Removes the mapping for this key from this OTreeMap if present.
+ * Removes the mapping for this key from this OMVRBTree if present.
*
* @param key
* key for which mapping should be removed
@@ -680,7 +705,7 @@ public V put(final K key, final V value) {
*/
@Override
public V remove(final Object key) {
- OTreeMapEntry<K, V> p = getEntry(key);
+ OMVRBTreeEntry<K, V> p = getEntry(key);
if (p == null)
return null;
@@ -700,15 +725,15 @@ public void clear() {
}
/**
- * Returns a shallow copy of this <tt>OTreeMap</tt> instance. (The keys and values themselves are not cloned.)
+ * Returns a shallow copy of this <tt>OMVRBTree</tt> instance. (The keys and values themselves are not cloned.)
*
* @return a shallow copy of this map
*/
@Override
public Object clone() {
- OTreeMap<K, V> clone = null;
+ OMVRBTree<K, V> clone = null;
try {
- clone = (OTreeMap<K, V>) super.clone();
+ clone = (OMVRBTree<K, V>) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
@@ -757,7 +782,7 @@ public Map.Entry<K, V> lastEntry() {
* @since 1.6
*/
public Entry<K, V> pollFirstEntry() {
- OTreeMapEntry<K, V> p = getFirstEntry();
+ OMVRBTreeEntry<K, V> p = getFirstEntry();
Map.Entry<K, V> result = exportEntry(p);
if (p != null)
deleteEntry(p);
@@ -768,7 +793,7 @@ public Entry<K, V> pollFirstEntry() {
* @since 1.6
*/
public Entry<K, V> pollLastEntry() {
- OTreeMapEntry<K, V> p = getLastEntry();
+ OMVRBTreeEntry<K, V> p = getLastEntry();
Map.Entry<K, V> result = exportEntry(p);
if (p != null)
deleteEntry(p);
@@ -1026,17 +1051,17 @@ public Iterator<V> iterator() {
@Override
public int size() {
- return OTreeMap.this.size();
+ return OMVRBTree.this.size();
}
@Override
public boolean contains(Object o) {
- return OTreeMap.this.containsValue(o);
+ return OMVRBTree.this.containsValue(o);
}
@Override
public boolean remove(Object o) {
- for (OTreeMapEntry<K, V> e = getFirstEntry(); e != null; e = successor(e)) {
+ for (OMVRBTreeEntry<K, V> e = getFirstEntry(); e != null; e = successor(e)) {
if (valEquals(e.getValue(), o)) {
deleteEntry(e);
return true;
@@ -1047,7 +1072,7 @@ public boolean remove(Object o) {
@Override
public void clear() {
- OTreeMap.this.clear();
+ OMVRBTree.this.clear();
}
}
@@ -1061,7 +1086,7 @@ public Iterator<Map.Entry<K, V>> iterator() {
public boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
- OTreeMapEntry<K, V> entry = (OTreeMapEntry<K, V>) o;
+ OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o;
V value = entry.getValue();
V p = get(entry.getKey());
return p != null && valEquals(p, value);
@@ -1071,9 +1096,9 @@ public boolean contains(Object o) {
public boolean remove(Object o) {
if (!(o instanceof Map.Entry))
return false;
- OTreeMapEntry<K, V> entry = (OTreeMapEntry<K, V>) o;
+ OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o;
V value = entry.getValue();
- OTreeMapEntry<K, V> p = getEntry(entry.getKey());
+ OMVRBTreeEntry<K, V> p = getEntry(entry.getKey());
if (p != null && valEquals(p.getValue(), value)) {
deleteEntry(p);
return true;
@@ -1083,12 +1108,12 @@ public boolean remove(Object o) {
@Override
public int size() {
- return OTreeMap.this.size();
+ return OMVRBTree.this.size();
}
@Override
public void clear() {
- OTreeMap.this.clear();
+ OMVRBTree.this.clear();
}
}
@@ -1116,17 +1141,17 @@ static final class KeySet<E> extends AbstractSet<E> implements ONavigableSet<E>
@Override
public Iterator<E> iterator() {
- if (m instanceof OTreeMap)
- return ((OTreeMap<E, Object>) m).keyIterator();
+ if (m instanceof OMVRBTree)
+ return ((OMVRBTree<E, Object>) m).keyIterator();
else
- return (((OTreeMap.NavigableSubMap) m).keyIterator());
+ return (((OMVRBTree.NavigableSubMap) m).keyIterator());
}
public Iterator<E> descendingIterator() {
- if (m instanceof OTreeMap)
- return ((OTreeMap<E, Object>) m).descendingKeyIterator();
+ if (m instanceof OMVRBTree)
+ return ((OMVRBTree<E, Object>) m).descendingKeyIterator();
else
- return (((OTreeMap.NavigableSubMap) m).descendingKeyIterator());
+ return (((OMVRBTree.NavigableSubMap) m).descendingKeyIterator());
}
@Override
@@ -1195,15 +1220,15 @@ public boolean remove(Object o) {
}
public ONavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
- return new OTreeSetMemory<E>(m.subMap(fromElement, fromInclusive, toElement, toInclusive));
+ return new OMVRBTreeSetMemory<E>(m.subMap(fromElement, fromInclusive, toElement, toInclusive));
}
public ONavigableSet<E> headSet(E toElement, boolean inclusive) {
- return new OTreeSetMemory<E>(m.headMap(toElement, inclusive));
+ return new OMVRBTreeSetMemory<E>(m.headMap(toElement, inclusive));
}
public ONavigableSet<E> tailSet(E fromElement, boolean inclusive) {
- return new OTreeSetMemory<E>(m.tailMap(fromElement, inclusive));
+ return new OMVRBTreeSetMemory<E>(m.tailMap(fromElement, inclusive));
}
public SortedSet<E> subSet(E fromElement, E toElement) {
@@ -1219,12 +1244,12 @@ public SortedSet<E> tailSet(E fromElement) {
}
public ONavigableSet<E> descendingSet() {
- return new OTreeSetMemory<E>(m.descendingMap());
+ return new OMVRBTreeSetMemory<E>(m.descendingMap());
}
}
final class EntryIterator extends AbstractEntryIterator<K, V, Map.Entry<K, V>> {
- EntryIterator(OTreeMapEntry<K, V> first) {
+ EntryIterator(OMVRBTreeEntry<K, V> first) {
super(first);
}
@@ -1234,7 +1259,7 @@ public Map.Entry<K, V> next() {
}
final class ValueIterator extends AbstractEntryIterator<K, V, V> {
- ValueIterator(OTreeMapEntry<K, V> first) {
+ ValueIterator(OMVRBTreeEntry<K, V> first) {
super(first);
}
@@ -1244,7 +1269,7 @@ public V next() {
}
final class KeyIterator extends AbstractEntryIterator<K, V, K> {
- KeyIterator(OTreeMapEntry<K, V> first) {
+ KeyIterator(OMVRBTreeEntry<K, V> first) {
super(first);
}
@@ -1254,7 +1279,7 @@ public K next() {
}
final class DescendingKeyIterator extends AbstractEntryIterator<K, V, K> {
- DescendingKeyIterator(OTreeMapEntry<K, V> first) {
+ DescendingKeyIterator(OMVRBTreeEntry<K, V> first) {
super(first);
}
@@ -1266,7 +1291,7 @@ public K next() {
// Little utilities
/**
- * Compares two keys using the correct comparison method for this OTreeMap.
+ * Compares two keys using the correct comparison method for this OMVRBTree.
*/
final int compare(Object k1, Object k2) {
return comparator == null ? ((Comparable<? super K>) k1).compareTo((K) k2) : comparator.compare((K) k1, (K) k2);
@@ -1282,14 +1307,14 @@ final static boolean valEquals(Object o1, Object o2) {
/**
* Return SimpleImmutableEntry for entry, or null if null
*/
- static <K, V> Map.Entry<K, V> exportEntry(OTreeMapEntry<K, V> e) {
+ static <K, V> Map.Entry<K, V> exportEntry(OMVRBTreeEntry<K, V> e) {
return e == null ? null : new OSimpleImmutableEntry<K, V>(e);
}
/**
* Return key for entry, or null if null
*/
- static <K, V> K keyOrNull(OTreeMapEntry<K, V> e) {
+ static <K, V> K keyOrNull(OMVRBTreeEntry<K, V> e) {
return e == null ? null : e.getKey();
}
@@ -1299,7 +1324,7 @@ static <K, V> K keyOrNull(OTreeMapEntry<K, V> e) {
* @throws NoSuchElementException
* if the Entry is null
*/
- static <K> K key(OTreeMapEntry<K, ?> e) {
+ static <K> K key(OMVRBTreeEntry<K, ?> e) {
if (e == null)
throw new NoSuchElementException();
return e.getKey();
@@ -1315,7 +1340,7 @@ static abstract class NavigableSubMap<K, V> extends AbstractMap<K, V> implements
/**
* The backing map.
*/
- final OTreeMap<K, V> m;
+ final OMVRBTree<K, V> m;
/**
* Endpoints are represented as triples (fromStart, lo, loInclusive) and (toEnd, hi, hiInclusive). If fromStart is true, then
@@ -1326,7 +1351,7 @@ static abstract class NavigableSubMap<K, V> extends AbstractMap<K, V> implements
final boolean fromStart, toEnd;
final boolean loInclusive, hiInclusive;
- NavigableSubMap(OTreeMap<K, V> m, boolean fromStart, K lo, boolean loInclusive, boolean toEnd, K hi, boolean hiInclusive) {
+ NavigableSubMap(OMVRBTree<K, V> m, boolean fromStart, K lo, boolean loInclusive, boolean toEnd, K hi, boolean hiInclusive) {
if (!fromStart && !toEnd) {
if (m.compare(lo, hi) > 0)
throw new IllegalArgumentException("fromKey > toKey");
@@ -1383,68 +1408,68 @@ final boolean inRange(Object key, boolean inclusive) {
* descending maps
*/
- final OTreeMapEntry<K, V> absLowest() {
- OTreeMapEntry<K, V> e = (fromStart ? m.getFirstEntry() : (loInclusive ? m.getCeilingEntry(lo) : m.getHigherEntry(lo)));
+ final OMVRBTreeEntry<K, V> absLowest() {
+ OMVRBTreeEntry<K, V> e = (fromStart ? m.getFirstEntry() : (loInclusive ? m.getCeilingEntry(lo) : m.getHigherEntry(lo)));
return (e == null || tooHigh(e.getKey())) ? null : e;
}
- final OTreeMapEntry<K, V> absHighest() {
- OTreeMapEntry<K, V> e = (toEnd ? m.getLastEntry() : (hiInclusive ? m.getFloorEntry(hi) : m.getLowerEntry(hi)));
+ final OMVRBTreeEntry<K, V> absHighest() {
+ OMVRBTreeEntry<K, V> e = (toEnd ? m.getLastEntry() : (hiInclusive ? m.getFloorEntry(hi) : m.getLowerEntry(hi)));
return (e == null || tooLow(e.getKey())) ? null : e;
}
- final OTreeMapEntry<K, V> absCeiling(K key) {
+ final OMVRBTreeEntry<K, V> absCeiling(K key) {
if (tooLow(key))
return absLowest();
- OTreeMapEntry<K, V> e = m.getCeilingEntry(key);
+ OMVRBTreeEntry<K, V> e = m.getCeilingEntry(key);
return (e == null || tooHigh(e.getKey())) ? null : e;
}
- final OTreeMapEntry<K, V> absHigher(K key) {
+ final OMVRBTreeEntry<K, V> absHigher(K key) {
if (tooLow(key))
return absLowest();
- OTreeMapEntry<K, V> e = m.getHigherEntry(key);
+ OMVRBTreeEntry<K, V> e = m.getHigherEntry(key);
return (e == null || tooHigh(e.getKey())) ? null : e;
}
- final OTreeMapEntry<K, V> absFloor(K key) {
+ final OMVRBTreeEntry<K, V> absFloor(K key) {
if (tooHigh(key))
return absHighest();
- OTreeMapEntry<K, V> e = m.getFloorEntry(key);
+ OMVRBTreeEntry<K, V> e = m.getFloorEntry(key);
return (e == null || tooLow(e.getKey())) ? null : e;
}
- final OTreeMapEntry<K, V> absLower(K key) {
+ final OMVRBTreeEntry<K, V> absLower(K key) {
if (tooHigh(key))
return absHighest();
- OTreeMapEntry<K, V> e = m.getLowerEntry(key);
+ OMVRBTreeEntry<K, V> e = m.getLowerEntry(key);
return (e == null || tooLow(e.getKey())) ? null : e;
}
/** Returns the absolute high fence for ascending traversal */
- final OTreeMapEntry<K, V> absHighFence() {
+ final OMVRBTreeEntry<K, V> absHighFence() {
return (toEnd ? null : (hiInclusive ? m.getHigherEntry(hi) : m.getCeilingEntry(hi)));
}
/** Return the absolute low fence for descending traversal */
- final OTreeMapEntry<K, V> absLowFence() {
+ final OMVRBTreeEntry<K, V> absLowFence() {
return (fromStart ? null : (loInclusive ? m.getLowerEntry(lo) : m.getFloorEntry(lo)));
}
// Abstract methods defined in ascending vs descending classes
// These relay to the appropriate absolute versions
- abstract OTreeMapEntry<K, V> subLowest();
+ abstract OMVRBTreeEntry<K, V> subLowest();
- abstract OTreeMapEntry<K, V> subHighest();
+ abstract OMVRBTreeEntry<K, V> subHighest();
- abstract OTreeMapEntry<K, V> subCeiling(K key);
+ abstract OMVRBTreeEntry<K, V> subCeiling(K key);
- abstract OTreeMapEntry<K, V> subHigher(K key);
+ abstract OMVRBTreeEntry<K, V> subHigher(K key);
- abstract OTreeMapEntry<K, V> subFloor(K key);
+ abstract OMVRBTreeEntry<K, V> subFloor(K key);
- abstract OTreeMapEntry<K, V> subLower(K key);
+ abstract OMVRBTreeEntry<K, V> subLower(K key);
/** Returns ascending iterator from the perspective of this submap */
abstract Iterator<K> keyIterator();
@@ -1535,7 +1560,7 @@ public final Map.Entry<K, V> lastEntry() {
}
public final Map.Entry<K, V> pollFirstEntry() {
- OTreeMapEntry<K, V> e = subLowest();
+ OMVRBTreeEntry<K, V> e = subLowest();
Map.Entry<K, V> result = exportEntry(e);
if (e != null)
m.deleteEntry(e);
@@ -1543,7 +1568,7 @@ public final Map.Entry<K, V> pollFirstEntry() {
}
public final Map.Entry<K, V> pollLastEntry() {
- OTreeMapEntry<K, V> e = subHighest();
+ OMVRBTreeEntry<K, V> e = subHighest();
Map.Entry<K, V> result = exportEntry(e);
if (e != null)
m.deleteEntry(e);
@@ -1558,7 +1583,7 @@ public final Map.Entry<K, V> pollLastEntry() {
@SuppressWarnings("rawtypes")
public final ONavigableSet<K> navigableKeySet() {
KeySet<K> nksv = navigableKeySetView;
- return (nksv != null) ? nksv : (navigableKeySetView = new OTreeMap.KeySet(this));
+ return (nksv != null) ? nksv : (navigableKeySetView = new OMVRBTree.KeySet(this));
}
@Override
@@ -1605,15 +1630,15 @@ public int size() {
@Override
public boolean isEmpty() {
- OTreeMapEntry<K, V> n = absLowest();
+ OMVRBTreeEntry<K, V> n = absLowest();
return n == null || tooHigh(n.getKey());
}
@Override
public boolean contains(final Object o) {
- if (!(o instanceof OTreeMapEntry))
+ if (!(o instanceof OMVRBTreeEntry))
return false;
- OTreeMapEntry<K, V> entry = (OTreeMapEntry<K, V>) o;
+ OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o;
K key = entry.getKey();
if (!inRange(key))
return false;
@@ -1623,13 +1648,13 @@ public boolean contains(final Object o) {
@Override
public boolean remove(final Object o) {
- if (!(o instanceof OTreeMapEntry))
+ if (!(o instanceof OMVRBTreeEntry))
return false;
- final OTreeMapEntry<K, V> entry = (OTreeMapEntry<K, V>) o;
+ final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o;
K key = entry.getKey();
if (!inRange(key))
return false;
- final OTreeMapEntry<K, V> node = m.getEntry(key);
+ final OMVRBTreeEntry<K, V> node = m.getEntry(key);
if (node != null && valEquals(node.getValue(), entry.getValue())) {
m.deleteEntry(node);
return true;
@@ -1642,12 +1667,12 @@ public boolean remove(final Object o) {
* Iterators for SubMaps
*/
abstract class SubMapIterator<T> implements Iterator<T> {
- OTreeMapEntry<K, V> lastReturned;
- OTreeMapEntry<K, V> next;
+ OMVRBTreeEntry<K, V> lastReturned;
+ OMVRBTreeEntry<K, V> next;
final K fenceKey;
int expectedModCount;
- SubMapIterator(final OTreeMapEntry<K, V> first, final OTreeMapEntry<K, V> fence) {
+ SubMapIterator(final OMVRBTreeEntry<K, V> first, final OMVRBTreeEntry<K, V> fence) {
expectedModCount = m.modCount;
lastReturned = null;
next = first;
@@ -1658,8 +1683,8 @@ public final boolean hasNext() {
return next != null && next.getKey() != fenceKey;
}
- final OTreeMapEntry<K, V> nextEntry() {
- OTreeMapEntry<K, V> e = next;
+ final OMVRBTreeEntry<K, V> nextEntry() {
+ OMVRBTreeEntry<K, V> e = next;
if (e == null || e.getKey() == fenceKey)
throw new NoSuchElementException();
if (m.modCount != expectedModCount)
@@ -1669,8 +1694,8 @@ final OTreeMapEntry<K, V> nextEntry() {
return e;
}
- final OTreeMapEntry<K, V> prevEntry() {
- OTreeMapEntry<K, V> e = next;
+ final OMVRBTreeEntry<K, V> prevEntry() {
+ OMVRBTreeEntry<K, V> e = next;
if (e == null || e.getKey() == fenceKey)
throw new NoSuchElementException();
if (m.modCount != expectedModCount)
@@ -1706,7 +1731,7 @@ final void removeDescending() {
}
final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> {
- SubMapEntryIterator(final OTreeMapEntry<K, V> first, final OTreeMapEntry<K, V> fence) {
+ SubMapEntryIterator(final OMVRBTreeEntry<K, V> first, final OMVRBTreeEntry<K, V> fence) {
super(first, fence);
}
@@ -1720,7 +1745,7 @@ public void remove() {
}
final class SubMapKeyIterator extends SubMapIterator<K> {
- SubMapKeyIterator(final OTreeMapEntry<K, V> first, final OTreeMapEntry<K, V> fence) {
+ SubMapKeyIterator(final OMVRBTreeEntry<K, V> first, final OMVRBTreeEntry<K, V> fence) {
super(first, fence);
}
@@ -1734,7 +1759,7 @@ public void remove() {
}
final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> {
- DescendingSubMapEntryIterator(final OTreeMapEntry<K, V> last, final OTreeMapEntry<K, V> fence) {
+ DescendingSubMapEntryIterator(final OMVRBTreeEntry<K, V> last, final OMVRBTreeEntry<K, V> fence) {
super(last, fence);
}
@@ -1748,7 +1773,7 @@ public void remove() {
}
final class DescendingSubMapKeyIterator extends SubMapIterator<K> {
- DescendingSubMapKeyIterator(final OTreeMapEntry<K, V> last, final OTreeMapEntry<K, V> fence) {
+ DescendingSubMapKeyIterator(final OMVRBTreeEntry<K, V> last, final OMVRBTreeEntry<K, V> fence) {
super(last, fence);
}
@@ -1768,7 +1793,7 @@ public void remove() {
static final class AscendingSubMap<K, V> extends NavigableSubMap<K, V> {
private static final long serialVersionUID = 912986545866124060L;
- AscendingSubMap(final OTreeMap<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd,
+ AscendingSubMap(final OMVRBTree<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd,
K hi, final boolean hiInclusive) {
super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
}
@@ -1827,32 +1852,32 @@ public Set<Map.Entry<K, V>> entrySet() {
}
@Override
- OTreeMapEntry<K, V> subLowest() {
+ OMVRBTreeEntry<K, V> subLowest() {
return absLowest();
}
@Override
- OTreeMapEntry<K, V> subHighest() {
+ OMVRBTreeEntry<K, V> subHighest() {
return absHighest();
}
@Override
- OTreeMapEntry<K, V> subCeiling(final K key) {
+ OMVRBTreeEntry<K, V> subCeiling(final K key) {
return absCeiling(key);
}
@Override
- OTreeMapEntry<K, V> subHigher(final K key) {
+ OMVRBTreeEntry<K, V> subHigher(final K key) {
return absHigher(key);
}
@Override
- OTreeMapEntry<K, V> subFloor(final K key) {
+ OMVRBTreeEntry<K, V> subFloor(final K key) {
return absFloor(key);
}
@Override
- OTreeMapEntry<K, V> subLower(final K key) {
+ OMVRBTreeEntry<K, V> subLower(final K key) {
return absLower(key);
}
}
@@ -1865,7 +1890,7 @@ static final class DescendingSubMap<K, V> extends NavigableSubMap<K, V> {
private final Comparator<? super K> reverseComparator = Collections.reverseOrder(m.comparator);
- DescendingSubMap(final OTreeMap<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd,
+ DescendingSubMap(final OMVRBTree<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd,
final K hi, final boolean hiInclusive) {
super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
}
@@ -1924,32 +1949,32 @@ public Set<Map.Entry<K, V>> entrySet() {
}
@Override
- OTreeMapEntry<K, V> subLowest() {
+ OMVRBTreeEntry<K, V> subLowest() {
return absHighest();
}
@Override
- OTreeMapEntry<K, V> subHighest() {
+ OMVRBTreeEntry<K, V> subHighest() {
return absLowest();
}
@Override
- OTreeMapEntry<K, V> subCeiling(final K key) {
+ OMVRBTreeEntry<K, V> subCeiling(final K key) {
return absFloor(key);
}
@Override
- OTreeMapEntry<K, V> subHigher(final K key) {
+ OMVRBTreeEntry<K, V> subHigher(final K key) {
return absLower(key);
}
@Override
- OTreeMapEntry<K, V> subFloor(final K key) {
+ OMVRBTreeEntry<K, V> subFloor(final K key) {
return absCeiling(key);
}
@Override
- OTreeMapEntry<K, V> subLower(final K key) {
+ OMVRBTreeEntry<K, V> subLower(final K key) {
return absHigher(key);
}
}
@@ -1964,10 +1989,10 @@ OTreeMapEntry<K, V> subLower(final K key) {
*/
/**
- * Returns the first Entry in the OTreeMap (according to the OTreeMap's key-sort function). Returns null if the OTreeMap is empty.
+ * Returns the first Entry in the OMVRBTree (according to the OMVRBTree's key-sort function). Returns null if the OMVRBTree is empty.
*/
- protected OTreeMapEntry<K, V> getFirstEntry() {
- OTreeMapEntry<K, V> p = root;
+ protected OMVRBTreeEntry<K, V> getFirstEntry() {
+ OMVRBTreeEntry<K, V> p = root;
if (p != null) {
if (p.getSize() > 0)
pageIndex = 0;
@@ -1979,10 +2004,10 @@ protected OTreeMapEntry<K, V> getFirstEntry() {
}
/**
- * Returns the last Entry in the OTreeMap (according to the OTreeMap's key-sort function). Returns null if the OTreeMap is empty.
+ * Returns the last Entry in the OMVRBTree (according to the OMVRBTree's key-sort function). Returns null if the OMVRBTree is empty.
*/
- protected final OTreeMapEntry<K, V> getLastEntry() {
- OTreeMapEntry<K, V> p = root;
+ protected final OMVRBTreeEntry<K, V> getLastEntry() {
+ OMVRBTreeEntry<K, V> p = root;
if (p != null)
while (p.getRight() != null)
p = p.getRight();
@@ -1996,11 +2021,11 @@ protected final OTreeMapEntry<K, V> getLastEntry() {
/**
* Returns the successor of the specified Entry, or null if no such.
*/
- public static <K, V> OTreeMapEntry<K, V> successor(final OTreeMapEntry<K, V> t) {
+ public static <K, V> OMVRBTreeEntry<K, V> successor(final OMVRBTreeEntry<K, V> t) {
if (t == null)
return null;
- OTreeMapEntry<K, V> p = null;
+ OMVRBTreeEntry<K, V> p = null;
if (t.getRight() != null) {
p = t.getRight();
@@ -2008,7 +2033,7 @@ public static <K, V> OTreeMapEntry<K, V> successor(final OTreeMapEntry<K, V> t)
p = p.getLeft();
} else {
p = t.getParent();
- OTreeMapEntry<K, V> ch = t;
+ OMVRBTreeEntry<K, V> ch = t;
while (p != null && ch == p.getRight()) {
ch = p;
p = p.getParent();
@@ -2021,16 +2046,16 @@ public static <K, V> OTreeMapEntry<K, V> successor(final OTreeMapEntry<K, V> t)
/**
* Returns the predecessor of the specified Entry, or null if no such.
*/
- public static <K, V> OTreeMapEntry<K, V> predecessor(final OTreeMapEntry<K, V> t) {
+ public static <K, V> OMVRBTreeEntry<K, V> predecessor(final OMVRBTreeEntry<K, V> t) {
if (t == null)
return null;
else if (t.getLeft() != null) {
- OTreeMapEntry<K, V> p = t.getLeft();
+ OMVRBTreeEntry<K, V> p = t.getLeft();
while (p.getRight() != null)
p = p.getRight();
return p;
} else {
- OTreeMapEntry<K, V> p = t.getParent();
+ OMVRBTreeEntry<K, V> p = t.getParent();
Entry<K, V> ch = t;
while (p != null && ch == p.getLeft()) {
ch = p;
@@ -2048,31 +2073,31 @@ else if (t.getLeft() != null) {
* checks in the main algorithms.
*/
- private static <K, V> boolean colorOf(final OTreeMapEntry<K, V> p) {
+ private static <K, V> boolean colorOf(final OMVRBTreeEntry<K, V> p) {
return (p == null ? BLACK : p.getColor());
}
- private static <K, V> OTreeMapEntry<K, V> parentOf(final OTreeMapEntry<K, V> p) {
+ private static <K, V> OMVRBTreeEntry<K, V> parentOf(final OMVRBTreeEntry<K, V> p) {
return (p == null ? null : p.getParent());
}
- private static <K, V> void setColor(final OTreeMapEntry<K, V> p, final boolean c) {
+ private static <K, V> void setColor(final OMVRBTreeEntry<K, V> p, final boolean c) {
if (p != null)
p.setColor(c);
}
- private static <K, V> OTreeMapEntry<K, V> leftOf(final OTreeMapEntry<K, V> p) {
+ private static <K, V> OMVRBTreeEntry<K, V> leftOf(final OMVRBTreeEntry<K, V> p) {
return (p == null) ? null : p.getLeft();
}
- private static <K, V> OTreeMapEntry<K, V> rightOf(final OTreeMapEntry<K, V> p) {
+ private static <K, V> OMVRBTreeEntry<K, V> rightOf(final OMVRBTreeEntry<K, V> p) {
return (p == null) ? null : p.getRight();
}
/** From CLR */
- private void rotateLeft(final OTreeMapEntry<K, V> p) {
+ private void rotateLeft(final OMVRBTreeEntry<K, V> p) {
if (p != null) {
- OTreeMapEntry<K, V> r = p.getRight();
+ OMVRBTreeEntry<K, V> r = p.getRight();
p.setRight(r.getLeft());
if (r.getLeft() != null)
r.getLeft().setParent(p);
@@ -2088,14 +2113,14 @@ else if (p.getParent().getLeft() == p)
}
}
- protected void setRoot(final OTreeMapEntry<K, V> iRoot) {
+ protected void setRoot(final OMVRBTreeEntry<K, V> iRoot) {
root = iRoot;
}
/** From CLR */
- private void rotateRight(final OTreeMapEntry<K, V> p) {
+ private void rotateRight(final OMVRBTreeEntry<K, V> p) {
if (p != null) {
- OTreeMapEntry<K, V> l = p.getLeft();
+ OMVRBTreeEntry<K, V> l = p.getLeft();
p.setLeft(l.getRight());
if (l.getRight() != null)
l.getRight().setParent(p);
@@ -2113,22 +2138,22 @@ else if (p.getParent().getRight() == p)
/** From CLR */
/*
- * private void fixAfterInsertion(OTreeMapEntry<K, V> x) { x.setColor(RED);
+ * private void fixAfterInsertion(OMVRBTreeEntry<K, V> x) { x.setColor(RED);
*
* // if (x != null && x != root && x.getParent() != null && x.getParent().getColor() == RED) { //
* //System.out.println("BEFORE FIX on node: " + x); // printInMemoryStructure(x);
*
- * OTreeMapEntry<K, V> parent; OTreeMapEntry<K, V> grandParent;
+ * OMVRBTreeEntry<K, V> parent; OMVRBTreeEntry<K, V> grandParent;
*
* while (x != null && x != root && x.getParent() != null && x.getParent().getColor() == RED) { parent = parentOf(x); grandParent
* = parentOf(parent);
*
- * if (parent == leftOf(grandParent)) { // MY PARENT IS THE LEFT OF THE GRANDFATHER. GET MY UNCLE final OTreeMapEntry<K, V> uncle
+ * if (parent == leftOf(grandParent)) { // MY PARENT IS THE LEFT OF THE GRANDFATHER. GET MY UNCLE final OMVRBTreeEntry<K, V> uncle
* = rightOf(grandParent); if (colorOf(uncle) == RED) { // SET MY PARENT AND UNCLE TO BLACK setColor(parent, BLACK);
* setColor(uncle, BLACK); // SET GRANDPARENT'S COLOR TO RED setColor(grandParent, RED); // CONTINUE RECURSIVELY WITH MY
* GRANDFATHER x = grandParent; } else { if (x == rightOf(parent)) { // I'M THE RIGHT x = parent; parent = parentOf(x);
* grandParent = parentOf(parent); rotateLeft(x); } setColor(parent, BLACK); setColor(grandParent, RED); rotateRight(grandParent);
- * } } else { // MY PARENT IS THE RIGHT OF THE GRANDFATHER. GET MY UNCLE final OTreeMapEntry<K, V> uncle = leftOf(grandParent); if
+ * } } else { // MY PARENT IS THE RIGHT OF THE GRANDFATHER. GET MY UNCLE final OMVRBTreeEntry<K, V> uncle = leftOf(grandParent); if
* (colorOf(uncle) == RED) { setColor(parent, BLACK); setColor(uncle, BLACK); setColor(grandParent, RED); x = grandParent; } else
* { if (x == leftOf(parent)) { x = parentOf(x); parent = parentOf(x); grandParent = parentOf(parent); rotateRight(x); }
* setColor(parent, BLACK); setColor(grandParent, RED); rotateLeft(grandParent); } } }
@@ -2138,32 +2163,32 @@ else if (p.getParent().getRight() == p)
* root.setColor(BLACK); }
*/
- private OTreeMapEntry<K, V> grandparent(final OTreeMapEntry<K, V> n) {
+ private OMVRBTreeEntry<K, V> grandparent(final OMVRBTreeEntry<K, V> n) {
return parentOf(parentOf(n));
}
- private OTreeMapEntry<K, V> uncle(final OTreeMapEntry<K, V> n) {
+ private OMVRBTreeEntry<K, V> uncle(final OMVRBTreeEntry<K, V> n) {
if (parentOf(n) == leftOf(grandparent(n)))
return rightOf(grandparent(n));
else
return leftOf(grandparent(n));
}
- private void fixAfterInsertion(final OTreeMapEntry<K, V> n) {
+ private void fixAfterInsertion(final OMVRBTreeEntry<K, V> n) {
if (parentOf(n) == null)
setColor(n, BLACK);
else
insert_case2(n);
}
- private void insert_case2(final OTreeMapEntry<K, V> n) {
+ private void insert_case2(final OMVRBTreeEntry<K, V> n) {
if (colorOf(parentOf(n)) == BLACK)
return; /* Tree is still valid */
else
insert_case3(n);
}
- private void insert_case3(final OTreeMapEntry<K, V> n) {
+ private void insert_case3(final OMVRBTreeEntry<K, V> n) {
if (uncle(n) != null && colorOf(uncle(n)) == RED) {
setColor(parentOf(n), BLACK);
setColor(uncle(n), BLACK);
@@ -2173,7 +2198,7 @@ private void insert_case3(final OTreeMapEntry<K, V> n) {
insert_case4(n);
}
- private void insert_case4(OTreeMapEntry<K, V> n) {
+ private void insert_case4(OMVRBTreeEntry<K, V> n) {
if (n == rightOf(parentOf(n)) && parentOf(n) == leftOf(grandparent(n))) {
rotateLeft(parentOf(n));
n = leftOf(n);
@@ -2184,7 +2209,7 @@ private void insert_case4(OTreeMapEntry<K, V> n) {
insert_case5(n);
}
- private void insert_case5(final OTreeMapEntry<K, V> n) {
+ private void insert_case5(final OMVRBTreeEntry<K, V> n) {
setColor(parentOf(n), BLACK);
setColor(grandparent(n), RED);
if (n == leftOf(parentOf(n)) && parentOf(n) == leftOf(grandparent(n))) {
@@ -2201,7 +2226,7 @@ private void insert_case5(final OTreeMapEntry<K, V> n) {
* @param iIndex
* -1 = delete the node, otherwise the item inside of it
*/
- void deleteEntry(OTreeMapEntry<K, V> p) {
+ void deleteEntry(OMVRBTreeEntry<K, V> p) {
size--;
if (listener != null)
@@ -2221,13 +2246,13 @@ void deleteEntry(OTreeMapEntry<K, V> p) {
// If strictly internal, copy successor's element to p and then make p
// point to successor.
if (p.getLeft() != null && p.getRight() != null) {
- OTreeMapEntry<K, V> s = successor(p);
+ OMVRBTreeEntry<K, V> s = successor(p);
p.copyFrom(s);
p = s;
} // p has 2 children
// Start fixup at replacement node, if it exists.
- final OTreeMapEntry<K, V> replacement = (p.getLeft() != null ? p.getLeft() : p.getRight());
+ final OMVRBTreeEntry<K, V> replacement = (p.getLeft() != null ? p.getLeft() : p.getRight());
if (replacement != null) {
// Link replacement to parent
@@ -2262,10 +2287,10 @@ else if (p == p.getParent().getRight())
}
/** From CLR */
- private void fixAfterDeletion(OTreeMapEntry<K, V> x) {
+ private void fixAfterDeletion(OMVRBTreeEntry<K, V> x) {
while (x != root && colorOf(x) == BLACK) {
if (x == leftOf(parentOf(x))) {
- OTreeMapEntry<K, V> sib = rightOf(parentOf(x));
+ OMVRBTreeEntry<K, V> sib = rightOf(parentOf(x));
if (colorOf(sib) == RED) {
setColor(sib, BLACK);
@@ -2291,7 +2316,7 @@ private void fixAfterDeletion(OTreeMapEntry<K, V> x) {
x = root;
}
} else { // symmetric
- OTreeMapEntry<K, V> sib = leftOf(parentOf(x));
+ OMVRBTreeEntry<K, V> sib = leftOf(parentOf(x));
if (colorOf(sib) == RED) {
setColor(sib, BLACK);
@@ -2325,11 +2350,11 @@ private void fixAfterDeletion(OTreeMapEntry<K, V> x) {
private static final long serialVersionUID = 919286545866124006L;
/**
- * Save the state of the <tt>OTreeMap</tt> instance to a stream (i.e., serialize it).
+ * Save the state of the <tt>OMVRBTree</tt> instance to a stream (i.e., serialize it).
*
- * @serialData The <i>size</i> of the OTreeMap (the number of key-value mappings) is emitted (int), followed by the key (Object)
- * and value (Object) for each key-value mapping represented by the OTreeMap. The key-value mappings are emitted in
- * key-order (as determined by the OTreeMap's Comparator, or by the keys' natural ordering if the OTreeMap has no
+ * @serialData The <i>size</i> of the OMVRBTree (the number of key-value mappings) is emitted (int), followed by the key (Object)
+ * and value (Object) for each key-value mapping represented by the OMVRBTree. The key-value mappings are emitted in
+ * key-order (as determined by the OMVRBTree's Comparator, or by the keys' natural ordering if the OMVRBTree has no
* Comparator).
*/
private void writeObject(final java.io.ObjectOutputStream s) throws java.io.IOException {
@@ -2348,7 +2373,7 @@ private void writeObject(final java.io.ObjectOutputStream s) throws java.io.IOEx
}
/**
- * Reconstitute the <tt>OTreeMap</tt> instance from a stream (i.e., deserialize it).
+ * Reconstitute the <tt>OMVRBTree</tt> instance from a stream (i.e., deserialize it).
*/
private void readObject(final java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
// Read in the Comparator and any hidden stuff
@@ -2382,7 +2407,7 @@ void addAllForOTreeSet(SortedSet<? extends K> set, V defaultVal) {
* stream of alternating serialized keys and values. (it == null, defaultVal == null). 4) A stream of serialized keys. (it ==
* null, defaultVal != null).
*
- * It is assumed that the comparator of the OTreeMap is already set prior to calling this method.
+ * It is assumed that the comparator of the OMVRBTree is already set prior to calling this method.
*
* @param size
* the number of keys (or key-value pairs) to be read from the iterator or stream
@@ -2407,7 +2432,7 @@ private void buildFromSorted(final int size, final Iterator<?> it, final java.io
/**
* Recursive "helper method" that does the real work of the previous method. Identically named parameters have identical
- * definitions. Additional parameters are documented below. It is assumed that the comparator and size fields of the OTreeMap are
+ * definitions. Additional parameters are documented below. It is assumed that the comparator and size fields of the OMVRBTree are
* already set prior to calling this method. (It ignores both fields.)
*
* @param level
@@ -2419,7 +2444,7 @@ private void buildFromSorted(final int size, final Iterator<?> it, final java.io
* @param redLevel
* the level at which nodes should be red. Must be equal to computeRedLevel for tree of this size.
*/
- private final OTreeMapEntry<K, V> buildFromSorted(final int level, final int lo, final int hi, final int redLevel,
+ private final OMVRBTreeEntry<K, V> buildFromSorted(final int level, final int lo, final int hi, final int redLevel,
final Iterator<?> it, final java.io.ObjectInputStream str, final V defaultVal) throws java.io.IOException,
ClassNotFoundException {
/*
@@ -2435,7 +2460,7 @@ private final OTreeMapEntry<K, V> buildFromSorted(final int level, final int lo,
final int mid = (lo + hi) / 2;
- OTreeMapEntry<K, V> left = null;
+ OMVRBTreeEntry<K, V> left = null;
if (lo < mid)
left = buildFromSorted(level + 1, lo, mid - 1, redLevel, it, str, defaultVal);
@@ -2444,7 +2469,7 @@ private final OTreeMapEntry<K, V> buildFromSorted(final int level, final int lo,
V value;
if (it != null) {
if (defaultVal == null) {
- OTreeMapEntry<K, V> entry = (OTreeMapEntry<K, V>) it.next();
+ OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) it.next();
key = entry.getKey();
value = entry.getValue();
} else {
@@ -2456,7 +2481,7 @@ private final OTreeMapEntry<K, V> buildFromSorted(final int level, final int lo,
value = (defaultVal != null ? defaultVal : (V) str.readObject());
}
- final OTreeMapEntry<K, V> middle = createEntry(key, value);
+ final OMVRBTreeEntry<K, V> middle = createEntry(key, value);
// color nodes in non-full bottom most level red
if (level == redLevel)
@@ -2468,7 +2493,7 @@ private final OTreeMapEntry<K, V> buildFromSorted(final int level, final int lo,
}
if (mid < hi) {
- OTreeMapEntry<K, V> right = buildFromSorted(level + 1, mid + 1, hi, redLevel, it, str, defaultVal);
+ OMVRBTreeEntry<K, V> right = buildFromSorted(level + 1, mid + 1, hi, redLevel, it, str, defaultVal);
middle.setRight(right);
right.setParent(middle);
}
@@ -2500,15 +2525,15 @@ public int getPageIndex() {
private void init() {
}
- public OTreeMapEntry<K, V> getRoot() {
+ public OMVRBTreeEntry<K, V> getRoot() {
return root;
}
- protected void printInMemoryStructure(final OTreeMapEntry<K, V> iRootNode) {
+ protected void printInMemoryStructure(final OMVRBTreeEntry<K, V> iRootNode) {
printInMemoryNode("root", iRootNode, 0);
}
- private void printInMemoryNode(final String iLabel, OTreeMapEntry<K, V> iNode, int iLevel) {
+ private void printInMemoryNode(final String iLabel, OMVRBTreeEntry<K, V> iNode, int iLevel) {
if (iNode == null)
return;
@@ -2524,52 +2549,52 @@ private void printInMemoryNode(final String iLabel, OTreeMapEntry<K, V> iNode, i
}
@SuppressWarnings("rawtypes")
- public void checkTreeStructure(final OTreeMapEntry<K, V> iRootNode) {
+ public void checkTreeStructure(final OMVRBTreeEntry<K, V> iRootNode) {
if (!runtimeCheckEnabled || iRootNode == null)
return;
int currPageIndex = pageIndex;
- OTreeMapEntry<K, V> prevNode = null;
+ OMVRBTreeEntry<K, V> prevNode = null;
int i = 0;
- for (OTreeMapEntry<K, V> e = iRootNode.getFirstInMemory(); e != null; e = e.getNextInMemory()) {
+ for (OMVRBTreeEntry<K, V> e = iRootNode.getFirstInMemory(); e != null; e = e.getNextInMemory()) {
if (prevNode != null) {
if (prevNode.getTree() == null)
- OLogManager.instance().error(this, "[OTreeMap.checkTreeStructure] Freed record %d found in memory\n", i);
+ OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Freed record %d found in memory\n", i);
if (((Comparable) e.getFirstKey()).compareTo(((Comparable) e.getLastKey())) > 0) {
- OLogManager.instance().error(this, "[OTreeMap.checkTreeStructure] begin key is > than last key\n", e.getFirstKey(),
+ OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] begin key is > than last key\n", e.getFirstKey(),
e.getLastKey());
printInMemoryStructure(iRootNode);
}
if (((Comparable) e.getFirstKey()).compareTo(((Comparable) prevNode.getLastKey())) < 0) {
OLogManager.instance().error(this,
- "[OTreeMap.checkTreeStructure] Node %s starts with a key minor than the last key of the previous node %s\n", e,
+ "[OMVRBTree.checkTreeStructure] Node %s starts with a key minor than the last key of the previous node %s\n", e,
prevNode);
printInMemoryStructure(e.getParentInMemory() != null ? e.getParentInMemory() : e);
}
}
if (e.getLeftInMemory() != null && e.getLeftInMemory() == e) {
- OLogManager.instance().error(this, "[OTreeMap.checkTreeStructure] Node %s has left that points to itself!\n", e);
+ OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Node %s has left that points to itself!\n", e);
printInMemoryStructure(iRootNode);
}
if (e.getRightInMemory() != null && e.getRightInMemory() == e) {
- OLogManager.instance().error(this, "[OTreeMap.checkTreeStructure] Node %s has right that points to itself!\n", e);
+ OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Node %s has right that points to itself!\n", e);
printInMemoryStructure(iRootNode);
}
if (e.getLeftInMemory() != null && e.getLeftInMemory() == e.getRightInMemory()) {
- OLogManager.instance().error(this, "[OTreeMap.checkTreeStructure] Node %s has left and right equals!\n", e);
+ OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Node %s has left and right equals!\n", e);
printInMemoryStructure(iRootNode);
}
if (e.getParentInMemory() != null && e.getParentInMemory().getRightInMemory() != e
&& e.getParentInMemory().getLeftInMemory() != e) {
OLogManager.instance().error(this,
- "[OTreeMap.checkTreeStructure] Node %s is the children of node %s but the cross-reference is missed!\n", e,
+ "[OMVRBTree.checkTreeStructure] Node %s is the children of node %s but the cross-reference is missed!\n", e,
e.getParentInMemory());
printInMemoryStructure(iRootNode);
}
diff --git a/commons/src/main/java/com/orientechnologies/common/collection/OTreeMapEntry.java b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeEntry.java
similarity index 82%
rename from commons/src/main/java/com/orientechnologies/common/collection/OTreeMapEntry.java
rename to commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeEntry.java
index 35e74c2f810..5948ec13f1a 100644
--- a/commons/src/main/java/com/orientechnologies/common/collection/OTreeMapEntry.java
+++ b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeEntry.java
@@ -18,15 +18,15 @@
import java.util.Map;
@SuppressWarnings("unchecked")
-public abstract class OTreeMapEntry<K, V> implements Map.Entry<K, V> {
- protected OTreeMap<K, V> tree;
+public abstract class OMVRBTreeEntry<K, V> implements Map.Entry<K, V> {
+ protected OMVRBTree<K, V> tree;
protected int size = 1;
protected int pageSize;
protected K[] keys;
protected V[] values;
- protected boolean color = OTreeMap.RED;
+ protected boolean color = OMVRBTree.RED;
private int pageSplitItems;
public static final int BINARY_SEARCH_THRESHOLD = 10;
@@ -35,7 +35,7 @@ public abstract class OTreeMapEntry<K, V> implements Map.Entry<K, V> {
* Constructor called on unmarshalling.
*
*/
- protected OTreeMapEntry(final OTreeMap<K, V> iTree) {
+ protected OMVRBTreeEntry(final OMVRBTree<K, V> iTree) {
this.tree = iTree;
init();
}
@@ -43,7 +43,7 @@ protected OTreeMapEntry(final OTreeMap<K, V> iTree) {
/**
* Make a new cell with given key, value, and parent, and with <tt>null</tt> child links, and BLACK color.
*/
- protected OTreeMapEntry(final OTreeMap<K, V> iTree, final K iKey, final V iValue, final OTreeMapEntry<K, V> iParent) {
+ protected OMVRBTreeEntry(final OMVRBTree<K, V> iTree, final K iKey, final V iValue, final OMVRBTreeEntry<K, V> iParent) {
this.tree = iTree;
setParent(iParent);
this.pageSize = tree.getPageSize();
@@ -61,7 +61,7 @@ protected OTreeMapEntry(final OTreeMap<K, V> iTree, final K iKey, final V iValue
* @param iPosition
* @param iLeft
*/
- protected OTreeMapEntry(final OTreeMapEntry<K, V> iParent, final int iPosition) {
+ protected OMVRBTreeEntry(final OMVRBTreeEntry<K, V> iParent, final int iPosition) {
this.tree = iParent.tree;
this.pageSize = tree.getPageSize();
this.keys = (K[]) new Object[pageSize];
@@ -75,32 +75,32 @@ protected OTreeMapEntry(final OTreeMapEntry<K, V> iParent, final int iPosition)
init();
}
- public abstract void setLeft(OTreeMapEntry<K, V> left);
+ public abstract void setLeft(OMVRBTreeEntry<K, V> left);
- public abstract OTreeMapEntry<K, V> getLeft();
+ public abstract OMVRBTreeEntry<K, V> getLeft();
- public abstract OTreeMapEntry<K, V> setRight(OTreeMapEntry<K, V> right);
+ public abstract OMVRBTreeEntry<K, V> setRight(OMVRBTreeEntry<K, V> right);
- public abstract OTreeMapEntry<K, V> getRight();
+ public abstract OMVRBTreeEntry<K, V> getRight();
- public abstract OTreeMapEntry<K, V> setParent(OTreeMapEntry<K, V> parent);
+ public abstract OMVRBTreeEntry<K, V> setParent(OMVRBTreeEntry<K, V> parent);
- public abstract OTreeMapEntry<K, V> getParent();
+ public abstract OMVRBTreeEntry<K, V> getParent();
- protected abstract OTreeMapEntry<K, V> getLeftInMemory();
+ protected abstract OMVRBTreeEntry<K, V> getLeftInMemory();
- protected abstract OTreeMapEntry<K, V> getParentInMemory();
+ protected abstract OMVRBTreeEntry<K, V> getParentInMemory();
- protected abstract OTreeMapEntry<K, V> getRightInMemory();
+ protected abstract OMVRBTreeEntry<K, V> getRightInMemory();
- protected abstract OTreeMapEntry<K, V> getNextInMemory();
+ protected abstract OMVRBTreeEntry<K, V> getNextInMemory();
/**
* Returns the first Entry only by traversing the memory, or null if no such.
*/
- public OTreeMapEntry<K, V> getFirstInMemory() {
- OTreeMapEntry<K, V> node = this;
- OTreeMapEntry<K, V> prev = this;
+ public OMVRBTreeEntry<K, V> getFirstInMemory() {
+ OMVRBTreeEntry<K, V> node = this;
+ OMVRBTreeEntry<K, V> prev = this;
while (node != null) {
prev = node;
@@ -113,9 +113,9 @@ public OTreeMapEntry<K, V> getFirstInMemory() {
/**
* Returns the previous of the current Entry only by traversing the memory, or null if no such.
*/
- public OTreeMapEntry<K, V> getPreviousInMemory() {
- OTreeMapEntry<K, V> t = this;
- OTreeMapEntry<K, V> p = null;
+ public OMVRBTreeEntry<K, V> getPreviousInMemory() {
+ OMVRBTreeEntry<K, V> t = this;
+ OMVRBTreeEntry<K, V> p = null;
if (t.getLeftInMemory() != null) {
p = t.getLeftInMemory();
@@ -132,13 +132,13 @@ public OTreeMapEntry<K, V> getPreviousInMemory() {
return p;
}
- protected OTreeMap<K, V> getTree() {
+ protected OMVRBTree<K, V> getTree() {
return tree;
}
public int getDepth() {
int level = 0;
- OTreeMapEntry<K, V> entry = this;
+ OMVRBTreeEntry<K, V> entry = this;
while (entry.getParent() != null) {
level++;
entry = entry.getParent();
@@ -382,7 +382,7 @@ public K getFirstKey() {
return getKey(0);
}
- protected void copyFrom(final OTreeMapEntry<K, V> iSource) {
+ protected void copyFrom(final OMVRBTreeEntry<K, V> iSource) {
keys = (K[]) new Object[iSource.keys.length];
for (int i = 0; i < iSource.keys.length; ++i)
keys[i] = iSource.keys[i];
diff --git a/commons/src/main/java/com/orientechnologies/common/collection/OTreeMapEntryMemory.java b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeEntryMemory.java
similarity index 56%
rename from commons/src/main/java/com/orientechnologies/common/collection/OTreeMapEntryMemory.java
rename to commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeEntryMemory.java
index 771cee6e36e..0a31d9f9269 100644
--- a/commons/src/main/java/com/orientechnologies/common/collection/OTreeMapEntryMemory.java
+++ b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeEntryMemory.java
@@ -15,23 +15,23 @@
*/
package com.orientechnologies.common.collection;
-public class OTreeMapEntryMemory<K, V> extends OTreeMapEntry<K, V> {
- protected OTreeMapEntryMemory<K, V> left = null;
- protected OTreeMapEntryMemory<K, V> right = null;
- protected OTreeMapEntryMemory<K, V> parent;
+public class OMVRBTreeEntryMemory<K, V> extends OMVRBTreeEntry<K, V> {
+ protected OMVRBTreeEntryMemory<K, V> left = null;
+ protected OMVRBTreeEntryMemory<K, V> right = null;
+ protected OMVRBTreeEntryMemory<K, V> parent;
/**
* Constructor called on unmarshalling.
*
*/
- protected OTreeMapEntryMemory(final OTreeMap<K, V> iTree) {
+ protected OMVRBTreeEntryMemory(final OMVRBTree<K, V> iTree) {
super(iTree);
}
/**
* Make a new cell with given key, value, and parent, and with <tt>null</tt> child links, and BLACK color.
*/
- protected OTreeMapEntryMemory(final OTreeMap<K, V> iTree, final K iKey, final V iValue, final OTreeMapEntryMemory<K, V> iParent) {
+ protected OMVRBTreeEntryMemory(final OMVRBTree<K, V> iTree, final K iKey, final V iValue, final OMVRBTreeEntryMemory<K, V> iParent) {
super(iTree, iKey, iValue, iParent);
}
@@ -42,26 +42,26 @@ protected OTreeMapEntryMemory(final OTreeMap<K, V> iTree, final K iKey, final V
* @param iPosition
* @param iLeft
*/
- protected OTreeMapEntryMemory(final OTreeMapEntry<K, V> iParent, final int iPosition) {
+ protected OMVRBTreeEntryMemory(final OMVRBTreeEntry<K, V> iParent, final int iPosition) {
super(iParent, iPosition);
setParent(iParent);
}
@Override
- public void setLeft(final OTreeMapEntry<K, V> left) {
- this.left = (OTreeMapEntryMemory<K, V>) left;
+ public void setLeft(final OMVRBTreeEntry<K, V> left) {
+ this.left = (OMVRBTreeEntryMemory<K, V>) left;
if (left != null && left.getParent() != this)
left.setParent(this);
}
@Override
- public OTreeMapEntry<K, V> getLeft() {
+ public OMVRBTreeEntry<K, V> getLeft() {
return left;
}
@Override
- public OTreeMapEntry<K, V> setRight(final OTreeMapEntry<K, V> right) {
- this.right = (OTreeMapEntryMemory<K, V>) right;
+ public OMVRBTreeEntry<K, V> setRight(final OMVRBTreeEntry<K, V> right) {
+ this.right = (OMVRBTreeEntryMemory<K, V>) right;
if (right != null && right.getParent() != this)
right.setParent(this);
@@ -69,27 +69,27 @@ public OTreeMapEntry<K, V> setRight(final OTreeMapEntry<K, V> right) {
}
@Override
- public OTreeMapEntry<K, V> getRight() {
+ public OMVRBTreeEntry<K, V> getRight() {
return right;
}
@Override
- public OTreeMapEntry<K, V> setParent(final OTreeMapEntry<K, V> parent) {
- this.parent = (OTreeMapEntryMemory<K, V>) parent;
+ public OMVRBTreeEntry<K, V> setParent(final OMVRBTreeEntry<K, V> parent) {
+ this.parent = (OMVRBTreeEntryMemory<K, V>) parent;
return parent;
}
@Override
- public OTreeMapEntry<K, V> getParent() {
+ public OMVRBTreeEntry<K, V> getParent() {
return parent;
}
/**
* Returns the successor of the current Entry only by traversing the memory, or null if no such.
*/
- public OTreeMapEntryMemory<K, V> getNextInMemory() {
- OTreeMapEntryMemory<K, V> t = this;
- OTreeMapEntryMemory<K, V> p = null;
+ public OMVRBTreeEntryMemory<K, V> getNextInMemory() {
+ OMVRBTreeEntryMemory<K, V> t = this;
+ OMVRBTreeEntryMemory<K, V> p = null;
if (t.right != null) {
p = t.right;
@@ -107,17 +107,17 @@ public OTreeMapEntryMemory<K, V> getNextInMemory() {
}
@Override
- protected OTreeMapEntry<K, V> getLeftInMemory() {
+ protected OMVRBTreeEntry<K, V> getLeftInMemory() {
return left;
}
@Override
- protected OTreeMapEntry<K, V> getParentInMemory() {
+ protected OMVRBTreeEntry<K, V> getParentInMemory() {
return parent;
}
@Override
- protected OTreeMapEntry<K, V> getRightInMemory() {
+ protected OMVRBTreeEntry<K, V> getRightInMemory() {
return right;
}
}
\ No newline at end of file
diff --git a/commons/src/main/java/com/orientechnologies/common/collection/OTreeMapEventListener.java b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeEventListener.java
similarity index 81%
rename from commons/src/main/java/com/orientechnologies/common/collection/OTreeMapEventListener.java
rename to commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeEventListener.java
index aeb6525b69b..a1b4862fbaf 100644
--- a/commons/src/main/java/com/orientechnologies/common/collection/OTreeMapEventListener.java
+++ b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeEventListener.java
@@ -20,8 +20,8 @@
*
* @author Luca Garulli (l.garulli--at--orientechnologies.com)
*/
-public interface OTreeMapEventListener<K, V> {
- public void signalTreeChanged(OTreeMap<K, V> iTree);
+public interface OMVRBTreeEventListener<K, V> {
+ public void signalTreeChanged(OMVRBTree<K, V> iTree);
- public void signalNodeChanged(OTreeMapEntry<K, V> iNode);
+ public void signalNodeChanged(OMVRBTreeEntry<K, V> iNode);
}
diff --git a/commons/src/main/java/com/orientechnologies/common/collection/OTreeMapMemory.java b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeMemory.java
similarity index 65%
rename from commons/src/main/java/com/orientechnologies/common/collection/OTreeMapMemory.java
rename to commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeMemory.java
index f089a091b99..3353de43801 100644
--- a/commons/src/main/java/com/orientechnologies/common/collection/OTreeMapMemory.java
+++ b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeMemory.java
@@ -20,22 +20,23 @@
import java.util.SortedMap;
@SuppressWarnings("serial")
-public class OTreeMapMemory<K, V> extends OTreeMap<K, V> {
+public class OMVRBTreeMemory<K, V> extends OMVRBTree<K, V> {
/**
- * Constructs a new, empty tree map, using the natural ordering of its keys. All keys inserted into the map must implement the
- * {@link Comparable} interface. Furthermore, all such keys must be <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> must not
- * throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and <tt>k2</tt> in the map. If the user attempts to put a key into
- * the map that violates this constraint (for example, the user attempts to put a string key into a map whose keys are integers),
- * the <tt>put(Object key, Object value)</tt> call will throw a <tt>ClassCastException</tt>.
+ * Memory based MVRB-Tree implementation. Constructs a new, empty tree map, using the natural ordering of its keys. All keys
+ * inserted into the map must implement the {@link Comparable} interface. Furthermore, all such keys must be <i>mutually
+ * comparable</i>: <tt>k1.compareTo(k2)</tt> must not throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and <tt>k2</tt>
+ * in the map. If the user attempts to put a key into the map that violates this constraint (for example, the user attempts to put
+ * a string key into a map whose keys are integers), the <tt>put(Object key, Object value)</tt> call will throw a
+ * <tt>ClassCastException</tt>.
*/
- public OTreeMapMemory() {
+ public OMVRBTreeMemory() {
}
- public OTreeMapMemory(final int iSize, final float iLoadFactor) {
+ public OMVRBTreeMemory(final int iSize, final float iLoadFactor) {
super(iSize, iLoadFactor);
}
- public OTreeMapMemory(final OTreeMapEventListener<K, V> iListener) {
+ public OMVRBTreeMemory(final OMVRBTreeEventListener<K, V> iListener) {
super(iListener);
}
@@ -50,7 +51,7 @@ public OTreeMapMemory(final OTreeMapEventListener<K, V> iListener) {
* the comparator that will be used to order this map. If <tt>null</tt>, the {@linkplain Comparable natural ordering} of
* the keys will be used.
*/
- public OTreeMapMemory(final Comparator<? super K> comparator) {
+ public OMVRBTreeMemory(final Comparator<? super K> comparator) {
super(comparator);
}
@@ -67,7 +68,7 @@ public OTreeMapMemory(final Comparator<? super K> comparator) {
* @throws NullPointerException
* if the specified map is null
*/
- public OTreeMapMemory(final Map<? extends K, ? extends V> m) {
+ public OMVRBTreeMemory(final Map<? extends K, ? extends V> m) {
super(m);
}
@@ -80,17 +81,17 @@ public OTreeMapMemory(final Map<? extends K, ? extends V> m) {
* @throws NullPointerException
* if the specified map is null
*/
- public OTreeMapMemory(final SortedMap<K, ? extends V> m) {
+ public OMVRBTreeMemory(final SortedMap<K, ? extends V> m) {
super(m);
}
@Override
- protected OTreeMapEntry<K, V> createEntry(final K key, final V value) {
- return new OTreeMapEntryMemory<K, V>(this, key, value, null);
+ protected OMVRBTreeEntry<K, V> createEntry(final K key, final V value) {
+ return new OMVRBTreeEntryMemory<K, V>(this, key, value, null);
}
@Override
- protected OTreeMapEntry<K, V> createEntry(final OTreeMapEntry<K, V> parent) {
- return new OTreeMapEntryMemory<K, V>(parent, parent.getPageSplitItems());
+ protected OMVRBTreeEntry<K, V> createEntry(final OMVRBTreeEntry<K, V> parent) {
+ return new OMVRBTreeEntryMemory<K, V>(parent, parent.getPageSplitItems());
}
}
diff --git a/commons/src/main/java/com/orientechnologies/common/collection/OTreeSetMemory.java b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeSetMemory.java
similarity index 90%
rename from commons/src/main/java/com/orientechnologies/common/collection/OTreeSetMemory.java
rename to commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeSetMemory.java
index 0d07bdb049d..f09e2c4fda2 100644
--- a/commons/src/main/java/com/orientechnologies/common/collection/OTreeSetMemory.java
+++ b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeSetMemory.java
@@ -24,7 +24,7 @@
import java.util.SortedSet;
@SuppressWarnings("unchecked")
-public class OTreeSetMemory<E> extends AbstractSet<E> implements ONavigableSet<E>, Cloneable, java.io.Serializable {
+public class OMVRBTreeSetMemory<E> extends AbstractSet<E> implements ONavigableSet<E>, Cloneable, java.io.Serializable {
/**
* The backing map.
*/
@@ -36,7 +36,7 @@ public class OTreeSetMemory<E> extends AbstractSet<E> implements ONavigableSet<E
/**
* Constructs a set backed by the specified navigable map.
*/
- OTreeSetMemory(ONavigableMap<E, Object> m) {
+ OMVRBTreeSetMemory(ONavigableMap<E, Object> m) {
this.m = m;
}
@@ -47,8 +47,8 @@ public class OTreeSetMemory<E> extends AbstractSet<E> implements ONavigableSet<E
* the user attempts to add an element to the set that violates this constraint (for example, the user attempts to add a string
* element to a set whose elements are integers), the {@code add} call will throw a {@code ClassCastException}.
*/
- public OTreeSetMemory() {
- this(new OTreeMapMemory<E, Object>());
+ public OMVRBTreeSetMemory() {
+ this(new OMVRBTreeMemory<E, Object>());
}
/**
@@ -61,8 +61,8 @@ public OTreeSetMemory() {
* the comparator that will be used to order this set. If {@code null}, the {@linkplain Comparable natural ordering} of
* the elements will be used.
*/
- public OTreeSetMemory(Comparator<? super E> comparator) {
- this(new OTreeMapMemory<E, Object>(comparator));
+ public OMVRBTreeSetMemory(Comparator<? super E> comparator) {
+ this(new OMVRBTreeMemory<E, Object>(comparator));
}
/**
@@ -78,7 +78,7 @@ public OTreeSetMemory(Comparator<? super E> comparator) {
* @throws NullPointerException
* if the specified collection is null
*/
- public OTreeSetMemory(Collection<? extends E> c) {
+ public OMVRBTreeSetMemory(Collection<? extends E> c) {
this();
addAll(c);
}
@@ -91,7 +91,7 @@ public OTreeSetMemory(Collection<? extends E> c) {
* @throws NullPointerException
* if the specified sorted set is null
*/
- public OTreeSetMemory(SortedSet<E> s) {
+ public OMVRBTreeSetMemory(SortedSet<E> s) {
this(s.comparator());
addAll(s);
}
@@ -120,7 +120,7 @@ public Iterator<E> descendingIterator() {
* @since 1.6
*/
public ONavigableSet<E> descendingSet() {
- return new OTreeSetMemory<E>(m.descendingMap());
+ return new OMVRBTreeSetMemory<E>(m.descendingMap());
}
/**
@@ -220,9 +220,9 @@ public void clear() {
@Override
public boolean addAll(Collection<? extends E> c) {
// Use linear-time version if applicable
- if (m.size() == 0 && c.size() > 0 && c instanceof SortedSet && m instanceof OTreeMap) {
+ if (m.size() == 0 && c.size() > 0 && c instanceof SortedSet && m instanceof OMVRBTree) {
SortedSet<? extends E> set = (SortedSet<? extends E>) c;
- OTreeMap<E, Object> map = (OTreeMap<E, Object>) m;
+ OMVRBTree<E, Object> map = (OMVRBTree<E, Object>) m;
Comparator<? super E> cc = (Comparator<? super E>) set.comparator();
Comparator<? super E> mc = map.comparator();
if (cc == mc || (cc != null && cc.equals(mc))) {
@@ -244,7 +244,7 @@ public boolean addAll(Collection<? extends E> c) {
* @since 1.6
*/
public ONavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
- return new OTreeSetMemory<E>(m.subMap(fromElement, fromInclusive, toElement, toInclusive));
+ return new OMVRBTreeSetMemory<E>(m.subMap(fromElement, fromInclusive, toElement, toInclusive));
}
/**
@@ -257,7 +257,7 @@ public ONavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement
* @since 1.6
*/
public ONavigableSet<E> headSet(E toElement, boolean inclusive) {
- return new OTreeSetMemory<E>(m.headMap(toElement, inclusive));
+ return new OMVRBTreeSetMemory<E>(m.headMap(toElement, inclusive));
}
/**
@@ -270,7 +270,7 @@ public ONavigableSet<E> headSet(E toElement, boolean inclusive) {
* @since 1.6
*/
public ONavigableSet<E> tailSet(E fromElement, boolean inclusive) {
- return new OTreeSetMemory<E>(m.tailMap(fromElement, inclusive));
+ return new OMVRBTreeSetMemory<E>(m.tailMap(fromElement, inclusive));
}
/**
@@ -399,14 +399,14 @@ public E pollLast() {
*/
@Override
public Object clone() {
- OTreeSetMemory<E> clone = null;
+ OMVRBTreeSetMemory<E> clone = null;
try {
- clone = (OTreeSetMemory<E>) super.clone();
+ clone = (OMVRBTreeSetMemory<E>) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
- clone.m = new OTreeMapMemory<E, Object>(m);
+ clone.m = new OMVRBTreeMemory<E, Object>(m);
return clone;
}
@@ -443,12 +443,12 @@ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException,
// Read in Comparator
Comparator<? super E> c = (Comparator<? super E>) s.readObject();
- // Create backing OTreeMap
- OTreeMap<E, Object> tm;
+ // Create backing OMVRBTree
+ OMVRBTree<E, Object> tm;
if (c == null)
- tm = new OTreeMapMemory<E, Object>();
+ tm = new OMVRBTreeMemory<E, Object>();
else
- tm = new OTreeMapMemory<E, Object>(c);
+ tm = new OMVRBTreeMemory<E, Object>(c);
m = tm;
// Read in size
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabase.java b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabase.java
index de3c17879c3..50226478abb 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabase.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabase.java
@@ -197,7 +197,7 @@ public interface ODatabase {
public long countClusterElements(String iClusterName);
/**
- * Adds a logical cluster. Logical clusters don't need separate files since are stored inside a OTreeMap instance. Access is
+ * Adds a logical cluster. Logical clusters don't need separate files since are stored inside a OMVRBTree instance. Access is
* slower than the physical cluster but the database size is reduced and less files are requires. This matters in some OS where a
* single process has limitation for the number of files can open. Most accessed entities should be stored inside a physical
* cluster.
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/kv/OKVDatabase.java b/core/src/main/java/com/orientechnologies/orient/core/db/kv/OKVDatabase.java
index 818c87c50a2..8f9d19af7c2 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/db/kv/OKVDatabase.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/db/kv/OKVDatabase.java
@@ -7,27 +7,27 @@
import com.orientechnologies.orient.core.record.impl.ORecordBytes;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerString;
import com.orientechnologies.orient.core.storage.impl.local.ODictionaryLocal;
-import com.orientechnologies.orient.core.type.tree.OTreeMapDatabase;
+import com.orientechnologies.orient.core.type.tree.OMVRBTreeDatabase;
public class OKVDatabase extends ODatabaseDocumentTx {
public OKVDatabase(final String iURL) {
super(iURL);
}
- public OTreeMapDatabase<String, String> getBucket(final ODatabaseRecordAbstract<ORecordBytes> iDb, final String iBucket)
+ public OMVRBTreeDatabase<String, String> getBucket(final ODatabaseRecordAbstract<ORecordBytes> iDb, final String iBucket)
throws IOException {
ORecordBytes rec = iDb.getDictionary().get(iBucket);
- OTreeMapDatabase<String, String> bucketTree = null;
+ OMVRBTreeDatabase<String, String> bucketTree = null;
if (rec != null) {
- bucketTree = new OTreeMapDatabase<String, String>(iDb, rec.getIdentity());
+ bucketTree = new OMVRBTreeDatabase<String, String>(iDb, rec.getIdentity());
bucketTree.load();
}
if (bucketTree == null) {
// CREATE THE BUCKET
- bucketTree = new OTreeMapDatabase<String, String>(iDb, ODictionaryLocal.DICTIONARY_DEF_CLUSTER_NAME,
+ bucketTree = new OMVRBTreeDatabase<String, String>(iDb, ODictionaryLocal.DICTIONARY_DEF_CLUSTER_NAME,
OStreamSerializerString.INSTANCE, OStreamSerializerString.INSTANCE);
bucketTree.save();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyIndexFullText.java b/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyIndexFullText.java
index 91e6a298d28..ab4531e5465 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyIndexFullText.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyIndexFullText.java
@@ -32,7 +32,7 @@
import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerListRID;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerString;
-import com.orientechnologies.orient.core.type.tree.OTreeMapDatabaseLazySave;
+import com.orientechnologies.orient.core.type.tree.OMVRBTreeDatabaseLazySave;
/**
* Fast index for full-text searches.
@@ -81,7 +81,7 @@ public OPropertyIndex create(final ODatabaseRecord<?> iDatabase, final OProperty
while (db != null && !(db instanceof ODatabaseRecord<?>))
db = db.getUnderlying();
- map = new OTreeMapDatabaseLazySave<String, List<ORecordId>>((ODatabaseRecord<?>) db, iClusterIndexName,
+ map = new OMVRBTreeDatabaseLazySave<String, List<ORecordId>>((ODatabaseRecord<?>) db, iClusterIndexName,
OStreamSerializerString.INSTANCE, OStreamSerializerListRID.INSTANCE);
map.lazySave();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyIndexMVRBTreeAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyIndexMVRBTreeAbstract.java
index 55f3e730cdd..ad7783a6074 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyIndexMVRBTreeAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyIndexMVRBTreeAbstract.java
@@ -31,7 +31,7 @@
import com.orientechnologies.orient.core.record.impl.ORecordBytes;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerListRID;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerString;
-import com.orientechnologies.orient.core.type.tree.OTreeMapDatabaseLazySave;
+import com.orientechnologies.orient.core.type.tree.OMVRBTreeDatabaseLazySave;
/**
* Handles indexing when records change.
@@ -41,7 +41,7 @@
*/
public abstract class OPropertyIndexMVRBTreeAbstract extends OSharedResource implements OPropertyIndex {
protected OProperty owner;
- protected OTreeMapDatabaseLazySave<String, List<ORecordId>> map;
+ protected OMVRBTreeDatabaseLazySave<String, List<ORecordId>> map;
public OPropertyIndexMVRBTreeAbstract() {
}
@@ -75,7 +75,7 @@ public OPropertyIndexMVRBTreeAbstract(final ODatabaseRecord<?> iDatabase, final
public OPropertyIndex create(final ODatabaseRecord<?> iDatabase, final OProperty iProperty, final String iClusterIndexName,
final OProgressListener iProgressListener) {
owner = iProperty;
- map = new OTreeMapDatabaseLazySave<String, List<ORecordId>>(iDatabase, iClusterIndexName, OStreamSerializerString.INSTANCE,
+ map = new OMVRBTreeDatabaseLazySave<String, List<ORecordId>>(iDatabase, iClusterIndexName, OStreamSerializerString.INSTANCE,
OStreamSerializerListRID.INSTANCE);
rebuild(iProgressListener);
return this;
@@ -233,7 +233,7 @@ public Iterator<Entry<String, List<ORecordId>>> iterator() {
}
protected void init(final ODatabaseRecord<?> iDatabase, final ORID iRecordId) {
- map = new OTreeMapDatabaseLazySave<String, List<ORecordId>>(iDatabase, iRecordId);
+ map = new OMVRBTreeDatabaseLazySave<String, List<ORecordId>>(iDatabase, iRecordId);
map.load();
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLogical.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLogical.java
index d83295720ac..b2bb660e3f8 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLogical.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLogical.java
@@ -26,7 +26,7 @@
import com.orientechnologies.orient.core.storage.OCluster;
import com.orientechnologies.orient.core.storage.OClusterPositionIterator;
import com.orientechnologies.orient.core.storage.OPhysicalPosition;
-import com.orientechnologies.orient.core.storage.tree.OTreeMapStorage;
+import com.orientechnologies.orient.core.storage.tree.OMVRBTreeStorage;
/**
* Handle a cluster using a logical structure stored into a real physical local cluster.<br/>
@@ -39,7 +39,7 @@ public class OClusterLogical implements OCluster {
private int id;
private int localClusterId;
- private OTreeMapStorage<Long, OPhysicalPosition> map;
+ private OMVRBTreeStorage<Long, OPhysicalPosition> map;
private OPhysicalPosition total;
private OSharedResourceExternal lock = new OSharedResourceExternal();
@@ -61,7 +61,7 @@ public OClusterLogical(final OStorageLocal iStorage, final int iId, final String
this(iName, iId, iPhysicalClusterId);
try {
- map = new OTreeMapStorage<Long, OPhysicalPosition>(iStorage, iStorage.getClusterById(iPhysicalClusterId).getName(),
+ map = new OMVRBTreeStorage<Long, OPhysicalPosition>(iStorage, iStorage.getClusterById(iPhysicalClusterId).getName(),
OStreamSerializerLong.INSTANCE, OStreamSerializerAnyStreamable.INSTANCE);
map.getRecord().setIdentity(iPhysicalClusterId, ORID.CLUSTER_POS_INVALID);
@@ -87,7 +87,7 @@ public OClusterLogical(final OStorageLocal iStorage, final String iName, final i
this(iName, iId, 0);
try {
- map = new OTreeMapStorage<Long, OPhysicalPosition>(iStorage, iStorage.getClusterById(iRecordId.getClusterId()).getName(),
+ map = new OMVRBTreeStorage<Long, OPhysicalPosition>(iStorage, iStorage.getClusterById(iRecordId.getClusterId()).getName(),
iRecordId);
map.load();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/ODictionaryLocal.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/ODictionaryLocal.java
index 72a736a3874..cb87386e8c2 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/ODictionaryLocal.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/ODictionaryLocal.java
@@ -31,14 +31,14 @@
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerAnyRecord;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerString;
import com.orientechnologies.orient.core.storage.OStorage;
-import com.orientechnologies.orient.core.type.tree.OTreeMapDatabase;
+import com.orientechnologies.orient.core.type.tree.OMVRBTreeDatabase;
@SuppressWarnings("unchecked")
public class ODictionaryLocal<T extends Object> implements ODictionaryInternal<T> {
public static final String DICTIONARY_DEF_CLUSTER_NAME = OStorage.CLUSTER_INTERNAL_NAME;
private ODatabaseComplex<T> database;
- private OTreeMapDatabase<String, T> tree;
+ private OMVRBTreeDatabase<String, T> tree;
public String clusterName = DICTIONARY_DEF_CLUSTER_NAME;
@@ -75,14 +75,14 @@ public int size() {
}
public void load() {
- tree = new OTreeMapDatabase<String, T>((ODatabaseRecord<?>) database, new ORecordId(
+ tree = new OMVRBTreeDatabase<String, T>((ODatabaseRecord<?>) database, new ORecordId(
database.getStorage().getConfiguration().dictionaryRecordId));
tree.load();
}
public void create() {
try {
- tree = new OTreeMapDatabase<String, T>((ODatabaseRecord<?>) database, clusterName, OStreamSerializerString.INSTANCE,
+ tree = new OMVRBTreeDatabase<String, T>((ODatabaseRecord<?>) database, clusterName, OStreamSerializerString.INSTANCE,
new OStreamSerializerAnyRecord((ODatabaseRecord<? extends ORecord<?>>) database));
tree.save();
@@ -93,7 +93,7 @@ public void create() {
}
}
- public OTreeMapDatabase<String, T> getTree() {
+ public OMVRBTreeDatabase<String, T> getTree() {
return tree;
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/tree/OTreeMapEntryStorage.java b/core/src/main/java/com/orientechnologies/orient/core/storage/tree/OMVRBTreeEntryStorage.java
similarity index 62%
rename from core/src/main/java/com/orientechnologies/orient/core/storage/tree/OTreeMapEntryStorage.java
rename to core/src/main/java/com/orientechnologies/orient/core/storage/tree/OMVRBTreeEntryStorage.java
index 39b59a4b6b9..2c6f4d31e19 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/tree/OTreeMapEntryStorage.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/tree/OMVRBTreeEntryStorage.java
@@ -17,11 +17,11 @@
import java.io.IOException;
-import com.orientechnologies.common.collection.OTreeMapEntry;
+import com.orientechnologies.common.collection.OMVRBTreeEntry;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.storage.ORawBuffer;
-import com.orientechnologies.orient.core.type.tree.OTreeMapEntryPersistent;
-import com.orientechnologies.orient.core.type.tree.OTreeMapPersistent;
+import com.orientechnologies.orient.core.type.tree.OMVRBTreeEntryPersistent;
+import com.orientechnologies.orient.core.type.tree.OMVRBTreePersistent;
/**
* Persistent TreeMap implementation that use a OStorage instance to handle the entries. This class can't be used also from the
@@ -34,27 +34,27 @@
* @param <V>
* Value type
*/
-public class OTreeMapEntryStorage<K, V> extends OTreeMapEntryPersistent<K, V> {
+public class OMVRBTreeEntryStorage<K, V> extends OMVRBTreeEntryPersistent<K, V> {
- public OTreeMapEntryStorage(OTreeMapEntry<K, V> iParent, int iPosition) {
+ public OMVRBTreeEntryStorage(OMVRBTreeEntry<K, V> iParent, int iPosition) {
super(iParent, iPosition);
record.setIdentity(pTree.getRecord().getIdentity().getClusterId(), ORID.CLUSTER_POS_INVALID);
}
- public OTreeMapEntryStorage(OTreeMapPersistent<K, V> iTree, K key, V value, OTreeMapEntryPersistent<K, V> iParent) {
+ public OMVRBTreeEntryStorage(OMVRBTreePersistent<K, V> iTree, K key, V value, OMVRBTreeEntryPersistent<K, V> iParent) {
super(iTree, key, value, iParent);
record.setIdentity(pTree.getRecord().getIdentity().getClusterId(), ORID.CLUSTER_POS_INVALID);
}
- public OTreeMapEntryStorage(OTreeMapPersistent<K, V> iTree, OTreeMapEntryPersistent<K, V> iParent, ORID iRecordId)
+ public OMVRBTreeEntryStorage(OMVRBTreePersistent<K, V> iTree, OMVRBTreeEntryPersistent<K, V> iParent, ORID iRecordId)
throws IOException {
super(iTree, iParent, iRecordId);
load();
}
@Override
- public OTreeMapEntryStorage<K, V> load() throws IOException {
- ORawBuffer raw = ((OTreeMapStorage<K, V>) tree).storage.readRecord(null, -1, record.getIdentity().getClusterId(), record
+ public OMVRBTreeEntryStorage<K, V> load() throws IOException {
+ ORawBuffer raw = ((OMVRBTreeStorage<K, V>) tree).storage.readRecord(null, -1, record.getIdentity().getClusterId(), record
.getIdentity().getClusterPosition(), null);
record.setVersion(raw.version);
@@ -65,18 +65,18 @@ public OTreeMapEntryStorage<K, V> load() throws IOException {
}
@Override
- public OTreeMapEntryStorage<K, V> save() throws IOException {
+ public OMVRBTreeEntryStorage<K, V> save() throws IOException {
record.fromStream(toStream());
if (record.getIdentity().isValid())
// UPDATE IT WITHOUT VERSION CHECK SINCE ALL IT'S LOCKED
- record.setVersion(((OTreeMapStorage<K, V>) tree).storage.updateRecord(0, record.getIdentity().getClusterId(), record
+ record.setVersion(((OMVRBTreeStorage<K, V>) tree).storage.updateRecord(0, record.getIdentity().getClusterId(), record
.getIdentity().getClusterPosition(), record.toStream(), -1, record.getRecordType()));
else {
// CREATE IT
record.setIdentity(
record.getIdentity().getClusterId(),
- ((OTreeMapStorage<K, V>) tree).storage.createRecord(record.getIdentity().getClusterId(), record.toStream(),
+ ((OMVRBTreeStorage<K, V>) tree).storage.createRecord(record.getIdentity().getClusterId(), record.toStream(),
record.getRecordType()));
}
record.unsetDirty();
@@ -91,17 +91,17 @@ public OTreeMapEntryStorage<K, V> save() throws IOException {
*
* @throws IOException
*/
- public OTreeMapEntryStorage<K, V> delete() throws IOException {
+ public OMVRBTreeEntryStorage<K, V> delete() throws IOException {
// EARLY LOAD LEFT AND DELETE IT RECURSIVELY
if (getLeft() != null)
- ((OTreeMapEntryPersistent<K, V>) getLeft()).delete();
+ ((OMVRBTreeEntryPersistent<K, V>) getLeft()).delete();
// EARLY LOAD RIGHT AND DELETE IT RECURSIVELY
if (getRight() != null)
- ((OTreeMapEntryPersistent<K, V>) getRight()).delete();
+ ((OMVRBTreeEntryPersistent<K, V>) getRight()).delete();
// DELETE MYSELF
- ((OTreeMapStorage<K, V>) tree).storage.deleteRecord(0, record.getIdentity(), record.getVersion());
+ ((OMVRBTreeStorage<K, V>) tree).storage.deleteRecord(0, record.getIdentity(), record.getVersion());
// FORCE REMOVING OF K/V AND SEIALIZED K/V AS WELL
keys = null;
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/tree/OTreeMapStorage.java b/core/src/main/java/com/orientechnologies/orient/core/storage/tree/OMVRBTreeStorage.java
similarity index 71%
rename from core/src/main/java/com/orientechnologies/orient/core/storage/tree/OTreeMapStorage.java
rename to core/src/main/java/com/orientechnologies/orient/core/storage/tree/OMVRBTreeStorage.java
index 6bdca91ed28..cb346b89e58 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/tree/OTreeMapStorage.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/tree/OMVRBTreeStorage.java
@@ -17,7 +17,7 @@
import java.io.IOException;
-import com.orientechnologies.common.collection.OTreeMapEntry;
+import com.orientechnologies.common.collection.OMVRBTreeEntry;
import com.orientechnologies.orient.core.exception.OConfigurationException;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.serialization.OMemoryInputStream;
@@ -26,28 +26,28 @@
import com.orientechnologies.orient.core.storage.ORawBuffer;
import com.orientechnologies.orient.core.storage.impl.local.OClusterLogical;
import com.orientechnologies.orient.core.storage.impl.local.OStorageLocal;
-import com.orientechnologies.orient.core.type.tree.OTreeMapEntryPersistent;
-import com.orientechnologies.orient.core.type.tree.OTreeMapPersistent;
+import com.orientechnologies.orient.core.type.tree.OMVRBTreeEntryPersistent;
+import com.orientechnologies.orient.core.type.tree.OMVRBTreePersistent;
/**
- * Persistent TreeMap implementation. The difference with the class OTreeMapPersistent is the level. In facts this class works
+ * Persistent MVRB-Tree implementation. The difference with the class OMVRBTreeDatabase is the level. In facts this class works
* directly at the storage level, while the other at database level. This class is used for Logical Clusters. It can'be
* transactional.
*
* @see OClusterLogical
*/
@SuppressWarnings("serial")
-public class OTreeMapStorage<K, V> extends OTreeMapPersistent<K, V> {
+public class OMVRBTreeStorage<K, V> extends OMVRBTreePersistent<K, V> {
protected OStorageLocal storage;
int clusterId;
- public OTreeMapStorage(final OStorageLocal iStorage, final String iClusterName, final ORID iRID) {
+ public OMVRBTreeStorage(final OStorageLocal iStorage, final String iClusterName, final ORID iRID) {
super(iClusterName, iRID);
storage = iStorage;
clusterId = storage.getClusterIdByName(OStorageLocal.CLUSTER_INTERNAL_NAME);
}
- public OTreeMapStorage(final OStorageLocal iStorage, String iClusterName, final OStreamSerializer iKeySerializer,
+ public OMVRBTreeStorage(final OStorageLocal iStorage, String iClusterName, final OStreamSerializer iKeySerializer,
final OStreamSerializer iValueSerializer) {
super(iClusterName, iKeySerializer, iValueSerializer);
storage = iStorage;
@@ -55,23 +55,23 @@ public OTreeMapStorage(final OStorageLocal iStorage, String iClusterName, final
}
@Override
- protected OTreeMapEntryPersistent<K, V> createEntry(OTreeMapEntry<K, V> iParent) {
- return new OTreeMapEntryStorage<K, V>(iParent, iParent.getPageSplitItems());
+ protected OMVRBTreeEntryPersistent<K, V> createEntry(OMVRBTreeEntry<K, V> iParent) {
+ return new OMVRBTreeEntryStorage<K, V>(iParent, iParent.getPageSplitItems());
}
@Override
- protected OTreeMapEntryPersistent<K, V> createEntry(final K key, final V value) {
+ protected OMVRBTreeEntryPersistent<K, V> createEntry(final K key, final V value) {
adjustPageSize();
- return new OTreeMapEntryStorage<K, V>(this, key, value, null);
+ return new OMVRBTreeEntryStorage<K, V>(this, key, value, null);
}
@Override
- protected OTreeMapEntryStorage<K, V> loadEntry(OTreeMapEntryPersistent<K, V> iParent, ORID iRecordId) throws IOException {
- OTreeMapEntryStorage<K, V> entry = null;//(OTreeMapEntryStorage<K, V>) cache.get(iRecordId);
+ protected OMVRBTreeEntryStorage<K, V> loadEntry(OMVRBTreeEntryPersistent<K, V> iParent, ORID iRecordId) throws IOException {
+ OMVRBTreeEntryStorage<K, V> entry = null;// (OMVRBTreeEntryStorage<K, V>) cache.get(iRecordId);
if (entry == null) {
// NOT FOUND: CREATE IT AND PUT IT INTO THE CACHE
- entry = new OTreeMapEntryStorage<K, V>(this, iParent, iRecordId);
-// cache.put(iRecordId, entry);
+ entry = new OMVRBTreeEntryStorage<K, V>(this, iParent, iRecordId);
+ // cache.put(iRecordId, entry);
} else
// FOUND: ASSIGN IT
entry.setParent(iParent);
@@ -80,7 +80,7 @@ protected OTreeMapEntryStorage<K, V> loadEntry(OTreeMapEntryPersistent<K, V> iPa
}
@Override
- public OTreeMapPersistent<K, V> load() throws IOException {
+ public OMVRBTreePersistent<K, V> load() throws IOException {
lock.acquireExclusiveLock();
try {
@@ -101,7 +101,7 @@ public OTreeMapPersistent<K, V> load() throws IOException {
}
@Override
- public OTreeMapPersistent<K, V> save() throws IOException {
+ public OMVRBTreePersistent<K, V> save() throws IOException {
lock.acquireExclusiveLock();
try {
diff --git a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapDatabase.java b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeDatabase.java
similarity index 64%
rename from core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapDatabase.java
rename to core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeDatabase.java
index 891a928909b..2139ee62b79 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapDatabase.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeDatabase.java
@@ -17,24 +17,29 @@
import java.io.IOException;
-import com.orientechnologies.common.collection.OTreeMapEntry;
+import com.orientechnologies.common.collection.OMVRBTreeEntry;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.serialization.OMemoryInputStream;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializer;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerFactory;
+/**
+ * Persistent MVRB-Tree implementation. The difference with the class OMVRBTreeStorage is the level. In facts this class works
+ * directly at the database level, while the other at storage level.
+ *
+ */
@SuppressWarnings("serial")
-public class OTreeMapDatabase<K, V> extends OTreeMapPersistent<K, V> {
+public class OMVRBTreeDatabase<K, V> extends OMVRBTreePersistent<K, V> {
protected ODatabaseRecord<?> database;
- public OTreeMapDatabase(final ODatabaseRecord<?> iDatabase, final ORID iRID) {
+ public OMVRBTreeDatabase(final ODatabaseRecord<?> iDatabase, final ORID iRID) {
super(iDatabase.getClusterNameById(iRID.getClusterId()), iRID);
database = iDatabase;
record.setDatabase(iDatabase);
}
- public OTreeMapDatabase(final ODatabaseRecord<?> iDatabase, String iClusterName, final OStreamSerializer iKeySerializer,
+ public OMVRBTreeDatabase(final ODatabaseRecord<?> iDatabase, String iClusterName, final OStreamSerializer iKeySerializer,
final OStreamSerializer iValueSerializer) {
super(iClusterName, iKeySerializer, iValueSerializer);
database = iDatabase;
@@ -42,26 +47,26 @@ public OTreeMapDatabase(final ODatabaseRecord<?> iDatabase, String iClusterName,
}
@Override
- protected OTreeMapEntryDatabase<K, V> createEntry(final K key, final V value) {
+ protected OMVRBTreeEntryDatabase<K, V> createEntry(final K key, final V value) {
adjustPageSize();
- return new OTreeMapEntryDatabase<K, V>(this, key, value, null);
+ return new OMVRBTreeEntryDatabase<K, V>(this, key, value, null);
}
@Override
- protected OTreeMapEntryDatabase<K, V> createEntry(final OTreeMapEntry<K, V> parent) {
+ protected OMVRBTreeEntryDatabase<K, V> createEntry(final OMVRBTreeEntry<K, V> parent) {
adjustPageSize();
- return new OTreeMapEntryDatabase<K, V>(parent, parent.getPageSplitItems());
+ return new OMVRBTreeEntryDatabase<K, V>(parent, parent.getPageSplitItems());
}
@Override
- protected OTreeMapEntryDatabase<K, V> loadEntry(final OTreeMapEntryPersistent<K, V> iParent, final ORID iRecordId)
+ protected OMVRBTreeEntryDatabase<K, V> loadEntry(final OMVRBTreeEntryPersistent<K, V> iParent, final ORID iRecordId)
throws IOException {
// SEARCH INTO THE CACHE
- OTreeMapEntryDatabase<K, V> entry = null;// (OTreeMapEntryDatabase<K, V>) cache.get(iRecordId);
+ OMVRBTreeEntryDatabase<K, V> entry = null;// (OMVRBTreeEntryDatabase<K, V>) cache.get(iRecordId);
if (entry == null) {
// NOT FOUND: CREATE IT AND PUT IT INTO THE CACHE
- entry = new OTreeMapEntryDatabase<K, V>(this, (OTreeMapEntryDatabase<K, V>) iParent, iRecordId);
+ entry = new OMVRBTreeEntryDatabase<K, V>(this, (OMVRBTreeEntryDatabase<K, V>) iParent, iRecordId);
// cache.put(iRecordId, entry);
} else {
// entry.load();
@@ -78,7 +83,7 @@ public ODatabaseRecord<?> getDatabase() {
}
@Override
- public OTreeMapPersistent<K, V> load() {
+ public OMVRBTreePersistent<K, V> load() {
if (!record.getIdentity().isValid())
// NOTHING TO LOAD
return this;
@@ -98,7 +103,7 @@ public OTreeMapPersistent<K, V> load() {
}
@Override
- public OTreeMapPersistent<K, V> save() throws IOException {
+ public OMVRBTreePersistent<K, V> save() throws IOException {
lock.acquireExclusiveLock();
try {
diff --git a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapDatabaseLazySave.java b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeDatabaseLazySave.java
similarity index 88%
rename from core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapDatabaseLazySave.java
rename to core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeDatabaseLazySave.java
index 60b2c448337..0e5949e9969 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapDatabaseLazySave.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeDatabaseLazySave.java
@@ -33,16 +33,16 @@
* @author Luca Garulli
*/
@SuppressWarnings("serial")
-public class OTreeMapDatabaseLazySave<K, V> extends OTreeMapDatabase<K, V> implements ODatabaseLifecycleListener {
+public class OMVRBTreeDatabaseLazySave<K, V> extends OMVRBTreeDatabase<K, V> implements ODatabaseLifecycleListener {
protected int maxUpdatesBeforeSave;
protected int updates = 0;
- public OTreeMapDatabaseLazySave(ODatabaseRecord<?> iDatabase, ORID iRID) {
+ public OMVRBTreeDatabaseLazySave(ODatabaseRecord<?> iDatabase, ORID iRID) {
super(iDatabase, iRID);
init(iDatabase);
}
- public OTreeMapDatabaseLazySave(ODatabaseRecord<?> iDatabase, String iClusterName, OStreamSerializer iKeySerializer,
+ public OMVRBTreeDatabaseLazySave(ODatabaseRecord<?> iDatabase, String iClusterName, OStreamSerializer iKeySerializer,
OStreamSerializer iValueSerializer) {
super(iDatabase, iClusterName, iKeySerializer, iValueSerializer);
init(iDatabase);
@@ -78,7 +78,7 @@ public void onTxRollback(ODatabase iDatabase) {
entryPoints.clear();
try {
if (root != null)
- ((OTreeMapEntryDatabase<K, V>) root).load();
+ ((OMVRBTreeEntryDatabase<K, V>) root).load();
} catch (IOException e) {
throw new OIndexException("Error on loading root node");
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapEntryDatabase.java b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeEntryDatabase.java
similarity index 74%
rename from core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapEntryDatabase.java
rename to core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeEntryDatabase.java
index 766dba45260..e2b159ed23b 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapEntryDatabase.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeEntryDatabase.java
@@ -17,7 +17,7 @@
import java.io.IOException;
-import com.orientechnologies.common.collection.OTreeMapEntry;
+import com.orientechnologies.common.collection.OMVRBTreeEntry;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.exception.OSerializationException;
import com.orientechnologies.orient.core.id.ORID;
@@ -33,7 +33,7 @@
* @param <V>
* Value type
*/
-public class OTreeMapEntryDatabase<K, V> extends OTreeMapEntryPersistent<K, V> {
+public class OMVRBTreeEntryDatabase<K, V> extends OMVRBTreeEntryPersistent<K, V> {
/**
* Called on event of splitting an entry.
*
@@ -43,9 +43,9 @@ public class OTreeMapEntryDatabase<K, V> extends OTreeMapEntryPersistent<K, V> {
* Current position
* @param iLeft
*/
- public OTreeMapEntryDatabase(OTreeMapEntry<K, V> iParent, int iPosition) {
+ public OMVRBTreeEntryDatabase(OMVRBTreeEntry<K, V> iParent, int iPosition) {
super(iParent, iPosition);
- record.setDatabase(((OTreeMapDatabase<K, V>) pTree).database);
+ record.setDatabase(((OMVRBTreeDatabase<K, V>) pTree).database);
}
/**
@@ -58,27 +58,27 @@ public OTreeMapEntryDatabase(OTreeMapEntry<K, V> iParent, int iPosition) {
* @param iRecordId
* Record to unmarshall
*/
- public OTreeMapEntryDatabase(OTreeMapDatabase<K, V> iTree, OTreeMapEntryDatabase<K, V> iParent, ORID iRecordId)
+ public OMVRBTreeEntryDatabase(OMVRBTreeDatabase<K, V> iTree, OMVRBTreeEntryDatabase<K, V> iParent, ORID iRecordId)
throws IOException {
super(iTree, iParent, iRecordId);
record.setDatabase(iTree.database);
load();
}
- public OTreeMapEntryDatabase(OTreeMapDatabase<K, V> iTree, K key, V value, OTreeMapEntryDatabase<K, V> iParent) {
+ public OMVRBTreeEntryDatabase(OMVRBTreeDatabase<K, V> iTree, K key, V value, OMVRBTreeEntryDatabase<K, V> iParent) {
super(iTree, key, value, iParent);
record.setDatabase(iTree.database);
}
@Override
- public OTreeMapEntryDatabase<K, V> load() throws IOException {
+ public OMVRBTreeEntryDatabase<K, V> load() throws IOException {
record.load();
fromStream(record.toStream());
return this;
}
@Override
- public OTreeMapEntryDatabase<K, V> save() throws OSerializationException {
+ public OMVRBTreeEntryDatabase<K, V> save() throws OSerializationException {
if (!record.isDirty())
return this;
@@ -102,15 +102,15 @@ public OTreeMapEntryDatabase<K, V> save() throws OSerializationException {
*
* @throws IOException
*/
- public OTreeMapEntryDatabase<K, V> delete() throws IOException {
+ public OMVRBTreeEntryDatabase<K, V> delete() throws IOException {
// EARLY LOAD LEFT AND DELETE IT RECURSIVELY
if (getLeft() != null)
- ((OTreeMapEntryPersistent<K, V>) getLeft()).delete();
+ ((OMVRBTreeEntryPersistent<K, V>) getLeft()).delete();
leftRid = null;
// EARLY LOAD RIGHT AND DELETE IT RECURSIVELY
if (getRight() != null)
- ((OTreeMapEntryPersistent<K, V>) getRight()).delete();
+ ((OMVRBTreeEntryPersistent<K, V>) getRight()).delete();
rightRid = null;
// DELETE MYSELF
diff --git a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapEntryPersistent.java b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeEntryPersistent.java
similarity index 83%
rename from core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapEntryPersistent.java
rename to core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeEntryPersistent.java
index 183fc89f875..d82791166c1 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapEntryPersistent.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeEntryPersistent.java
@@ -18,7 +18,7 @@
import java.io.IOException;
import java.util.Set;
-import com.orientechnologies.common.collection.OTreeMapEntry;
+import com.orientechnologies.common.collection.OMVRBTreeEntry;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.profiler.OProfiler;
import com.orientechnologies.orient.core.exception.OConfigurationException;
@@ -80,8 +80,8 @@
* @param <V>
*/
@SuppressWarnings("unchecked")
-public abstract class OTreeMapEntryPersistent<K, V> extends OTreeMapEntry<K, V> implements OSerializableStream {
- protected OTreeMapPersistent<K, V> pTree;
+public abstract class OMVRBTreeEntryPersistent<K, V> extends OMVRBTreeEntry<K, V> implements OSerializableStream {
+ protected OMVRBTreePersistent<K, V> pTree;
byte[][] serializedKeys;
byte[][] serializedValues;
@@ -92,9 +92,9 @@ public abstract class OTreeMapEntryPersistent<K, V> extends OTreeMapEntry<K, V>
public ORecordBytesLazy record;
- protected OTreeMapEntryPersistent<K, V> parent;
- protected OTreeMapEntryPersistent<K, V> left;
- protected OTreeMapEntryPersistent<K, V> right;
+ protected OMVRBTreeEntryPersistent<K, V> parent;
+ protected OMVRBTreeEntryPersistent<K, V> left;
+ protected OMVRBTreeEntryPersistent<K, V> right;
/**
* Called on event of splitting an entry.
@@ -105,9 +105,9 @@ public abstract class OTreeMapEntryPersistent<K, V> extends OTreeMapEntry<K, V>
* Current position
* @param iLeft
*/
- public OTreeMapEntryPersistent(final OTreeMapEntry<K, V> iParent, final int iPosition) {
+ public OMVRBTreeEntryPersistent(final OMVRBTreeEntry<K, V> iParent, final int iPosition) {
super(iParent, iPosition);
- pTree = (OTreeMapPersistent<K, V>) tree;
+ pTree = (OMVRBTreePersistent<K, V>) tree;
record = new ORecordBytesLazy(this);
setParent(iParent);
@@ -122,7 +122,7 @@ record = new ORecordBytesLazy(this);
serializedKeys = new byte[pageSize][];
serializedValues = new byte[pageSize][];
- final OTreeMapEntryPersistent<K, V> p = (OTreeMapEntryPersistent<K, V>) iParent;
+ final OMVRBTreeEntryPersistent<K, V> p = (OMVRBTreeEntryPersistent<K, V>) iParent;
System.arraycopy(p.serializedKeys, iPosition, serializedKeys, 0, size);
System.arraycopy(p.serializedValues, iPosition, serializedValues, 0, size);
@@ -140,19 +140,19 @@ record = new ORecordBytesLazy(this);
* @param iRecordId
* Record to unmarshall
*/
- public OTreeMapEntryPersistent(final OTreeMapPersistent<K, V> iTree, final OTreeMapEntryPersistent<K, V> iParent,
+ public OMVRBTreeEntryPersistent(final OMVRBTreePersistent<K, V> iTree, final OMVRBTreeEntryPersistent<K, V> iParent,
final ORID iRecordId) throws IOException {
super(iTree);
pTree = iTree;
record = new ORecordBytesLazy(this);
record.setIdentity((ORecordId) iRecordId);
- parent = (OTreeMapEntryPersistent<K, V>) iParent;
+ parent = (OMVRBTreeEntryPersistent<K, V>) iParent;
parentRid = iParent == null ? ORecordId.EMPTY_RECORD_ID : parent.record.getIdentity();
}
- public OTreeMapEntryPersistent(final OTreeMapPersistent<K, V> iTree, final K key, final V value,
- final OTreeMapEntryPersistent<K, V> iParent) {
+ public OMVRBTreeEntryPersistent(final OMVRBTreePersistent<K, V> iTree, final K key, final V value,
+ final OMVRBTreeEntryPersistent<K, V> iParent) {
super(iTree, key, value, iParent);
pTree = iTree;
@@ -170,22 +170,22 @@ record = new ORecordBytesLazy(this);
markDirty();
}
- public OTreeMapEntryPersistent<K, V> load() throws IOException {
+ public OMVRBTreeEntryPersistent<K, V> load() throws IOException {
return this;
}
- public OTreeMapEntryPersistent<K, V> save() throws IOException {
+ public OMVRBTreeEntryPersistent<K, V> save() throws IOException {
return this;
}
- public OTreeMapEntryPersistent<K, V> delete() throws IOException {
+ public OMVRBTreeEntryPersistent<K, V> delete() throws IOException {
pTree.removeEntryPoint(this);
// if (record.getIdentity().isValid())
// pTree.cache.remove(record.getIdentity());
// DELETE THE NODE FROM THE PENDING RECORDS TO COMMIT
- for (OTreeMapEntryPersistent<K, V> node : pTree.recordsToCommit) {
+ for (OMVRBTreeEntryPersistent<K, V> node : pTree.recordsToCommit) {
if (node.record.getIdentity().equals(record.getIdentity())) {
pTree.recordsToCommit.remove(node);
break;
@@ -274,10 +274,10 @@ protected int checkToDisconnect(final int iDepthLevel) {
public int getDepthInMemory() {
int level = 0;
- OTreeMapEntryPersistent<K, V> entry = this;
+ OMVRBTreeEntryPersistent<K, V> entry = this;
while (entry.parent != null) {
level++;
- entry = (OTreeMapEntryPersistent<K, V>) entry.parent;
+ entry = (OMVRBTreeEntryPersistent<K, V>) entry.parent;
}
return level;
}
@@ -285,16 +285,16 @@ public int getDepthInMemory() {
@Override
public int getDepth() {
int level = 0;
- OTreeMapEntryPersistent<K, V> entry = this;
+ OMVRBTreeEntryPersistent<K, V> entry = this;
while (entry.getParent() != null) {
level++;
- entry = (OTreeMapEntryPersistent<K, V>) entry.getParent();
+ entry = (OMVRBTreeEntryPersistent<K, V>) entry.getParent();
}
return level;
}
@Override
- public OTreeMapEntry<K, V> getParent() {
+ public OMVRBTreeEntry<K, V> getParent() {
if (parentRid == null)
return null;
@@ -331,11 +331,11 @@ else if (parent.rightRid.isValid() && parent.rightRid.equals(record.getIdentity(
}
@Override
- public OTreeMapEntry<K, V> setParent(final OTreeMapEntry<K, V> iParent) {
+ public OMVRBTreeEntry<K, V> setParent(final OMVRBTreeEntry<K, V> iParent) {
if (iParent != getParent()) {
markDirty();
- this.parent = (OTreeMapEntryPersistent<K, V>) iParent;
+ this.parent = (OMVRBTreeEntryPersistent<K, V>) iParent;
this.parentRid = iParent == null ? ORecordId.EMPTY_RECORD_ID : parent.record.getIdentity();
if (parent != null) {
@@ -353,7 +353,7 @@ public OTreeMapEntry<K, V> setParent(final OTreeMapEntry<K, V> iParent) {
}
@Override
- public OTreeMapEntry<K, V> getLeft() {
+ public OMVRBTreeEntry<K, V> getLeft() {
if (left == null && leftRid.isValid()) {
try {
// System.out.println("Node " + record.getIdentity() + " is loading LEFT node " + leftRid + "...");
@@ -371,11 +371,11 @@ public OTreeMapEntry<K, V> getLeft() {
}
@Override
- public void setLeft(final OTreeMapEntry<K, V> iLeft) {
+ public void setLeft(final OMVRBTreeEntry<K, V> iLeft) {
if (iLeft == left)
return;
- left = (OTreeMapEntryPersistent<K, V>) iLeft;
+ left = (OMVRBTreeEntryPersistent<K, V>) iLeft;
// if (left == null || !left.record.getIdentity().isValid() || !left.record.getIdentity().equals(leftRid)) {
markDirty();
this.leftRid = iLeft == null ? ORecordId.EMPTY_RECORD_ID : left.record.getIdentity();
@@ -388,7 +388,7 @@ public void setLeft(final OTreeMapEntry<K, V> iLeft) {
}
@Override
- public OTreeMapEntry<K, V> getRight() {
+ public OMVRBTreeEntry<K, V> getRight() {
if (rightRid.isValid() && right == null) {
// LAZY LOADING OF THE RIGHT LEAF
try {
@@ -406,11 +406,11 @@ public OTreeMapEntry<K, V> getRight() {
}
@Override
- public OTreeMapEntry<K, V> setRight(final OTreeMapEntry<K, V> iRight) {
+ public OMVRBTreeEntry<K, V> setRight(final OMVRBTreeEntry<K, V> iRight) {
if (iRight == right)
return this;
- right = (OTreeMapEntryPersistent<K, V>) iRight;
+ right = (OMVRBTreeEntryPersistent<K, V>) iRight;
// if (right == null || !right.record.getIdentity().isValid() || !right.record.getIdentity().equals(rightRid)) {
markDirty();
rightRid = iRight == null ? ORecordId.EMPTY_RECORD_ID : right.record.getIdentity();
@@ -458,10 +458,10 @@ public void checkEntryStructure() {
}
@Override
- protected void copyFrom(final OTreeMapEntry<K, V> iSource) {
+ protected void copyFrom(final OMVRBTreeEntry<K, V> iSource) {
markDirty();
- final OTreeMapEntryPersistent<K, V> source = (OTreeMapEntryPersistent<K, V>) iSource;
+ final OMVRBTreeEntryPersistent<K, V> source = (OMVRBTreeEntryPersistent<K, V>) iSource;
parent = source.parent;
left = source.left;
@@ -528,7 +528,7 @@ protected void remove() {
public K getKeyAt(final int iIndex) {
if (keys[iIndex] == null)
try {
- OProfiler.getInstance().updateCounter("OTreeMapEntryP.unserializeKey", 1);
+ OProfiler.getInstance().updateCounter("OMVRBTreeEntryP.unserializeKey", 1);
keys[iIndex] = (K) pTree.keySerializer.fromStream(serializedKeys[iIndex]);
} catch (IOException e) {
@@ -544,7 +544,7 @@ public K getKeyAt(final int iIndex) {
protected V getValueAt(final int iIndex) {
if (values[iIndex] == null)
try {
- OProfiler.getInstance().updateCounter("OTreeMapEntryP.unserializeValue", 1);
+ OProfiler.getInstance().updateCounter("OMVRBTreeEntryP.unserializeValue", 1);
values[iIndex] = (V) pTree.valueSerializer.fromStream(serializedValues[iIndex]);
} catch (IOException e) {
@@ -594,9 +594,9 @@ private int getMaxDepthInMemory(final int iCurrDepthLevel) {
/**
* Returns the successor of the current Entry only by traversing the memory, or null if no such.
*/
- public OTreeMapEntryPersistent<K, V> getNextInMemory() {
- OTreeMapEntryPersistent<K, V> t = this;
- OTreeMapEntryPersistent<K, V> p = null;
+ public OMVRBTreeEntryPersistent<K, V> getNextInMemory() {
+ OMVRBTreeEntryPersistent<K, V> t = this;
+ OMVRBTreeEntryPersistent<K, V> p = null;
if (t.right != null) {
p = t.right;
@@ -657,7 +657,7 @@ public final OSerializableStream fromStream(final byte[] iStream) throws OSerial
} finally {
buffer.close();
- OProfiler.getInstance().stopChrono("OTreeMapEntryP.fromStream", timer);
+ OProfiler.getInstance().stopChrono("OMVRBTreeEntryP.fromStream", timer);
}
}
@@ -675,7 +675,7 @@ public final byte[] toStream() throws OSerializationException {
// FORCE DIRTY
parent.record.setDirty();
- ((OTreeMapEntryDatabase<K, V>) parent).save();
+ ((OMVRBTreeEntryDatabase<K, V>) parent).save();
parentRid = parent.record.getIdentity();
record.setDirty();
}
@@ -684,7 +684,7 @@ public final byte[] toStream() throws OSerializationException {
// FORCE DIRTY
left.record.setDirty();
- ((OTreeMapEntryDatabase<K, V>) left).save();
+ ((OMVRBTreeEntryDatabase<K, V>) left).save();
leftRid = left.record.getIdentity();
record.setDirty();
}
@@ -693,7 +693,7 @@ public final byte[] toStream() throws OSerializationException {
// FORCE DIRTY
right.record.setDirty();
- ((OTreeMapEntryDatabase<K, V>) right).save();
+ ((OMVRBTreeEntryDatabase<K, V>) right).save();
rightRid = right.record.getIdentity();
record.setDirty();
}
@@ -736,7 +736,7 @@ public final byte[] toStream() throws OSerializationException {
checkEntryStructure();
- OProfiler.getInstance().stopChrono("OTreeMapEntryP.toStream", timer);
+ OProfiler.getInstance().stopChrono("OMVRBTreeEntryP.toStream", timer);
}
}
@@ -748,7 +748,7 @@ public final byte[] toStream() throws OSerializationException {
private void serializeNewKeys() throws IOException {
for (int i = 0; i < size; ++i) {
if (serializedKeys[i] == null) {
- OProfiler.getInstance().updateCounter("OTreeMapEntryP.serializeValue", 1);
+ OProfiler.getInstance().updateCounter("OMVRBTreeEntryP.serializeValue", 1);
serializedKeys[i] = pTree.keySerializer.toStream(keys[i]);
}
@@ -763,7 +763,7 @@ private void serializeNewKeys() throws IOException {
private void serializeNewValues() throws IOException {
for (int i = 0; i < size; ++i) {
if (serializedValues[i] == null) {
- OProfiler.getInstance().updateCounter("OTreeMapEntryP.serializeKey", 1);
+ OProfiler.getInstance().updateCounter("OMVRBTreeEntryP.serializeKey", 1);
serializedValues[i] = pTree.valueSerializer.toStream(values[i]);
}
@@ -791,10 +791,10 @@ private void markDirty() {
// public boolean equals(final Object o) {
// if (this == o)
// return true;
- // if (!(o instanceof OTreeMapEntryPersistent<?, ?>))
+ // if (!(o instanceof OMVRBTreeEntryPersistent<?, ?>))
// return false;
//
- // final OTreeMapEntryPersistent<?, ?> e = (OTreeMapEntryPersistent<?, ?>) o;
+ // final OMVRBTreeEntryPersistent<?, ?> e = (OMVRBTreeEntryPersistent<?, ?>) o;
//
// if (record != null && e.record != null)
// return record.getIdentity().equals(e.record.getIdentity());
@@ -809,17 +809,17 @@ private void markDirty() {
// }
@Override
- protected OTreeMapEntry<K, V> getLeftInMemory() {
+ protected OMVRBTreeEntry<K, V> getLeftInMemory() {
return left;
}
@Override
- protected OTreeMapEntry<K, V> getParentInMemory() {
+ protected OMVRBTreeEntry<K, V> getParentInMemory() {
return parent;
}
@Override
- protected OTreeMapEntry<K, V> getRightInMemory() {
+ protected OMVRBTreeEntry<K, V> getRightInMemory() {
return right;
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapPersistent.java b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreePersistent.java
similarity index 78%
rename from core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapPersistent.java
rename to core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreePersistent.java
index 6d9bb304349..83a432d849c 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapPersistent.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreePersistent.java
@@ -23,9 +23,9 @@
import java.util.Map;
import java.util.Set;
-import com.orientechnologies.common.collection.OTreeMap;
-import com.orientechnologies.common.collection.OTreeMapEntry;
-import com.orientechnologies.common.collection.OTreeMapEventListener;
+import com.orientechnologies.common.collection.OMVRBTree;
+import com.orientechnologies.common.collection.OMVRBTreeEntry;
+import com.orientechnologies.common.collection.OMVRBTreeEventListener;
import com.orientechnologies.common.concur.resource.OSharedResourceExternal;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.profiler.OProfiler;
@@ -43,17 +43,15 @@
import com.orientechnologies.orient.core.serialization.OSerializableStream;
import com.orientechnologies.orient.core.serialization.serializer.record.OSerializationThreadLocal;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializer;
-import com.orientechnologies.orient.core.storage.impl.local.OClusterLogical;
/**
- * Persistent TreeMap implementation. The difference with the class OTreeMapPersistent is the level. In facts this class works
- * directly at the storage level, while the other at database level. This class is used for Logical Clusters. It can'be
+ * Persistent based MVRB-Tree implementation. The difference with the class OMVRBTreePersistent is the level. In facts this class
+ * works directly at the storage level, while the other at database level. This class is used for Logical Clusters. It can'be
* transactional. It uses the entryPoints linked list to get the best entry point for searching a node.
*
- * @see OClusterLogical
*/
@SuppressWarnings("serial")
-public abstract class OTreeMapPersistent<K, V> extends OTreeMap<K, V> implements OTreeMapEventListener<K, V>, OSerializableStream {
+public abstract class OMVRBTreePersistent<K, V> extends OMVRBTree<K, V> implements OMVRBTreeEventListener<K, V>, OSerializableStream {
protected int optimizeThreshold;
protected OSharedResourceExternal lock = new OSharedResourceExternal();
@@ -61,7 +59,7 @@ public abstract class OTreeMapPersistent<K, V> extends OTreeMap<K, V> implements
protected OStreamSerializer keySerializer;
protected OStreamSerializer valueSerializer;
- protected final Set<OTreeMapEntryPersistent<K, V>> recordsToCommit = new HashSet<OTreeMapEntryPersistent<K, V>>();
+ protected final Set<OMVRBTreeEntryPersistent<K, V>> recordsToCommit = new HashSet<OMVRBTreeEntryPersistent<K, V>>();
protected final OMemoryOutputStream entryRecordBuffer;
protected final String clusterName;
@@ -72,20 +70,20 @@ public abstract class OTreeMapPersistent<K, V> extends OTreeMap<K, V> implements
// STORES IN MEMORY DIRECT REFERENCES TO PORTION OF THE TREE
protected int entryPointsSize;
protected float optimizeEntryPointsFactor;
- protected volatile List<OTreeMapEntryPersistent<K, V>> entryPoints = new ArrayList<OTreeMapEntryPersistent<K, V>>(
+ protected volatile List<OMVRBTreeEntryPersistent<K, V>> entryPoints = new ArrayList<OMVRBTreeEntryPersistent<K, V>>(
entryPointsSize);
- protected List<OTreeMapEntryPersistent<K, V>> newEntryPoints = new ArrayList<OTreeMapEntryPersistent<K, V>>(
+ protected List<OMVRBTreeEntryPersistent<K, V>> newEntryPoints = new ArrayList<OMVRBTreeEntryPersistent<K, V>>(
entryPointsSize);
- // protected Map<ORID, OTreeMapEntryPersistent<K, V>> cache = new HashMap<ORID, OTreeMapEntryPersistent<K, V>>();
+ // protected Map<ORID, OMVRBTreeEntryPersistent<K, V>> cache = new HashMap<ORID, OMVRBTreeEntryPersistent<K, V>>();
- public OTreeMapPersistent(final String iClusterName, final ORID iRID) {
+ public OMVRBTreePersistent(final String iClusterName, final ORID iRID) {
this(iClusterName, null, null);
record.setIdentity(iRID.getClusterId(), iRID.getClusterPosition());
config();
}
- public OTreeMapPersistent(String iClusterName, final OStreamSerializer iKeySerializer, final OStreamSerializer iValueSerializer) {
+ public OMVRBTreePersistent(String iClusterName, final OStreamSerializer iKeySerializer, final OStreamSerializer iValueSerializer) {
// MINIMIZE I/O USING A LARGER PAGE THAN THE DEFAULT USED IN MEMORY
super(1024, 0.7f);
config();
@@ -101,16 +99,16 @@ record = new ORecordBytesLazy(this);
setListener(this);
}
- public abstract OTreeMapPersistent<K, V> load() throws IOException;
+ public abstract OMVRBTreePersistent<K, V> load() throws IOException;
- public abstract OTreeMapPersistent<K, V> save() throws IOException;
+ public abstract OMVRBTreePersistent<K, V> save() throws IOException;
protected abstract void serializerFromStream(OMemoryInputStream stream) throws IOException;
/**
* Lazy loads a node.
*/
- protected abstract OTreeMapEntryPersistent<K, V> loadEntry(OTreeMapEntryPersistent<K, V> iParent, ORID iRecordId)
+ protected abstract OMVRBTreeEntryPersistent<K, V> loadEntry(OMVRBTreeEntryPersistent<K, V> iParent, ORID iRecordId)
throws IOException;
@Override
@@ -120,7 +118,7 @@ public void clear() {
try {
if (root != null) {
- ((OTreeMapEntryPersistent<K, V>) root).delete();
+ ((OMVRBTreeEntryPersistent<K, V>) root).delete();
super.clear();
getListener().signalTreeChanged(this);
}
@@ -135,7 +133,7 @@ public void clear() {
} finally {
lock.releaseExclusiveLock();
- OProfiler.getInstance().stopChrono("OTreeMapPersistent.clear", timer);
+ OProfiler.getInstance().stopChrono("OMVRBTreePersistent.clear", timer);
}
}
@@ -148,7 +146,7 @@ public void unload() {
try {
// DISCONNECT ALL THE NODES
- for (OTreeMapEntryPersistent<K, V> entryPoint : entryPoints)
+ for (OMVRBTreeEntryPersistent<K, V> entryPoint : entryPoints)
entryPoint.disconnect(true);
entryPoints.clear();
@@ -165,7 +163,7 @@ public void unload() {
} finally {
lock.releaseExclusiveLock();
- OProfiler.getInstance().stopChrono("OTreeMapPersistent.unload", timer);
+ OProfiler.getInstance().stopChrono("OMVRBTreePersistent.unload", timer);
}
}
@@ -185,7 +183,7 @@ public void optimize() {
// printInMemoryStructure();
- OTreeMapEntryPersistent<K, V> pRoot = (OTreeMapEntryPersistent<K, V>) root;
+ OMVRBTreeEntryPersistent<K, V> pRoot = (OMVRBTreeEntryPersistent<K, V>) root;
final int depth = pRoot.getMaxDepthInMemory();
@@ -196,8 +194,8 @@ public void optimize() {
pRoot.checkToDisconnect((int) (entryPointsSize * optimizeEntryPointsFactor));
if (isRuntimeCheckEnabled()) {
- for (OTreeMapEntryPersistent<K, V> entryPoint : entryPoints)
- for (OTreeMapEntryPersistent<K, V> e = (OTreeMapEntryPersistent<K, V>) entryPoint.getFirstInMemory(); e != null; e = e
+ for (OMVRBTreeEntryPersistent<K, V> entryPoint : entryPoints)
+ for (OMVRBTreeEntryPersistent<K, V> e = (OMVRBTreeEntryPersistent<K, V>) entryPoint.getFirstInMemory(); e != null; e = e
.getNextInMemory())
e.checkEntryStructure();
}
@@ -208,14 +206,14 @@ public void optimize() {
if (isRuntimeCheckEnabled()) {
if (entryPoints.size() > 0)
- for (OTreeMapEntryPersistent<K, V> entryPoint : entryPoints)
+ for (OMVRBTreeEntryPersistent<K, V> entryPoint : entryPoints)
checkTreeStructure(entryPoint.getFirstInMemory());
else
checkTreeStructure(root);
}
lock.releaseExclusiveLock();
- OProfiler.getInstance().stopChrono("OTreeMapPersistent.optimize", timer);
+ OProfiler.getInstance().stopChrono("OMVRBTreePersistent.optimize", timer);
if (OLogManager.instance().isDebugEnabled())
OLogManager.instance().debug(this, "Optimization completed in %d ms\n", System.currentTimeMillis() - timer);
@@ -239,7 +237,7 @@ public V put(final K key, final V value) {
} finally {
lock.releaseExclusiveLock();
- OProfiler.getInstance().stopChrono("OTreeMapPersistent.put", timer);
+ OProfiler.getInstance().stopChrono("OMVRBTreePersistent.put", timer);
}
}
@@ -260,7 +258,7 @@ public void putAll(final Map<? extends K, ? extends V> map) {
} finally {
lock.releaseExclusiveLock();
- OProfiler.getInstance().stopChrono("OTreeMapPersistent.putAll", timer);
+ OProfiler.getInstance().stopChrono("OMVRBTreePersistent.putAll", timer);
}
}
@@ -286,7 +284,7 @@ public void commitChanges(final ODatabaseRecord<?> iDatabase) {
try {
if (recordsToCommit.size() > 0) {
- final List<OTreeMapEntryPersistent<K, V>> tmp = new ArrayList<OTreeMapEntryPersistent<K, V>>();
+ final List<OMVRBTreeEntryPersistent<K, V>> tmp = new ArrayList<OMVRBTreeEntryPersistent<K, V>>();
while (recordsToCommit.iterator().hasNext()) {
// COMMIT BEFORE THE NEW RECORDS (TO ASSURE RID IN RELATIONSHIPS)
@@ -294,7 +292,7 @@ public void commitChanges(final ODatabaseRecord<?> iDatabase) {
recordsToCommit.clear();
- for (OTreeMapEntryPersistent<K, V> node : tmp)
+ for (OMVRBTreeEntryPersistent<K, V> node : tmp)
if (node.record.isDirty()) {
if (iDatabase != null)
// REPLACE THE DATABASE WITH THE NEW ACQUIRED
@@ -325,7 +323,7 @@ public void commitChanges(final ODatabaseRecord<?> iDatabase) {
} finally {
lock.releaseExclusiveLock();
- OProfiler.getInstance().stopChrono("OTreeMapPersistent.commitChanges", timer);
+ OProfiler.getInstance().stopChrono("OMVRBTreePersistent.commitChanges", timer);
}
}
@@ -352,11 +350,11 @@ public OSerializableStream fromStream(final byte[] iStream) throws OSerializatio
} catch (Exception e) {
- OLogManager.instance().error(this, "Error on unmarshalling OTreeMapPersistent object from record: %s", e,
+ OLogManager.instance().error(this, "Error on unmarshalling OMVRBTreePersistent object from record: %s", e,
OSerializationException.class, rootRid);
} finally {
- OProfiler.getInstance().stopChrono("OTreeMapPersistent.fromStream", timer);
+ OProfiler.getInstance().stopChrono("OMVRBTreePersistent.fromStream", timer);
}
return this;
}
@@ -377,7 +375,7 @@ public byte[] toStream() throws OSerializationException {
try {
if (root != null) {
- OTreeMapEntryPersistent<K, V> pRoot = (OTreeMapEntryPersistent<K, V>) root;
+ OMVRBTreeEntryPersistent<K, V> pRoot = (OMVRBTreeEntryPersistent<K, V>) root;
if (pRoot.record.getIdentity().isNew()) {
// FIRST TIME: SAVE IT
pRoot.save();
@@ -401,16 +399,16 @@ public byte[] toStream() throws OSerializationException {
} finally {
marshalledRecords.remove(identityRecord);
- OProfiler.getInstance().stopChrono("OTreeMapPersistent.toStream", timer);
+ OProfiler.getInstance().stopChrono("OMVRBTreePersistent.toStream", timer);
}
}
- public void signalTreeChanged(final OTreeMap<K, V> iTree) {
+ public void signalTreeChanged(final OMVRBTree<K, V> iTree) {
record.setDirty();
}
- public void signalNodeChanged(final OTreeMapEntry<K, V> iNode) {
- recordsToCommit.add((OTreeMapEntryPersistent<K, V>) iNode);
+ public void signalNodeChanged(final OMVRBTreeEntry<K, V> iNode) {
+ recordsToCommit.add((OMVRBTreeEntryPersistent<K, V>) iNode);
}
@Override
@@ -601,7 +599,7 @@ protected void updateUsageCounter() {
*/
@SuppressWarnings("unchecked")
@Override
- protected OTreeMapEntry<K, V> getBestEntryPoint(final Object iKey) {
+ protected OMVRBTreeEntry<K, V> getBestEntryPoint(final Object iKey) {
final Comparable<? super K> key = (Comparable<? super K>) iKey;
if (entryPoints.size() == 0)
@@ -609,11 +607,11 @@ protected OTreeMapEntry<K, V> getBestEntryPoint(final Object iKey) {
return root;
// SEARCH THE BEST KEY
- OTreeMapEntryPersistent<K, V> e;
+ OMVRBTreeEntryPersistent<K, V> e;
int entryPointSize = entryPoints.size();
int cmp;
- OTreeMapEntryPersistent<K, V> bestNode = null;
- if (entryPointSize < OTreeMapEntry.BINARY_SEARCH_THRESHOLD) {
+ OMVRBTreeEntryPersistent<K, V> bestNode = null;
+ if (entryPointSize < OMVRBTreeEntry.BINARY_SEARCH_THRESHOLD) {
// LINEAR SEARCH
for (int i = 0; i < entryPointSize; ++i) {
e = entryPoints.get(i);
@@ -687,7 +685,7 @@ protected OTreeMapEntry<K, V> getBestEntryPoint(final Object iKey) {
/**
* Remove an entry point from the list
*/
- void removeEntryPoint(final OTreeMapEntryPersistent<K, V> iEntry) {
+ void removeEntryPoint(final OMVRBTreeEntryPersistent<K, V> iEntry) {
for (int i = 0; i < entryPoints.size(); ++i)
if (entryPoints.get(i) == iEntry) {
entryPoints.remove(i);
@@ -696,16 +694,16 @@ void removeEntryPoint(final OTreeMapEntryPersistent<K, V> iEntry) {
}
/**
- * Returns the first Entry in the OTreeMap (according to the OTreeMap's key-sort function). Returns null if the OTreeMap is empty.
+ * Returns the first Entry in the OMVRBTree (according to the OMVRBTree's key-sort function). Returns null if the OMVRBTree is empty.
*/
@Override
- protected OTreeMapEntry<K, V> getFirstEntry() {
+ protected OMVRBTreeEntry<K, V> getFirstEntry() {
if (entryPoints.size() > 0) {
// FIND THE FIRST ELEMENT STARTING FROM THE FIRST NODE
- OTreeMapEntryPersistent<K, V> e = entryPoints.get(0);
+ OMVRBTreeEntryPersistent<K, V> e = entryPoints.get(0);
while (e.getLeft() != null) {
- e = (OTreeMapEntryPersistent<K, V>) e.getLeft();
+ e = (OMVRBTreeEntryPersistent<K, V>) e.getLeft();
}
return e;
}
@@ -715,12 +713,12 @@ protected OTreeMapEntry<K, V> getFirstEntry() {
// private void printInMemoryStructure() {
// System.out.println("* Entrypoints (" + entryPoints.size() + "), in cache=" + cache.size() + ": *");
- // for (OTreeMapEntryPersistent<K, V> entryPoint : entryPoints)
+ // for (OMVRBTreeEntryPersistent<K, V> entryPoint : entryPoints)
// printInMemoryStructure(entryPoint);
// }
@Override
- protected void setRoot(final OTreeMapEntry<K, V> iRoot) {
+ protected void setRoot(final OMVRBTreeEntry<K, V> iRoot) {
if (iRoot == root)
return;
diff --git a/kv/src/main/java/com/orientechnologies/orient/kv/index/OTreeMapPersistentAsynch.java b/kv/src/main/java/com/orientechnologies/orient/kv/index/OMVRBTreePersistentAsynch.java
similarity index 59%
rename from kv/src/main/java/com/orientechnologies/orient/kv/index/OTreeMapPersistentAsynch.java
rename to kv/src/main/java/com/orientechnologies/orient/kv/index/OMVRBTreePersistentAsynch.java
index a8dd0f816a0..952cea1fc7e 100644
--- a/kv/src/main/java/com/orientechnologies/orient/kv/index/OTreeMapPersistentAsynch.java
+++ b/kv/src/main/java/com/orientechnologies/orient/kv/index/OMVRBTreePersistentAsynch.java
@@ -4,46 +4,46 @@
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializer;
-import com.orientechnologies.orient.core.type.tree.OTreeMapDatabase;
+import com.orientechnologies.orient.core.type.tree.OMVRBTreeDatabase;
import com.orientechnologies.orient.kv.OSharedBinaryDatabase;
/**
* Wrapper class for persistent tree map. It handles the asynchronous commit of changes done by the external
- * OTreeMapPersistentAsynchThread singleton thread.
+ * OMVRBTreePersistentAsynchThread singleton thread.
*
* @author Luca Garulli
*
* @param <K>
* @param <V>
- * @see OTreeMapPersistentAsynchThread
+ * @see OMVRBTreePersistentAsynchThread
*/
@SuppressWarnings("serial")
-public class OTreeMapPersistentAsynch<K, V> extends OTreeMapDatabase<K, V> {
+public class OMVRBTreePersistentAsynch<K, V> extends OMVRBTreeDatabase<K, V> {
- public OTreeMapPersistentAsynch(final ODatabaseRecord<?> iDatabase, final String iClusterName,
+ public OMVRBTreePersistentAsynch(final ODatabaseRecord<?> iDatabase, final String iClusterName,
final OStreamSerializer iKeySerializer, final OStreamSerializer iValueSerializer) {
super(iDatabase, iClusterName, iKeySerializer, iValueSerializer);
- OTreeMapPersistentAsynchThread.getInstance().registerMap(this);
+ OMVRBTreePersistentAsynchThread.getInstance().registerMap(this);
}
- public OTreeMapPersistentAsynch(final ODatabaseRecord<?> iDatabase, final ORID iRID) {
+ public OMVRBTreePersistentAsynch(final ODatabaseRecord<?> iDatabase, final ORID iRID) {
super(iDatabase, iRID);
- OTreeMapPersistentAsynchThread.getInstance().registerMap(this);
+ OMVRBTreePersistentAsynchThread.getInstance().registerMap(this);
}
/**
- * Doesn't commit changes since they are scheduled by the external OTreeMapPersistentAsynchThread singleton thread.
+ * Doesn't commit changes since they are scheduled by the external OMVRBTreePersistentAsynchThread singleton thread.
*
- * @see OTreeMapPersistentAsynchThread#execute()
+ * @see OMVRBTreePersistentAsynchThread#execute()
*/
@Override
public void commitChanges(final ODatabaseRecord<?> iDatabase) {
}
/**
- * Commits changes for real. It's called by OTreeMapPersistentAsynchThread singleton thread.
+ * Commits changes for real. It's called by OMVRBTreePersistentAsynchThread singleton thread.
*
- * @see OTreeMapPersistentAsynchThread#execute()
+ * @see OMVRBTreePersistentAsynchThread#execute()
*/
public void executeCommitChanges() {
ODatabaseBinary db = null;
diff --git a/kv/src/main/java/com/orientechnologies/orient/kv/index/OTreeMapPersistentAsynchThread.java b/kv/src/main/java/com/orientechnologies/orient/kv/index/OMVRBTreePersistentAsynchThread.java
similarity index 73%
rename from kv/src/main/java/com/orientechnologies/orient/kv/index/OTreeMapPersistentAsynchThread.java
rename to kv/src/main/java/com/orientechnologies/orient/kv/index/OMVRBTreePersistentAsynchThread.java
index 232780bd2e9..54251ca97c8 100644
--- a/kv/src/main/java/com/orientechnologies/orient/kv/index/OTreeMapPersistentAsynchThread.java
+++ b/kv/src/main/java/com/orientechnologies/orient/kv/index/OMVRBTreePersistentAsynchThread.java
@@ -28,13 +28,13 @@
* @author Luca Garulli
*
*/
-public class OTreeMapPersistentAsynchThread extends OSoftThread {
+public class OMVRBTreePersistentAsynchThread extends OSoftThread {
private long delay = 0;
- private Set<OTreeMapPersistentAsynch<?, ?>> maps = new HashSet<OTreeMapPersistentAsynch<?, ?>>();
- private static OTreeMapPersistentAsynchThread instance = new OTreeMapPersistentAsynchThread();
+ private Set<OMVRBTreePersistentAsynch<?, ?>> maps = new HashSet<OMVRBTreePersistentAsynch<?, ?>>();
+ private static OMVRBTreePersistentAsynchThread instance = new OMVRBTreePersistentAsynchThread();
- public OTreeMapPersistentAsynchThread setDelay(final int iDelay) {
+ public OMVRBTreePersistentAsynchThread setDelay(final int iDelay) {
delay = iDelay;
return this;
}
@@ -44,13 +44,13 @@ public OTreeMapPersistentAsynchThread setDelay(final int iDelay) {
*
* @param iMap
*/
- public synchronized void registerMap(final OTreeMapPersistentAsynch<?, ?> iMap) {
+ public synchronized void registerMap(final OMVRBTreePersistentAsynch<?, ?> iMap) {
maps.add(iMap);
}
@Override
protected synchronized void execute() throws Exception {
- for (OTreeMapPersistentAsynch<?, ?> map : maps) {
+ for (OMVRBTreePersistentAsynch<?, ?> map : maps) {
try {
synchronized (map) {
@@ -68,7 +68,7 @@ protected void afterExecution() throws InterruptedException {
pauseCurrentThread(delay);
}
- public static OTreeMapPersistentAsynchThread getInstance() {
+ public static OMVRBTreePersistentAsynchThread getInstance() {
return instance;
}
}
diff --git a/kv/src/main/java/com/orientechnologies/orient/kv/network/protocol/http/OKVDictionaryBucketManager.java b/kv/src/main/java/com/orientechnologies/orient/kv/network/protocol/http/OKVDictionaryBucketManager.java
index 3ad704979c2..39031630f10 100644
--- a/kv/src/main/java/com/orientechnologies/orient/kv/network/protocol/http/OKVDictionaryBucketManager.java
+++ b/kv/src/main/java/com/orientechnologies/orient/kv/network/protocol/http/OKVDictionaryBucketManager.java
@@ -22,8 +22,8 @@
import com.orientechnologies.orient.core.db.record.ODatabaseBinary;
import com.orientechnologies.orient.core.record.impl.ORecordBytes;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerString;
-import com.orientechnologies.orient.core.type.tree.OTreeMapDatabase;
-import com.orientechnologies.orient.kv.index.OTreeMapPersistentAsynch;
+import com.orientechnologies.orient.core.type.tree.OMVRBTreeDatabase;
+import com.orientechnologies.orient.kv.index.OMVRBTreePersistentAsynch;
/**
* Caches bucket tree maps to be reused across calls.
@@ -32,12 +32,12 @@
*
*/
public class OKVDictionaryBucketManager {
- private static Map<String, OTreeMapDatabase<String, String>> bucketCache = new HashMap<String, OTreeMapDatabase<String, String>>();
+ private static Map<String, OMVRBTreeDatabase<String, String>> bucketCache = new HashMap<String, OMVRBTreeDatabase<String, String>>();
private static final String DEFAULT_CLUSTER_NAME = "default";
public static synchronized Map<String, String> getDictionaryBucket(final ODatabaseBinary iDatabase, final String iName,
final boolean iAsynchMode) throws IOException {
- OTreeMapDatabase<String, String> bucket = bucketCache.get(iDatabase.getName() + ":" + iName);
+ OMVRBTreeDatabase<String, String> bucket = bucketCache.get(iDatabase.getName() + ":" + iName);
if (bucket != null)
return bucket;
@@ -47,10 +47,10 @@ public static synchronized Map<String, String> getDictionaryBucket(final ODataba
if (record == null) {
// CREATE THE BUCKET TRANSPARENTLY
if (iAsynchMode)
- bucket = new OTreeMapPersistentAsynch<String, String>(iDatabase, DEFAULT_CLUSTER_NAME, OStreamSerializerString.INSTANCE,
+ bucket = new OMVRBTreePersistentAsynch<String, String>(iDatabase, DEFAULT_CLUSTER_NAME, OStreamSerializerString.INSTANCE,
OStreamSerializerString.INSTANCE);
else
- bucket = new OTreeMapDatabase<String, String>(iDatabase, DEFAULT_CLUSTER_NAME, OStreamSerializerString.INSTANCE,
+ bucket = new OMVRBTreeDatabase<String, String>(iDatabase, DEFAULT_CLUSTER_NAME, OStreamSerializerString.INSTANCE,
OStreamSerializerString.INSTANCE);
bucket.save();
@@ -58,9 +58,9 @@ public static synchronized Map<String, String> getDictionaryBucket(final ODataba
iDatabase.getDictionary().put(iName, bucket.getRecord());
} else {
if (iAsynchMode)
- bucket = new OTreeMapPersistentAsynch<String, String>(iDatabase, record.getIdentity());
+ bucket = new OMVRBTreePersistentAsynch<String, String>(iDatabase, record.getIdentity());
else
- bucket = new OTreeMapDatabase<String, String>(iDatabase, record.getIdentity());
+ bucket = new OMVRBTreeDatabase<String, String>(iDatabase, record.getIdentity());
bucket.load();
}
diff --git a/kv/src/main/java/com/orientechnologies/orient/kv/network/protocol/http/local/ONetworkProtocolHttpKVLocal.java b/kv/src/main/java/com/orientechnologies/orient/kv/network/protocol/http/local/ONetworkProtocolHttpKVLocal.java
index 000cebfbc77..db38c31f2cd 100644
--- a/kv/src/main/java/com/orientechnologies/orient/kv/network/protocol/http/local/ONetworkProtocolHttpKVLocal.java
+++ b/kv/src/main/java/com/orientechnologies/orient/kv/network/protocol/http/local/ONetworkProtocolHttpKVLocal.java
@@ -21,7 +21,7 @@
import com.orientechnologies.common.exception.OException;
import com.orientechnologies.orient.core.db.record.ODatabaseBinary;
import com.orientechnologies.orient.kv.OSharedBinaryDatabase;
-import com.orientechnologies.orient.kv.index.OTreeMapPersistentAsynchThread;
+import com.orientechnologies.orient.kv.index.OMVRBTreePersistentAsynchThread;
import com.orientechnologies.orient.kv.network.protocol.http.OKVDictionary;
import com.orientechnologies.orient.kv.network.protocol.http.OKVDictionaryBucketManager;
import com.orientechnologies.orient.kv.network.protocol.http.ONetworkProtocolHttpKV;
@@ -37,8 +37,8 @@ public class ONetworkProtocolHttpKVLocal extends ONetworkProtocolHttpKV implemen
// START ASYNCH THREAD IF CONFIGURED
String v = OServerMain.server().getConfiguration().getProperty(ASYNCH_COMMIT_DELAY_PAR);
if (v != null) {
- OTreeMapPersistentAsynchThread.getInstance().setDelay(Integer.parseInt(v));
- OTreeMapPersistentAsynchThread.getInstance().start();
+ OMVRBTreePersistentAsynchThread.getInstance().setDelay(Integer.parseInt(v));
+ OMVRBTreePersistentAsynchThread.getInstance().start();
asynchMode = true;
}
//
diff --git a/tests/src/test/java/com/orientechnologies/orient/test/internal/index/OTreeMapSpeedTest.java b/tests/src/test/java/com/orientechnologies/orient/test/internal/index/OMVRBTreeSpeedTest.java
similarity index 82%
rename from tests/src/test/java/com/orientechnologies/orient/test/internal/index/OTreeMapSpeedTest.java
rename to tests/src/test/java/com/orientechnologies/orient/test/internal/index/OMVRBTreeSpeedTest.java
index dda27ba43f1..685c27d0e3c 100644
--- a/tests/src/test/java/com/orientechnologies/orient/test/internal/index/OTreeMapSpeedTest.java
+++ b/tests/src/test/java/com/orientechnologies/orient/test/internal/index/OMVRBTreeSpeedTest.java
@@ -18,13 +18,13 @@
import org.testng.Assert;
import org.testng.annotations.Test;
+import com.orientechnologies.common.collection.OMVRBTreeMemory;
import com.orientechnologies.common.collection.ONavigableMap;
-import com.orientechnologies.common.collection.OTreeMapMemory;
import com.orientechnologies.common.test.SpeedTestMonoThread;
-public class OTreeMapSpeedTest extends SpeedTestMonoThread {
+public class OMVRBTreeSpeedTest extends SpeedTestMonoThread {
- private ONavigableMap<Integer, Integer> tree = new OTreeMapMemory<Integer, Integer>();
+ private ONavigableMap<Integer, Integer> tree = new OMVRBTreeMemory<Integer, Integer>();
@Override
@Test(enabled = false)
@@ -61,8 +61,8 @@ public void cycle() {
}
data.printSnapshot();
- // if (tree instanceof OTreeMap<?, ?>) {
- // System.out.println("Total nodes: " + ((OTreeMap<?, ?>) tree).getNodes());
+ // if (tree instanceof OMVRBTree<?, ?>) {
+ // System.out.println("Total nodes: " + ((OMVRBTree<?, ?>) tree).getNodes());
// }
System.out.println("Delete all the elements one by one...");
|
87beaa8aac80dec24f5eccb957a4d53c2b11586c
|
arquillian$arquillian-graphene
|
ARQGRA-204: Support innitialization of Page Fragments nested in other
Page Fragments, initialization of List<WebElement> fixed
|
a
|
https://github.com/arquillian/arquillian-graphene
|
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingPageFragments.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingPageFragments.java
index 2f02a872b..a35255793 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingPageFragments.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingPageFragments.java
@@ -23,6 +23,7 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
import java.net.URL;
import java.util.List;
@@ -32,6 +33,7 @@
import org.jboss.arquillian.graphene.enricher.fragment.AbstractPageFragmentStub;
import org.jboss.arquillian.graphene.enricher.page.EmbeddedPage;
import org.jboss.arquillian.graphene.enricher.page.TestPage;
+import org.jboss.arquillian.graphene.enricher.page.fragment.PageFragmentWithEmbeddedAnotherPageFragmentStub;
import org.jboss.arquillian.graphene.spi.annotations.Page;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Test;
@@ -51,6 +53,9 @@ public class TestInitializingPageFragments {
@FindBy(xpath = "//div[@id='rootElement']")
private AbstractPageFragmentStub abstractPageFragmentStub;
+ @FindBy(xpath = "//div[@id='rootElement']")
+ private PageFragmentWithEmbeddedAnotherPageFragmentStub pageFragmentWithEmbeddedAnotherPageFragment;
+
@FindBy(xpath = "//input")
private WebElement input;
@@ -63,11 +68,11 @@ public class TestInitializingPageFragments {
private final String EXPECTED_NESTED_ELEMENT_TEXT = "Some Value";
@Drone
- WebDriver selenium;
+ private WebDriver selenium;
public void loadPage() {
URL page = this.getClass().getClassLoader()
- .getResource("org/jboss/arquillian/graphene/ftest/pageFragmentsEnricher/sample.html");
+ .getResource("org/jboss/arquillian/graphene/ftest/pageFragmentsEnricher/sample.html");
selenium.get(page.toExternalForm());
}
@@ -82,14 +87,14 @@ public void testpageFragmentIsInitialized() {
public void testPageFragmentHasSetRootCorrectly() {
loadPage();
assertEquals("The root was not set correctly!", abstractPageFragmentStub.invokeMethodOnElementRefByXpath(),
- EXPECTED_NESTED_ELEMENT_TEXT);
+ EXPECTED_NESTED_ELEMENT_TEXT);
}
@Test
public void testPageObjectInitialisedCorrectly() {
loadPage();
assertEquals("The page object was not set correctly!", testPage.getAbstractPageFragment()
- .invokeMethodOnElementRefByXpath(), EXPECTED_NESTED_ELEMENT_TEXT);
+ .invokeMethodOnElementRefByXpath(), EXPECTED_NESTED_ELEMENT_TEXT);
}
@Test
@@ -99,43 +104,41 @@ public void testOtherWebElementsInitialisedCorrectly() {
input.sendKeys(EXPECTED_VALUE);
assertEquals("The value of the input is wrong, the element which represents it was not initialised correctly!",
- input.getAttribute("value"), EXPECTED_VALUE);
+ input.getAttribute("value"), EXPECTED_VALUE);
}
@Test
public void testEmbeddedPageObjectInitializedCorrectly() {
loadPage();
assertEquals("The embedded page was not initialized correctly!", EmbeddedPage.EXPECTED_TEXT_OF_EMBEDDED_ELEM, testPage
- .getEmbeddedPage().invokeMethodOnEmbeddedElement());
+ .getEmbeddedPage().invokeMethodOnEmbeddedElement());
}
@Test
public void testInitializeListOfWebElementsInjectedToTests() {
loadPage();
- checkInitializationOfWebElements(divs);
+ checkInitializationOfWebElements(divs, "Outside PageFragment");
}
@Test
public void testInitializeListOfWebElementsInjectedToPageFragments() {
loadPage();
- checkInitializationOfWebElements(abstractPageFragmentStub.getDivs());
+ checkInitializationOfWebElements(abstractPageFragmentStub.getSpansInPageFragment(), "Inside PageFragment");
}
- private void checkInitializationOfWebElements(List<WebElement> webElements) {
- assertNotNull("The list of WebElements was not initialized correctly!", webElements);
-
- for (int i = 1; i <= 3; i++) {
- WebElement webElement = webElements.get(i - 1);
- assertEquals("The WebElement number " + i + " from list was not initialized correctly!", String.valueOf(i),
- webElement.getText());
- }
+ @Test
+ public void testInitializeListOfWebElementsInjectedToPageObject() {
+ loadPage();
+ checkInitializationOfWebElements(testPage.getParagraphs(), "Inside PageObject");
}
@Test
public void testSupportForAdvancedActions() {
+ loadPage();
+
WebDriver driver = GrapheneContext.getProxyForInterfaces(HasInputDevices.class);
Actions builder = new Actions(driver);
@@ -146,8 +149,34 @@ public void testSupportForAdvancedActions() {
// following with WebElements from Page Fragments
builder.click(abstractPageFragmentStub.getLocatorRefByXPath());
// following with List of WebElements from Page Fragments
- builder.click(abstractPageFragmentStub.getDivs().get(0));
+ builder.click(abstractPageFragmentStub.getSpansInPageFragment().get(0));
builder.perform();
}
+
+ @Test
+ public void testInitializationOfEmbeddedPageFragmentsInOtherPageFragments() {
+ loadPage();
+
+ WebElement element = pageFragmentWithEmbeddedAnotherPageFragment.getEmbeddedPageFragment().getLocatorRefByClassName();
+
+ assertEquals("The Page Fragment ebmedded in another Page Fragment was not initialized correctly!", element.getText(),
+ "Value of element in embedded page fragment");
+ }
+
+ private void checkInitializationOfWebElements(List<WebElement> webElements, String expectedValueOfWebElements) {
+ assertNotNull("The list of WebElements was not initialized correctly!", webElements);
+
+ for (int i = 1; i <= 3; i++) {
+ WebElement webElement = null;
+ try {
+ webElement = webElements.get(i - 1);
+ } catch (IndexOutOfBoundsException ex) {
+ fail("The List<WebElement> was not initialized correclty! " + ex);
+ return;
+ }
+ assertEquals("The WebElement number " + i + " from list was not initialized correctly!", expectedValueOfWebElements
+ + " " + String.valueOf(i), webElement.getText());
+ }
+ }
}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/TestPage.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/TestPage.java
index 3b1464b60..fb6d8550f 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/TestPage.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/TestPage.java
@@ -21,6 +21,8 @@
*/
package org.jboss.arquillian.graphene.enricher.page;
+import java.util.List;
+
import org.jboss.arquillian.graphene.enricher.fragment.AbstractPageFragmentStub;
import org.jboss.arquillian.graphene.spi.annotations.Page;
import org.openqa.selenium.WebElement;
@@ -39,7 +41,10 @@ public class TestPage extends AbstractPage {
@FindBy(xpath = "//input")
private WebElement input;
-
+
+ @FindBy(className="paragraphs")
+ private List<WebElement> paragraphs;
+
@Page
private EmbeddedPage embeddedPage;
@@ -74,4 +79,12 @@ public EmbeddedPage getEmbeddedPage() {
public void setEmbeddedPage(EmbeddedPage embeddedPage) {
this.embeddedPage = embeddedPage;
}
+
+ public List<WebElement> getParagraphs() {
+ return paragraphs;
+ }
+
+ public void setParagraphs(List<WebElement> paragraphs) {
+ this.paragraphs = paragraphs;
+ }
}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/fragment/PageFragmentWithEmbeddedAnotherPageFragmentStub.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/fragment/PageFragmentWithEmbeddedAnotherPageFragmentStub.java
new file mode 100644
index 000000000..bbd3bd2c6
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/fragment/PageFragmentWithEmbeddedAnotherPageFragmentStub.java
@@ -0,0 +1,50 @@
+/**
+ * JBoss, Home of Professional Open Source
+ * Copyright 2011, Red Hat, Inc. and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.arquillian.graphene.enricher.page.fragment;
+
+import org.jboss.arquillian.graphene.enricher.fragment.AbstractPageFragmentStub;
+import org.jboss.arquillian.graphene.spi.annotations.Root;
+import org.openqa.selenium.WebElement;
+import org.openqa.selenium.support.FindBy;
+
+/**
+ * @author Juraj Huska
+ */
+public class PageFragmentWithEmbeddedAnotherPageFragmentStub {
+
+ @SuppressWarnings("unused")
+ @Root
+ private WebElement root;
+
+ @FindBy(className="rootOfEmbeddedPageFragment")
+ private AbstractPageFragmentStub embeddedPageFragment;
+
+ public AbstractPageFragmentStub getEmbeddedPageFragment() {
+ return embeddedPageFragment;
+ }
+
+ public void setEmbeddedPageFragment(AbstractPageFragmentStub embeddedPageFragment) {
+ this.embeddedPageFragment = embeddedPageFragment;
+ }
+
+
+}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/pageFragmentsEnricher/sample.html b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/pageFragmentsEnricher/sample.html
index f4216cd1e..b75033ec3 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/pageFragmentsEnricher/sample.html
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/pageFragmentsEnricher/sample.html
@@ -7,6 +7,13 @@
<body>
<div id="rootElement">
<div class="refByXpath">Some Value</div>
+ <span class="spans">Inside PageFragment 1</span>
+ <span class="spans">Inside PageFragment 2</span>
+ <span class="spans">Inside PageFragment 3</span>
+
+ <div class="rootOfEmbeddedPageFragment">
+ <div class="classNameRef">Value of element in embedded page fragment</div>
+ </div>
</div>
<div class="refByXpath">Some value too</div>
@@ -16,10 +23,18 @@
<div id="embeddedElement">This is embedded element</div>
<input type="text" id="input" />
-
- <div class="divs">1</div>
- <div class="divs">2</div>
- <div class="divs">3</div>
+
+ <div class="rootOfEmbeddedPageFragment">
+ <div class="classNameRef">Different value</div>
+ </div>
+
+ <div class="divs">Outside PageFragment 1</div>
+ <div class="divs">Outside PageFragment 2</div>
+ <div class="divs">Outside PageFragment 3</div>
+
+ <p class="paragraphs">Inside PageObject 1</p>
+ <p class="paragraphs">Inside PageObject 2</p>
+ <p class="paragraphs">Inside PageObject 3</p>
</body>
</html>
\ No newline at end of file
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/Factory.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/Factory.java
index 1819092f9..a0882db57 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/Factory.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/Factory.java
@@ -22,6 +22,8 @@
package org.jboss.arquillian.graphene.enricher;
import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Iterator;
import java.util.List;
import org.jboss.arquillian.graphene.context.GrapheneContext;
@@ -68,11 +70,82 @@ public static <T> T initializePageFragment(Class<T> clazzOfPageFragment, final W
setObjectToField(fields.get(0), pageFragment, rootOfPageFragment);
}
- fields = ReflectionHelper.getFieldsWithAnnotation(clazzOfPageFragment, FindBy.class);
- initNotPageFragmentsFields(fields, pageFragment, rootOfPageFragment);
+ initFieldsAnnotatedByFindBy(pageFragment, rootOfPageFragment);
return pageFragment;
}
+
+ static void initFieldsAnnotatedByFindBy(Object object, WebElement root) {
+
+ // gets all fields with findBy annotations and then removes these
+ // which are not Page Fragments
+ List<Field> fields = ReflectionHelper.getFieldsWithAnnotation(object.getClass(), FindBy.class);
+
+ List<Field> copy = new ArrayList<Field>();
+ copy.addAll(fields);
+
+ fields = removePlainFindBy(fields);
+ initPageFragmentsFields(fields, object, root);
+
+ // initialize other non Page Fragment fields annotated with FindBy
+ copy.removeAll(fields);
+ Factory.initNotPageFragmentsFields(copy, object, root);
+ }
+
+ /**
+ * It removes all fields with type <code>WebElement</code> from the given list of fields.
+ *
+ * @param findByFields
+ * @return
+ */
+ private static List<Field> removePlainFindBy(List<Field> findByFields) {
+
+ for (Iterator<Field> i = findByFields.iterator(); i.hasNext();) {
+
+ Field field = i.next();
+
+ Class<?> fieldType = field.getType();
+
+ if (fieldType.equals(WebElement.class)) {
+ i.remove();
+ } else if (fieldType.equals(List.class)) {
+ i.remove();
+ }
+ }
+
+ return findByFields;
+ }
+
+ private static void initPageFragmentsFields(List<Field> fields, Object objectToSetPageFragment, WebElement root) {
+ for (Field pageFragmentField : fields) {
+
+ Class<?> implementationClass = pageFragmentField.getType();
+
+ String errorMsgBegin = "The Page Fragment: " + implementationClass + " declared in "
+ + objectToSetPageFragment.getClass() + " can not be initialized properly. The possible reason is: ";
+
+ FindBy findBy = pageFragmentField.getAnnotation(FindBy.class);
+ final By by = Factory.getReferencedBy(findBy);
+
+ if (by == null) {
+ throw new IllegalArgumentException(errorMsgBegin
+ + "Your declaration of Page Fragment in tests is annotated with @FindBy without any "
+ + "parameters, in other words without reference to root of the particular Page Fragment on the page!");
+ }
+
+ WebElement rootElement = Factory.setUpTheProxyForWebElement(by, root);
+
+ Object pageFragment = null;
+ try {
+ pageFragment = Factory.initializePageFragment(implementationClass, rootElement);
+
+ } catch (IllegalArgumentException ex) {
+ throw new IllegalArgumentException(errorMsgBegin + ex.getMessage(), ex);
+ }
+
+ Factory.setObjectToField(pageFragmentField, objectToSetPageFragment, pageFragment);
+ }
+ }
public static <T> T instantiatePageFragment(Class<T> clazz) {
try {
@@ -106,7 +179,7 @@ public static void initNotPageFragmentsFields(List<Field> fields, Object object,
} else if (fieldType.equals(List.class)) {
// it is List of WebElements
- List<WebElement> elements = setUpTheProxyForListOfWebElements(by);
+ List<WebElement> elements = setUpTheProxyForListOfWebElements(by, root);
setObjectToField(i, object, elements);
}
@@ -153,13 +226,13 @@ public static void setObjectToField(Field field, Object objectWithField, Object
}
}
- public static List<WebElement> setUpTheProxyForListOfWebElements(final By by) {
+ public static List<WebElement> setUpTheProxyForListOfWebElements(final By by, final WebElement root) {
List<WebElement> elements = GrapheneProxy.getProxyForFutureTarget(new GrapheneProxy.FutureTarget() {
@Override
public Object getTarget() {
WebDriver driver = GrapheneContext.getProxy();
- List<WebElement> elements = driver.findElements(by);
+ List<WebElement> elements = root == null ? driver.findElements(by) : root.findElements(by);
return elements;
}
}, List.class);
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentsEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentsEnricher.java
index f087a70be..80d774075 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentsEnricher.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentsEnricher.java
@@ -26,16 +26,11 @@
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
-import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Iterator;
import java.util.List;
import org.jboss.arquillian.graphene.spi.annotations.Page;
import org.jboss.arquillian.test.spi.TestEnricher;
-import org.openqa.selenium.By;
-import org.openqa.selenium.WebElement;
-import org.openqa.selenium.support.FindBy;
/**
* Enricher is a class for injecting into fields initialised <code>WebElement</code> and Page Fragments instances.
@@ -54,7 +49,7 @@ public void enrich(Object testCase) {
// at first initialize findBy annotations
if (ReflectionHelper.isClassPresent(FIND_BY_ANNOTATION)) {
- initFieldsAnnotatedByFindBy(testCase);
+ Factory.initFieldsAnnotatedByFindBy(testCase, null);
}
// initialize Page objects if there are any
if (ReflectionHelper.isClassPresent(PAGE_ANNOTATION)) {
@@ -65,23 +60,6 @@ public void enrich(Object testCase) {
}
}
- private void initFieldsAnnotatedByFindBy(Object object) {
-
- // gets all fields with findBy annotations and then removes these
- // which are not Page Fragments
- List<Field> fields = ReflectionHelper.getFieldsWithAnnotation(object.getClass(), FindBy.class);
-
- List<Field> copy = new ArrayList<Field>();
- copy.addAll(fields);
-
- fields = removePlainFindBy(fields);
- initPageFragmentsFields(fields, object);
-
- // initialize other non Page Fragment fields annotated with FindBy
- copy.removeAll(fields);
- Factory.initNotPageFragmentsFields(copy, object, null);
- }
-
private void initializePageObjectFields(Object testCase, List<Field> fields) {
for (Field i : fields) {
@@ -144,61 +122,6 @@ private TypeVariable<?>[] getSuperClassTypeParameters(Object testCase) {
return typeParameters;
}
- private void initPageFragmentsFields(List<Field> fields, Object objectToSetPageFragment) {
- for (Field pageFragmentField : fields) {
-
- Class<?> implementationClass = pageFragmentField.getType();
-
- String errorMsgBegin = "The Page Fragment: " + implementationClass + " declared in "
- + objectToSetPageFragment.getClass() + " can not be initialized properly. The possible reason is: ";
-
- FindBy findBy = pageFragmentField.getAnnotation(FindBy.class);
- final By by = Factory.getReferencedBy(findBy);
-
- if (by == null) {
- throw new IllegalArgumentException(errorMsgBegin
- + "Your declaration of Page Fragment in tests is annotated with @FindBy without any "
- + "parameters, in other words without reference to root of the particular Page Fragment on the page!");
- }
-
- WebElement rootElement = Factory.setUpTheProxyForWebElement(by, null);
-
- Object pageFragment = null;
- try {
- pageFragment = Factory.initializePageFragment(implementationClass, rootElement);
-
- } catch (IllegalArgumentException ex) {
- throw new IllegalArgumentException(errorMsgBegin + ex.getMessage(), ex);
- }
-
- Factory.setObjectToField(pageFragmentField, objectToSetPageFragment, pageFragment);
- }
- }
-
- /**
- * It removes all fields with type <code>WebElement</code> from the given list of fields.
- *
- * @param findByFields
- * @return
- */
- private List<Field> removePlainFindBy(List<Field> findByFields) {
-
- for (Iterator<Field> i = findByFields.iterator(); i.hasNext();) {
-
- Field field = i.next();
-
- Class<?> fieldType = field.getType();
-
- if (fieldType.equals(WebElement.class)) {
- i.remove();
- } else if (fieldType.equals(List.class)) {
- i.remove();
- }
- }
-
- return findByFields;
- }
-
@Override
public Object[] resolve(Method method) {
return new Object[method.getParameterTypes().length];
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/fragment/AbstractPageFragmentStub.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/fragment/AbstractPageFragmentStub.java
index 1386f6ee2..208f2cc71 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/fragment/AbstractPageFragmentStub.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/fragment/AbstractPageFragmentStub.java
@@ -61,8 +61,8 @@ public class AbstractPageFragmentStub {
@FindBy(css = "cssSelectorRef")
private WebElement locatorRefByCssSelector;
- @FindBy(className="divs")
- private List<WebElement> divs;
+ @FindBy(className="spans")
+ private List<WebElement> spansInPageFragment;
public String invokeMethodOnRoot() {
return root.getText();
@@ -168,12 +168,12 @@ public void setLocatorRefByCssSelector(WebElement locatorRefByCssSelector) {
this.locatorRefByCssSelector = locatorRefByCssSelector;
}
- public List<WebElement> getDivs() {
- return divs;
+ public List<WebElement> getSpansInPageFragment() {
+ return spansInPageFragment;
}
- public void setDivs(List<WebElement> divs) {
- this.divs = divs;
+ public void setSpans(List<WebElement> divs) {
+ this.spansInPageFragment = divs;
}
}
|
d5323221449f55323f7b3558350f3e078007ac1c
|
tapiji
|
updated licenses
|
p
|
https://github.com/tapiji/tapiji
|
diff --git a/at.ac.tuwien.inso.eclipse.i18n.jsf.feature/epl-v10.html b/at.ac.tuwien.inso.eclipse.i18n.jsf.feature/epl-v10.html
new file mode 100644
index 00000000..ed4b1966
--- /dev/null
+++ b/at.ac.tuwien.inso.eclipse.i18n.jsf.feature/epl-v10.html
@@ -0,0 +1,328 @@
+<html xmlns:o="urn:schemas-microsoft-com:office:office"
+xmlns:w="urn:schemas-microsoft-com:office:word"
+xmlns="http://www.w3.org/TR/REC-html40">
+
+<head>
+<meta http-equiv=Content-Type content="text/html; charset=windows-1252">
+<meta name=ProgId content=Word.Document>
+<meta name=Generator content="Microsoft Word 9">
+<meta name=Originator content="Microsoft Word 9">
+<link rel=File-List
+href="./Eclipse%20EPL%202003_11_10%20Final_files/filelist.xml">
+<title>Eclipse Public License - Version 1.0</title>
+<!--[if gte mso 9]><xml>
+ <o:DocumentProperties>
+ <o:Revision>2</o:Revision>
+ <o:TotalTime>3</o:TotalTime>
+ <o:Created>2004-03-05T23:03:00Z</o:Created>
+ <o:LastSaved>2004-03-05T23:03:00Z</o:LastSaved>
+ <o:Pages>4</o:Pages>
+ <o:Words>1626</o:Words>
+ <o:Characters>9270</o:Characters>
+ <o:Lines>77</o:Lines>
+ <o:Paragraphs>18</o:Paragraphs>
+ <o:CharactersWithSpaces>11384</o:CharactersWithSpaces>
+ <o:Version>9.4402</o:Version>
+ </o:DocumentProperties>
+</xml><![endif]--><!--[if gte mso 9]><xml>
+ <w:WordDocument>
+ <w:TrackRevisions/>
+ </w:WordDocument>
+</xml><![endif]-->
+<style>
+<!--
+ /* Font Definitions */
+@font-face
+ {font-family:Tahoma;
+ panose-1:2 11 6 4 3 5 4 4 2 4;
+ mso-font-charset:0;
+ mso-generic-font-family:swiss;
+ mso-font-pitch:variable;
+ mso-font-signature:553679495 -2147483648 8 0 66047 0;}
+ /* Style Definitions */
+p.MsoNormal, li.MsoNormal, div.MsoNormal
+ {mso-style-parent:"";
+ margin:0in;
+ margin-bottom:.0001pt;
+ mso-pagination:widow-orphan;
+ font-size:12.0pt;
+ font-family:"Times New Roman";
+ mso-fareast-font-family:"Times New Roman";}
+p
+ {margin-right:0in;
+ mso-margin-top-alt:auto;
+ mso-margin-bottom-alt:auto;
+ margin-left:0in;
+ mso-pagination:widow-orphan;
+ font-size:12.0pt;
+ font-family:"Times New Roman";
+ mso-fareast-font-family:"Times New Roman";}
+p.BalloonText, li.BalloonText, div.BalloonText
+ {mso-style-name:"Balloon Text";
+ margin:0in;
+ margin-bottom:.0001pt;
+ mso-pagination:widow-orphan;
+ font-size:8.0pt;
+ font-family:Tahoma;
+ mso-fareast-font-family:"Times New Roman";}
+@page Section1
+ {size:8.5in 11.0in;
+ margin:1.0in 1.25in 1.0in 1.25in;
+ mso-header-margin:.5in;
+ mso-footer-margin:.5in;
+ mso-paper-source:0;}
+div.Section1
+ {page:Section1;}
+-->
+</style>
+</head>
+
+<body lang=EN-US style='tab-interval:.5in'>
+
+<div class=Section1>
+
+<p align=center style='text-align:center'><b>Eclipse Public License - v 1.0</b>
+</p>
+
+<p><span style='font-size:10.0pt'>THE ACCOMPANYING PROGRAM IS PROVIDED UNDER
+THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE,
+REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE
+OF THIS AGREEMENT.</span> </p>
+
+<p><b><span style='font-size:10.0pt'>1. DEFINITIONS</span></b> </p>
+
+<p><span style='font-size:10.0pt'>"Contribution" means:</span> </p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a)
+in the case of the initial Contributor, the initial code and documentation
+distributed under this Agreement, and<br clear=left>
+b) in the case of each subsequent Contributor:</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>i)
+changes to the Program, and</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii)
+additions to the Program;</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>where
+such changes and/or additions to the Program originate from and are distributed
+by that particular Contributor. A Contribution 'originates' from a Contributor
+if it was added to the Program by such Contributor itself or anyone acting on
+such Contributor's behalf. Contributions do not include additions to the
+Program which: (i) are separate modules of software distributed in conjunction
+with the Program under their own license agreement, and (ii) are not derivative
+works of the Program. </span></p>
+
+<p><span style='font-size:10.0pt'>"Contributor" means any person or
+entity that distributes the Program.</span> </p>
+
+<p><span style='font-size:10.0pt'>"Licensed Patents " mean patent
+claims licensable by a Contributor which are necessarily infringed by the use
+or sale of its Contribution alone or when combined with the Program. </span></p>
+
+<p><span style='font-size:10.0pt'>"Program" means the Contributions
+distributed in accordance with this Agreement.</span> </p>
+
+<p><span style='font-size:10.0pt'>"Recipient" means anyone who
+receives the Program under this Agreement, including all Contributors.</span> </p>
+
+<p><b><span style='font-size:10.0pt'>2. GRANT OF RIGHTS</span></b> </p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a)
+Subject to the terms of this Agreement, each Contributor hereby grants Recipient
+a non-exclusive, worldwide, royalty-free copyright license to<span
+style='color:red'> </span>reproduce, prepare derivative works of, publicly
+display, publicly perform, distribute and sublicense the Contribution of such
+Contributor, if any, and such derivative works, in source code and object code
+form.</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b)
+Subject to the terms of this Agreement, each Contributor hereby grants
+Recipient a non-exclusive, worldwide,<span style='color:green'> </span>royalty-free
+patent license under Licensed Patents to make, use, sell, offer to sell, import
+and otherwise transfer the Contribution of such Contributor, if any, in source
+code and object code form. This patent license shall apply to the combination
+of the Contribution and the Program if, at the time the Contribution is added
+by the Contributor, such addition of the Contribution causes such combination
+to be covered by the Licensed Patents. The patent license shall not apply to
+any other combinations which include the Contribution. No hardware per se is
+licensed hereunder. </span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>c)
+Recipient understands that although each Contributor grants the licenses to its
+Contributions set forth herein, no assurances are provided by any Contributor
+that the Program does not infringe the patent or other intellectual property
+rights of any other entity. Each Contributor disclaims any liability to Recipient
+for claims brought by any other entity based on infringement of intellectual
+property rights or otherwise. As a condition to exercising the rights and
+licenses granted hereunder, each Recipient hereby assumes sole responsibility
+to secure any other intellectual property rights needed, if any. For example,
+if a third party patent license is required to allow Recipient to distribute
+the Program, it is Recipient's responsibility to acquire that license before
+distributing the Program.</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>d)
+Each Contributor represents that to its knowledge it has sufficient copyright
+rights in its Contribution, if any, to grant the copyright license set forth in
+this Agreement. </span></p>
+
+<p><b><span style='font-size:10.0pt'>3. REQUIREMENTS</span></b> </p>
+
+<p><span style='font-size:10.0pt'>A Contributor may choose to distribute the
+Program in object code form under its own license agreement, provided that:</span>
+</p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a)
+it complies with the terms and conditions of this Agreement; and</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b)
+its license agreement:</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>i)
+effectively disclaims on behalf of all Contributors all warranties and
+conditions, express and implied, including warranties or conditions of title
+and non-infringement, and implied warranties or conditions of merchantability
+and fitness for a particular purpose; </span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii)
+effectively excludes on behalf of all Contributors all liability for damages,
+including direct, indirect, special, incidental and consequential damages, such
+as lost profits; </span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>iii)
+states that any provisions which differ from this Agreement are offered by that
+Contributor alone and not by any other party; and</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>iv)
+states that source code for the Program is available from such Contributor, and
+informs licensees how to obtain it in a reasonable manner on or through a
+medium customarily used for software exchange.<span style='color:blue'> </span></span></p>
+
+<p><span style='font-size:10.0pt'>When the Program is made available in source
+code form:</span> </p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a)
+it must be made available under this Agreement; and </span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) a
+copy of this Agreement must be included with each copy of the Program. </span></p>
+
+<p><span style='font-size:10.0pt'>Contributors may not remove or alter any
+copyright notices contained within the Program. </span></p>
+
+<p><span style='font-size:10.0pt'>Each Contributor must identify itself as the
+originator of its Contribution, if any, in a manner that reasonably allows
+subsequent Recipients to identify the originator of the Contribution. </span></p>
+
+<p><b><span style='font-size:10.0pt'>4. COMMERCIAL DISTRIBUTION</span></b> </p>
+
+<p><span style='font-size:10.0pt'>Commercial distributors of software may
+accept certain responsibilities with respect to end users, business partners
+and the like. While this license is intended to facilitate the commercial use
+of the Program, the Contributor who includes the Program in a commercial
+product offering should do so in a manner which does not create potential
+liability for other Contributors. Therefore, if a Contributor includes the
+Program in a commercial product offering, such Contributor ("Commercial
+Contributor") hereby agrees to defend and indemnify every other
+Contributor ("Indemnified Contributor") against any losses, damages and
+costs (collectively "Losses") arising from claims, lawsuits and other
+legal actions brought by a third party against the Indemnified Contributor to
+the extent caused by the acts or omissions of such Commercial Contributor in
+connection with its distribution of the Program in a commercial product
+offering. The obligations in this section do not apply to any claims or Losses
+relating to any actual or alleged intellectual property infringement. In order
+to qualify, an Indemnified Contributor must: a) promptly notify the Commercial
+Contributor in writing of such claim, and b) allow the Commercial Contributor
+to control, and cooperate with the Commercial Contributor in, the defense and
+any related settlement negotiations. The Indemnified Contributor may participate
+in any such claim at its own expense.</span> </p>
+
+<p><span style='font-size:10.0pt'>For example, a Contributor might include the
+Program in a commercial product offering, Product X. That Contributor is then a
+Commercial Contributor. If that Commercial Contributor then makes performance
+claims, or offers warranties related to Product X, those performance claims and
+warranties are such Commercial Contributor's responsibility alone. Under this
+section, the Commercial Contributor would have to defend claims against the
+other Contributors related to those performance claims and warranties, and if a
+court requires any other Contributor to pay any damages as a result, the
+Commercial Contributor must pay those damages.</span> </p>
+
+<p><b><span style='font-size:10.0pt'>5. NO WARRANTY</span></b> </p>
+
+<p><span style='font-size:10.0pt'>EXCEPT AS EXPRESSLY SET FORTH IN THIS
+AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT
+WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING,
+WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
+MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely
+responsible for determining the appropriateness of using and distributing the
+Program and assumes all risks associated with its exercise of rights under this
+Agreement , including but not limited to the risks and costs of program errors,
+compliance with applicable laws, damage to or loss of data, programs or
+equipment, and unavailability or interruption of operations. </span></p>
+
+<p><b><span style='font-size:10.0pt'>6. DISCLAIMER OF LIABILITY</span></b> </p>
+
+<p><span style='font-size:10.0pt'>EXCEPT AS EXPRESSLY SET FORTH IN THIS
+AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING WITHOUT LIMITATION LOST PROFITS), 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 OR DISTRIBUTION OF
+THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF
+THE POSSIBILITY OF SUCH DAMAGES.</span> </p>
+
+<p><b><span style='font-size:10.0pt'>7. GENERAL</span></b> </p>
+
+<p><span style='font-size:10.0pt'>If any provision of this Agreement is invalid
+or unenforceable under applicable law, it shall not affect the validity or
+enforceability of the remainder of the terms of this Agreement, and without
+further action by the parties hereto, such provision shall be reformed to the
+minimum extent necessary to make such provision valid and enforceable.</span> </p>
+
+<p><span style='font-size:10.0pt'>If Recipient institutes patent litigation
+against any entity (including a cross-claim or counterclaim in a lawsuit)
+alleging that the Program itself (excluding combinations of the Program with
+other software or hardware) infringes such Recipient's patent(s), then such
+Recipient's rights granted under Section 2(b) shall terminate as of the date
+such litigation is filed. </span></p>
+
+<p><span style='font-size:10.0pt'>All Recipient's rights under this Agreement
+shall terminate if it fails to comply with any of the material terms or
+conditions of this Agreement and does not cure such failure in a reasonable
+period of time after becoming aware of such noncompliance. If all Recipient's
+rights under this Agreement terminate, Recipient agrees to cease use and
+distribution of the Program as soon as reasonably practicable. However,
+Recipient's obligations under this Agreement and any licenses granted by
+Recipient relating to the Program shall continue and survive. </span></p>
+
+<p><span style='font-size:10.0pt'>Everyone is permitted to copy and distribute
+copies of this Agreement, but in order to avoid inconsistency the Agreement is
+copyrighted and may only be modified in the following manner. The Agreement
+Steward reserves the right to publish new versions (including revisions) of
+this Agreement from time to time. No one other than the Agreement Steward has
+the right to modify this Agreement. The Eclipse Foundation is the initial
+Agreement Steward. The Eclipse Foundation may assign the responsibility to
+serve as the Agreement Steward to a suitable separate entity. Each new version
+of the Agreement will be given a distinguishing version number. The Program
+(including Contributions) may always be distributed subject to the version of
+the Agreement under which it was received. In addition, after a new version of
+the Agreement is published, Contributor may elect to distribute the Program
+(including its Contributions) under the new version. Except as expressly stated
+in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to
+the intellectual property of any Contributor under this Agreement, whether
+expressly, by implication, estoppel or otherwise. All rights in the Program not
+expressly granted under this Agreement are reserved.</span> </p>
+
+<p><span style='font-size:10.0pt'>This Agreement is governed by the laws of the
+State of New York and the intellectual property laws of the United States of
+America. No party to this Agreement will bring a legal action under this
+Agreement more than one year after the cause of action arose. Each party waives
+its rights to a jury trial in any resulting litigation.</span> </p>
+
+<p class=MsoNormal><![if !supportEmptyParas]> <![endif]><o:p></o:p></p>
+
+</div>
+
+</body>
+
+</html>
\ No newline at end of file
diff --git a/at.ac.tuwien.inso.eclipse.i18n.jsf.feature/feature.xml b/at.ac.tuwien.inso.eclipse.i18n.jsf.feature/feature.xml
index 1a042b09..b8b17f83 100644
--- a/at.ac.tuwien.inso.eclipse.i18n.jsf.feature/feature.xml
+++ b/at.ac.tuwien.inso.eclipse.i18n.jsf.feature/feature.xml
@@ -17,228 +17,334 @@ reserved.
</copyright>
<license url="http://www.eclipse.org/legal/epl-v10.html">
- *Eclipse Public License - v 1.0*
-
-THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
-PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF
-THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
-
-*1. DEFINITIONS*
-
-"Contribution" means:
-
-a) in the case of the initial Contributor, the initial code and
-documentation distributed under this Agreement, and
-
-b) in the case of each subsequent Contributor:
-
-i) changes to the Program, and
-
-ii) additions to the Program;
-
-where such changes and/or additions to the Program originate from and
-are distributed by that particular Contributor. A Contribution
-'originates' from a Contributor if it was added to the Program by such
-Contributor itself or anyone acting on such Contributor's behalf.
-Contributions do not include additions to the Program which: (i) are
-separate modules of software distributed in conjunction with the Program
-under their own license agreement, and (ii) are not derivative works of
-the Program.
-
-"Contributor" means any person or entity that distributes the Program.
-
-"Licensed Patents" mean patent claims licensable by a Contributor which
-are necessarily infringed by the use or sale of its Contribution alone
-or when combined with the Program.
-
-"Program" means the Contributions distributed in accordance with this
-Agreement.
-
-"Recipient" means anyone who receives the Program under this Agreement,
-including all Contributors.
-
-*2. GRANT OF RIGHTS*
-
-a) Subject to the terms of this Agreement, each Contributor hereby
-grants Recipient a non-exclusive, worldwide, royalty-free copyright
-license to reproduce, prepare derivative works of, publicly display,
-publicly perform, distribute and sublicense the Contribution of such
-Contributor, if any, and such derivative works, in source code and
-object code form.
-
-b) Subject to the terms of this Agreement, each Contributor hereby
-grants Recipient a non-exclusive, worldwide, royalty-free patent license
-under Licensed Patents to make, use, sell, offer to sell, import and
-otherwise transfer the Contribution of such Contributor, if any, in
-source code and object code form. This patent license shall apply to the
-combination of the Contribution and the Program if, at the time the
-Contribution is added by the Contributor, such addition of the
-Contribution causes such combination to be covered by the Licensed
-Patents. The patent license shall not apply to any other combinations
-which include the Contribution. No hardware per se is licensed hereunder.
-
-c) Recipient understands that although each Contributor grants the
-licenses to its Contributions set forth herein, no assurances are
-provided by any Contributor that the Program does not infringe the
-patent or other intellectual property rights of any other entity. Each
-Contributor disclaims any liability to Recipient for claims brought by
-any other entity based on infringement of intellectual property rights
-or otherwise. As a condition to exercising the rights and licenses
-granted hereunder, each Recipient hereby assumes sole responsibility to
-secure any other intellectual property rights needed, if any. For
-example, if a third party patent license is required to allow Recipient
-to distribute the Program, it is Recipient's responsibility to acquire
-that license before distributing the Program.
-
-d) Each Contributor represents that to its knowledge it has sufficient
-copyright rights in its Contribution, if any, to grant the copyright
-license set forth in this Agreement.
-
-*3. REQUIREMENTS*
-
-A Contributor may choose to distribute the Program in object code form
-under its own license agreement, provided that:
-
-a) it complies with the terms and conditions of this Agreement; and
-
-b) its license agreement:
-
-i) effectively disclaims on behalf of all Contributors all warranties
-and conditions, express and implied, including warranties or conditions
-of title and non-infringement, and implied warranties or conditions of
-merchantability and fitness for a particular purpose;
-
-ii) effectively excludes on behalf of all Contributors all liability for
-damages, including direct, indirect, special, incidental and
-consequential damages, such as lost profits;
-
-iii) states that any provisions which differ from this Agreement are
-offered by that Contributor alone and not by any other party; and
-
-iv) states that source code for the Program is available from such
-Contributor, and informs licensees how to obtain it in a reasonable
-manner on or through a medium customarily used for software exchange.
-
-When the Program is made available in source code form:
-
-a) it must be made available under this Agreement; and
-
-b) a copy of this Agreement must be included with each copy of the Program.
-
-Contributors may not remove or alter any copyright notices contained
-within the Program.
-
-Each Contributor must identify itself as the originator of its
-Contribution, if any, in a manner that reasonably allows subsequent
-Recipients to identify the originator of the Contribution.
-
-*4. COMMERCIAL DISTRIBUTION*
-
-Commercial distributors of software may accept certain responsibilities
-with respect to end users, business partners and the like. While this
-license is intended to facilitate the commercial use of the Program, the
-Contributor who includes the Program in a commercial product offering
-should do so in a manner which does not create potential liability for
-other Contributors. Therefore, if a Contributor includes the Program in
-a commercial product offering, such Contributor ("Commercial
-Contributor") hereby agrees to defend and indemnify every other
-Contributor ("Indemnified Contributor") against any losses, damages and
-costs (collectively "Losses") arising from claims, lawsuits and other
-legal actions brought by a third party against the Indemnified
-Contributor to the extent caused by the acts or omissions of such
-Commercial Contributor in connection with its distribution of the
-Program in a commercial product offering. The obligations in this
-section do not apply to any claims or Losses relating to any actual or
-alleged intellectual property infringement. In order to qualify, an
-Indemnified Contributor must: a) promptly notify the Commercial
-Contributor in writing of such claim, and b) allow the Commercial
-Contributor to control, and cooperate with the Commercial Contributor
-in, the defense and any related settlement negotiations. The Indemnified
-Contributor may participate in any such claim at its own expense.
-
-For example, a Contributor might include the Program in a commercial
-product offering, Product X. That Contributor is then a Commercial
-Contributor. If that Commercial Contributor then makes performance
-claims, or offers warranties related to Product X, those performance
-claims and warranties are such Commercial Contributor's responsibility
-alone. Under this section, the Commercial Contributor would have to
-defend claims against the other Contributors related to those
-performance claims and warranties, and if a court requires any other
-Contributor to pay any damages as a result, the Commercial Contributor
-must pay those damages.
-
-*5. NO WARRANTY*
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED
-ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
-EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES
-OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR
-A PARTICULAR PURPOSE. Each Recipient is solely responsible for
-determining the appropriateness of using and distributing the Program
-and assumes all risks associated with its exercise of rights under this
-Agreement , including but not limited to the risks and costs of program
-errors, compliance with applicable laws, damage to or loss of data,
-programs or equipment, and unavailability or interruption of operations.
-
-*6. DISCLAIMER OF LIABILITY*
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR
-ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT,
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING
-WITHOUT LIMITATION LOST PROFITS), 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 OR
-DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
-HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-
-*7. GENERAL*
-
-If any provision of this Agreement is invalid or unenforceable under
-applicable law, it shall not affect the validity or enforceability of
-the remainder of the terms of this Agreement, and without further action
-by the parties hereto, such provision shall be reformed to the minimum
-extent necessary to make such provision valid and enforceable.
-
-If Recipient institutes patent litigation against any entity (including
-a cross-claim or counterclaim in a lawsuit) alleging that the Program
-itself (excluding combinations of the Program with other software or
-hardware) infringes such Recipient's patent(s), then such Recipient's
-rights granted under Section 2(b) shall terminate as of the date such
-litigation is filed.
-
-All Recipient's rights under this Agreement shall terminate if it fails
-to comply with any of the material terms or conditions of this Agreement
-and does not cure such failure in a reasonable period of time after
-becoming aware of such noncompliance. If all Recipient's rights under
-this Agreement terminate, Recipient agrees to cease use and distribution
-of the Program as soon as reasonably practicable. However, Recipient's
-obligations under this Agreement and any licenses granted by Recipient
-relating to the Program shall continue and survive.
-
-Everyone is permitted to copy and distribute copies of this Agreement,
-but in order to avoid inconsistency the Agreement is copyrighted and may
-only be modified in the following manner. The Agreement Steward reserves
-the right to publish new versions (including revisions) of this
-Agreement from time to time. No one other than the Agreement Steward has
-the right to modify this Agreement. The Eclipse Foundation is the
-initial Agreement Steward. The Eclipse Foundation may assign the
-responsibility to serve as the Agreement Steward to a suitable separate
-entity. Each new version of the Agreement will be given a distinguishing
-version number. The Program (including Contributions) may always be
-distributed subject to the version of the Agreement under which it was
-received. In addition, after a new version of the Agreement is
-published, Contributor may elect to distribute the Program (including
-its Contributions) under the new version. Except as expressly stated in
-Sections 2(a) and 2(b) above, Recipient receives no rights or licenses
-to the intellectual property of any Contributor under this Agreement,
-whether expressly, by implication, estoppel or otherwise. All rights in
-the Program not expressly granted under this Agreement are reserved.
-
-This Agreement is governed by the laws of the State of New York and the
-intellectual property laws of the United States of America. No party to
-this Agreement will bring a legal action under this Agreement more than
-one year after the cause of action arose. Each party waives its rights
-to a jury trial in any resulting litigation.
+ <html xmlns:o="urn:schemas-microsoft-com:office:office"
+xmlns:w="urn:schemas-microsoft-com:office:word"
+xmlns="http://www.w3.org/TR/REC-html40">
+
+<head>
+<meta http-equiv=Content-Type content="text/html; charset=windows-1252">
+<meta name=ProgId content=Word.Document>
+<meta name=Generator content="Microsoft Word 9">
+<meta name=Originator content="Microsoft Word 9">
+<link rel=File-List
+href="./Eclipse%20EPL%202003_11_10%20Final_files/filelist.xml">
+<title>Eclipse Public License - Version 1.0</title>
+<!--[if gte mso 9]><xml>
+ <o:DocumentProperties>
+ <o:Revision>2</o:Revision>
+ <o:TotalTime>3</o:TotalTime>
+ <o:Created>2004-03-05T23:03:00Z</o:Created>
+ <o:LastSaved>2004-03-05T23:03:00Z</o:LastSaved>
+ <o:Pages>4</o:Pages>
+ <o:Words>1626</o:Words>
+ <o:Characters>9270</o:Characters>
+ <o:Lines>77</o:Lines>
+ <o:Paragraphs>18</o:Paragraphs>
+ <o:CharactersWithSpaces>11384</o:CharactersWithSpaces>
+ <o:Version>9.4402</o:Version>
+ </o:DocumentProperties>
+</xml><![endif]--><!--[if gte mso 9]><xml>
+ <w:WordDocument>
+ <w:TrackRevisions/>
+ </w:WordDocument>
+</xml><![endif]-->
+<style>
+<!--
+ /* Font Definitions */
+@font-face
+ {font-family:Tahoma;
+ panose-1:2 11 6 4 3 5 4 4 2 4;
+ mso-font-charset:0;
+ mso-generic-font-family:swiss;
+ mso-font-pitch:variable;
+ mso-font-signature:553679495 -2147483648 8 0 66047 0;}
+ /* Style Definitions */
+p.MsoNormal, li.MsoNormal, div.MsoNormal
+ {mso-style-parent:"";
+ margin:0in;
+ margin-bottom:.0001pt;
+ mso-pagination:widow-orphan;
+ font-size:12.0pt;
+ font-family:"Times New Roman";
+ mso-fareast-font-family:"Times New Roman";}
+p
+ {margin-right:0in;
+ mso-margin-top-alt:auto;
+ mso-margin-bottom-alt:auto;
+ margin-left:0in;
+ mso-pagination:widow-orphan;
+ font-size:12.0pt;
+ font-family:"Times New Roman";
+ mso-fareast-font-family:"Times New Roman";}
+p.BalloonText, li.BalloonText, div.BalloonText
+ {mso-style-name:"Balloon Text";
+ margin:0in;
+ margin-bottom:.0001pt;
+ mso-pagination:widow-orphan;
+ font-size:8.0pt;
+ font-family:Tahoma;
+ mso-fareast-font-family:"Times New Roman";}
+@page Section1
+ {size:8.5in 11.0in;
+ margin:1.0in 1.25in 1.0in 1.25in;
+ mso-header-margin:.5in;
+ mso-footer-margin:.5in;
+ mso-paper-source:0;}
+div.Section1
+ {page:Section1;}
+-->
+</style>
+</head>
+
+<body lang=EN-US style='tab-interval:.5in'>
+
+<div class=Section1>
+
+<p align=center style='text-align:center'><b>Eclipse Public License - v 1.0</b>
+</p>
+
+<p><span style='font-size:10.0pt'>THE ACCOMPANYING PROGRAM IS PROVIDED UNDER
+THE TERMS OF THIS ECLIPSE PUBLIC LICENSE (&quot;AGREEMENT&quot;). ANY USE,
+REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE
+OF THIS AGREEMENT.</span> </p>
+
+<p><b><span style='font-size:10.0pt'>1. DEFINITIONS</span></b> </p>
+
+<p><span style='font-size:10.0pt'>&quot;Contribution&quot; means:</span> </p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a)
+in the case of the initial Contributor, the initial code and documentation
+distributed under this Agreement, and<br clear=left>
+b) in the case of each subsequent Contributor:</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>i)
+changes to the Program, and</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii)
+additions to the Program;</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>where
+such changes and/or additions to the Program originate from and are distributed
+by that particular Contributor. A Contribution 'originates' from a Contributor
+if it was added to the Program by such Contributor itself or anyone acting on
+such Contributor's behalf. Contributions do not include additions to the
+Program which: (i) are separate modules of software distributed in conjunction
+with the Program under their own license agreement, and (ii) are not derivative
+works of the Program. </span></p>
+
+<p><span style='font-size:10.0pt'>&quot;Contributor&quot; means any person or
+entity that distributes the Program.</span> </p>
+
+<p><span style='font-size:10.0pt'>&quot;Licensed Patents &quot; mean patent
+claims licensable by a Contributor which are necessarily infringed by the use
+or sale of its Contribution alone or when combined with the Program. </span></p>
+
+<p><span style='font-size:10.0pt'>&quot;Program&quot; means the Contributions
+distributed in accordance with this Agreement.</span> </p>
+
+<p><span style='font-size:10.0pt'>&quot;Recipient&quot; means anyone who
+receives the Program under this Agreement, including all Contributors.</span> </p>
+
+<p><b><span style='font-size:10.0pt'>2. GRANT OF RIGHTS</span></b> </p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a)
+Subject to the terms of this Agreement, each Contributor hereby grants Recipient
+a non-exclusive, worldwide, royalty-free copyright license to<span
+style='color:red'> </span>reproduce, prepare derivative works of, publicly
+display, publicly perform, distribute and sublicense the Contribution of such
+Contributor, if any, and such derivative works, in source code and object code
+form.</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b)
+Subject to the terms of this Agreement, each Contributor hereby grants
+Recipient a non-exclusive, worldwide,<span style='color:green'> </span>royalty-free
+patent license under Licensed Patents to make, use, sell, offer to sell, import
+and otherwise transfer the Contribution of such Contributor, if any, in source
+code and object code form. This patent license shall apply to the combination
+of the Contribution and the Program if, at the time the Contribution is added
+by the Contributor, such addition of the Contribution causes such combination
+to be covered by the Licensed Patents. The patent license shall not apply to
+any other combinations which include the Contribution. No hardware per se is
+licensed hereunder. </span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>c)
+Recipient understands that although each Contributor grants the licenses to its
+Contributions set forth herein, no assurances are provided by any Contributor
+that the Program does not infringe the patent or other intellectual property
+rights of any other entity. Each Contributor disclaims any liability to Recipient
+for claims brought by any other entity based on infringement of intellectual
+property rights or otherwise. As a condition to exercising the rights and
+licenses granted hereunder, each Recipient hereby assumes sole responsibility
+to secure any other intellectual property rights needed, if any. For example,
+if a third party patent license is required to allow Recipient to distribute
+the Program, it is Recipient's responsibility to acquire that license before
+distributing the Program.</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>d)
+Each Contributor represents that to its knowledge it has sufficient copyright
+rights in its Contribution, if any, to grant the copyright license set forth in
+this Agreement. </span></p>
+
+<p><b><span style='font-size:10.0pt'>3. REQUIREMENTS</span></b> </p>
+
+<p><span style='font-size:10.0pt'>A Contributor may choose to distribute the
+Program in object code form under its own license agreement, provided that:</span>
+</p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a)
+it complies with the terms and conditions of this Agreement; and</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b)
+its license agreement:</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>i)
+effectively disclaims on behalf of all Contributors all warranties and
+conditions, express and implied, including warranties or conditions of title
+and non-infringement, and implied warranties or conditions of merchantability
+and fitness for a particular purpose; </span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii)
+effectively excludes on behalf of all Contributors all liability for damages,
+including direct, indirect, special, incidental and consequential damages, such
+as lost profits; </span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>iii)
+states that any provisions which differ from this Agreement are offered by that
+Contributor alone and not by any other party; and</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>iv)
+states that source code for the Program is available from such Contributor, and
+informs licensees how to obtain it in a reasonable manner on or through a
+medium customarily used for software exchange.<span style='color:blue'> </span></span></p>
+
+<p><span style='font-size:10.0pt'>When the Program is made available in source
+code form:</span> </p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a)
+it must be made available under this Agreement; and </span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) a
+copy of this Agreement must be included with each copy of the Program. </span></p>
+
+<p><span style='font-size:10.0pt'>Contributors may not remove or alter any
+copyright notices contained within the Program. </span></p>
+
+<p><span style='font-size:10.0pt'>Each Contributor must identify itself as the
+originator of its Contribution, if any, in a manner that reasonably allows
+subsequent Recipients to identify the originator of the Contribution. </span></p>
+
+<p><b><span style='font-size:10.0pt'>4. COMMERCIAL DISTRIBUTION</span></b> </p>
+
+<p><span style='font-size:10.0pt'>Commercial distributors of software may
+accept certain responsibilities with respect to end users, business partners
+and the like. While this license is intended to facilitate the commercial use
+of the Program, the Contributor who includes the Program in a commercial
+product offering should do so in a manner which does not create potential
+liability for other Contributors. Therefore, if a Contributor includes the
+Program in a commercial product offering, such Contributor (&quot;Commercial
+Contributor&quot;) hereby agrees to defend and indemnify every other
+Contributor (&quot;Indemnified Contributor&quot;) against any losses, damages and
+costs (collectively &quot;Losses&quot;) arising from claims, lawsuits and other
+legal actions brought by a third party against the Indemnified Contributor to
+the extent caused by the acts or omissions of such Commercial Contributor in
+connection with its distribution of the Program in a commercial product
+offering. The obligations in this section do not apply to any claims or Losses
+relating to any actual or alleged intellectual property infringement. In order
+to qualify, an Indemnified Contributor must: a) promptly notify the Commercial
+Contributor in writing of such claim, and b) allow the Commercial Contributor
+to control, and cooperate with the Commercial Contributor in, the defense and
+any related settlement negotiations. The Indemnified Contributor may participate
+in any such claim at its own expense.</span> </p>
+
+<p><span style='font-size:10.0pt'>For example, a Contributor might include the
+Program in a commercial product offering, Product X. That Contributor is then a
+Commercial Contributor. If that Commercial Contributor then makes performance
+claims, or offers warranties related to Product X, those performance claims and
+warranties are such Commercial Contributor's responsibility alone. Under this
+section, the Commercial Contributor would have to defend claims against the
+other Contributors related to those performance claims and warranties, and if a
+court requires any other Contributor to pay any damages as a result, the
+Commercial Contributor must pay those damages.</span> </p>
+
+<p><b><span style='font-size:10.0pt'>5. NO WARRANTY</span></b> </p>
+
+<p><span style='font-size:10.0pt'>EXCEPT AS EXPRESSLY SET FORTH IN THIS
+AGREEMENT, THE PROGRAM IS PROVIDED ON AN &quot;AS IS&quot; BASIS, WITHOUT
+WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING,
+WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
+MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely
+responsible for determining the appropriateness of using and distributing the
+Program and assumes all risks associated with its exercise of rights under this
+Agreement , including but not limited to the risks and costs of program errors,
+compliance with applicable laws, damage to or loss of data, programs or
+equipment, and unavailability or interruption of operations. </span></p>
+
+<p><b><span style='font-size:10.0pt'>6. DISCLAIMER OF LIABILITY</span></b> </p>
+
+<p><span style='font-size:10.0pt'>EXCEPT AS EXPRESSLY SET FORTH IN THIS
+AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING WITHOUT LIMITATION LOST PROFITS), 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 OR DISTRIBUTION OF
+THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF
+THE POSSIBILITY OF SUCH DAMAGES.</span> </p>
+
+<p><b><span style='font-size:10.0pt'>7. GENERAL</span></b> </p>
+
+<p><span style='font-size:10.0pt'>If any provision of this Agreement is invalid
+or unenforceable under applicable law, it shall not affect the validity or
+enforceability of the remainder of the terms of this Agreement, and without
+further action by the parties hereto, such provision shall be reformed to the
+minimum extent necessary to make such provision valid and enforceable.</span> </p>
+
+<p><span style='font-size:10.0pt'>If Recipient institutes patent litigation
+against any entity (including a cross-claim or counterclaim in a lawsuit)
+alleging that the Program itself (excluding combinations of the Program with
+other software or hardware) infringes such Recipient's patent(s), then such
+Recipient's rights granted under Section 2(b) shall terminate as of the date
+such litigation is filed. </span></p>
+
+<p><span style='font-size:10.0pt'>All Recipient's rights under this Agreement
+shall terminate if it fails to comply with any of the material terms or
+conditions of this Agreement and does not cure such failure in a reasonable
+period of time after becoming aware of such noncompliance. If all Recipient's
+rights under this Agreement terminate, Recipient agrees to cease use and
+distribution of the Program as soon as reasonably practicable. However,
+Recipient's obligations under this Agreement and any licenses granted by
+Recipient relating to the Program shall continue and survive. </span></p>
+
+<p><span style='font-size:10.0pt'>Everyone is permitted to copy and distribute
+copies of this Agreement, but in order to avoid inconsistency the Agreement is
+copyrighted and may only be modified in the following manner. The Agreement
+Steward reserves the right to publish new versions (including revisions) of
+this Agreement from time to time. No one other than the Agreement Steward has
+the right to modify this Agreement. The Eclipse Foundation is the initial
+Agreement Steward. The Eclipse Foundation may assign the responsibility to
+serve as the Agreement Steward to a suitable separate entity. Each new version
+of the Agreement will be given a distinguishing version number. The Program
+(including Contributions) may always be distributed subject to the version of
+the Agreement under which it was received. In addition, after a new version of
+the Agreement is published, Contributor may elect to distribute the Program
+(including its Contributions) under the new version. Except as expressly stated
+in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to
+the intellectual property of any Contributor under this Agreement, whether
+expressly, by implication, estoppel or otherwise. All rights in the Program not
+expressly granted under this Agreement are reserved.</span> </p>
+
+<p><span style='font-size:10.0pt'>This Agreement is governed by the laws of the
+State of New York and the intellectual property laws of the United States of
+America. No party to this Agreement will bring a legal action under this
+Agreement more than one year after the cause of action arose. Each party waives
+its rights to a jury trial in any resulting litigation.</span> </p>
+
+<p class=MsoNormal><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p>
+
+</div>
+
+</body>
+
+</html>
</license>
<requires>
|
ab4b6c1a9260307b51b8ca0f5b22628dda694207
|
belaban$jgroups
|
added functionality to replicate locks from primary to backup nodes
|
p
|
https://github.com/belaban/jgroups
|
diff --git a/src/org/jgroups/blocks/locking/AbstractLockService.java b/src/org/jgroups/blocks/locking/AbstractLockService.java
index 6b3fbe250bd..78683918a5f 100644
--- a/src/org/jgroups/blocks/locking/AbstractLockService.java
+++ b/src/org/jgroups/blocks/locking/AbstractLockService.java
@@ -119,6 +119,12 @@ public void receive(Message msg) {
case LOCK_DENIED:
handleLockDeniedResponse(req.lock_name, req.owner);
break;
+ case CREATE_LOCK:
+ handleCreateLockRequest(req.lock_name, req.owner, msg.getSrc());
+ break;
+ case DELETE_LOCK:
+ handleDeleteLockRequest(req.lock_name, msg.getSrc());
+ break;
default:
log.error("Request of type " + req.type + " not known");
break;
@@ -126,6 +132,7 @@ public void receive(Message msg) {
}
+
public void viewAccepted(View view) {
this.view=view;
if(log.isDebugEnabled())
@@ -135,8 +142,8 @@ public void viewAccepted(View view) {
entry.getValue().handleView(members);
}
for(Map.Entry<String,ServerLock> entry: server_locks.entrySet()) {
- ServerLock queue=entry.getValue();
- if(queue.isEmpty() && queue.current_owner == null)
+ ServerLock lock=entry.getValue();
+ if(lock.isEmpty() && lock.current_owner == null)
server_locks.remove(entry.getKey());
}
}
@@ -251,6 +258,20 @@ protected void handleLockDeniedResponse(String lock_name, Owner owner) {
lock.lockDenied();
}
+ protected void handleCreateLockRequest(String lock_name, Owner owner, Address sender) {
+ synchronized(server_locks) {
+ server_locks.put(lock_name, new ServerLock(lock_name, owner));
+ }
+ }
+
+
+ protected void handleDeleteLockRequest(String lock_name, Address sender) {
+ synchronized(server_locks) {
+ server_locks.remove(lock_name);
+ }
+ }
+
+
protected ClientLock getLock(String name, Owner owner, boolean create_if_absent) {
synchronized(client_locks) {
Map<Owner,ClientLock> owners=client_locks.get(name);
@@ -345,11 +366,16 @@ public ServerLock(String lock_name) {
this.lock_name=lock_name;
}
+ protected ServerLock(String lock_name, Owner owner) {
+ this.lock_name=lock_name;
+ this.current_owner=owner;
+ }
+
protected synchronized void handleRequest(Request req) {
switch(req.type) {
case GRANT_LOCK:
if(current_owner == null) {
- current_owner=req.owner;
+ setOwner(req.owner);
sendLockResponse(AbstractLockService.Type.LOCK_GRANTED, req.owner, req.lock_name);
}
else {
@@ -367,10 +393,8 @@ protected synchronized void handleRequest(Request req) {
case RELEASE_LOCK:
if(current_owner == null)
break;
- if(current_owner.equals(req.owner)) {
- current_owner=null;
- notifyUnlocked(req.lock_name, req.owner);
- }
+ if(current_owner.equals(req.owner))
+ setOwner(null);
else
addToQueue(req);
break;
@@ -384,8 +408,7 @@ protected synchronized void handleRequest(Request req) {
protected synchronized void handleView(List<Address> members) {
if(current_owner != null && !members.contains(current_owner.address)) {
Owner tmp=current_owner;
- current_owner=null;
- notifyUnlocked(lock_name, tmp);
+ setOwner(null);
if(log.isDebugEnabled())
log.debug("unlocked \"" + lock_name + "\" because owner " + tmp + " left");
}
@@ -446,7 +469,7 @@ protected void processQueue() {
while(!queue.isEmpty()) {
Request req=queue.remove(0);
if(req.type == AbstractLockService.Type.GRANT_LOCK) {
- current_owner=req.owner;
+ setOwner(req.owner);
sendLockResponse(AbstractLockService.Type.LOCK_GRANTED, req.owner, req.lock_name);
break;
}
@@ -454,6 +477,20 @@ protected void processQueue() {
}
}
+ protected void setOwner(Owner owner) {
+ if(owner == null) {
+ if(current_owner != null) {
+ Owner tmp=current_owner;
+ current_owner=null;
+ notifyUnlocked(lock_name, tmp);
+ }
+ }
+ else {
+ current_owner=owner;
+ notifyLocked(lock_name, owner);
+ }
+ }
+
public boolean isEmpty() {return queue.isEmpty();}
public String toString() {
diff --git a/src/org/jgroups/blocks/locking/CentralLockService.java b/src/org/jgroups/blocks/locking/CentralLockService.java
index 02ff57cafa9..448b356f706 100644
--- a/src/org/jgroups/blocks/locking/CentralLockService.java
+++ b/src/org/jgroups/blocks/locking/CentralLockService.java
@@ -4,9 +4,12 @@
import org.jgroups.JChannel;
import org.jgroups.View;
import org.jgroups.annotations.Experimental;
+import org.jgroups.util.Util;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
/**
* Implementation of a lock service which acquires locks by contacting the coordinator.</p> Because the central
@@ -15,7 +18,7 @@
* @author Bela Ban
*/
@Experimental
-public class CentralLockService extends AbstractLockService {
+public class CentralLockService extends AbstractLockService implements LockNotification {
protected Address coord;
protected boolean is_coord;
@@ -27,10 +30,12 @@ public class CentralLockService extends AbstractLockService {
public CentralLockService() {
super();
+ addLockListener(this);
}
public CentralLockService(JChannel ch) {
super(ch);
+ addLockListener(this);
}
public Address getCoord() {
@@ -59,6 +64,14 @@ protected void sendReleaseLockRequest(String lock_name, Owner owner) {
sendRequest(coord, Type.RELEASE_LOCK, lock_name, owner, 0, false);
}
+ protected void sendCreateLockRequest(Address dest, String lock_name, Owner owner) {
+ sendRequest(dest, AbstractLockService.Type.CREATE_LOCK, lock_name, owner, 0, false);
+ }
+
+ protected void sendDeleteLockRequest(Address dest, String lock_name) {
+ sendRequest(dest, AbstractLockService.Type.DELETE_LOCK, lock_name, null, 0, false);
+ }
+
public void viewAccepted(View view) {
super.viewAccepted(view);
@@ -72,12 +85,9 @@ public void viewAccepted(View view) {
if(num_backups > 0) {
List<Address> new_joiners=null;
synchronized(backups) {
- List<Address> tmp=determineBackups(view.getMembers());
- if(!tmp.isEmpty() && !tmp.equals(backups)) {
- // copy locks to new joiners
-
+ List<Address> tmp=Util.pickNext(view.getMembers(), ch.getAddress(), num_backups);
+ if(!tmp.isEmpty() && !tmp.equals(backups))
new_joiners=determineNewJoiners();
- }
backups.clear();
backups.addAll(tmp);
}
@@ -86,20 +96,45 @@ public void viewAccepted(View view) {
}
}
+ public void lockCreated(String name) {
+ }
+ public void lockDeleted(String name) {
+ }
- protected List<Address> determineBackups(List<Address> members) {
- List<Address> retval=new ArrayList<Address>();
+ public void locked(String lock_name, Owner owner) {
+ updateBackups(Type.CREATE_LOCK, lock_name, owner);
+ }
- return retval;
+ public void unlocked(String lock_name, Owner owner) {
+ updateBackups(Type.DELETE_LOCK, lock_name, owner);
}
+ protected void updateBackups(Type type, String lock_name, Owner owner) {
+ synchronized(backups) {
+ for(Address backup: backups)
+ sendRequest(backup, type, lock_name, owner, 0, false);
+ }
+ }
+
+
+
protected List<Address> determineNewJoiners() {
return null;
}
protected void copyLocksTo(List<Address> new_joiners) {
+ Map<String,ServerLock> copy;
+ synchronized(server_locks) {
+ copy=new HashMap<String,ServerLock>(server_locks);
+ }
+
+ for(Map.Entry<String,ServerLock> entry: server_locks.entrySet()) {
+ for(Address joiner: new_joiners)
+ sendCreateLockRequest(joiner, entry.getKey(), entry.getValue().current_owner);
+ }
}
+
}
|
04dc178154d9e2cb658448efec7484c543d9d650
|
bendisposto$prob
|
added visible/invisible support for connections
|
a
|
https://github.com/hhu-stups/prob-rodinplugin
|
diff --git a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/part/BConnectionEditPart.java b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/part/BConnectionEditPart.java
index 0771f7ce..3f09133d 100644
--- a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/part/BConnectionEditPart.java
+++ b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/part/BConnectionEditPart.java
@@ -13,6 +13,7 @@
import org.eclipse.draw2d.ChopboxAnchor;
import org.eclipse.draw2d.Connection;
import org.eclipse.draw2d.ConnectionAnchor;
+import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.MidpointLocator;
@@ -21,6 +22,7 @@
import org.eclipse.draw2d.PositionConstants;
import org.eclipse.draw2d.XYAnchor;
import org.eclipse.draw2d.geometry.Point;
+import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.AccessibleAnchorProvider;
import org.eclipse.gef.ConnectionEditPart;
import org.eclipse.gef.DragTracker;
@@ -42,8 +44,11 @@
import org.eclipse.swt.widgets.Display;
import de.bmotionstudio.gef.editor.AttributeConstants;
+import de.bmotionstudio.gef.editor.BMotionStudioImage;
+import de.bmotionstudio.gef.editor.EditorImageRegistry;
import de.bmotionstudio.gef.editor.attribute.BAttributeConnectionSourceDecoration;
import de.bmotionstudio.gef.editor.command.ConnectionDeleteCommand;
+import de.bmotionstudio.gef.editor.figure.AbstractBMotionFigure;
import de.bmotionstudio.gef.editor.model.BConnection;
import de.bmotionstudio.gef.editor.model.BControl;
@@ -89,7 +94,34 @@ protected Command getDeleteCommand(GroupRequest request) {
@Override
protected IFigure createEditFigure() {
- PolylineConnection connection = new PolylineConnection();
+ PolylineConnection connection = new PolylineConnection() {
+
+ private boolean visible;
+
+ @Override
+ public void paint(Graphics g) {
+ if (!visible && !isRunning()) {
+ Rectangle clientArea = getClientArea();
+ g.drawImage(
+ BMotionStudioImage
+ .getImage(EditorImageRegistry.IMG_ICON_CONTROL_HIDDEN),
+ clientArea.x, clientArea.y);
+ g.setAlpha(AbstractBMotionFigure.HIDDEN_ALPHA_VALUE);
+ }
+ super.paint(g);
+ }
+
+ @Override
+ public void setVisible(boolean visible) {
+ if (!isRunning()) {
+ this.visible = visible;
+ repaint();
+ } else {
+ super.setVisible(visible);
+ }
+ }
+
+ };
conLabel = new Label();
MidpointLocator locator = new MidpointLocator(connection, 0);
locator.setRelativePosition(PositionConstants.NORTH);
diff --git a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/part/SwitchPart.java b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/part/SwitchPart.java
index cb28c211..61ee4e3d 100644
--- a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/part/SwitchPart.java
+++ b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/part/SwitchPart.java
@@ -34,11 +34,10 @@ public void refreshEditFigure(IFigure figure, BControl model,
Object value = evt.getNewValue();
String aID = evt.getPropertyName();
-
+ Switch sw = (Switch) model;
+
if (aID.equals(AttributeConstants.ATTRIBUTE_SWITCH_POSITION)) {
- Switch sw = (Switch) model;
-
Track track1 = sw.getTrack1();
Track track2 = sw.getTrack2();
@@ -64,9 +63,14 @@ public void refreshEditFigure(IFigure figure, BControl model,
if (aID.equals(AttributeConstants.ATTRIBUTE_SWITCH_DIRECTION))
refreshEditLayout(figure, model);
- if (aID.equals(AttributeConstants.ATTRIBUTE_VISIBLE))
- ((SwitchFigure) figure)
- .setVisible(Boolean.valueOf(value.toString()));
+ if (aID.equals(AttributeConstants.ATTRIBUTE_VISIBLE)) {
+ Boolean visible = Boolean.valueOf(value.toString());
+ ((SwitchFigure) figure).setVisible(visible);
+ sw.getTrack1().setAttributeValue(
+ AttributeConstants.ATTRIBUTE_VISIBLE, visible);
+ sw.getTrack2().setAttributeValue(
+ AttributeConstants.ATTRIBUTE_VISIBLE, visible);
+ }
}
|
b784b84322f3113e43fe4cade915d18f74a85132
|
tapiji
|
Adapts the namespace of all TapiJI plug-ins to org.eclipselabs.tapiji.*.
|
p
|
https://github.com/tapiji/tapiji
|
diff --git a/at.ac.tuwien.inso.eclpise.i18n.feature/.project b/at.ac.tuwien.inso.eclpise.i18n.feature/.project
index 492ae3b9..2f00ea08 100644
--- a/at.ac.tuwien.inso.eclpise.i18n.feature/.project
+++ b/at.ac.tuwien.inso.eclpise.i18n.feature/.project
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
- <name>at.ac.tuwien.inso.eclpise.i18n.feature</name>
+ <name>org.eclipselabs.tapiji.tools.feature</name>
<comment></comment>
<projects>
</projects>
diff --git a/at.ac.tuwien.inso.eclpise.i18n.feature/feature.xml b/at.ac.tuwien.inso.eclpise.i18n.feature/feature.xml
index df57a461..13e86664 100644
--- a/at.ac.tuwien.inso.eclpise.i18n.feature/feature.xml
+++ b/at.ac.tuwien.inso.eclpise.i18n.feature/feature.xml
@@ -1,10 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<feature
- id="at.ac.tuwien.inso.eclpise.i18n.feature"
+ id="org.eclipselabs.tapiji.tools.feature"
label="Internationalization Feature"
version="0.0.1.qualifier"
provider-name="Vienna University of Technology"
- plugin="at.ac.tuwien.inso.eclipse.i18n"
+ plugin="org.eclipselabs.tapiji.tools.feature"
os="linux,macosx,win32">
<description url="http://code.google.com/a/eclipselabs.org/p/tapiji/">
@@ -21,18 +21,15 @@ task and introduces additional complexity into development.
</copyright>
<license url="http://www.eclipse.org/legal/epl-v10.html">
- *Eclipse Public License - v 1.0*
+ Eclipse Public License - v 1.0
-THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
-PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF
-THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
+THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
-*1. DEFINITIONS*
+1. DEFINITIONS
"Contribution" means:
-a) in the case of the initial Contributor, the initial code and
-documentation distributed under this Agreement, and
+a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and
b) in the case of each subsequent Contributor:
@@ -40,88 +37,41 @@ i) changes to the Program, and
ii) additions to the Program;
-where such changes and/or additions to the Program originate from and
-are distributed by that particular Contributor. A Contribution
-'originates' from a Contributor if it was added to the Program by such
-Contributor itself or anyone acting on such Contributor's behalf.
-Contributions do not include additions to the Program which: (i) are
-separate modules of software distributed in conjunction with the Program
-under their own license agreement, and (ii) are not derivative works of
-the Program.
+where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program.
"Contributor" means any person or entity that distributes the Program.
-"Licensed Patents" mean patent claims licensable by a Contributor which
-are necessarily infringed by the use or sale of its Contribution alone
-or when combined with the Program.
-
-"Program" means the Contributions distributed in accordance with this
-Agreement.
-
-"Recipient" means anyone who receives the Program under this Agreement,
-including all Contributors.
-
-*2. GRANT OF RIGHTS*
-
-a) Subject to the terms of this Agreement, each Contributor hereby
-grants Recipient a non-exclusive, worldwide, royalty-free copyright
-license to reproduce, prepare derivative works of, publicly display,
-publicly perform, distribute and sublicense the Contribution of such
-Contributor, if any, and such derivative works, in source code and
-object code form.
-
-b) Subject to the terms of this Agreement, each Contributor hereby
-grants Recipient a non-exclusive, worldwide, royalty-free patent license
-under Licensed Patents to make, use, sell, offer to sell, import and
-otherwise transfer the Contribution of such Contributor, if any, in
-source code and object code form. This patent license shall apply to the
-combination of the Contribution and the Program if, at the time the
-Contribution is added by the Contributor, such addition of the
-Contribution causes such combination to be covered by the Licensed
-Patents. The patent license shall not apply to any other combinations
-which include the Contribution. No hardware per se is licensed hereunder.
-
-c) Recipient understands that although each Contributor grants the
-licenses to its Contributions set forth herein, no assurances are
-provided by any Contributor that the Program does not infringe the
-patent or other intellectual property rights of any other entity. Each
-Contributor disclaims any liability to Recipient for claims brought by
-any other entity based on infringement of intellectual property rights
-or otherwise. As a condition to exercising the rights and licenses
-granted hereunder, each Recipient hereby assumes sole responsibility to
-secure any other intellectual property rights needed, if any. For
-example, if a third party patent license is required to allow Recipient
-to distribute the Program, it is Recipient's responsibility to acquire
-that license before distributing the Program.
-
-d) Each Contributor represents that to its knowledge it has sufficient
-copyright rights in its Contribution, if any, to grant the copyright
-license set forth in this Agreement.
-
-*3. REQUIREMENTS*
-
-A Contributor may choose to distribute the Program in object code form
-under its own license agreement, provided that:
+"Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.
+
+"Program" means the Contributions distributed in accordance with this Agreement.
+
+"Recipient" means anyone who receives the Program under this Agreement, including all Contributors.
+
+2. GRANT OF RIGHTS
+
+a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form.
+
+b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
+
+c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program.
+
+d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement.
+
+3. REQUIREMENTS
+
+A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:
a) it complies with the terms and conditions of this Agreement; and
b) its license agreement:
-i) effectively disclaims on behalf of all Contributors all warranties
-and conditions, express and implied, including warranties or conditions
-of title and non-infringement, and implied warranties or conditions of
-merchantability and fitness for a particular purpose;
+i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
-ii) effectively excludes on behalf of all Contributors all liability for
-damages, including direct, indirect, special, incidental and
-consequential damages, such as lost profits;
+ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;
-iii) states that any provisions which differ from this Agreement are
-offered by that Contributor alone and not by any other party; and
+iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and
-iv) states that source code for the Program is available from such
-Contributor, and informs licensees how to obtain it in a reasonable
-manner on or through a medium customarily used for software exchange.
+iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange.
When the Program is made available in source code form:
@@ -129,120 +79,35 @@ a) it must be made available under this Agreement; and
b) a copy of this Agreement must be included with each copy of the Program.
-Contributors may not remove or alter any copyright notices contained
-within the Program.
-
-Each Contributor must identify itself as the originator of its
-Contribution, if any, in a manner that reasonably allows subsequent
-Recipients to identify the originator of the Contribution.
-
-*4. COMMERCIAL DISTRIBUTION*
-
-Commercial distributors of software may accept certain responsibilities
-with respect to end users, business partners and the like. While this
-license is intended to facilitate the commercial use of the Program, the
-Contributor who includes the Program in a commercial product offering
-should do so in a manner which does not create potential liability for
-other Contributors. Therefore, if a Contributor includes the Program in
-a commercial product offering, such Contributor ("Commercial
-Contributor") hereby agrees to defend and indemnify every other
-Contributor ("Indemnified Contributor") against any losses, damages and
-costs (collectively "Losses") arising from claims, lawsuits and other
-legal actions brought by a third party against the Indemnified
-Contributor to the extent caused by the acts or omissions of such
-Commercial Contributor in connection with its distribution of the
-Program in a commercial product offering. The obligations in this
-section do not apply to any claims or Losses relating to any actual or
-alleged intellectual property infringement. In order to qualify, an
-Indemnified Contributor must: a) promptly notify the Commercial
-Contributor in writing of such claim, and b) allow the Commercial
-Contributor to control, and cooperate with the Commercial Contributor
-in, the defense and any related settlement negotiations. The Indemnified
-Contributor may participate in any such claim at its own expense.
-
-For example, a Contributor might include the Program in a commercial
-product offering, Product X. That Contributor is then a Commercial
-Contributor. If that Commercial Contributor then makes performance
-claims, or offers warranties related to Product X, those performance
-claims and warranties are such Commercial Contributor's responsibility
-alone. Under this section, the Commercial Contributor would have to
-defend claims against the other Contributors related to those
-performance claims and warranties, and if a court requires any other
-Contributor to pay any damages as a result, the Commercial Contributor
-must pay those damages.
-
-*5. NO WARRANTY*
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED
-ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
-EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES
-OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR
-A PARTICULAR PURPOSE. Each Recipient is solely responsible for
-determining the appropriateness of using and distributing the Program
-and assumes all risks associated with its exercise of rights under this
-Agreement , including but not limited to the risks and costs of program
-errors, compliance with applicable laws, damage to or loss of data,
-programs or equipment, and unavailability or interruption of operations.
-
-*6. DISCLAIMER OF LIABILITY*
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR
-ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT,
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING
-WITHOUT LIMITATION LOST PROFITS), 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 OR
-DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
-HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-
-*7. GENERAL*
-
-If any provision of this Agreement is invalid or unenforceable under
-applicable law, it shall not affect the validity or enforceability of
-the remainder of the terms of this Agreement, and without further action
-by the parties hereto, such provision shall be reformed to the minimum
-extent necessary to make such provision valid and enforceable.
-
-If Recipient institutes patent litigation against any entity (including
-a cross-claim or counterclaim in a lawsuit) alleging that the Program
-itself (excluding combinations of the Program with other software or
-hardware) infringes such Recipient's patent(s), then such Recipient's
-rights granted under Section 2(b) shall terminate as of the date such
-litigation is filed.
-
-All Recipient's rights under this Agreement shall terminate if it fails
-to comply with any of the material terms or conditions of this Agreement
-and does not cure such failure in a reasonable period of time after
-becoming aware of such noncompliance. If all Recipient's rights under
-this Agreement terminate, Recipient agrees to cease use and distribution
-of the Program as soon as reasonably practicable. However, Recipient's
-obligations under this Agreement and any licenses granted by Recipient
-relating to the Program shall continue and survive.
-
-Everyone is permitted to copy and distribute copies of this Agreement,
-but in order to avoid inconsistency the Agreement is copyrighted and may
-only be modified in the following manner. The Agreement Steward reserves
-the right to publish new versions (including revisions) of this
-Agreement from time to time. No one other than the Agreement Steward has
-the right to modify this Agreement. The Eclipse Foundation is the
-initial Agreement Steward. The Eclipse Foundation may assign the
-responsibility to serve as the Agreement Steward to a suitable separate
-entity. Each new version of the Agreement will be given a distinguishing
-version number. The Program (including Contributions) may always be
-distributed subject to the version of the Agreement under which it was
-received. In addition, after a new version of the Agreement is
-published, Contributor may elect to distribute the Program (including
-its Contributions) under the new version. Except as expressly stated in
-Sections 2(a) and 2(b) above, Recipient receives no rights or licenses
-to the intellectual property of any Contributor under this Agreement,
-whether expressly, by implication, estoppel or otherwise. All rights in
-the Program not expressly granted under this Agreement are reserved.
-
-This Agreement is governed by the laws of the State of New York and the
-intellectual property laws of the United States of America. No party to
-this Agreement will bring a legal action under this Agreement more than
-one year after the cause of action arose. Each party waives its rights
-to a jury trial in any resulting litigation.
+Contributors may not remove or alter any copyright notices contained within the Program.
+
+Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution.
+
+4. COMMERCIAL DISTRIBUTION
+
+Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.
+
+For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.
+
+5. NO WARRANTY
+
+EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.
+
+6. DISCLAIMER OF LIABILITY
+
+EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), 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 OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+7. GENERAL
+
+If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
+
+If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed.
+
+All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.
+
+Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.
+
+This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation.
</license>
<requires>
@@ -269,30 +134,30 @@ to a jury trial in any resulting litigation.
</requires>
<plugin
- id="at.ac.tuwien.inso.eclipse.i18n"
+ id="com.essiembre.eclipse.i18n.resourcebundle"
download-size="0"
install-size="0"
- version="0.0.1.qualifier"
- unpack="false"/>
+ version="0.7.7"/>
<plugin
- id="at.ac.tuwien.inso.eclipse.i18n.java"
+ id="org.eclipselabs.tapiji.tools.core"
download-size="0"
install-size="0"
- version="0.0.1.qualifier"
+ version="0.0.0"
unpack="false"/>
<plugin
- id="at.ac.tuwien.inso.eclipse.rbe"
+ id="org.eclipselabs.tapiji.tools.java"
download-size="0"
install-size="0"
- version="0.0.1.qualifier"
+ version="0.0.0"
unpack="false"/>
<plugin
- id="com.essiembre.eclipse.i18n.resourcebundle"
+ id="org.eclipselabs.tapiji.translator.rbe"
download-size="0"
install-size="0"
- version="0.7.7"/>
+ version="0.0.0"
+ unpack="false"/>
</feature>
|
c095c8f95cadbd5fac7952da6aaa4c13aae1274e
|
drools
|
refactor GAV to ReleaseId--
|
p
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/main/java/org/drools/cdi/KieCDIExtension.java b/drools-compiler/src/main/java/org/drools/cdi/KieCDIExtension.java
index bfac3dd44d2..f6c4df153f6 100644
--- a/drools-compiler/src/main/java/org/drools/cdi/KieCDIExtension.java
+++ b/drools-compiler/src/main/java/org/drools/cdi/KieCDIExtension.java
@@ -3,7 +3,7 @@
import org.drools.kproject.models.KieSessionModelImpl;
import org.kie.KieBase;
import org.kie.KieServices;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieBaseModel;
import org.kie.builder.KieSessionModel;
import org.kie.builder.KieSessionModel.KieSessionType;
@@ -11,7 +11,7 @@
import org.kie.builder.impl.KieContainerImpl;
import org.kie.builder.impl.KieProject;
import org.kie.cdi.KBase;
-import org.kie.cdi.KGAV;
+import org.kie.cdi.KReleaseId;
import org.kie.cdi.KSession;
import org.kie.runtime.KieContainer;
import org.kie.runtime.KieSession;
@@ -52,7 +52,7 @@ public class KieCDIExtension
private Map<KieCDIEntry, KieCDIEntry> kBaseNames;
private Map<KieCDIEntry, KieCDIEntry> kSessionNames;
- private Map<GAV, KieContainer> gavs;
+ private Map<ReleaseId, KieContainer> gavs;
private Map<String, KieCDIEntry> named;
@@ -67,7 +67,7 @@ public KieCDIExtension() { }
public void init() {
KieServices ks = KieServices.Factory.get();
- gavs = new HashMap<GAV, KieContainer>();
+ gavs = new HashMap<ReleaseId, KieContainer>();
classpathKContainer = (KieContainerImpl) ks.getKieClasspathContainer(); //new KieContainerImpl( kProject, null );
named = new HashMap<String, KieCDIExtension.KieCDIEntry>();
}
@@ -89,13 +89,13 @@ public <Object> void processInjectionTarget(@Observes ProcessInjectionTarget<Obj
continue;
}
- KGAV kGAV = ip.getAnnotated().getAnnotation( KGAV.class );
- GAV gav = null;
- if ( kGAV != null ) {
- gav = ks.newGav( kGAV.groupId(),
- kGAV.artifactId(),
- kGAV.version() );
- gavs.put( gav,
+ KReleaseId KReleaseId = ip.getAnnotated().getAnnotation( KReleaseId.class );
+ ReleaseId releaseId = null;
+ if ( KReleaseId != null ) {
+ releaseId = ks.newReleaseId(KReleaseId.groupId(),
+ KReleaseId.artifactId(),
+ KReleaseId.version());
+ gavs.put(releaseId,
null );
}
@@ -108,22 +108,22 @@ public <Object> void processInjectionTarget(@Observes ProcessInjectionTarget<Obj
Class< ? extends Annotation> scope = ApplicationScoped.class;
if ( kBase != null ) {
- addKBaseInjectionPoint(ip, kBase, namedStr, scope, gav);
+ addKBaseInjectionPoint(ip, kBase, namedStr, scope, releaseId);
} else if ( kSession != null ) {
- addKSessionInjectionPoint(ip, kSession, namedStr, scope, gav);
+ addKSessionInjectionPoint(ip, kSession, namedStr, scope, releaseId);
}
}
}
}
- public void addKBaseInjectionPoint(InjectionPoint ip, KBase kBase, String namedStr, Class< ? extends Annotation> scope, GAV gav) {
+ public void addKBaseInjectionPoint(InjectionPoint ip, KBase kBase, String namedStr, Class< ? extends Annotation> scope, ReleaseId releaseId) {
if ( kBaseNames == null ) {
kBaseNames = new HashMap<KieCDIEntry, KieCDIEntry>();
}
KieCDIEntry newEntry = new KieCDIEntry( kBase.value(),
scope,
- gav,
+ releaseId,
namedStr );
KieCDIEntry existingEntry = kBaseNames.remove( newEntry );
@@ -154,14 +154,14 @@ public void addKBaseInjectionPoint(InjectionPoint ip, KBase kBase, String namedS
}
}
- public void addKSessionInjectionPoint(InjectionPoint ip, KSession kSession, String namedStr, Class< ? extends Annotation> scope, GAV gav) {
+ public void addKSessionInjectionPoint(InjectionPoint ip, KSession kSession, String namedStr, Class< ? extends Annotation> scope, ReleaseId releaseId) {
if ( kSessionNames == null ) {
kSessionNames = new HashMap<KieCDIEntry, KieCDIEntry>();
}
KieCDIEntry newEntry = new KieCDIEntry( kSession.value(),
scope,
- gav,
+ releaseId,
namedStr );
KieCDIEntry existingEntry = kSessionNames.remove( newEntry );
@@ -200,16 +200,16 @@ public void afterBeanDiscovery(@Observes AfterBeanDiscovery abd,
// to array, so we don't mutate that which we are iterating over
if ( !gavs.isEmpty() ) {
- for ( GAV gav : gavs.keySet().toArray( new GAV[gavs.size()] ) ) {
- KieContainer kContainer = ks.newKieContainer(gav);
+ for ( ReleaseId releaseId : gavs.keySet().toArray( new ReleaseId[gavs.size()] ) ) {
+ KieContainer kContainer = ks.newKieContainer(releaseId);
if ( kContainer == null ) {
- log.error( "Unable to retrieve KieContainer for GAV {}",
- gav.toString() );
+ log.error( "Unable to retrieve KieContainer for ReleaseId {}",
+ releaseId.toString() );
} else {
- log.debug( "KieContainer retrieved for GAV {}",
- gav.toString() );
+ log.debug( "KieContainer retrieved for ReleaseId {}",
+ releaseId.toString() );
}
- gavs.put( gav,
+ gavs.put(releaseId,
kContainer );
}
}
@@ -234,14 +234,14 @@ public void afterBeanDiscovery(@Observes AfterBeanDiscovery abd,
public void addKBaseBean(AfterBeanDiscovery abd,
KieCDIEntry entry) {
- GAV gav = entry.getkGAV();
+ ReleaseId releaseId = entry.getkGAV();
KieContainerImpl kieContainer = classpathKContainer; // default to classpath, but allow it to be overriden
- if ( gav != null ) {
- kieContainer = (KieContainerImpl) gavs.get( gav );
+ if ( releaseId != null ) {
+ kieContainer = (KieContainerImpl) gavs.get(releaseId);
if ( kieContainer == null ) {
- log.error( "Unable to create KBase({}), could not retrieve KieContainer for GAV {}",
+ log.error( "Unable to create KBase({}), could not retrieve KieContainer for ReleaseId {}",
entry.getKieTypeName(),
- gav.toString() );
+ releaseId.toString() );
return;
}
}
@@ -282,14 +282,14 @@ public void addKBaseBean(AfterBeanDiscovery abd,
public void addKSessionBean(AfterBeanDiscovery abd,
KieCDIEntry entry) {
- GAV gav = entry.getkGAV();
+ ReleaseId releaseId = entry.getkGAV();
KieContainerImpl kieContainer = classpathKContainer; // default to classpath, but allow it to be overriden
- if ( gav != null ) {
- kieContainer = (KieContainerImpl) gavs.get( gav );
+ if ( releaseId != null ) {
+ kieContainer = (KieContainerImpl) gavs.get(releaseId);
if ( kieContainer == null ) {
- log.error( "Unable to create KSession({}), could not retrieve KieContainer for GAV {}",
+ log.error( "Unable to create KSession({}), could not retrieve KieContainer for ReleaseId {}",
entry.getKieTypeName(),
- gav.toString() );
+ releaseId.toString() );
return;
}
}
@@ -397,13 +397,13 @@ public String toString() {
}
} );
}
- if ( kContainer.getGAV() != null ) {
- final String groupId = kContainer.getGAV().getGroupId();
- final String artifactId = kContainer.getGAV().getArtifactId();
- final String version = kContainer.getGAV().getVersion();
- set.add( new KGAV() {
+ if ( kContainer.getReleaseId() != null ) {
+ final String groupId = kContainer.getReleaseId().getGroupId();
+ final String artifactId = kContainer.getReleaseId().getArtifactId();
+ final String version = kContainer.getReleaseId().getVersion();
+ set.add( new KReleaseId() {
public Class< ? extends Annotation> annotationType() {
- return KGAV.class;
+ return KReleaseId.class;
}
public String groupId() {
@@ -419,7 +419,7 @@ public String version() {
}
public String toString() {
- return "KGAV[groupId=" + groupId + " artifactId" + artifactId + " version=" + version + "]";
+ return "KReleaseId[groupId=" + groupId + " artifactId" + artifactId + " version=" + version + "]";
}
} );
}
@@ -536,13 +536,13 @@ public String toString() {
}
} );
}
- if ( kContainer.getGAV() != null ) {
- final String groupId = kContainer.getGAV().getGroupId();
- final String artifactId = kContainer.getGAV().getArtifactId();
- final String version = kContainer.getGAV().getVersion();
- set.add( new KGAV() {
+ if ( kContainer.getReleaseId() != null ) {
+ final String groupId = kContainer.getReleaseId().getGroupId();
+ final String artifactId = kContainer.getReleaseId().getArtifactId();
+ final String version = kContainer.getReleaseId().getVersion();
+ set.add( new KReleaseId() {
public Class< ? extends Annotation> annotationType() {
- return KGAV.class;
+ return KReleaseId.class;
}
@Override
@@ -561,7 +561,7 @@ public String version() {
}
public String toString() {
- return "KGAV[groupId=" + groupId + " artifactId" + artifactId + " version=" + version + "]";
+ return "KReleaseId[groupId=" + groupId + " artifactId" + artifactId + " version=" + version + "]";
}
} );
}
@@ -670,13 +670,13 @@ public String toString() {
}
} );
}
- if ( kContainer.getGAV() != null ) {
- final String groupId = kContainer.getGAV().getGroupId();
- final String artifactId = kContainer.getGAV().getArtifactId();
- final String version = kContainer.getGAV().getVersion();
- set.add( new KGAV() {
+ if ( kContainer.getReleaseId() != null ) {
+ final String groupId = kContainer.getReleaseId().getGroupId();
+ final String artifactId = kContainer.getReleaseId().getArtifactId();
+ final String version = kContainer.getReleaseId().getVersion();
+ set.add( new KReleaseId() {
public Class< ? extends Annotation> annotationType() {
- return KGAV.class;
+ return KReleaseId.class;
}
@Override
@@ -695,7 +695,7 @@ public String version() {
}
public String toString() {
- return "KGAV[groupId=" + groupId + " artifactId" + artifactId + " version=" + version + "]";
+ return "KReleaseId[groupId=" + groupId + " artifactId" + artifactId + " version=" + version + "]";
}
} );
}
@@ -752,18 +752,18 @@ public boolean isNullable() {
public static class KieCDIEntry {
private String kieTypeName;
private Class< ? extends Annotation> scope;
- private GAV kGav;
+ private ReleaseId kReleaseId;
private String named;
private Set<InjectionPoint> injectionPoints;
public KieCDIEntry(String kieTypeName,
Class< ? extends Annotation> scope,
- GAV gav,
+ ReleaseId releaseId,
String named) {
super();
this.kieTypeName = kieTypeName;
this.scope = scope;
- this.kGav = gav;
+ this.kReleaseId = releaseId;
this.named = named;
this.injectionPoints = new HashSet<InjectionPoint>();
}
@@ -797,12 +797,12 @@ public void setScope(Class< ? extends Annotation> scope) {
return scope;
}
- public GAV getkGAV() {
- return kGav;
+ public ReleaseId getkGAV() {
+ return kReleaseId;
}
- public void setkGAV(GAV kGav) {
- this.kGav = kGav;
+ public void setkGAV(ReleaseId kReleaseId) {
+ this.kReleaseId = kReleaseId;
}
/**
@@ -833,7 +833,7 @@ public void setInjectionPoints(Set<InjectionPoint> injectionPoints) {
public int hashCode() {
final int prime = 31;
int result = 1;
- result = prime * result + ((kGav == null) ? 0 : kGav.hashCode());
+ result = prime * result + ((kReleaseId == null) ? 0 : kReleaseId.hashCode());
result = prime * result + ((kieTypeName == null) ? 0 : kieTypeName.hashCode());
result = prime * result + ((named == null) ? 0 : named.hashCode());
result = prime * result + ((scope == null) ? 0 : scope.hashCode());
@@ -846,9 +846,9 @@ public boolean equals(java.lang.Object obj) {
if ( obj == null ) return false;
if ( getClass() != obj.getClass() ) return false;
KieCDIEntry other = (KieCDIEntry) obj;
- if ( kGav == null ) {
- if ( other.kGav != null ) return false;
- } else if ( !kGav.equals( other.kGav ) ) return false;
+ if ( kReleaseId == null ) {
+ if ( other.kReleaseId != null ) return false;
+ } else if ( !kReleaseId.equals( other.kReleaseId) ) return false;
if ( kieTypeName == null ) {
if ( other.kieTypeName != null ) return false;
} else if ( !kieTypeName.equals( other.kieTypeName ) ) return false;
@@ -863,7 +863,7 @@ public boolean equals(java.lang.Object obj) {
@Override
public String toString() {
- return "KieCDIEntry [kieTypeName=" + kieTypeName + ", scope=" + scope + ", kGav=" + kGav + ", named=" + named + "]";
+ return "KieCDIEntry [kieTypeName=" + kieTypeName + ", scope=" + scope + ", kReleaseId=" + kReleaseId + ", named=" + named + "]";
}
}
diff --git a/drools-compiler/src/main/java/org/drools/kproject/GAVImpl.java b/drools-compiler/src/main/java/org/drools/kproject/ReleaseIdImpl.java
similarity index 82%
rename from drools-compiler/src/main/java/org/drools/kproject/GAVImpl.java
rename to drools-compiler/src/main/java/org/drools/kproject/ReleaseIdImpl.java
index 8ee485e90e0..b60516c089d 100644
--- a/drools-compiler/src/main/java/org/drools/kproject/GAVImpl.java
+++ b/drools-compiler/src/main/java/org/drools/kproject/ReleaseIdImpl.java
@@ -2,20 +2,19 @@
import java.io.IOException;
import java.io.StringReader;
-import java.nio.charset.MalformedInputException;
import java.util.Properties;
import org.drools.core.util.StringUtils;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
-public class GAVImpl implements GAV {
+public class ReleaseIdImpl implements ReleaseId {
private final String groupId;
private final String artifactId;
private final String version;
- public GAVImpl(String groupId,
- String artifactId,
- String version) {
+ public ReleaseIdImpl(String groupId,
+ String artifactId,
+ String version) {
this.groupId = groupId;
this.artifactId = artifactId;
this.version = version;
@@ -50,23 +49,23 @@ public String getPomPropertiesPath() {
return "META-INF/maven/" + groupId + "/" + artifactId + "/pom.properties";
}
- public static GAV fromPropertiesString(String string) {
+ public static ReleaseId fromPropertiesString(String string) {
Properties props = new Properties();
- GAV gav = null;
+ ReleaseId releaseId = null;
try {
props.load( new StringReader( string ) );
String groupId = props.getProperty( "groupId" );
String artifactId = props.getProperty( "artifactId" );
String version = props.getProperty( "version" );
if ( StringUtils.isEmpty( groupId ) || StringUtils.isEmpty( artifactId ) || StringUtils.isEmpty( version ) ) {
- throw new RuntimeException("pom.properties exists but GAV content is malformed\n" + string);
+ throw new RuntimeException("pom.properties exists but ReleaseId content is malformed\n" + string);
}
- gav = new GAVImpl( groupId, artifactId, version );
+ releaseId = new ReleaseIdImpl( groupId, artifactId, version );
} catch ( IOException e ) {
throw new RuntimeException( "pom.properties was malformed\n" + string, e );
}
- return gav;
+ return releaseId;
}
@Override
@@ -74,7 +73,7 @@ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
- GAVImpl that = (GAVImpl) o;
+ ReleaseIdImpl that = (ReleaseIdImpl) o;
if (artifactId != null ? !artifactId.equals(that.artifactId) : that.artifactId != null) return false;
if (groupId != null ? !groupId.equals(that.groupId) : that.groupId != null) return false;
diff --git a/drools-compiler/src/main/java/org/kie/builder/impl/AbstractKieModule.java b/drools-compiler/src/main/java/org/kie/builder/impl/AbstractKieModule.java
index e02b3bf46ce..277cdb8d86b 100644
--- a/drools-compiler/src/main/java/org/kie/builder/impl/AbstractKieModule.java
+++ b/drools-compiler/src/main/java/org/kie/builder/impl/AbstractKieModule.java
@@ -8,7 +8,7 @@
import org.kie.KieBaseConfiguration;
import org.kie.KnowledgeBaseFactory;
import org.kie.builder.CompositeKnowledgeBuilder;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieBaseModel;
import org.kie.builder.KieModuleModel;
import org.kie.builder.KnowledgeBuilder;
@@ -45,15 +45,15 @@ public abstract class AbstractKieModule
private final Map<String, Results> resultsCache = new HashMap<String, Results>();
- protected final GAV gav;
+ protected final ReleaseId releaseId;
private final KieModuleModel kModuleModel;
- private Map<GAV, InternalKieModule> dependencies;
+ private Map<ReleaseId, InternalKieModule> dependencies;
- public AbstractKieModule(GAV gav, KieModuleModel kModuleModel) {
- this.gav = gav;
+ public AbstractKieModule(ReleaseId releaseId, KieModuleModel kModuleModel) {
+ this.releaseId = releaseId;
this.kModuleModel = kModuleModel;
}
@@ -63,14 +63,14 @@ public KieModuleModel getKieModuleModel() {
// public void index() {
// if ( kieModules == null ) {
-// kieModules = new HashMap<GAV, InternalKieModule>();
+// kieModules = new HashMap<ReleaseId, InternalKieModule>();
// kieModules.putAll( dependencies );
-// kieModules.put( gav, this );
+// kieModules.put( releaseId, this );
// indexParts( kieModules, kBaseModels, kSessionModels, kJarFromKBaseName );
// }
// }
//
-// public Map<GAV, InternalKieModule> getKieModules() {
+// public Map<ReleaseId, InternalKieModule> getKieModules() {
// if ( kieModules == null ) {
// index();
// }
@@ -79,9 +79,9 @@ public KieModuleModel getKieModuleModel() {
// public void verify(Messages messages) {
// if ( kieModules == null ) {
-// kieModules = new HashMap<GAV, InternalKieModule>();
+// kieModules = new HashMap<ReleaseId, InternalKieModule>();
// kieModules.putAll( dependencies );
-// kieModules.put( gav, this );
+// kieModules.put( releaseId, this );
// indexParts( kieModules, kBaseModels, kSessionModels, kJarFromKBaseName );
//
// for ( KieBaseModel model : kBaseModels.values() ) {
@@ -90,19 +90,19 @@ public KieModuleModel getKieModuleModel() {
// }
// }
- public Map<GAV, InternalKieModule> getDependencies() {
- return dependencies == null ? Collections.<GAV, InternalKieModule>emptyMap() : dependencies;
+ public Map<ReleaseId, InternalKieModule> getDependencies() {
+ return dependencies == null ? Collections.<ReleaseId, InternalKieModule>emptyMap() : dependencies;
}
public void addDependency(InternalKieModule dependency) {
if (dependencies == null) {
- dependencies = new HashMap<GAV, InternalKieModule>();
+ dependencies = new HashMap<ReleaseId, InternalKieModule>();
}
- dependencies.put(dependency.getGAV(), dependency);
+ dependencies.put(dependency.getReleaseId(), dependency);
}
- public GAV getGAV() {
- return gav;
+ public ReleaseId getReleaseId() {
+ return releaseId;
}
public Map<String, Collection<KnowledgePackage>> getKnowledgePackageCache() {
@@ -175,7 +175,7 @@ public static KieBase createKieBase(KieBaseModelImpl kBaseModel,
InternalKieModule kModule = indexedParts.getKieModuleForKBase( kBaseModel.getName() );
- Collection<KnowledgePackage> pkgs = kModule.getKnowledgePackageCache().get( kBaseModel.getName() );
+ Collection<KnowledgePackage> pkgs = kModule.getKnowledgePackageCache().get(kBaseModel.getName());
if ( pkgs == null ) {
KnowledgeBuilder kbuilder = buildKnowledgePackages(kBaseModel, indexedParts, messages);
diff --git a/drools-compiler/src/main/java/org/kie/builder/impl/AbstractKieProject.java b/drools-compiler/src/main/java/org/kie/builder/impl/AbstractKieProject.java
index 5678b40f357..cc5958803d5 100644
--- a/drools-compiler/src/main/java/org/kie/builder/impl/AbstractKieProject.java
+++ b/drools-compiler/src/main/java/org/kie/builder/impl/AbstractKieProject.java
@@ -2,7 +2,7 @@
import org.drools.kproject.models.KieBaseModelImpl;
import org.drools.kproject.models.KieSessionModelImpl;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieBaseModel;
import org.kie.builder.KieModuleModel;
import org.kie.builder.KieSessionModel;
@@ -34,9 +34,9 @@ public ResultsImpl verify() {
public void verify(ResultsImpl messages) {
for ( KieBaseModel model : kBaseModels.values() ) {
- AbstractKieModule.buildKnowledgePackages( (KieBaseModelImpl) model,
- this,
- messages );
+ AbstractKieModule.buildKnowledgePackages((KieBaseModelImpl) model,
+ this,
+ messages);
}
}
@@ -60,7 +60,7 @@ public KieSessionModel getKieSessionModel(String kSessionName) {
return kSessionModels.get( kSessionName );
}
- protected void indexParts(Map<GAV, InternalKieModule> kieModules,
+ protected void indexParts(Map<ReleaseId, InternalKieModule> kieModules,
Map<String, InternalKieModule> kJarFromKBaseName) {
for ( InternalKieModule kJar : kieModules.values() ) {
KieModuleModel kieProject = kJar.getKieModuleModel();
diff --git a/drools-compiler/src/main/java/org/kie/builder/impl/ClasspathKieProject.java b/drools-compiler/src/main/java/org/kie/builder/impl/ClasspathKieProject.java
index f626d905742..24ded685d19 100644
--- a/drools-compiler/src/main/java/org/kie/builder/impl/ClasspathKieProject.java
+++ b/drools-compiler/src/main/java/org/kie/builder/impl/ClasspathKieProject.java
@@ -1,12 +1,12 @@
package org.kie.builder.impl;
import org.drools.core.util.StringUtils;
-import org.drools.kproject.GAVImpl;
+import org.drools.kproject.ReleaseIdImpl;
import org.drools.kproject.models.KieModuleModelImpl;
import org.drools.xml.MinimalPomParser;
import org.drools.xml.PomModel;
import org.kie.KieServices;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieModuleModel;
import org.kie.builder.KieRepository;
import org.kie.internal.utils.ClassLoaderUtil;
@@ -38,7 +38,7 @@ public class ClasspathKieProject extends AbstractKieProject {
private static final Logger log = LoggerFactory.getLogger( ClasspathKieProject.class );
- private Map<GAV, InternalKieModule> kieModules = new HashMap<GAV, InternalKieModule>();
+ private Map<ReleaseId, InternalKieModule> kieModules = new HashMap<ReleaseId, InternalKieModule>();
private Map<String, InternalKieModule> kJarFromKBaseName = new HashMap<String, InternalKieModule>();
@@ -60,7 +60,7 @@ public void init() {
indexParts(kieModules, kJarFromKBaseName);
}
- public GAV getGAV() {
+ public ReleaseId getGAV() {
return null;
}
@@ -82,10 +82,10 @@ public void discoverKieModules() {
String fixedURL = fixURLFromKProjectPath( url );
InternalKieModule kModule = fetchKModule(url, fixedURL);
- GAV gav = kModule.getGAV();
- kieModules.put(gav, kModule);
+ ReleaseId releaseId = kModule.getReleaseId();
+ kieModules.put(releaseId, kModule);
- log.debug( "Discovered classpath module " + gav.toExternalForm() );
+ log.debug( "Discovered classpath module " + releaseId.toExternalForm() );
kr.addKieModule(kModule);
@@ -103,7 +103,7 @@ public static InternalKieModule fetchKModule(URL url, String fixedURL) {
String pomProperties = getPomProperties( fixedURL );
- GAV gav = GAVImpl.fromPropertiesString( pomProperties );
+ ReleaseId releaseId = ReleaseIdImpl.fromPropertiesString(pomProperties);
String rootPath = fixedURL;
if ( rootPath.lastIndexOf( ':' ) > 0 ) {
@@ -113,11 +113,11 @@ public static InternalKieModule fetchKModule(URL url, String fixedURL) {
InternalKieModule kJar;
File file = new File( rootPath );
if ( fixedURL.endsWith( ".jar" ) ) {
- kJar = new ZipKieModule( gav,
+ kJar = new ZipKieModule(releaseId,
kieProject,
file );
} else if ( file.isDirectory() ) {
- kJar = new FileKieModule( gav,
+ kJar = new FileKieModule(releaseId,
kieProject,
file );
} else {
@@ -206,9 +206,9 @@ public static String getPomProperties(String urlPathToAdd) {
KieBuilderImpl.validatePomModel( pomModel ); // throws an exception if invalid
- GAVImpl gav = ( GAVImpl ) KieServices.Factory.get().newGav( pomModel.getGroupId(),
- pomModel.getArtifactId(),
- pomModel.getVersion() );
+ ReleaseIdImpl gav = (ReleaseIdImpl) KieServices.Factory.get().newReleaseId(pomModel.getGroupId(),
+ pomModel.getArtifactId(),
+ pomModel.getVersion());
String str = KieBuilderImpl.generatePomProperties( gav );
log.info( "Recursed up folders, found and used pom.xml " + file );
diff --git a/drools-compiler/src/main/java/org/kie/builder/impl/FileKieModule.java b/drools-compiler/src/main/java/org/kie/builder/impl/FileKieModule.java
index 966766ddf8c..d5cdd26f53a 100644
--- a/drools-compiler/src/main/java/org/kie/builder/impl/FileKieModule.java
+++ b/drools-compiler/src/main/java/org/kie/builder/impl/FileKieModule.java
@@ -8,16 +8,16 @@
import java.util.Collection;
import org.drools.core.util.IoUtils;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieModuleModel;
public class FileKieModule extends AbstractKieModule implements InternalKieModule {
private final File file;
- public FileKieModule(GAV gav,
+ public FileKieModule(ReleaseId releaseId,
KieModuleModel kieProject,
File file) {
- super( gav, kieProject );
+ super(releaseId, kieProject );
this.file = file;
}
@@ -59,7 +59,7 @@ public byte[] getBytes() {
}
public String toString() {
- return "FileKieModule[ GAV=" + getGAV() + "file=" + file + "]";
+ return "FileKieModule[ ReleaseId=" + getReleaseId() + "file=" + file + "]";
}
}
diff --git a/drools-compiler/src/main/java/org/kie/builder/impl/InternalKieModule.java b/drools-compiler/src/main/java/org/kie/builder/impl/InternalKieModule.java
index 75ad672ce9e..451b8fce268 100644
--- a/drools-compiler/src/main/java/org/kie/builder/impl/InternalKieModule.java
+++ b/drools-compiler/src/main/java/org/kie/builder/impl/InternalKieModule.java
@@ -1,6 +1,6 @@
package org.kie.builder.impl;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieModule;
import org.kie.builder.KieModuleModel;
import org.kie.builder.Results;
@@ -20,7 +20,7 @@ public interface InternalKieModule extends KieModule {
byte[] getBytes( );
- Map<GAV, InternalKieModule> getDependencies();
+ Map<ReleaseId, InternalKieModule> getDependencies();
void addDependency(InternalKieModule dependency);
diff --git a/drools-compiler/src/main/java/org/kie/builder/impl/InternalKieScanner.java b/drools-compiler/src/main/java/org/kie/builder/impl/InternalKieScanner.java
index 0c2c60bafc1..03cbc10c998 100644
--- a/drools-compiler/src/main/java/org/kie/builder/impl/InternalKieScanner.java
+++ b/drools-compiler/src/main/java/org/kie/builder/impl/InternalKieScanner.java
@@ -1,6 +1,6 @@
package org.kie.builder.impl;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieModule;
import org.kie.builder.KieScanner;
import org.kie.runtime.KieContainer;
@@ -9,5 +9,5 @@ public interface InternalKieScanner extends KieScanner {
void setKieContainer(KieContainer kieContainer);
- KieModule loadArtifact(GAV gav);
+ KieModule loadArtifact(ReleaseId releaseId);
}
diff --git a/drools-compiler/src/main/java/org/kie/builder/impl/KieBuilderImpl.java b/drools-compiler/src/main/java/org/kie/builder/impl/KieBuilderImpl.java
index b889c2b983d..1488859dbce 100644
--- a/drools-compiler/src/main/java/org/kie/builder/impl/KieBuilderImpl.java
+++ b/drools-compiler/src/main/java/org/kie/builder/impl/KieBuilderImpl.java
@@ -8,14 +8,14 @@
import org.drools.commons.jci.readers.ResourceReader;
import org.drools.compiler.io.memory.MemoryFileSystem;
import org.drools.core.util.StringUtils;
-import org.drools.kproject.GAVImpl;
+import org.drools.kproject.ReleaseIdImpl;
import org.drools.kproject.models.KieModuleModelImpl;
import org.drools.xml.MinimalPomParser;
import org.drools.xml.PomModel;
import org.kie.KieBaseConfiguration;
import org.kie.KieServices;
import org.kie.KnowledgeBaseFactory;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieBaseModel;
import org.kie.builder.KieBuilder;
import org.kie.builder.KieFileSystem;
@@ -53,7 +53,7 @@ public class KieBuilderImpl
private PomModel pomModel;
private byte[] pomXml;
- private GAV gav;
+ private ReleaseId releaseId;
private byte[] kModuleModelXml;
private KieModuleModel kModuleModel;
@@ -91,7 +91,7 @@ private void init() {
results = new ResultsImpl();
- // if pomXML is null it will generate a default, using default GAV
+ // if pomXML is null it will generate a default, using default ReleaseId
// if pomXml is invalid, it assign pomModel to null
buildPomModel();
@@ -100,24 +100,24 @@ private void init() {
buildKieModuleModel();
if ( pomModel != null ) {
- // creates GAV from build pom
- // If the pom was generated, it will be the same as teh default GAV
- gav = ks.newGav( pomModel.getGroupId(),
- pomModel.getArtifactId(),
- pomModel.getVersion() );
+ // creates ReleaseId from build pom
+ // If the pom was generated, it will be the same as teh default ReleaseId
+ releaseId = ks.newReleaseId(pomModel.getGroupId(),
+ pomModel.getArtifactId(),
+ pomModel.getVersion());
}
}
public KieBuilder buildAll() {
- // gav and kModule will be null if a provided pom.xml or kmodule.xml is invalid
- if ( !isBuilt() && gav != null && kModuleModel != null ) {
+ // releaseId and kModule will be null if a provided pom.xml or kmodule.xml is invalid
+ if ( !isBuilt() && releaseId != null && kModuleModel != null ) {
trgMfs = new MemoryFileSystem();
writePomAndKModule();
compileJavaClasses();
addKBasesFilesToTrg();
- kModule = new MemoryKieModule( gav,
+ kModule = new MemoryKieModule(releaseId,
kModuleModel,
trgMfs );
@@ -282,7 +282,7 @@ public void buildPomModel() {
public static void validatePomModel(PomModel pomModel) {
if ( StringUtils.isEmpty( pomModel.getGroupId() ) || StringUtils.isEmpty( pomModel.getArtifactId() ) || StringUtils.isEmpty( pomModel.getVersion() ) ) {
- throw new RuntimeException( "Maven pom.properties exists but GAV content is malformed" );
+ throw new RuntimeException( "Maven pom.properties exists but ReleaseId content is malformed" );
}
}
@@ -290,8 +290,8 @@ public static byte[] getOrGeneratePomXml(ResourceReader mfs) {
if ( mfs.isAvailable( "pom.xml" ) ) {
return mfs.getBytes( "pom.xml" );
} else {
- // There is no pom.xml, and thus no GAV, so generate a pom.xml from the global detault.
- return generatePomXml( KieServices.Factory.get().getRepository().getDefaultGAV() ).getBytes();
+ // There is no pom.xml, and thus no ReleaseId, so generate a pom.xml from the global detault.
+ return generatePomXml( KieServices.Factory.get().getRepository().getDefaultReleaseId() ).getBytes();
}
}
@@ -299,12 +299,12 @@ public void writePomAndKModule() {
addMetaInfBuilder();
if ( pomXml != null ) {
- GAVImpl g = (GAVImpl) gav;
+ ReleaseIdImpl g = (ReleaseIdImpl) releaseId;
trgMfs.write( g.getPomXmlPath(),
pomXml,
true );
trgMfs.write( g.getPomPropertiesPath(),
- generatePomProperties( gav ).getBytes(),
+ generatePomProperties(releaseId).getBytes(),
true );
}
@@ -316,22 +316,22 @@ public void writePomAndKModule() {
}
}
- public static String generatePomXml(GAV gav) {
+ public static String generatePomXml(ReleaseId releaseId) {
StringBuilder sBuilder = new StringBuilder();
sBuilder.append( "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n" );
sBuilder.append( " xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\"> \n" );
sBuilder.append( " <modelVersion>4.0.0</modelVersion> \n" );
sBuilder.append( " <groupId>" );
- sBuilder.append( gav.getGroupId() );
+ sBuilder.append( releaseId.getGroupId() );
sBuilder.append( "</groupId> \n" );
sBuilder.append( " <artifactId>" );
- sBuilder.append( gav.getArtifactId() );
+ sBuilder.append( releaseId.getArtifactId() );
sBuilder.append( "</artifactId> \n" );
sBuilder.append( " <version>" );
- sBuilder.append( gav.getVersion() );
+ sBuilder.append( releaseId.getVersion() );
sBuilder.append( "</version> \n" );
sBuilder.append( " <packaging>jar</packaging> \n" );
@@ -342,18 +342,18 @@ public static String generatePomXml(GAV gav) {
return sBuilder.toString();
}
- public static String generatePomProperties(GAV gav) {
+ public static String generatePomProperties(ReleaseId releaseId) {
StringBuilder sBuilder = new StringBuilder();
sBuilder.append( "groupId=" );
- sBuilder.append( gav.getGroupId() );
+ sBuilder.append( releaseId.getGroupId() );
sBuilder.append( "\n" );
sBuilder.append( "artifactId=" );
- sBuilder.append( gav.getArtifactId() );
+ sBuilder.append( releaseId.getArtifactId() );
sBuilder.append( "\n" );
sBuilder.append( "version=" );
- sBuilder.append( gav.getVersion() );
+ sBuilder.append( releaseId.getVersion() );
sBuilder.append( "\n" );
return sBuilder.toString();
diff --git a/drools-compiler/src/main/java/org/kie/builder/impl/KieContainerImpl.java b/drools-compiler/src/main/java/org/kie/builder/impl/KieContainerImpl.java
index de9bb986921..7694dfe0d61 100644
--- a/drools-compiler/src/main/java/org/kie/builder/impl/KieContainerImpl.java
+++ b/drools-compiler/src/main/java/org/kie/builder/impl/KieContainerImpl.java
@@ -4,7 +4,7 @@
import org.drools.kproject.models.KieSessionModelImpl;
import org.kie.KieBase;
import org.kie.KnowledgeBaseFactory;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieBaseModel;
import org.kie.builder.KieModule;
import org.kie.builder.KieRepository;
@@ -43,13 +43,13 @@ public KieContainerImpl(KieProject kProject,
kProject.init();
}
- public GAV getGAV() {
+ public ReleaseId getReleaseId() {
return kProject.getGAV();
}
- public void updateToVersion(GAV gav) {
+ public void updateToVersion(ReleaseId releaseId) {
kBases.clear();
- this.kProject = new KieModuleKieProject( (InternalKieModule)kr.getKieModule(gav), kr );
+ this.kProject = new KieModuleKieProject( (InternalKieModule)kr.getKieModule(releaseId), kr );
this.kProject.init();
}
diff --git a/drools-compiler/src/main/java/org/kie/builder/impl/KieFileSystemImpl.java b/drools-compiler/src/main/java/org/kie/builder/impl/KieFileSystemImpl.java
index 12c8728b358..ac2a0fa252a 100644
--- a/drools-compiler/src/main/java/org/kie/builder/impl/KieFileSystemImpl.java
+++ b/drools-compiler/src/main/java/org/kie/builder/impl/KieFileSystemImpl.java
@@ -1,13 +1,11 @@
package org.kie.builder.impl;
import org.drools.compiler.io.memory.MemoryFileSystem;
-import org.drools.io.internal.InternalResource;
import org.drools.kproject.models.KieModuleModelImpl;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieFileSystem;
import org.kie.io.Resource;
import org.kie.io.ResourceConfiguration;
-import org.kie.io.ResourceType;
import org.kie.io.ResourceTypeImpl;
import java.io.ByteArrayOutputStream;
@@ -87,8 +85,8 @@ public MemoryFileSystem asMemoryFileSystem() {
return mfs;
}
- public KieFileSystem generateAndWritePomXML(GAV gav) {
- write("pom.xml", KieBuilderImpl.generatePomXml( gav ) );
+ public KieFileSystem generateAndWritePomXML(ReleaseId releaseId) {
+ write("pom.xml", KieBuilderImpl.generatePomXml(releaseId) );
return this;
}
diff --git a/drools-compiler/src/main/java/org/kie/builder/impl/KieModuleKieProject.java b/drools-compiler/src/main/java/org/kie/builder/impl/KieModuleKieProject.java
index 4023e166509..0f62cb64156 100644
--- a/drools-compiler/src/main/java/org/kie/builder/impl/KieModuleKieProject.java
+++ b/drools-compiler/src/main/java/org/kie/builder/impl/KieModuleKieProject.java
@@ -1,7 +1,7 @@
package org.kie.builder.impl;
import org.drools.core.util.ClassUtils;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieRepository;
import org.kie.internal.utils.ClassLoaderUtil;
import org.kie.internal.utils.CompositeClassLoader;
@@ -21,7 +21,7 @@ public class KieModuleKieProject extends AbstractKieProject {
private static final Logger log = LoggerFactory.getLogger( KieModuleKieProject.class );
- private Map<GAV, InternalKieModule> kieModules;
+ private Map<ReleaseId, InternalKieModule> kieModules;
private final Map<String, InternalKieModule> kJarFromKBaseName = new HashMap<String, InternalKieModule>();
@@ -38,9 +38,9 @@ public KieModuleKieProject(InternalKieModule kieModule,
public void init() {
if ( kieModules == null ) {
- kieModules = new HashMap<GAV, InternalKieModule>();
+ kieModules = new HashMap<ReleaseId, InternalKieModule>();
kieModules.putAll( kieModule.getDependencies() );
- kieModules.put( kieModule.getGAV(),
+ kieModules.put( kieModule.getReleaseId(),
kieModule );
indexParts( kieModules, kJarFromKBaseName );
initClassLaoder();
@@ -63,16 +63,16 @@ public void initClassLaoder() {
}
}
- public GAV getGAV() {
- return kieModule.getGAV();
+ public ReleaseId getGAV() {
+ return kieModule.getReleaseId();
}
public InternalKieModule getKieModuleForKBase(String kBaseName) {
- return this.kJarFromKBaseName.get( kBaseName );
+ return this.kJarFromKBaseName.get(kBaseName);
}
public boolean kieBaseExists(String kBaseName) {
- return kBaseModels.containsKey( kBaseName );
+ return kBaseModels.containsKey(kBaseName);
}
@Override
diff --git a/drools-compiler/src/main/java/org/kie/builder/impl/KieProject.java b/drools-compiler/src/main/java/org/kie/builder/impl/KieProject.java
index e65d5e4e262..ffa3828c537 100644
--- a/drools-compiler/src/main/java/org/kie/builder/impl/KieProject.java
+++ b/drools-compiler/src/main/java/org/kie/builder/impl/KieProject.java
@@ -1,13 +1,13 @@
package org.kie.builder.impl;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieBaseModel;
import org.kie.builder.KieSessionModel;
import org.kie.internal.utils.CompositeClassLoader;
public interface KieProject {
- GAV getGAV();
+ ReleaseId getGAV();
InternalKieModule getKieModuleForKBase(String kBaseName);
diff --git a/drools-compiler/src/main/java/org/kie/builder/impl/KieRepositoryImpl.java b/drools-compiler/src/main/java/org/kie/builder/impl/KieRepositoryImpl.java
index 32635dfb4a8..1c11b1cc162 100644
--- a/drools-compiler/src/main/java/org/kie/builder/impl/KieRepositoryImpl.java
+++ b/drools-compiler/src/main/java/org/kie/builder/impl/KieRepositoryImpl.java
@@ -1,13 +1,12 @@
package org.kie.builder.impl;
import org.drools.io.internal.InternalResource;
-import org.drools.kproject.GAVImpl;
+import org.drools.kproject.ReleaseIdImpl;
import org.drools.kproject.models.KieModuleModelImpl;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieModule;
import org.kie.builder.KieRepository;
import org.kie.builder.KieScanner;
-import org.kie.builder.Results;
import org.kie.internal.utils.ServiceRegistryImpl;
import org.kie.io.Resource;
import org.kie.runtime.KieContainer;
@@ -42,17 +41,17 @@ public class KieRepositoryImpl
private final KieModuleRepo kieModuleRepo = new KieModuleRepo();
- private final AtomicReference<GAV> defaultGAV = new AtomicReference( new GAVImpl( DEFAULT_GROUP,
+ private final AtomicReference<ReleaseId> defaultGAV = new AtomicReference( new ReleaseIdImpl( DEFAULT_GROUP,
DEFAULT_ARTIFACT,
DEFAULT_VERSION ) );
private InternalKieScanner internalKieScanner;
- public void setDefaultGAV(GAV gav) {
- this.defaultGAV.set( gav );
+ public void setDefaultGAV(ReleaseId releaseId) {
+ this.defaultGAV.set(releaseId);
}
- public GAV getDefaultGAV() {
+ public ReleaseId getDefaultReleaseId() {
return this.defaultGAV.get();
}
@@ -61,34 +60,34 @@ public void addKieModule(KieModule kieModule) {
log.info( "KieModule was added:" + kieModule);
}
- public KieModule getKieModule(GAV gav) {
- VersionRange versionRange = new VersionRange(gav.getVersion());
+ public KieModule getKieModule(ReleaseId releaseId) {
+ VersionRange versionRange = new VersionRange(releaseId.getVersion());
- KieModule kieModule = kieModuleRepo.load(gav, versionRange);
+ KieModule kieModule = kieModuleRepo.load(releaseId, versionRange);
if ( kieModule == null ) {
- log.debug( "KieModule Lookup. GAV {} was not in cache, checking classpath",
- gav.toExternalForm() );
- kieModule = checkClasspathForKieModule(gav);
+ log.debug( "KieModule Lookup. ReleaseId {} was not in cache, checking classpath",
+ releaseId.toExternalForm() );
+ kieModule = checkClasspathForKieModule(releaseId);
}
if ( kieModule == null ) {
- log.debug( "KieModule Lookup. GAV {} was not in cache, checking maven repository",
- gav.toExternalForm() );
- kieModule = loadKieModuleFromMavenRepo(gav);
+ log.debug( "KieModule Lookup. ReleaseId {} was not in cache, checking maven repository",
+ releaseId.toExternalForm() );
+ kieModule = loadKieModuleFromMavenRepo(releaseId);
}
return kieModule;
}
- private KieModule checkClasspathForKieModule(GAV gav) {
+ private KieModule checkClasspathForKieModule(ReleaseId releaseId) {
// TODO
// ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
- // URL url = classLoader.getResource( ((GAVImpl)gav).getPomPropertiesPath() );
+ // URL url = classLoader.getResource( ((ReleaseIdImpl)releaseId).getPomPropertiesPath() );
return null;
}
- private KieModule loadKieModuleFromMavenRepo(GAV gav) {
- return getInternalKieScanner().loadArtifact( gav );
+ private KieModule loadKieModuleFromMavenRepo(ReleaseId releaseId) {
+ return getInternalKieScanner().loadArtifact(releaseId);
}
private InternalKieScanner getInternalKieScanner() {
@@ -110,7 +109,7 @@ private static class DummyKieScanner
public void setKieContainer(KieContainer kieContainer) {
}
- public KieModule loadArtifact(GAV gav) {
+ public KieModule loadArtifact(ReleaseId releaseId) {
return null;
}
@@ -166,26 +165,26 @@ private static class KieModuleRepo {
private final Map<String, TreeMap<ComparableVersion, KieModule>> kieModules = new HashMap<String, TreeMap<ComparableVersion, KieModule>>();
void store(KieModule kieModule) {
- GAV gav = kieModule.getGAV();
- String ga = gav.getGroupId() + ":" + gav.getArtifactId();
+ ReleaseId releaseId = kieModule.getReleaseId();
+ String ga = releaseId.getGroupId() + ":" + releaseId.getArtifactId();
TreeMap<ComparableVersion, KieModule> artifactMap = kieModules.get(ga);
if (artifactMap == null) {
artifactMap = new TreeMap<ComparableVersion, KieModule>();
kieModules.put(ga, artifactMap);
}
- artifactMap.put(new ComparableVersion(gav.getVersion()), kieModule);
+ artifactMap.put(new ComparableVersion(releaseId.getVersion()), kieModule);
}
- KieModule load(GAV gav, VersionRange versionRange) {
- String ga = gav.getGroupId() + ":" + gav.getArtifactId();
+ KieModule load(ReleaseId releaseId, VersionRange versionRange) {
+ String ga = releaseId.getGroupId() + ":" + releaseId.getArtifactId();
TreeMap<ComparableVersion, KieModule> artifactMap = kieModules.get(ga);
if (artifactMap == null) {
return null;
}
if (versionRange.fixed) {
- return artifactMap.get(new ComparableVersion(gav.getVersion()));
+ return artifactMap.get(new ComparableVersion(releaseId.getVersion()));
}
if (versionRange.upperBound == null) {
diff --git a/drools-compiler/src/main/java/org/kie/builder/impl/KieServicesImpl.java b/drools-compiler/src/main/java/org/kie/builder/impl/KieServicesImpl.java
index ae912e9daec..a5ab109b239 100644
--- a/drools-compiler/src/main/java/org/kie/builder/impl/KieServicesImpl.java
+++ b/drools-compiler/src/main/java/org/kie/builder/impl/KieServicesImpl.java
@@ -4,11 +4,11 @@
import org.drools.command.impl.CommandFactoryServiceImpl;
import org.drools.concurrent.ExecutorProviderImpl;
import org.drools.io.impl.ResourceFactoryServiceImpl;
-import org.drools.kproject.GAVImpl;
+import org.drools.kproject.ReleaseIdImpl;
import org.drools.kproject.models.KieModuleModelImpl;
import org.drools.marshalling.impl.MarshallerProviderImpl;
import org.kie.KieServices;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieBuilder;
import org.kie.builder.KieFileSystem;
import org.kie.builder.KieModuleModel;
@@ -69,10 +69,10 @@ public void nullKieClasspathContainer() {
}
}
- public KieContainer newKieContainer(GAV gav) {
- InternalKieModule kieModule = (InternalKieModule) getRepository().getKieModule(gav);
+ public KieContainer newKieContainer(ReleaseId releaseId) {
+ InternalKieModule kieModule = (InternalKieModule) getRepository().getKieModule(releaseId);
if (kieModule == null) {
- throw new RuntimeException("Cannot find KieModule: " + gav);
+ throw new RuntimeException("Cannot find KieModule: " + releaseId);
}
KieProject kProject = new KieModuleKieProject( kieModule, getRepository() );
return new KieContainerImpl( kProject, getRepository() );
@@ -122,8 +122,8 @@ public KieStoreServices getStoreServices() {
return ServiceRegistryImpl.getInstance().get( KieStoreServices.class );
}
- public GAV newGav(String groupId, String artifactId, String version) {
- return new GAVImpl(groupId, artifactId, version);
+ public ReleaseId newReleaseId(String groupId, String artifactId, String version) {
+ return new ReleaseIdImpl(groupId, artifactId, version);
}
public KieModuleModel newKieModuleModel() {
diff --git a/drools-compiler/src/main/java/org/kie/builder/impl/MemoryKieModule.java b/drools-compiler/src/main/java/org/kie/builder/impl/MemoryKieModule.java
index dd61a6d7b99..a3de9fdac1d 100644
--- a/drools-compiler/src/main/java/org/kie/builder/impl/MemoryKieModule.java
+++ b/drools-compiler/src/main/java/org/kie/builder/impl/MemoryKieModule.java
@@ -3,7 +3,7 @@
import org.drools.commons.jci.readers.ResourceReader;
import org.drools.compiler.io.memory.MemoryFileSystem;
import org.drools.kproject.models.KieModuleModelImpl;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieModuleModel;
import java.io.File;
@@ -13,12 +13,12 @@ public class MemoryKieModule extends AbstractKieModule implements ResourceReader
private final MemoryFileSystem mfs;
- public MemoryKieModule(GAV gav) {
- this(gav, new KieModuleModelImpl(), new MemoryFileSystem());
+ public MemoryKieModule(ReleaseId releaseId) {
+ this(releaseId, new KieModuleModelImpl(), new MemoryFileSystem());
}
- public MemoryKieModule(GAV gav, KieModuleModel kieProject, MemoryFileSystem mfs) {
- super(gav, kieProject);
+ public MemoryKieModule(ReleaseId releaseId, KieModuleModel kieProject, MemoryFileSystem mfs) {
+ super(releaseId, kieProject);
this.mfs = mfs;
}
@@ -52,6 +52,6 @@ public byte[] getBytes() {
}
public String toString() {
- return "MemoryKieModule[ GAV=" + getGAV() + "]";
+ return "MemoryKieModule[ ReleaseId=" + getReleaseId() + "]";
}
}
diff --git a/drools-compiler/src/main/java/org/kie/builder/impl/ZipKieModule.java b/drools-compiler/src/main/java/org/kie/builder/impl/ZipKieModule.java
index 056355f5b76..f3283893e62 100644
--- a/drools-compiler/src/main/java/org/kie/builder/impl/ZipKieModule.java
+++ b/drools-compiler/src/main/java/org/kie/builder/impl/ZipKieModule.java
@@ -2,7 +2,7 @@
import org.drools.core.util.IoUtils;
import org.drools.kproject.models.KieModuleModelImpl;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieModuleModel;
import java.io.File;
@@ -16,14 +16,14 @@ public class ZipKieModule extends AbstractKieModule implements InternalKieModule
private final File file;
private Map<String, ZipEntry> zipEntries;
- public ZipKieModule(GAV gav, File jar) {
- this(gav, getKieModuleModelFromJar(jar), jar);
+ public ZipKieModule(ReleaseId releaseId, File jar) {
+ this(releaseId, getKieModuleModelFromJar(jar), jar);
}
- public ZipKieModule(GAV gav,
+ public ZipKieModule(ReleaseId releaseId,
KieModuleModel kieProject,
File file) {
- super( gav, kieProject );
+ super(releaseId, kieProject );
this.file = file;
this.zipEntries = IoUtils.buildZipFileMapEntries( file );
}
@@ -32,7 +32,7 @@ private static KieModuleModel getKieModuleModelFromJar(File jar) {
ZipFile zipFile = null;
try {
zipFile = new ZipFile( jar );
- ZipEntry zipEntry = zipFile.getEntry( KieModuleModelImpl.KMODULE_JAR_PATH );
+ ZipEntry zipEntry = zipFile.getEntry(KieModuleModelImpl.KMODULE_JAR_PATH);
return KieModuleModelImpl.fromXML(zipFile.getInputStream(zipEntry));
} catch ( Exception e ) {
throw new RuntimeException("Unable to load kmodule.xml from " + jar.getAbsolutePath(), e);
@@ -92,6 +92,6 @@ public byte[] getBytes() {
}
public String toString() {
- return "ZipKieModule[ GAV=" + getGAV() + "file=" + file + "]";
+ return "ZipKieModule[ ReleaseId=" + getReleaseId() + "file=" + file + "]";
}
}
diff --git a/drools-compiler/src/test/java/org/drools/builder/KieBuilderTest.java b/drools-compiler/src/test/java/org/drools/builder/KieBuilderTest.java
index 84a07a57756..239d2610504 100644
--- a/drools-compiler/src/test/java/org/drools/builder/KieBuilderTest.java
+++ b/drools-compiler/src/test/java/org/drools/builder/KieBuilderTest.java
@@ -3,7 +3,7 @@
import org.drools.compiler.io.memory.MemoryFileSystem;
import org.drools.core.util.FileManager;
-import org.drools.kproject.GAVImpl;
+import org.drools.kproject.ReleaseIdImpl;
import org.drools.kproject.models.KieBaseModelImpl;
import org.junit.After;
import org.junit.Before;
@@ -11,7 +11,7 @@
import org.junit.Test;
import org.kie.KieBase;
import org.kie.KieServices;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieBaseModel;
import org.kie.builder.KieBuilder;
import org.kie.builder.KieFileSystem;
@@ -54,14 +54,14 @@ public void tearDown() throws Exception {
public void testInMemory() throws ClassNotFoundException, InterruptedException, IOException {
String namespace = "org.kie.test";
- GAV gav = KieServices.Factory.get().newGav( namespace, "memory", "1.0-SNAPSHOT" );
+ ReleaseId releaseId = KieServices.Factory.get().newReleaseId(namespace, "memory", "1.0-SNAPSHOT");
KieModuleModel kProj = createKieProject(namespace);
KieFileSystem kfs = KieServices.Factory.get().newKieFileSystem();
- generateAll(kfs, namespace, gav, kProj);
+ generateAll(kfs, namespace, releaseId, kProj);
- createAndTestKieContainer(gav, createKieBuilder(kfs), namespace );
+ createAndTestKieContainer(releaseId, createKieBuilder(kfs), namespace );
}
@Test
@@ -70,16 +70,16 @@ public void testOnDisc() throws ClassNotFoundException, InterruptedException, IO
KieModuleModel kProj = createKieProject(namespace);
- GAV gav = KieServices.Factory.get().newGav( namespace, "memory", "1.0-SNAPSHOT" );
+ ReleaseId releaseId = KieServices.Factory.get().newReleaseId(namespace, "memory", "1.0-SNAPSHOT");
KieFileSystem kfs = KieServices.Factory.get().newKieFileSystem();
- generateAll(kfs, namespace, gav, kProj);
+ generateAll(kfs, namespace, releaseId, kProj);
MemoryFileSystem mfs = ((KieFileSystemImpl)kfs).asMemoryFileSystem();
File file = fileManager.getRootDirectory() ;
mfs.writeAsFs( file );
- createAndTestKieContainer(gav, createKieBuilder(kfs), namespace);
+ createAndTestKieContainer(releaseId, createKieBuilder(kfs), namespace);
}
@Test
@@ -87,10 +87,10 @@ public void testKieModuleDepednencies() throws ClassNotFoundException, Interrupt
KieServices ks = KieServices.Factory.get();
String namespace1 = "org.kie.test1";
- GAV gav1 = KieServices.Factory.get().newGav( namespace1, "memory", "1.0-SNAPSHOT" );
+ ReleaseId releaseId1 = KieServices.Factory.get().newReleaseId(namespace1, "memory", "1.0-SNAPSHOT");
KieModuleModel kProj1 = createKieProject(namespace1);
KieFileSystem kfs1 = KieServices.Factory.get().newKieFileSystem();
- generateAll(kfs1, namespace1, gav1, kProj1);
+ generateAll(kfs1, namespace1, releaseId1, kProj1);
KieBuilder kb1 = createKieBuilder(kfs1);
kb1.buildAll();
@@ -98,18 +98,18 @@ public void testKieModuleDepednencies() throws ClassNotFoundException, Interrupt
fail("Unable to build KieJar\n" + kb1.getResults( ).toString() );
}
KieRepository kr = ks.getRepository();
- KieModule kModule1 = kr.getKieModule(gav1);
+ KieModule kModule1 = kr.getKieModule(releaseId1);
assertNotNull( kModule1 );
String namespace2 = "org.kie.test2";
- GAV gav2 = KieServices.Factory.get().newGav( namespace2, "memory", "1.0-SNAPSHOT" );
+ ReleaseId releaseId2 = KieServices.Factory.get().newReleaseId(namespace2, "memory", "1.0-SNAPSHOT");
KieModuleModel kProj2 = createKieProject(namespace2);
KieBaseModelImpl kieBase2 = ( KieBaseModelImpl ) kProj2.getKieBaseModels().get( namespace2 );
kieBase2.addInclude( namespace1 );
KieFileSystem kfs2 = KieServices.Factory.get().newKieFileSystem();
- generateAll(kfs2, namespace2, gav2, kProj2);
+ generateAll(kfs2, namespace2, releaseId2, kProj2);
KieBuilder kb2 = createKieBuilder(kfs2);
@@ -118,10 +118,10 @@ public void testKieModuleDepednencies() throws ClassNotFoundException, Interrupt
if ( kb2.getResults().hasMessages(Level.ERROR) ) {
fail("Unable to build KieJar\n" + kb2.getResults( ).toString() );
}
- KieModule kModule2= kr.getKieModule(gav2);
+ KieModule kModule2= kr.getKieModule(releaseId2);
assertNotNull( kModule2);
- KieContainer kContainer = ks.newKieContainer(gav2);
+ KieContainer kContainer = ks.newKieContainer(releaseId2);
KieBase kBase = kContainer.getKieBase( namespace2 );
KieSession kSession = kBase.newKieSession();
@@ -144,7 +144,7 @@ public void testNoPomXml() throws ClassNotFoundException, InterruptedException,
KieModuleModel kProj = createKieProject(namespace);
- GAV gav = KieServices.Factory.get().getRepository().getDefaultGAV();
+ ReleaseId releaseId = KieServices.Factory.get().getRepository().getDefaultReleaseId();
KieFileSystem kfs = KieServices.Factory.get().newKieFileSystem();
generateKProjectXML( kfs, namespace, kProj );
@@ -153,29 +153,29 @@ public void testNoPomXml() throws ClassNotFoundException, InterruptedException,
MemoryFileSystem mfs = ((KieFileSystemImpl)kfs).asMemoryFileSystem();
- createAndTestKieContainer(gav, createKieBuilder(kfs), namespace );
+ createAndTestKieContainer(releaseId, createKieBuilder(kfs), namespace );
}
@Test @Ignore
public void testNoProjectXml() throws ClassNotFoundException, InterruptedException, IOException {
String namespace = "org.kie.test";
- GAV gav = KieServices.Factory.get().newGav( namespace, "memory", "1.0-SNAPSHOT" );
+ ReleaseId releaseId = KieServices.Factory.get().newReleaseId(namespace, "memory", "1.0-SNAPSHOT");
KieFileSystem kfs = KieServices.Factory.get().newKieFileSystem();
- generatePomXML(kfs, gav);
+ generatePomXML(kfs, releaseId);
generateMessageClass( kfs, namespace );
generateRule( kfs, namespace );
MemoryFileSystem mfs = ((KieFileSystemImpl)kfs).asMemoryFileSystem();
- createAndTestKieContainer(gav, createKieBuilder(kfs), null );
+ createAndTestKieContainer(releaseId, createKieBuilder(kfs), null );
}
public void testNoPomAndProjectXml() throws ClassNotFoundException, InterruptedException, IOException {
String namespace = "org.kie.test";
- GAV gav = KieServices.Factory.get().getRepository().getDefaultGAV();
+ ReleaseId releaseId = KieServices.Factory.get().getRepository().getDefaultReleaseId();
KieFileSystem kfs = KieServices.Factory.get().newKieFileSystem();
generateMessageClass( kfs, namespace );
@@ -183,7 +183,7 @@ public void testNoPomAndProjectXml() throws ClassNotFoundException, InterruptedE
MemoryFileSystem mfs = ((KieFileSystemImpl)kfs).asMemoryFileSystem();
- createAndTestKieContainer(gav, createKieBuilder(kfs), null );
+ createAndTestKieContainer(releaseId, createKieBuilder(kfs), null );
}
@Test
@@ -192,10 +192,10 @@ public void testInvalidPomXmlGAV() throws ClassNotFoundException, InterruptedExc
KieModuleModel kProj = createKieProject(namespace);
- GAV gav = new GAVImpl( "", "", "" );
+ ReleaseId releaseId = new ReleaseIdImpl( "", "", "" );
KieFileSystem kfs = KieServices.Factory.get().newKieFileSystem();
- generatePomXML(kfs, gav);
+ generatePomXML(kfs, releaseId);
generateMessageClass( kfs, namespace );
generateRule( kfs, namespace );
@@ -213,7 +213,7 @@ public void testInvalidPomXmlContent() throws ClassNotFoundException, Interrupte
KieModuleModel kProj = createKieProject(namespace);
- GAV gav = KieServices.Factory.get().newGav( namespace, "memory", "1.0-SNAPSHOT" );
+ ReleaseId releaseId = KieServices.Factory.get().newReleaseId(namespace, "memory", "1.0-SNAPSHOT");
KieFileSystem kfs = KieServices.Factory.get().newKieFileSystem();
kfs.write( "pom.xml", "xxxx" );
@@ -232,10 +232,10 @@ public void testInvalidProjectXml() throws ClassNotFoundException, InterruptedEx
KieModuleModel kProj = createKieProject(namespace);
- GAV gav = KieServices.Factory.get().newGav( namespace, "memory", "1.0-SNAPSHOT" );
+ ReleaseId releaseId = KieServices.Factory.get().newReleaseId(namespace, "memory", "1.0-SNAPSHOT");
KieFileSystem kfs = KieServices.Factory.get().newKieFileSystem();
- generatePomXML(kfs, gav);
+ generatePomXML(kfs, releaseId);
kfs.writeKModuleXML("xxxx" );
generateMessageClass( kfs, namespace );
generateRule( kfs, namespace );
@@ -257,16 +257,16 @@ public KieModuleModel createKieProject(String namespace) {
return kProj;
}
- public void generateAll(KieFileSystem kfs, String namespace, GAV gav, KieModuleModel kProj) {
- generatePomXML(kfs, gav);
+ public void generateAll(KieFileSystem kfs, String namespace, ReleaseId releaseId, KieModuleModel kProj) {
+ generatePomXML(kfs, releaseId);
generateKProjectXML( kfs, namespace, kProj );
generateMessageClass( kfs, namespace );
generateRule( kfs, namespace );
}
- public void generatePomXML(KieFileSystem kfs, GAV gav) {
- kfs.writePomXML( KieBuilderImpl.generatePomXml( gav ) );
+ public void generatePomXML(KieFileSystem kfs, ReleaseId releaseId) {
+ kfs.writePomXML( KieBuilderImpl.generatePomXml(releaseId) );
}
public void generateKProjectXML(KieFileSystem kfs, String namespace, KieModuleModel kProj) {
@@ -291,7 +291,7 @@ public KieBuilder createKieBuilder(File file) {
return ks.newKieBuilder( file );
}
- public void createAndTestKieContainer(GAV gav, KieBuilder kb, String kBaseName) throws IOException,
+ public void createAndTestKieContainer(ReleaseId releaseId, KieBuilder kb, String kBaseName) throws IOException,
ClassNotFoundException,
InterruptedException {
KieServices ks = KieServices.Factory.get();
@@ -302,10 +302,10 @@ public void createAndTestKieContainer(GAV gav, KieBuilder kb, String kBaseName)
fail("Unable to build KieModule\n" + kb.getResults( ).toString() );
}
KieRepository kr = ks.getRepository();
- KieModule kJar = kr.getKieModule(gav);
+ KieModule kJar = kr.getKieModule(releaseId);
assertNotNull( kJar );
- KieContainer kContainer = ks.newKieContainer(gav);
+ KieContainer kContainer = ks.newKieContainer(releaseId);
KieBase kBase = kBaseName != null ? kContainer.getKieBase( kBaseName ) : kContainer.getKieBase();
KieSession kSession = kBase.newKieSession();
diff --git a/drools-compiler/src/test/java/org/drools/cdi/CDIGAVTest.java b/drools-compiler/src/test/java/org/drools/cdi/CDIGAVTest.java
index c3c4c1914cf..371b234cb6d 100644
--- a/drools-compiler/src/test/java/org/drools/cdi/CDIGAVTest.java
+++ b/drools-compiler/src/test/java/org/drools/cdi/CDIGAVTest.java
@@ -1,47 +1,7 @@
package org.drools.cdi;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
-import javax.enterprise.context.ApplicationScoped;
-import javax.enterprise.context.SessionScoped;
-import javax.enterprise.inject.spi.Bean;
-import javax.enterprise.inject.spi.BeanManager;
-import javax.enterprise.util.AnnotationLiteral;
-import javax.inject.Inject;
-
-import org.drools.cdi.example.CDIExamplesTest;
-import org.drools.cdi.example.Message;
-import org.drools.cdi.example.Message2;
-import org.drools.cdi.example.Message2Impl1;
-import org.drools.cdi.example.Message2Impl2;
-import org.drools.cdi.example.MessageImpl;
-import org.drools.cdi.example.MessageProducers;
-import org.drools.cdi.example.MessageProducers2;
-import org.drools.cdi.example.Msg;
-import org.drools.cdi.example.Msg1;
-import org.drools.cdi.example.Msg2;
-import org.drools.kproject.AbstractKnowledgeTest;
-import org.drools.kproject.KPTest;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.Ignore;
-import org.junit.Test;
import org.junit.runner.RunWith;
-import org.kie.KieBase;
-import org.kie.KieServices;
-import org.kie.KnowledgeBase;
-import org.kie.builder.KieRepository;
-import org.kie.cdi.KBase;
-import org.kie.cdi.KGAV;
-import org.kie.cdi.KSession;
-import org.kie.command.KieCommands;
-import org.kie.runtime.KieSession;
-import org.kie.runtime.StatelessKieSession;
-
-import static org.junit.Assert.*;
@RunWith(CDITestRunner.class)
@Ignore
@@ -49,37 +9,37 @@ public class CDIGAVTest {
// public static AbstractKnowledgeTest helper;
//
// @Inject
-// @KBase("jar1.KBase1") @KGAV(groupId = "jar1",
+// @KBase("jar1.KBase1") @KReleaseId(groupId = "jar1",
// artifactId = "art1",
// version = "1.0")
// private KieBase jar1KBase1v10;
//
// @Inject
-// @KBase("jar1.KBase1") @KGAV(groupId = "jar1",
+// @KBase("jar1.KBase1") @KReleaseId(groupId = "jar1",
// artifactId = "art1",
// version = "1.1")
// private KieBase jar1KBase1v11;
//
// @Inject
-// @KSession("jar1.KSession1") @KGAV( groupId = "jar1",
+// @KSession("jar1.KSession1") @KReleaseId( groupId = "jar1",
// artifactId = "art1",
// version = "1.0" )
// private StatelessKieSession kbase1ksession1v10;
//
// @Inject
-// @KSession("jar1.KSession1") @KGAV( groupId = "jar1",
+// @KSession("jar1.KSession1") @KReleaseId( groupId = "jar1",
// artifactId = "art1",
// version = "1.1" )
// private StatelessKieSession kbase1ksession1v11;
//
// @Inject
-// @KSession("jar1.KSession2") @KGAV( groupId = "jar1",
+// @KSession("jar1.KSession2") @KReleaseId( groupId = "jar1",
// artifactId = "art1",
// version = "1.0" )
// private KieSession kbase1ksession2v10;
//
// @Inject
-// @KSession("jar1.KSession2") @KGAV( groupId = "jar1",
+// @KSession("jar1.KSession2") @KReleaseId( groupId = "jar1",
// artifactId = "art1",
// version = "1.1" )
// private KieSession kbase1ksession2v11;
diff --git a/drools-compiler/src/test/java/org/drools/cdi/CDINamedTest.java b/drools-compiler/src/test/java/org/drools/cdi/CDINamedTest.java
index 4ed945221c0..ad7814c5a11 100644
--- a/drools-compiler/src/test/java/org/drools/cdi/CDINamedTest.java
+++ b/drools-compiler/src/test/java/org/drools/cdi/CDINamedTest.java
@@ -1,48 +1,7 @@
package org.drools.cdi;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
-import javax.enterprise.context.ApplicationScoped;
-import javax.enterprise.context.SessionScoped;
-import javax.enterprise.inject.spi.Bean;
-import javax.enterprise.inject.spi.BeanManager;
-import javax.enterprise.util.AnnotationLiteral;
-import javax.inject.Inject;
-import javax.inject.Named;
-
-import org.drools.cdi.example.CDIExamplesTest;
-import org.drools.cdi.example.Message;
-import org.drools.cdi.example.Message2;
-import org.drools.cdi.example.Message2Impl1;
-import org.drools.cdi.example.Message2Impl2;
-import org.drools.cdi.example.MessageImpl;
-import org.drools.cdi.example.MessageProducers;
-import org.drools.cdi.example.MessageProducers2;
-import org.drools.cdi.example.Msg;
-import org.drools.cdi.example.Msg1;
-import org.drools.cdi.example.Msg2;
-import org.drools.kproject.AbstractKnowledgeTest;
-import org.drools.kproject.KPTest;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.Ignore;
-import org.junit.Test;
import org.junit.runner.RunWith;
-import org.kie.KieBase;
-import org.kie.KieServices;
-import org.kie.KnowledgeBase;
-import org.kie.builder.KieRepository;
-import org.kie.cdi.KBase;
-import org.kie.cdi.KGAV;
-import org.kie.cdi.KSession;
-import org.kie.command.KieCommands;
-import org.kie.runtime.KieSession;
-import org.kie.runtime.StatelessKieSession;
-
-import static org.junit.Assert.*;
@RunWith(CDITestRunner.class)
@Ignore
@@ -52,7 +11,7 @@ public class CDINamedTest {
// @Inject
// @KBase("jar1.KBase1")
// @Named("kb1")
-// @KGAV(groupId = "jar1",
+// @KReleaseId(groupId = "jar1",
// artifactId = "art1",
// version = "1.0")
// private KieBase jar1KBase1kb1;
@@ -60,7 +19,7 @@ public class CDINamedTest {
// @Inject
// @KBase("jar1.KBase1")
// @Named("kb2")
-// @KGAV(groupId = "jar1",
+// @KReleaseId(groupId = "jar1",
// artifactId = "art1",
// version = "1.0")
// private KieBase jar1KBase1kb2;
@@ -68,14 +27,14 @@ public class CDINamedTest {
// @Inject
// @KBase("jar1.KBase1")
// @Named("kb2")
-// @KGAV(groupId = "jar1",
+// @KReleaseId(groupId = "jar1",
// artifactId = "art1",
// version = "1.0")
// private KieBase jar1KBase1kb22;
//
// @Inject
// @KSession("jar1.KSession1")
-// @KGAV( groupId = "jar1",
+// @KReleaseId( groupId = "jar1",
// artifactId = "art1",
// version = "1.0" )
// @Named("sks1")
@@ -83,7 +42,7 @@ public class CDINamedTest {
//
// @Inject
// @KSession("jar1.KSession1")
-// @KGAV( groupId = "jar1",
+// @KReleaseId( groupId = "jar1",
// artifactId = "art1",
// version = "1.0" )
// @Named("sks2")
@@ -91,7 +50,7 @@ public class CDINamedTest {
//
// @Inject
// @KSession("jar1.KSession1")
-// @KGAV( groupId = "jar1",
+// @KReleaseId( groupId = "jar1",
// artifactId = "art1",
// version = "1.0" )
// @Named("sks2")
@@ -99,7 +58,7 @@ public class CDINamedTest {
//
// @Inject
// @KSession("jar1.KSession2")
-// @KGAV( groupId = "jar1",
+// @KReleaseId( groupId = "jar1",
// artifactId = "art1",
// version = "1.0" )
// @Named("ks1")
@@ -107,7 +66,7 @@ public class CDINamedTest {
//
// @Inject
// @KSession("jar1.KSession2")
-// @KGAV( groupId = "jar1",
+// @KReleaseId( groupId = "jar1",
// artifactId = "art1",
// version = "1.0" )
// @Named("ks2")
@@ -115,7 +74,7 @@ public class CDINamedTest {
//
// @Inject
// @KSession("jar1.KSession2")
-// @KGAV( groupId = "jar1",
+// @KReleaseId( groupId = "jar1",
// artifactId = "art1",
// version = "1.0" )
// @Named("ks2")
diff --git a/drools-compiler/src/test/java/org/drools/cdi/CDITestRunner.java b/drools-compiler/src/test/java/org/drools/cdi/CDITestRunner.java
index 0d96f89a69e..078750b094b 100644
--- a/drools-compiler/src/test/java/org/drools/cdi/CDITestRunner.java
+++ b/drools-compiler/src/test/java/org/drools/cdi/CDITestRunner.java
@@ -23,7 +23,7 @@
import org.kie.builder.impl.KieRepositoryImpl;
import org.kie.builder.impl.KieServicesImpl;
import org.kie.cdi.KBase;
-import org.kie.cdi.KGAV;
+import org.kie.cdi.KReleaseId;
import org.kie.cdi.KSession;
import org.kie.command.KieCommands;
import org.kie.io.KieResources;
@@ -49,7 +49,7 @@ public static Weld createWeld(String... classes) {
list.add( KieCDIExtension.class.getName() );
list.add( KBase.class.getName() );
list.add( KSession.class.getName() );
- list.add( KGAV.class.getName() );
+ list.add( KReleaseId.class.getName() );
list.add( KieServices.class.getName() );
list.add( KieServicesImpl.class.getName() );
list.add( KieRepository.class.getName() );
diff --git a/drools-compiler/src/test/java/org/drools/cdi/KieContainerInjectionTest.java b/drools-compiler/src/test/java/org/drools/cdi/KieContainerInjectionTest.java
index 56539ca39b8..2c7bc15fd8f 100644
--- a/drools-compiler/src/test/java/org/drools/cdi/KieContainerInjectionTest.java
+++ b/drools-compiler/src/test/java/org/drools/cdi/KieContainerInjectionTest.java
@@ -1,14 +1,10 @@
package org.drools.cdi;
-import javax.inject.Inject;
-
import org.junit.Ignore;
-import org.kie.cdi.KGAV;
-import org.kie.runtime.KieContainer;
@Ignore
public class KieContainerInjectionTest {
//
-// //@Inject @KGAV(groupId="org.drools", artifactId="drools-core")
+// //@Inject @KReleaseId(groupId="org.drools", artifactId="drools-core")
// KieContainer kr2;
}
diff --git a/drools-compiler/src/test/java/org/drools/cdi/KieServicesInjectionTest.java b/drools-compiler/src/test/java/org/drools/cdi/KieServicesInjectionTest.java
index 03f6884af18..fbc3f2b0b9f 100644
--- a/drools-compiler/src/test/java/org/drools/cdi/KieServicesInjectionTest.java
+++ b/drools-compiler/src/test/java/org/drools/cdi/KieServicesInjectionTest.java
@@ -2,22 +2,14 @@
import javax.inject.Inject;
-import org.drools.kproject.AbstractKnowledgeTest;
import org.junit.AfterClass;
import org.junit.BeforeClass;
-import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.kie.KieBase;
import org.kie.KieServices;
import org.kie.builder.KieRepository;
-import org.kie.cdi.KBase;
-import org.kie.cdi.KGAV;
-import org.kie.cdi.KSession;
import org.kie.command.KieCommands;
import org.kie.io.KieResources;
-import org.kie.runtime.KieContainer;
-import org.kie.runtime.KieSession;
import static org.junit.Assert.*;
@@ -64,7 +56,7 @@ public void testKieServicesInjection() {
@Test
public void testKieRepositoryInjection() {
assertNotNull( kr );
- assertNotNull( kr.getDefaultGAV() );
+ assertNotNull( kr.getDefaultReleaseId() );
}
diff --git a/drools-compiler/src/test/java/org/drools/integrationtests/KieHelloWorldTest.java b/drools-compiler/src/test/java/org/drools/integrationtests/KieHelloWorldTest.java
index 703c304d82a..141d275a054 100644
--- a/drools-compiler/src/test/java/org/drools/integrationtests/KieHelloWorldTest.java
+++ b/drools-compiler/src/test/java/org/drools/integrationtests/KieHelloWorldTest.java
@@ -4,7 +4,7 @@
import org.drools.Message;
import org.junit.Test;
import org.kie.KieServices;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieBaseModel;
import org.kie.builder.KieBuilder;
import org.kie.builder.KieFileSystem;
@@ -34,7 +34,7 @@ public void testHelloWorld() throws Exception {
KieFileSystem kfs = ks.newKieFileSystem().write( "src/main/resources/r1.drl", drl );
ks.newKieBuilder( kfs ).buildAll();
- KieSession ksession = ks.newKieContainer(ks.getRepository().getDefaultGAV()).newKieSession();
+ KieSession ksession = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).newKieSession();
ksession.insert(new Message("Hello World"));
int count = ksession.fireAllRules();
@@ -75,16 +75,16 @@ public void testHelloWorldWithPackages() throws Exception {
KieServices ks = KieServices.Factory.get();
- GAV gav = ks.newGav("org.kie", "hello-world", "1.0-SNAPSHOT");
+ ReleaseId releaseId = ks.newReleaseId("org.kie", "hello-world", "1.0-SNAPSHOT");
KieFileSystem kfs = ks.newKieFileSystem()
- .generateAndWritePomXML( gav )
+ .generateAndWritePomXML(releaseId)
.write("src/main/resources/KBase1/org/pkg1/r1.drl", drl1)
.write("src/main/resources/KBase1/org/pkg2/r2.drl", drl2)
.writeKModuleXML(createKieProjectWithPackages(ks, "org.pkg1").toXML());
ks.newKieBuilder( kfs ).buildAll();
- KieSession ksession = ks.newKieContainer(gav).newKieSession("KSession1");
+ KieSession ksession = ks.newKieContainer(releaseId).newKieSession("KSession1");
ksession.insert(new Message("Hello World"));
int count = ksession.fireAllRules();
@@ -108,16 +108,16 @@ public void testHelloWorldWithWildcardPackages() throws Exception {
KieServices ks = KieServices.Factory.get();
- GAV gav = ks.newGav("org.kie", "hello-world", "1.0-SNAPSHOT");
+ ReleaseId releaseId = ks.newReleaseId("org.kie", "hello-world", "1.0-SNAPSHOT");
KieFileSystem kfs = ks.newKieFileSystem()
- .generateAndWritePomXML( gav )
+ .generateAndWritePomXML(releaseId)
.write("src/main/resources/KBase1/org/pkg1/test/r1.drl", drl1)
.write("src/main/resources/KBase1/org/pkg2/test/r2.drl", drl2)
.writeKModuleXML( createKieProjectWithPackages(ks, "org.pkg1.*").toXML());
ks.newKieBuilder( kfs ).buildAll();
- KieSession ksession = ks.newKieContainer(gav).newKieSession("KSession1");
+ KieSession ksession = ks.newKieContainer(releaseId).newKieSession("KSession1");
ksession.insert(new Message("Hello World"));
int count = ksession.fireAllRules();
@@ -148,33 +148,33 @@ public void testHelloWorldOnVersionRange() throws Exception {
buildVersion(ks, "Aloha Earth", "1.1");
buildVersion(ks, "Hi Universe", "1.2");
- GAV latestGav = ks.newGav("org.kie", "hello-world", "LATEST");
+ ReleaseId latestReleaseId = ks.newReleaseId("org.kie", "hello-world", "LATEST");
- KieSession ksession = ks.newKieContainer(latestGav).newKieSession("KSession1");
+ KieSession ksession = ks.newKieContainer(latestReleaseId).newKieSession("KSession1");
ksession.insert(new Message("Hello World"));
assertEquals( 0, ksession.fireAllRules() );
- ksession = ks.newKieContainer(latestGav).newKieSession("KSession1");
+ ksession = ks.newKieContainer(latestReleaseId).newKieSession("KSession1");
ksession.insert(new Message("Hi Universe"));
assertEquals( 1, ksession.fireAllRules() );
- GAV gav1 = ks.newGav("org.kie", "hello-world", "1.0");
+ ReleaseId releaseId1 = ks.newReleaseId("org.kie", "hello-world", "1.0");
- ksession = ks.newKieContainer(gav1).newKieSession("KSession1");
+ ksession = ks.newKieContainer(releaseId1).newKieSession("KSession1");
ksession.insert(new Message("Hello World"));
assertEquals( 1, ksession.fireAllRules() );
- ksession = ks.newKieContainer(gav1).newKieSession("KSession1");
+ ksession = ks.newKieContainer(releaseId1).newKieSession("KSession1");
ksession.insert(new Message("Hi Universe"));
assertEquals( 0, ksession.fireAllRules() );
- GAV gav2 = ks.newGav("org.kie", "hello-world", "[1.0,1.2)");
+ ReleaseId releaseId2 = ks.newReleaseId("org.kie", "hello-world", "[1.0,1.2)");
- ksession = ks.newKieContainer(gav2).newKieSession("KSession1");
+ ksession = ks.newKieContainer(releaseId2).newKieSession("KSession1");
ksession.insert(new Message("Aloha Earth"));
assertEquals( 1, ksession.fireAllRules() );
- ksession = ks.newKieContainer(gav2).newKieSession("KSession1");
+ ksession = ks.newKieContainer(releaseId2).newKieSession("KSession1");
ksession.insert(new Message("Hi Universe"));
assertEquals( 0, ksession.fireAllRules() );
}
@@ -186,10 +186,10 @@ private void buildVersion(KieServices ks, String message, String version) {
"then\n" +
"end\n";
- GAV gav = ks.newGav("org.kie", "hello-world", version);
+ ReleaseId releaseId = ks.newReleaseId("org.kie", "hello-world", version);
KieFileSystem kfs = ks.newKieFileSystem()
- .generateAndWritePomXML( gav )
+ .generateAndWritePomXML(releaseId)
.write("src/main/resources/KBase1/org/pkg1/r1.drl", drl)
.writeKModuleXML(createKieProjectWithPackages(ks, "*").toXML());
ks.newKieBuilder( kfs ).buildAll();
@@ -219,36 +219,36 @@ public void testHelloWorldWithPackagesAnd2KieBases() throws Exception {
KieServices ks = KieServices.Factory.get();
- GAV gav = ks.newGav("org.kie", "hello-world", "1.0-SNAPSHOT");
+ ReleaseId releaseId = ks.newReleaseId("org.kie", "hello-world", "1.0-SNAPSHOT");
KieFileSystem kfs = ks.newKieFileSystem()
- .generateAndWritePomXML( gav )
+ .generateAndWritePomXML(releaseId)
.write("src/main/resources/KBase1/org/pkg1/r1.drl", drl1)
.write("src/main/resources/KBase1/org/pkg2/r2.drl", drl2)
.writeKModuleXML(createKieProjectWithPackagesAnd2KieBases(ks).toXML());
ks.newKieBuilder( kfs ).buildAll();
- KieSession ksession = ks.newKieContainer(gav).newKieSession("KSession1");
+ KieSession ksession = ks.newKieContainer(releaseId).newKieSession("KSession1");
ksession.insert(new Message("Hello World"));
assertEquals( 1, ksession.fireAllRules() );
- ksession = ks.newKieContainer(gav).newKieSession("KSession1");
+ ksession = ks.newKieContainer(releaseId).newKieSession("KSession1");
ksession.insert(new Message("Hi Universe"));
assertEquals( 1, ksession.fireAllRules() );
- ksession = ks.newKieContainer(gav).newKieSession("KSession1");
+ ksession = ks.newKieContainer(releaseId).newKieSession("KSession1");
ksession.insert(new Message("Aloha Earth"));
assertEquals( 0, ksession.fireAllRules() );
- ksession = ks.newKieContainer(gav).newKieSession("KSession2");
+ ksession = ks.newKieContainer(releaseId).newKieSession("KSession2");
ksession.insert(new Message("Hello World"));
assertEquals( 1, ksession.fireAllRules() );
- ksession = ks.newKieContainer(gav).newKieSession("KSession2");
+ ksession = ks.newKieContainer(releaseId).newKieSession("KSession2");
ksession.insert(new Message("Hi Universe"));
assertEquals( 0, ksession.fireAllRules() );
- ksession = ks.newKieContainer(gav).newKieSession("KSession2");
+ ksession = ks.newKieContainer(releaseId).newKieSession("KSession2");
ksession.insert(new Message("Aloha Earth"));
assertEquals(1, ksession.fireAllRules());
}
diff --git a/drools-compiler/src/test/java/org/drools/kproject/AbstractKnowledgeTest.java b/drools-compiler/src/test/java/org/drools/kproject/AbstractKnowledgeTest.java
index 8cf072d27b9..b672d8a2421 100644
--- a/drools-compiler/src/test/java/org/drools/kproject/AbstractKnowledgeTest.java
+++ b/drools-compiler/src/test/java/org/drools/kproject/AbstractKnowledgeTest.java
@@ -12,7 +12,7 @@
import org.drools.kproject.models.KieModuleModelImpl;
import org.junit.After;
import org.junit.Before;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieBaseModel;
import org.kie.builder.KieBuilder;
import org.kie.builder.KieModuleModel;
@@ -146,8 +146,8 @@ public KieModuleModel createKieModule(String namespace,
kfs.write( "src/main/resources/META-INF/beans.xml", generateBeansXML( kproj ) );
kfs.writeKModuleXML( ((KieModuleModelImpl)kproj).toXML() );
- GAV gav = ks.newGav( namespace, "art1", version );
- kfs.generateAndWritePomXML( gav );
+ ReleaseId releaseId = ks.newReleaseId(namespace, "art1", version);
+ kfs.generateAndWritePomXML(releaseId);
String kBase1R1 = getRule( namespace + ".test1", "rule1", version );
String kBase1R2 = getRule( namespace + ".test1", "rule2", version );
@@ -169,7 +169,7 @@ public KieModuleModel createKieModule(String namespace,
KieBuilder kBuilder = ks.newKieBuilder( kfs );
kBuilder.buildAll();
- if ( kBuilder.getResults().hasMessages( Level.ERROR ) ) {
+ if ( kBuilder.getResults().hasMessages(Level.ERROR) ) {
fail( "should not have errors" + kBuilder.getResults() );
}
MemoryKieModule kieModule = ( MemoryKieModule ) kBuilder.getKieModule();
diff --git a/drools-compiler/src/test/java/org/drools/kproject/KieProjectCDITest.java b/drools-compiler/src/test/java/org/drools/kproject/KieProjectCDITest.java
index 4d1925bcaed..7ea75a821d1 100644
--- a/drools-compiler/src/test/java/org/drools/kproject/KieProjectCDITest.java
+++ b/drools-compiler/src/test/java/org/drools/kproject/KieProjectCDITest.java
@@ -1,23 +1,13 @@
package org.drools.kproject;
import org.drools.cdi.CDITestRunner;
-import org.drools.cdi.KieCDIExtension;
-import org.drools.cdi.CDITestRunner.TestWeldSEDeployment;
import org.drools.kproject.models.KieModuleModelImpl;
import org.drools.rule.JavaDialectRuntimeData;
-import org.jboss.weld.bootstrap.api.Bootstrap;
-import org.jboss.weld.bootstrap.spi.Deployment;
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
-import org.jboss.weld.resources.spi.ResourceLoader;
-import org.junit.AfterClass;
import org.junit.Test;
import org.kie.KieServices;
-import org.kie.builder.impl.AbstractKieModule;
import org.kie.builder.impl.KieServicesImpl;
-import org.kie.cdi.KBase;
-import org.kie.cdi.KGAV;
-import org.kie.cdi.KSession;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.util.AnnotationLiteral;
@@ -27,9 +17,7 @@
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
-import java.util.ArrayList;
import java.util.Enumeration;
-import java.util.List;
import java.util.Set;
import static org.junit.Assert.assertNotNull;
diff --git a/drools-compiler/src/test/java/org/drools/kproject/KieProjectRuntimeModulesTest.java b/drools-compiler/src/test/java/org/drools/kproject/KieProjectRuntimeModulesTest.java
index 7a4f10f2ab5..1a3cd0e8602 100644
--- a/drools-compiler/src/test/java/org/drools/kproject/KieProjectRuntimeModulesTest.java
+++ b/drools-compiler/src/test/java/org/drools/kproject/KieProjectRuntimeModulesTest.java
@@ -5,7 +5,7 @@
import org.junit.Test;
import org.kie.KieBase;
import org.kie.KieServices;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieModuleModel;
import org.kie.builder.impl.FileKieModule;
import org.kie.builder.impl.KieContainerImpl;
@@ -28,34 +28,34 @@ public void createMultpleJarAndFileResources() throws IOException,
KieModuleModel kProjModel3 = createKieModule( "jar3", true );
KieModuleModel kProjModel4 = createKieModule( "fol4", false );
- GAV gav1 = KieServices.Factory.get().newGav( "jar1",
- "art1",
- "1.0-SNAPSHOT" );
- GAV gav2 = KieServices.Factory.get().newGav( "jar2",
- "art1",
- "1.0-SNAPSHOT" );
- GAV gav3 = KieServices.Factory.get().newGav( "jar3",
- "art1",
- "1.0-SNAPSHOT" );
- GAV gav4 = KieServices.Factory.get().newGav( "fol4",
- "art1",
- "1.0-SNAPSHOT" );
+ ReleaseId releaseId1 = KieServices.Factory.get().newReleaseId("jar1",
+ "art1",
+ "1.0-SNAPSHOT");
+ ReleaseId releaseId2 = KieServices.Factory.get().newReleaseId("jar2",
+ "art1",
+ "1.0-SNAPSHOT");
+ ReleaseId releaseId3 = KieServices.Factory.get().newReleaseId("jar3",
+ "art1",
+ "1.0-SNAPSHOT");
+ ReleaseId releaseId4 = KieServices.Factory.get().newReleaseId("fol4",
+ "art1",
+ "1.0-SNAPSHOT");
java.io.File file1 = fileManager.newFile( "jar1.jar" );
java.io.File file2 = fileManager.newFile( "jar2.jar" );
java.io.File file3 = fileManager.newFile( "jar3.jar" );
java.io.File fol4 = fileManager.newFile( "fol4" );
- ZipKieModule mod1 = new ZipKieModule( gav1,
+ ZipKieModule mod1 = new ZipKieModule(releaseId1,
kProjModel1,
file1 );
- ZipKieModule mod2 = new ZipKieModule( gav2,
+ ZipKieModule mod2 = new ZipKieModule(releaseId2,
kProjModel2,
file2 );
- ZipKieModule mod3 = new ZipKieModule( gav3,
+ ZipKieModule mod3 = new ZipKieModule(releaseId3,
kProjModel3,
file3 );
- FileKieModule mod4 = new FileKieModule( gav4,
+ FileKieModule mod4 = new FileKieModule(releaseId4,
kProjModel4,
fol4 );
diff --git a/drools-compiler/src/test/java/org/kie/builder/WireListenerTest.java b/drools-compiler/src/test/java/org/kie/builder/WireListenerTest.java
index 91e21c695fb..32d99e9ab43 100644
--- a/drools-compiler/src/test/java/org/kie/builder/WireListenerTest.java
+++ b/drools-compiler/src/test/java/org/kie/builder/WireListenerTest.java
@@ -27,9 +27,9 @@ public class WireListenerTest {
public void testWireListener() throws Exception {
KieServices ks = KieServices.Factory.get();
- GAV gav = ks.newGav("org.kie", "listener-test", "1.0-SNAPSHOT");
- build(ks, gav);
- KieContainer kieContainer = ks.newKieContainer(gav);
+ ReleaseId releaseId = ks.newReleaseId("org.kie", "listener-test", "1.0-SNAPSHOT");
+ build(ks, releaseId);
+ KieContainer kieContainer = ks.newKieContainer(releaseId);
KieSession ksession = kieContainer.newKieSession();
ksession.fireAllRules();
@@ -39,7 +39,7 @@ public void testWireListener() throws Exception {
assertEquals(1, retractEvents.size());
}
- private void build(KieServices ks, GAV gav) throws IOException {
+ private void build(KieServices ks, ReleaseId releaseId) throws IOException {
KieModuleModel kproj = ks.newKieModuleModel();
KieSessionModel ksession1 = kproj.newKieBaseModel("KBase1").newKieSessionModel("KSession1").setDefault(true);
@@ -48,7 +48,7 @@ private void build(KieServices ks, GAV gav) throws IOException {
KieFileSystem kfs = ks.newKieFileSystem();
kfs.writeKModuleXML(kproj.toXML())
- .writePomXML( generatePomXml(gav) )
+ .writePomXML( generatePomXml(releaseId) )
.write("src/main/resources/KBase1/rules.drl", createDRL());
KieBuilder kieBuilder = ks.newKieBuilder(kfs);
diff --git a/drools-compiler/src/test/java/org/kie/util/ChangeSetBuilderTest.java b/drools-compiler/src/test/java/org/kie/util/ChangeSetBuilderTest.java
index 908e6185596..f3630658f8a 100644
--- a/drools-compiler/src/test/java/org/kie/util/ChangeSetBuilderTest.java
+++ b/drools-compiler/src/test/java/org/kie/util/ChangeSetBuilderTest.java
@@ -3,7 +3,7 @@
import org.drools.kproject.models.KieModuleModelImpl;
import org.junit.Test;
import org.kie.KieServices;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieBaseModel;
import org.kie.builder.KieModuleModel;
import org.kie.builder.KieSessionModel;
@@ -196,7 +196,7 @@ public void testModified2() {
private InternalKieModule createKieJar( String... drls) {
InternalKieModule kieJar = mock( InternalKieModule.class );
KieServices ks = KieServices.Factory.get();
- GAV gav = ks.newGav("org.kie", "hello-world", "1.0-SNAPSHOT");
+ ReleaseId releaseId = ks.newReleaseId("org.kie", "hello-world", "1.0-SNAPSHOT");
List<String> drlFs = new ArrayList<String>();
@@ -207,12 +207,12 @@ private InternalKieModule createKieJar( String... drls) {
when( kieJar.getBytes( fileName ) ).thenReturn( drls[i].getBytes() );
}
}
- when( kieJar.getBytes( KieModuleModelImpl.KMODULE_JAR_PATH ) ).thenReturn( createKieProjectWithPackages(ks, gav).toXML().getBytes() );
+ when( kieJar.getBytes( KieModuleModelImpl.KMODULE_JAR_PATH ) ).thenReturn( createKieProjectWithPackages(ks, releaseId).toXML().getBytes() );
when( kieJar.getFileNames() ).thenReturn( drlFs );
return ( InternalKieModule ) kieJar;
}
- private KieModuleModel createKieProjectWithPackages(KieServices ks, GAV gav) {
+ private KieModuleModel createKieProjectWithPackages(KieServices ks, ReleaseId releaseId) {
KieModuleModel kproj = ks.newKieModuleModel();
KieBaseModel kieBaseModel1 = kproj.newKieBaseModel("KBase1")
diff --git a/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetIntegrationExampleTest.java b/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetIntegrationExampleTest.java
index 947275ef269..0953eba67ba 100644
--- a/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetIntegrationExampleTest.java
+++ b/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetIntegrationExampleTest.java
@@ -67,7 +67,7 @@ private KieSession getKieSession(Resource dt) {
assertTrue( kb.getResults().getMessages().isEmpty() );
// get the session
- KieSession ksession = ks.newKieContainer(ks.getRepository().getDefaultGAV()).newKieSession();
+ KieSession ksession = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).newKieSession();
return ksession;
}
diff --git a/drools-maven-plugin/src/main/java/org/drools/BuildMojo.java b/drools-maven-plugin/src/main/java/org/drools/BuildMojo.java
index e16977ecda5..8a0875eec7c 100644
--- a/drools-maven-plugin/src/main/java/org/drools/BuildMojo.java
+++ b/drools-maven-plugin/src/main/java/org/drools/BuildMojo.java
@@ -58,7 +58,7 @@ public void execute() throws MojoExecutionException, MojoFailureException {
try {
KieRepository kr = ks.getRepository();
KieModule kModule = kr.addKieModule( ks.getResources().newFileSystemResource( sourceFolder ) );
- KieContainerImpl kContainer = (KieContainerImpl)ks.newKieContainer(kModule.getGAV());
+ KieContainerImpl kContainer = (KieContainerImpl)ks.newKieContainer(kModule.getReleaseId());
KieProject kieProject = kContainer.getKieProject();
ResultsImpl messages = kieProject.verify();
diff --git a/drools-persistence-jpa/src/test/java/org/kie/persistence/session/JpaPersistentStatefulSessionTest.java b/drools-persistence-jpa/src/test/java/org/kie/persistence/session/JpaPersistentStatefulSessionTest.java
index 63adabf3eba..6767d252051 100644
--- a/drools-persistence-jpa/src/test/java/org/kie/persistence/session/JpaPersistentStatefulSessionTest.java
+++ b/drools-persistence-jpa/src/test/java/org/kie/persistence/session/JpaPersistentStatefulSessionTest.java
@@ -90,7 +90,7 @@ public void testFactHandleSerialization() {
KieFileSystem kfs = ks.newKieFileSystem().write( "src/main/resources/r1.drl", str );
ks.newKieBuilder( kfs ).buildAll();
- KieBase kbase = ks.newKieContainer(ks.getRepository().getDefaultGAV()).getKieBase();
+ KieBase kbase = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).getKieBase();
KieSession ksession = JPAKnowledgeService.newStatefulKnowledgeSession( kbase, null, env );
List<?> list = new ArrayList<Object>();
@@ -148,7 +148,7 @@ public void testLocalTransactionPerStatement() {
KieFileSystem kfs = ks.newKieFileSystem().write( "src/main/resources/r1.drl", str );
ks.newKieBuilder( kfs ).buildAll();
- KieBase kbase = ks.newKieContainer(ks.getRepository().getDefaultGAV()).getKieBase();
+ KieBase kbase = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).getKieBase();
KieSession ksession = JPAKnowledgeService.newStatefulKnowledgeSession( kbase, null, env );
List<?> list = new ArrayList<Object>();
@@ -185,7 +185,7 @@ public void testUserTransactions() throws Exception {
KieFileSystem kfs = ks.newKieFileSystem().write( "src/main/resources/r1.drl", str );
ks.newKieBuilder( kfs ).buildAll();
- KieBase kbase = ks.newKieContainer(ks.getRepository().getDefaultGAV()).getKieBase();
+ KieBase kbase = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).getKieBase();
UserTransaction ut = (UserTransaction) new InitialContext().lookup( "java:comp/UserTransaction" );
ut.begin();
@@ -270,7 +270,7 @@ public void testInterceptor() {
KieFileSystem kfs = ks.newKieFileSystem().write( "src/main/resources/r1.drl", str );
ks.newKieBuilder( kfs ).buildAll();
- KieBase kbase = ks.newKieContainer(ks.getRepository().getDefaultGAV()).getKieBase();
+ KieBase kbase = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).getKieBase();
KieSession ksession = JPAKnowledgeService.newStatefulKnowledgeSession( kbase, null, env );
SingleSessionCommandService sscs = (SingleSessionCommandService)
@@ -306,7 +306,7 @@ public void testSetFocus() {
KieFileSystem kfs = ks.newKieFileSystem().write( "src/main/resources/r1.drl", str );
ks.newKieBuilder( kfs ).buildAll();
- KieBase kbase = ks.newKieContainer(ks.getRepository().getDefaultGAV()).getKieBase();
+ KieBase kbase = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).getKieBase();
KieSession ksession = JPAKnowledgeService.newStatefulKnowledgeSession( kbase, null, env );
List<?> list = new ArrayList<Object>();
@@ -328,7 +328,7 @@ public void testSetFocus() {
@Test
public void testSharedReferences() {
KieServices ks = KieServices.Factory.get();
- KieBase kbase = ks.newKieContainer(ks.getRepository().getDefaultGAV()).getKieBase();
+ KieBase kbase = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).getKieBase();
KieSession ksession = JPAKnowledgeService.newStatefulKnowledgeSession( kbase, null, env );
Person x = new Person( "test" );
@@ -357,7 +357,7 @@ public void testSharedReferences() {
public void testMergeConfig() {
// JBRULES-3155
KieServices ks = KieServices.Factory.get();
- KieBase kbase = ks.newKieContainer(ks.getRepository().getDefaultGAV()).getKieBase();
+ KieBase kbase = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).getKieBase();
Properties properties = new Properties();
properties.put("drools.processInstanceManagerFactory", "com.example.CustomJPAProcessInstanceManagerFactory");
diff --git a/kie-ci/src/main/java/org/drools/scanner/ArtifactResolver.java b/kie-ci/src/main/java/org/drools/scanner/ArtifactResolver.java
index fefc3ec0f27..4df88728d64 100644
--- a/kie-ci/src/main/java/org/drools/scanner/ArtifactResolver.java
+++ b/kie-ci/src/main/java/org/drools/scanner/ArtifactResolver.java
@@ -2,7 +2,7 @@
import org.apache.maven.project.MavenProject;
import org.drools.scanner.embedder.EmbeddedPomParser;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.sonatype.aether.artifact.Artifact;
import java.io.File;
@@ -51,8 +51,8 @@ Collection<DependencyDescriptor> getAllDependecies() {
return dependencies;
}
- public static ArtifactResolver getResolverFor(GAV gav, boolean allowDefaultPom) {
- MavenProject mavenProject = getMavenProjectForGAV(gav);
+ public static ArtifactResolver getResolverFor(ReleaseId releaseId, boolean allowDefaultPom) {
+ MavenProject mavenProject = getMavenProjectForGAV(releaseId);
return mavenProject == null ?
(allowDefaultPom ? new ArtifactResolver() : null) :
new ArtifactResolver(mavenProject);
@@ -67,8 +67,8 @@ public static ArtifactResolver getResolverFor(File pomFile) {
return new ArtifactResolver(mavenProject);
}
- static MavenProject getMavenProjectForGAV(GAV gav) {
- String artifactName = gav.getGroupId() + ":" + gav.getArtifactId() + ":pom:" + gav.getVersion();
+ static MavenProject getMavenProjectForGAV(ReleaseId releaseId) {
+ String artifactName = releaseId.getGroupId() + ":" + releaseId.getArtifactId() + ":pom:" + releaseId.getVersion();
Artifact artifact = MavenRepository.getMavenRepository().resolveArtifact(artifactName);
return artifact != null ? parseMavenPom(artifact.getFile()) : null;
}
diff --git a/kie-ci/src/main/java/org/drools/scanner/DependencyDescriptor.java b/kie-ci/src/main/java/org/drools/scanner/DependencyDescriptor.java
index bb664538a27..968ccd1aecd 100644
--- a/kie-ci/src/main/java/org/drools/scanner/DependencyDescriptor.java
+++ b/kie-ci/src/main/java/org/drools/scanner/DependencyDescriptor.java
@@ -3,8 +3,8 @@
import org.apache.maven.artifact.versioning.ArtifactVersion;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.apache.maven.model.Dependency;
-import org.drools.kproject.GAVImpl;
-import org.kie.builder.GAV;
+import org.drools.kproject.ReleaseIdImpl;
+import org.kie.builder.ReleaseId;
import org.sonatype.aether.artifact.Artifact;
public class DependencyDescriptor {
@@ -38,10 +38,10 @@ public DependencyDescriptor(String groupId, String artifactId, String version, S
artifactVersion = new DefaultArtifactVersion(version);
}
- public DependencyDescriptor(GAV gav) {
- groupId = gav.getGroupId();
- artifactId = gav.getArtifactId();
- version = gav.getVersion();
+ public DependencyDescriptor(ReleaseId releaseId) {
+ groupId = releaseId.getGroupId();
+ artifactId = releaseId.getArtifactId();
+ version = releaseId.getVersion();
type = "jar";
artifactVersion = new DefaultArtifactVersion(version);
}
@@ -58,8 +58,8 @@ public String getVersion() {
return version;
}
- public GAV getGav() {
- return new GAVImpl(groupId, artifactId, version);
+ public ReleaseId getGav() {
+ return new ReleaseIdImpl(groupId, artifactId, version);
}
public String getType() {
diff --git a/kie-ci/src/main/java/org/drools/scanner/KieModuleMetaData.java b/kie-ci/src/main/java/org/drools/scanner/KieModuleMetaData.java
index f3af0cec34a..bab133533ed 100644
--- a/kie-ci/src/main/java/org/drools/scanner/KieModuleMetaData.java
+++ b/kie-ci/src/main/java/org/drools/scanner/KieModuleMetaData.java
@@ -1,6 +1,6 @@
package org.drools.scanner;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import java.io.File;
import java.util.Collection;
@@ -14,8 +14,8 @@ public interface KieModuleMetaData {
Class<?> getClass(String pkgName, String className);
public static class Factory {
- public static KieModuleMetaData newKieModuleMetaData(GAV gav) {
- return new KieModuleMetaDataImpl(gav);
+ public static KieModuleMetaData newKieModuleMetaData(ReleaseId releaseId) {
+ return new KieModuleMetaDataImpl(releaseId);
}
public KieModuleMetaData newKieModuleMetaDataImpl(File pomFile) {
diff --git a/kie-ci/src/main/java/org/drools/scanner/KieModuleMetaDataImpl.java b/kie-ci/src/main/java/org/drools/scanner/KieModuleMetaDataImpl.java
index 10198b0c2f2..d437cd6600c 100644
--- a/kie-ci/src/main/java/org/drools/scanner/KieModuleMetaDataImpl.java
+++ b/kie-ci/src/main/java/org/drools/scanner/KieModuleMetaDataImpl.java
@@ -1,6 +1,6 @@
package org.drools.scanner;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.sonatype.aether.artifact.Artifact;
import java.io.File;
@@ -30,11 +30,11 @@ public class KieModuleMetaDataImpl implements KieModuleMetaData {
private URLClassLoader classLoader;
- private GAV gav;
+ private ReleaseId releaseId;
- public KieModuleMetaDataImpl(GAV gav) {
- this.artifactResolver = getResolverFor(gav, false);
- this.gav = gav;
+ public KieModuleMetaDataImpl(ReleaseId releaseId) {
+ this.artifactResolver = getResolverFor(releaseId, false);
+ this.releaseId = releaseId;
init();
}
@@ -77,8 +77,8 @@ private ClassLoader getClassLoader() {
}
private void init() {
- if (gav != null) {
- addArtifact(artifactResolver.resolveArtifact(gav.toString()));
+ if (releaseId != null) {
+ addArtifact(artifactResolver.resolveArtifact(releaseId.toString()));
}
for (DependencyDescriptor dep : artifactResolver.getAllDependecies()) {
addArtifact(artifactResolver.resolveArtifact(dep.toString()));
diff --git a/kie-ci/src/main/java/org/drools/scanner/KieRepositoryScannerImpl.java b/kie-ci/src/main/java/org/drools/scanner/KieRepositoryScannerImpl.java
index 0d8164831f5..c153caa0d26 100644
--- a/kie-ci/src/main/java/org/drools/scanner/KieRepositoryScannerImpl.java
+++ b/kie-ci/src/main/java/org/drools/scanner/KieRepositoryScannerImpl.java
@@ -1,7 +1,7 @@
package org.drools.scanner;
import org.drools.kproject.models.KieModuleModelImpl;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieModule;
import org.kie.builder.KieScanner;
import org.kie.builder.Message;
@@ -44,12 +44,12 @@ public class KieRepositoryScannerImpl implements InternalKieScanner {
public void setKieContainer(KieContainer kieContainer) {
this.kieContainer = kieContainer;
- DependencyDescriptor projectDescr = new DependencyDescriptor(kieContainer.getGAV());
+ DependencyDescriptor projectDescr = new DependencyDescriptor(kieContainer.getReleaseId());
if (!projectDescr.isFixedVersion()) {
usedDependencies.add(projectDescr);
}
- artifactResolver = getResolverFor(kieContainer.getGAV(), true);
+ artifactResolver = getResolverFor(kieContainer.getReleaseId(), true);
init();
}
@@ -70,27 +70,27 @@ private void init() {
indexAtifacts(artifacts);
}
- public KieModule loadArtifact(GAV gav) {
- String artifactName = gav.toString();
+ public KieModule loadArtifact(ReleaseId releaseId) {
+ String artifactName = releaseId.toString();
Artifact artifact = getArtifactResolver().resolveArtifact(artifactName);
- return artifact != null ? buildArtifact(gav, artifact) : loadPomArtifact(gav);
+ return artifact != null ? buildArtifact(releaseId, artifact) : loadPomArtifact(releaseId);
}
- private KieModule loadPomArtifact(GAV gav) {
- ArtifactResolver resolver = getResolverFor(gav, false);
+ private KieModule loadPomArtifact(ReleaseId releaseId) {
+ ArtifactResolver resolver = getResolverFor(releaseId, false);
if (resolver == null) {
return null;
}
- MemoryKieModule kieModule = new MemoryKieModule(gav);
+ MemoryKieModule kieModule = new MemoryKieModule(releaseId);
addDependencies(kieModule, resolver, resolver.getPomDirectDependencies());
build(kieModule);
return kieModule;
}
- private InternalKieModule buildArtifact(GAV gav, Artifact artifact) {
+ private InternalKieModule buildArtifact(ReleaseId releaseId, Artifact artifact) {
ArtifactResolver resolver = getArtifactResolver();
- ZipKieModule kieModule = new ZipKieModule(gav, artifact.getFile());
+ ZipKieModule kieModule = new ZipKieModule(releaseId, artifact.getFile());
addDependencies(kieModule, resolver, resolver.getArtifactDependecies(new DependencyDescriptor(artifact).toString()));
build(kieModule);
return kieModule;
@@ -100,8 +100,8 @@ private void addDependencies(InternalKieModule kieModule, ArtifactResolver resol
for (DependencyDescriptor dep : dependencies) {
Artifact depArtifact = resolver.resolveArtifact(dep.toString());
if (isKJar(depArtifact.getFile())) {
- GAV depGav = new DependencyDescriptor(depArtifact).getGav();
- kieModule.addDependency(new ZipKieModule(depGav, depArtifact.getFile()));
+ ReleaseId depReleaseId = new DependencyDescriptor(depArtifact).getGav();
+ kieModule.addDependency(new ZipKieModule(depReleaseId, depArtifact.getFile()));
}
}
}
@@ -154,11 +154,11 @@ public void scanNow() {
log.info("The following artifacts have been updated: " + updatedArtifacts);
}
- private void updateKieModule(Artifact artifact, GAV gav) {
- ZipKieModule kieModule = new ZipKieModule(gav, artifact.getFile());
+ private void updateKieModule(Artifact artifact, ReleaseId releaseId) {
+ ZipKieModule kieModule = new ZipKieModule(releaseId, artifact.getFile());
ResultsImpl messages = build(kieModule);
if ( messages.filterMessages(Message.Level.ERROR).isEmpty()) {
- kieContainer.updateToVersion(gav);
+ kieContainer.updateToVersion(releaseId);
}
}
diff --git a/kie-ci/src/main/java/org/drools/scanner/MavenRepository.java b/kie-ci/src/main/java/org/drools/scanner/MavenRepository.java
index 65dc36eac36..37035e3a1ca 100644
--- a/kie-ci/src/main/java/org/drools/scanner/MavenRepository.java
+++ b/kie-ci/src/main/java/org/drools/scanner/MavenRepository.java
@@ -1,7 +1,7 @@
package org.drools.scanner;
import org.apache.maven.project.MavenProject;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.impl.InternalKieModule;
import org.sonatype.aether.artifact.Artifact;
import org.sonatype.aether.collection.CollectRequest;
@@ -85,8 +85,8 @@ public Artifact resolveArtifact(String artifactName) {
return artifactResult.getArtifact();
}
- public void deployArtifact(GAV gav, InternalKieModule kieModule, File pomfile) {
- File jarFile = new File( System.getProperty( "java.io.tmpdir" ), gav + ".jar");
+ public void deployArtifact(ReleaseId releaseId, InternalKieModule kieModule, File pomfile) {
+ File jarFile = new File( System.getProperty( "java.io.tmpdir" ), releaseId + ".jar");
try {
FileOutputStream fos = new FileOutputStream(jarFile);
fos.write(kieModule.getBytes());
@@ -95,11 +95,11 @@ public void deployArtifact(GAV gav, InternalKieModule kieModule, File pomfile) {
} catch (IOException e) {
throw new RuntimeException(e);
}
- deployArtifact(gav, jarFile, pomfile);
+ deployArtifact(releaseId, jarFile, pomfile);
}
- public void deployArtifact(GAV gav, File jar, File pomfile) {
- Artifact jarArtifact = new DefaultArtifact( gav.getGroupId(), gav.getArtifactId(), "jar", gav.getVersion() );
+ public void deployArtifact(ReleaseId releaseId, File jar, File pomfile) {
+ Artifact jarArtifact = new DefaultArtifact( releaseId.getGroupId(), releaseId.getArtifactId(), "jar", releaseId.getVersion() );
jarArtifact = jarArtifact.setFile( jar );
Artifact pomArtifact = new SubArtifact( jarArtifact, "", "pom" );
diff --git a/kie-ci/src/test/java/org/drools/scanner/KieModuleMetaDataTest.java b/kie-ci/src/test/java/org/drools/scanner/KieModuleMetaDataTest.java
index 563f7292448..f64be1188ed 100644
--- a/kie-ci/src/test/java/org/drools/scanner/KieModuleMetaDataTest.java
+++ b/kie-ci/src/test/java/org/drools/scanner/KieModuleMetaDataTest.java
@@ -2,7 +2,7 @@
import org.junit.Ignore;
import org.junit.Test;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.KieServices;
import static junit.framework.Assert.assertEquals;
@@ -12,8 +12,8 @@ public class KieModuleMetaDataTest {
@Test @Ignore
public void testKScanner() throws Exception {
- GAV gav = KieServices.Factory.get().newGav("org.drools", "drools-core", "5.5.0.Final");
- KieModuleMetaData kieModuleMetaData = KieModuleMetaData.Factory.newKieModuleMetaData(gav);
+ ReleaseId releaseId = KieServices.Factory.get().newReleaseId("org.drools", "drools-core", "5.5.0.Final");
+ KieModuleMetaData kieModuleMetaData = KieModuleMetaData.Factory.newKieModuleMetaData(releaseId);
assertEquals(17, kieModuleMetaData.getClasses("org.drools.runtime").size());
diff --git a/kie-ci/src/test/java/org/drools/scanner/KieRepositoryScannerTest.java b/kie-ci/src/test/java/org/drools/scanner/KieRepositoryScannerTest.java
index 1cfdb9aa6a9..5fc70cb6fd3 100644
--- a/kie-ci/src/test/java/org/drools/scanner/KieRepositoryScannerTest.java
+++ b/kie-ci/src/test/java/org/drools/scanner/KieRepositoryScannerTest.java
@@ -6,7 +6,7 @@
import org.junit.Ignore;
import org.junit.Test;
import org.kie.KieServices;
-import org.kie.builder.GAV;
+import org.kie.builder.ReleaseId;
import org.kie.builder.KieBaseModel;
import org.kie.builder.KieBuilder;
import org.kie.builder.KieFileSystem;
@@ -39,8 +39,8 @@ public class KieRepositoryScannerTest {
public void setUp() throws Exception {
this.fileManager = new FileManager();
this.fileManager.setUp();
- GAV gav = KieServices.Factory.get().newGav("org.kie", "scanner-test", "1.0-SNAPSHOT");
- kPom = createKPom(gav);
+ ReleaseId releaseId = KieServices.Factory.get().newReleaseId("org.kie", "scanner-test", "1.0-SNAPSHOT");
+ kPom = createKPom(releaseId);
}
@After
@@ -57,23 +57,23 @@ private void resetFileManager() {
@Test @Ignore
public void testKScanner() throws Exception {
KieServices ks = KieServices.Factory.get();
- GAV gav = ks.newGav("org.kie", "scanner-test", "1.0-SNAPSHOT");
+ ReleaseId releaseId = ks.newReleaseId("org.kie", "scanner-test", "1.0-SNAPSHOT");
- InternalKieModule kJar1 = createKieJar(ks, gav, "rule1", "rule2");
- KieContainer kieContainer = ks.newKieContainer(gav);
+ InternalKieModule kJar1 = createKieJar(ks, releaseId, "rule1", "rule2");
+ KieContainer kieContainer = ks.newKieContainer(releaseId);
MavenRepository repository = getMavenRepository();
- repository.deployArtifact(gav, kJar1, kPom);
+ repository.deployArtifact(releaseId, kJar1, kPom);
// create a ksesion and check it works as expected
KieSession ksession = kieContainer.newKieSession("KSession1");
checkKSession(ksession, "rule1", "rule2");
// create a new kjar
- InternalKieModule kJar2 = createKieJar(ks, gav, "rule2", "rule3");
+ InternalKieModule kJar2 = createKieJar(ks, releaseId, "rule2", "rule3");
// deploy it on maven
- repository.deployArtifact(gav, kJar2, kPom);
+ repository.deployArtifact(releaseId, kJar2, kPom);
// since I am not calling start() on the scanner it means it won't have automatic scheduled scanning
KieScanner scanner = ks.newKieScanner(kieContainer);
@@ -89,21 +89,21 @@ public void testKScanner() throws Exception {
@Test @Ignore
public void testKScannerWithKJarContainingClasses() throws Exception {
KieServices ks = KieServices.Factory.get();
- GAV gav = ks.newGav("org.kie", "scanner-test", "1.0-SNAPSHOT");
+ ReleaseId releaseId = ks.newReleaseId("org.kie", "scanner-test", "1.0-SNAPSHOT");
- InternalKieModule kJar1 = createKieJarWithClass(ks, gav, 2, 7);
+ InternalKieModule kJar1 = createKieJarWithClass(ks, releaseId, 2, 7);
MavenRepository repository = getMavenRepository();
- repository.deployArtifact(gav, kJar1, kPom);
+ repository.deployArtifact(releaseId, kJar1, kPom);
- KieContainer kieContainer = ks.newKieContainer(gav);
+ KieContainer kieContainer = ks.newKieContainer(releaseId);
KieScanner scanner = ks.newKieScanner(kieContainer);
KieSession ksession = kieContainer.newKieSession("KSession1");
checkKSession(ksession, 14);
- InternalKieModule kJar2 = createKieJarWithClass(ks, gav, 3, 5);
- repository.deployArtifact(gav, kJar2, kPom);
+ InternalKieModule kJar2 = createKieJarWithClass(ks, releaseId, 3, 5);
+ repository.deployArtifact(releaseId, kJar2, kPom);
scanner.scanNow();
@@ -116,7 +116,7 @@ public void testLoadKieJarFromMavenRepo() throws Exception {
// This test depends from the former one (UGLY!) and must be run immediately after it
KieServices ks = KieServices.Factory.get();
- KieContainer kieContainer = ks.newKieContainer(ks.newGav("org.kie", "scanner-test", "1.0-SNAPSHOT"));
+ KieContainer kieContainer = ks.newKieContainer(ks.newReleaseId("org.kie", "scanner-test", "1.0-SNAPSHOT"));
KieSession ksession2 = kieContainer.newKieSession("KSession1");
checkKSession(ksession2, 15);
@@ -125,25 +125,25 @@ public void testLoadKieJarFromMavenRepo() throws Exception {
@Test @Ignore
public void testScannerOnPomProject() throws Exception {
KieServices ks = KieServices.Factory.get();
- GAV gav1 = ks.newGav("org.kie", "scanner-test", "1.0");
- GAV gav2 = ks.newGav("org.kie", "scanner-test", "2.0");
+ ReleaseId releaseId1 = ks.newReleaseId("org.kie", "scanner-test", "1.0");
+ ReleaseId releaseId2 = ks.newReleaseId("org.kie", "scanner-test", "2.0");
MavenRepository repository = getMavenRepository();
repository.deployPomArtifact("org.kie", "scanner-master-test", "1.0", createMasterKPom());
resetFileManager();
- InternalKieModule kJar1 = createKieJarWithClass(ks, gav1, 2, 7);
- repository.deployArtifact(gav1, kJar1, createKPom(gav1));
+ InternalKieModule kJar1 = createKieJarWithClass(ks, releaseId1, 2, 7);
+ repository.deployArtifact(releaseId1, kJar1, createKPom(releaseId1));
- KieContainer kieContainer = ks.newKieContainer(ks.newGav("org.kie", "scanner-master-test", "LATEST"));
+ KieContainer kieContainer = ks.newKieContainer(ks.newReleaseId("org.kie", "scanner-master-test", "LATEST"));
KieSession ksession = kieContainer.newKieSession("KSession1");
checkKSession(ksession, 14);
KieScanner scanner = ks.newKieScanner(kieContainer);
- InternalKieModule kJar2 = createKieJarWithClass(ks, gav2, 3, 5);
- repository.deployArtifact(gav2, kJar2, createKPom(gav1));
+ InternalKieModule kJar2 = createKieJarWithClass(ks, releaseId2, 3, 5);
+ repository.deployArtifact(releaseId2, kJar2, createKPom(releaseId1));
scanner.scanNow();
@@ -151,21 +151,21 @@ public void testScannerOnPomProject() throws Exception {
checkKSession(ksession2, 15);
}
- private File createKPom(GAV gav) throws IOException {
+ private File createKPom(ReleaseId releaseId) throws IOException {
File pomFile = fileManager.newFile("pom.xml");
- fileManager.write(pomFile, getPom(gav));
+ fileManager.write(pomFile, getPom(releaseId));
return pomFile;
}
- private String getPom(GAV gav) {
+ private String getPom(ReleaseId releaseId) {
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
"\n" +
- " <groupId>" + gav.getGroupId() + "</groupId>\n" +
- " <artifactId>" + gav.getArtifactId() + "</artifactId>\n" +
- " <version>" + gav.getVersion() + "</version>\n" +
+ " <groupId>" + releaseId.getGroupId() + "</groupId>\n" +
+ " <artifactId>" + releaseId.getArtifactId() + "</artifactId>\n" +
+ " <version>" + releaseId.getVersion() + "</version>\n" +
"\n" +
"</project>";
}
@@ -196,7 +196,7 @@ private File createMasterKPom() throws IOException {
return pomFile;
}
- private InternalKieModule createKieJar(KieServices ks, GAV gav, String... rules) throws IOException {
+ private InternalKieModule createKieJar(KieServices ks, ReleaseId releaseId, String... rules) throws IOException {
KieFileSystem kfs = ks.newKieFileSystem();
for (String rule : rules) {
String file = "org/test/" + rule + ".drl";
@@ -214,7 +214,7 @@ private InternalKieModule createKieJar(KieServices ks, GAV gav, String... rules)
.setClockType( ClockTypeOption.get("realtime") );
kfs.writeKModuleXML(kproj.toXML());
- kfs.writePomXML( getPom(gav) );
+ kfs.writePomXML( getPom(releaseId) );
KieBuilder kieBuilder = ks.newKieBuilder(kfs);
assertTrue(kieBuilder.buildAll().getResults().getMessages().isEmpty());
@@ -243,7 +243,7 @@ private void checkKSession(KieSession ksession, Object... results) {
}
}
- private InternalKieModule createKieJarWithClass(KieServices ks, GAV gav, int value, int factor) throws IOException {
+ private InternalKieModule createKieJarWithClass(KieServices ks, ReleaseId releaseId, int value, int factor) throws IOException {
KieFileSystem kieFileSystem = ks.newKieFileSystem();
KieModuleModel kproj = ks.newKieModuleModel();
@@ -258,7 +258,7 @@ private InternalKieModule createKieJarWithClass(KieServices ks, GAV gav, int val
kieFileSystem
.writeKModuleXML(kproj.toXML())
- .writePomXML(getPom(gav))
+ .writePomXML(getPom(releaseId))
.write("src/main/resources/" + kieBaseModel1.getName() + "/rule1.drl", createDRLForJavaSource(value))
.write("src/main/java/org/kie/test/Bean.java", createJavaSource(factor));
|
62a5d99c731b3ad33f4657f1ad6b9bac90fb4203
|
Mylyn Reviews
|
317535: Dynamically add parts to any part (319357)
added a prototype for marking tasks as reviews (see bug 317867)
added PartAdvisor implementation which removes uninteresting parts from the task editor and adds the review part
added a ReviewDataManager, which keeps the review data in-memory
|
a
|
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
|
diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewConstants.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewConstants.java
index 0d56af59..704be905 100644
--- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewConstants.java
+++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewConstants.java
@@ -18,4 +18,8 @@ public class ReviewConstants {
public static final String REVIEW_DATA_CONTAINER = "review-data.zip";
public static final String REVIEW_DATA_FILE = "reviews-data.xml";
+
+ public static final String ATTR_CACHED_REVIEW = "review";
+
+ public static final String ATTR_REVIEW_FLAG = "isReview";
}
diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewData.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewData.java
new file mode 100644
index 00000000..5d51f5af
--- /dev/null
+++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewData.java
@@ -0,0 +1,41 @@
+package org.eclipse.mylyn.reviews.core;
+
+import org.eclipse.mylyn.reviews.core.model.review.Review;
+import org.eclipse.mylyn.tasks.core.ITask;
+
+public class ReviewData {
+ private boolean outgoing;
+ private Review review;
+ private ITask task;
+
+ public ReviewData(ITask task, Review review) {
+ this.task=task;
+ this.review = review;
+ }
+
+ public boolean isOutgoing() {
+ return outgoing;
+ }
+
+ public void setOutgoing() {
+ this.outgoing = true;
+ }
+
+ public void setOutgoing(boolean outgoing) {
+ this.outgoing = outgoing;
+ }
+
+ public ITask getTask() {
+ return task;
+ }
+
+ public Review getReview() {
+ return review;
+ }
+
+ public Object getModificationDate() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataManager.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataManager.java
new file mode 100644
index 00000000..f6938555
--- /dev/null
+++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataManager.java
@@ -0,0 +1,32 @@
+package org.eclipse.mylyn.reviews.core;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.eclipse.mylyn.internal.provisional.tasks.core.TasksUtil;
+import org.eclipse.mylyn.internal.tasks.core.LocalTask;
+import org.eclipse.mylyn.reviews.core.model.review.Review;
+import org.eclipse.mylyn.tasks.core.ITask;
+import org.eclipse.mylyn.tasks.core.data.TaskData;
+
+public class ReviewDataManager {
+ private Map<ITask, ReviewData> cached = new HashMap<ITask, ReviewData>();
+
+ public void storeOutgoingTask(ITask task, Review review) {
+ ReviewData reviewData = new ReviewData(task, review);
+ reviewData.setOutgoing();
+ cached.put(task, reviewData);
+ }
+
+ public ReviewData getReviewData(ITask task) {
+ if (task == null)
+ return null;
+ return cached.get(task);
+ }
+
+ public void storeTask(ITask task, Review review) {
+ ReviewData reviewData = new ReviewData(task, review);
+ cached.put(task, reviewData);
+ }
+
+}
diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataStore.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataStore.java
new file mode 100644
index 00000000..7a8b715b
--- /dev/null
+++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataStore.java
@@ -0,0 +1,102 @@
+package org.eclipse.mylyn.reviews.core;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+import java.util.zip.ZipOutputStream;
+
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.resource.ResourceSet;
+import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
+import org.eclipse.mylyn.reviews.core.model.review.Review;
+import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
+
+public class ReviewDataStore {
+
+ private String storeRootDir;
+
+ public ReviewDataStore(String storeRootDir) {
+ this.storeRootDir = storeRootDir;
+ }
+
+ public void storeReviewData(String repositoryUrl, String taskId,
+ Review review, String id) {
+ try {
+
+ File file = getFile(repositoryUrl, taskId);
+ createDirectoriesIfNecessary(file);
+ if (!file.exists()) {
+ file.createNewFile();
+ ZipOutputStream outputStream = new ZipOutputStream(
+ new FileOutputStream(file));
+ ResourceSet resourceSet = new ResourceSetImpl();
+
+ Resource resource = resourceSet.createResource(URI
+ .createFileURI("")); //$NON-NLS-1$
+
+ resource.getContents().add(review);
+ resource.getContents().add(review.getScope().get(0));
+ if (review.getResult() != null)
+ resource.getContents().add(review.getResult());
+
+ outputStream.putNextEntry(new ZipEntry(id));
+ resource.save(outputStream, null);
+ outputStream.closeEntry();
+ outputStream.close();
+ } else {
+ // TODO append
+
+ }
+ } catch (Exception e) {
+ // TODO: handle exception
+ e.printStackTrace();
+ }
+ }
+
+ private void createDirectoriesIfNecessary(File file) {
+ File parent = file.getParentFile();
+ if(!parent.exists()) {
+ parent.mkdirs();
+ }
+ }
+
+ public List<Review> loadReviewData(String repositoryUrl, String taskId) {
+ List<Review> reviews = new ArrayList<Review>();
+ try {
+
+ File file = getFile(repositoryUrl, taskId);
+ ZipInputStream inputStream = new ZipInputStream(
+ new FileInputStream(file));
+ inputStream.getNextEntry();
+ ResourceSet resourceSet = new ResourceSetImpl();
+ resourceSet.getPackageRegistry().put(ReviewPackage.eNS_URI,
+ ReviewPackage.eINSTANCE);
+ Resource resource = resourceSet.createResource(URI.createURI(""));
+ resource.load(inputStream, null);
+ for (EObject item : resource.getContents()) {
+ if (item instanceof Review) {
+ Review review = (Review) item;
+ reviews.add(review);
+ }
+ }
+ } catch (Exception e) {
+ // TODO: handle exception
+ e.printStackTrace();
+ }
+ return reviews;
+ }
+
+ private File getFile(String repositoryUrl, String taskId) {
+ File path = new File(storeRootDir + File.separator + "reviews"
+ + File.separator + URLEncoder.encode(repositoryUrl)
+ + File.separator);
+ return new File(path, taskId);
+ }
+}
diff --git a/org.eclipse.mylyn.reviews.ui/META-INF/MANIFEST.MF b/org.eclipse.mylyn.reviews.ui/META-INF/MANIFEST.MF
index c9787808..815e29e9 100644
--- a/org.eclipse.mylyn.reviews.ui/META-INF/MANIFEST.MF
+++ b/org.eclipse.mylyn.reviews.ui/META-INF/MANIFEST.MF
@@ -6,7 +6,7 @@ Bundle-Version: 0.0.1
Bundle-Activator: org.eclipse.mylyn.reviews.ui.ReviewsUiPlugin
Require-Bundle: org.eclipse.ui,
org.eclipse.core.runtime,
- org.eclipse.mylyn.tasks.ui;bundle-version="3.3.0",
+ org.eclipse.mylyn.tasks.ui;bundle-version="3.5.0",
org.eclipse.ui.forms;bundle-version="3.4.1",
org.eclipse.mylyn.tasks.core;bundle-version="3.3.0",
org.eclipse.compare;bundle-version="3.5.0",
diff --git a/org.eclipse.mylyn.reviews.ui/plugin.xml b/org.eclipse.mylyn.reviews.ui/plugin.xml
index 32061672..c4691453 100644
--- a/org.eclipse.mylyn.reviews.ui/plugin.xml
+++ b/org.eclipse.mylyn.reviews.ui/plugin.xml
@@ -17,10 +17,6 @@
class="org.eclipse.mylyn.reviews.ui.editors.CreateReviewTaskEditorPageFactory"
id="org.eclipse.mylyn.reviews.ui.pageFactory">
</pageFactory>
- <pageFactory
- class="org.eclipse.mylyn.reviews.ui.ReviewTaskEditorPageFactory"
- id="org.eclipse.mylyn.reviews.ui.reviewPageFactory">
- </pageFactory>
</extension>
<extension
point="org.eclipse.ui.editors">
@@ -46,5 +42,17 @@
</action>
</objectContribution>
</extension>
+ <extension
+ point="org.eclipse.mylyn.tasks.ui.taskEditorPageContribution">
+ <repositoryPart
+ class="org.eclipse.mylyn.reviews.ui.editors.ReviewTaskEditorPart"
+ id="org.eclipse.mylyn.reviews.ui.reviewPart"
+ path="attachments">
+ </repositoryPart>
+ <partAdvisor
+ class="org.eclipse.mylyn.reviews.ui.editors.ReviewTaskEditorPartAdvisor"
+ id="org.eclipse.mylyn.reviews.ui.reviewPart">
+ </partAdvisor>
+ </extension>
</plugin>
diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewTaskEditorPageFactory.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewTaskEditorPageFactory.java
deleted file mode 100644
index d4f71a90..00000000
--- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewTaskEditorPageFactory.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- *******************************************************************************/
-package org.eclipse.mylyn.reviews.ui;
-
-import java.util.List;
-
-import org.eclipse.mylyn.internal.tasks.core.RepositoryModel;
-import org.eclipse.mylyn.reviews.core.ReviewConstants;
-import org.eclipse.mylyn.reviews.ui.editors.ReviewTaskEditorPage;
-import org.eclipse.mylyn.tasks.core.ITask;
-import org.eclipse.mylyn.tasks.core.ITaskAttachment;
-import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
-import org.eclipse.mylyn.tasks.core.data.TaskData;
-import org.eclipse.mylyn.tasks.ui.TasksUi;
-import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPageFactory;
-import org.eclipse.mylyn.tasks.ui.editors.TaskEditor;
-import org.eclipse.mylyn.tasks.ui.editors.TaskEditorInput;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.forms.editor.IFormPage;
-
-/*
- * @author Kilian Matt
- */
-public class ReviewTaskEditorPageFactory extends AbstractTaskEditorPageFactory {
-
- @Override
- public boolean canCreatePageFor(TaskEditorInput input) {
- ITask task = input.getTask();
- try {
-
- TaskData taskData = TasksUi.getTaskDataManager().getTaskData(task);
- if (taskData != null) {
- List<TaskAttribute> attributesByType = taskData
- .getAttributeMapper().getAttributesByType(taskData,
- TaskAttribute.TYPE_ATTACHMENT);
- for (TaskAttribute attribute : attributesByType) {
- ITaskAttachment taskAttachment = ((RepositoryModel)TasksUi.getRepositoryModel()).createTaskAttachment(attribute);
- taskData.getAttributeMapper().updateTaskAttachment(
- taskAttachment, attribute);
- if (taskAttachment.getFileName().equals(
- ReviewConstants.REVIEW_DATA_CONTAINER))
- return true;
-
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return false;
- }
-
- @Override
- public IFormPage createPage(TaskEditor parentEditor) {
- return new ReviewTaskEditorPage(parentEditor);
- }
-
- @Override
- public Image getPageImage() {
- return Images.SMALL_ICON.createImage();
- }
-
- @Override
- public String getPageText() {
- return Messages.ReviewTaskEditorPageFactory_PageTitle;
- }
-
- @Override
- public int getPriority() {
- return PRIORITY_ADDITIONS;
- }
-
- @Override
- public String[] getConflictingIds(TaskEditorInput input) {
- return new String[] { "org.eclipse.mylyn.bugzilla.ui.pageFactory" };
- }
-}
diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewsUiPlugin.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewsUiPlugin.java
index 6c04acbb..ec4a177f 100644
--- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewsUiPlugin.java
+++ b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewsUiPlugin.java
@@ -10,11 +10,13 @@
*******************************************************************************/
package org.eclipse.mylyn.reviews.ui;
+import org.eclipse.mylyn.reviews.core.ReviewDataManager;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
+ *
* @author Kilian Matt
*/
public class ReviewsUiPlugin extends AbstractUIPlugin {
@@ -25,6 +27,8 @@ public class ReviewsUiPlugin extends AbstractUIPlugin {
// The shared instance
private static ReviewsUiPlugin plugin;
+ private static ReviewDataManager reviewDataManager;
+
/**
* The constructor
*/
@@ -66,4 +70,11 @@ public static ReviewsUiPlugin getDefault() {
return plugin;
}
+ public static ReviewDataManager getDataManager() {
+ if (reviewDataManager == null) {
+ reviewDataManager = new ReviewDataManager();
+ }
+ return reviewDataManager;
+ }
+
}
diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/DelegateReviewTaskEditorPart.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/DelegateReviewTaskEditorPart.java
deleted file mode 100644
index 804d3c84..00000000
--- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/DelegateReviewTaskEditorPart.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- *******************************************************************************/
-package org.eclipse.mylyn.reviews.ui.editors;
-
-import org.eclipse.jface.viewers.ArrayContentProvider;
-import org.eclipse.jface.viewers.ComboViewer;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.mylyn.internal.tasks.ui.editors.EditorUtil;
-import org.eclipse.mylyn.reviews.core.model.review.Rating;
-import org.eclipse.mylyn.reviews.core.model.review.Review;
-import org.eclipse.mylyn.reviews.core.model.review.ReviewFactory;
-import org.eclipse.mylyn.reviews.ui.Images;
-import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.IFormColors;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.Section;
-
-/*
- * @author Kilian Matt
- */
-public class DelegateReviewTaskEditorPart extends AbstractTaskEditorPart {
- public static final String ID_PART_REVIEW = "org.eclipse.mylyn.reviews.ui.editors.DelegateReviewTaskEditorPart"; //$NON-NLS-1$
-
- public DelegateReviewTaskEditorPart() {
- setPartName("Review");
- }
-
- @Override
- public void createControl(Composite parent, FormToolkit toolkit) {
-
- Section section = createSection(parent, toolkit, true);
- EditorUtil.setTitleBarForeground(section,
- toolkit.getColors().getColor(IFormColors.TITLE));
-
- GridLayout gl = new GridLayout();
- GridData gd = new GridData(SWT.FILL, SWT.NONE, false, false);
- gd.horizontalSpan = 4;
- section.setLayout(gl);
- section.setLayoutData(gd);
-
- Composite composite = toolkit.createComposite(section);
- GridLayout layout = new GridLayout(2, false);
- layout.marginWidth = 5;
- composite.setLayout(layout);
-
- Composite resultComposite = toolkit.createComposite(composite);
- resultComposite.setLayoutData(new GridData(SWT.FILL, SWT.DEFAULT, true, false));
- resultComposite.setLayout(new GridLayout(2, false));
- final ComboViewer ratingList = new ComboViewer(resultComposite,
- SWT.READ_ONLY | SWT.BORDER | SWT.FLAT);
- ratingList.setContentProvider(ArrayContentProvider.getInstance());
-
- ratingList.setLabelProvider(new LabelProvider() {
- @Override
- public String getText(Object element) {
- // TODO externalize string
- return ((Rating) element).getName();
- }
-
- @Override
- public Image getImage(Object element) {
- Rating rating = ((Rating) element);
- switch (rating) {
- case FAILED:
- return Images.REVIEW_RESULT_FAILED.createImage();
- case NONE:
- return Images.REVIEW_RESULT_NONE.createImage();
- case PASSED:
- return Images.REVIEW_RESULT_PASSED.createImage();
- case WARNING:
- return Images.REVIEW_RESULT_WARNING.createImage();
- }
- return super.getImage(element);
- }
- });
- ratingList.setInput(Rating.VALUES);
- ratingList.getControl().setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
- final Text commentText = toolkit.createText(resultComposite, "",
- SWT.BORDER|SWT.MULTI);
- gd=new GridData(SWT.FILL, SWT.DEFAULT, true,
- false);
- gd.heightHint=30;
- commentText.setLayoutData(gd);
-
- Review review = getTaskEditorPage().getReview();
- if (review.getResult() != null) {
- Rating rating = review.getResult().getRating();
- ratingList.setSelection(new StructuredSelection(rating));
- commentText.setText(review.getResult().getText());
- }
- commentText.addModifyListener(new ModifyListener() {
-
- public void modifyText(ModifyEvent e) {
- getTaskEditorPage().setDirty();
- Review review = getTaskEditorPage().getReview();
- if (review.getResult() == null) {
- review.setResult(ReviewFactory.eINSTANCE
- .createReviewResult());
- }
- review.getResult().setText(commentText.getText());
- }
- });
- ratingList.addSelectionChangedListener(new ISelectionChangedListener() {
-
- public void selectionChanged(SelectionChangedEvent event) {
- getTaskEditorPage().setDirty();
- Rating rating = (Rating) ((IStructuredSelection) event
- .getSelection()).getFirstElement();
- Review review = getTaskEditorPage().getReview();
- if (review.getResult() == null) {
- review.setResult(ReviewFactory.eINSTANCE
- .createReviewResult());
- }
- review.getResult().setRating(rating);
- }
- });
-
- toolkit.paintBordersFor(composite);
- section.setClient(composite);
- setSection(toolkit, section);
- }
-
- @Override
- public ReviewTaskEditorPage getTaskEditorPage() {
- return (ReviewTaskEditorPage) super.getTaskEditorPage();
- }
-}
diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPage.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPage.java
deleted file mode 100644
index 1f8e787f..00000000
--- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPage.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- *******************************************************************************/
-package org.eclipse.mylyn.reviews.ui.editors;
-
-import java.io.ByteArrayOutputStream;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipOutputStream;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.emf.common.util.URI;
-import org.eclipse.emf.ecore.resource.Resource;
-import org.eclipse.emf.ecore.resource.ResourceSet;
-import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.mylyn.internal.bugzilla.ui.editor.BugzillaTaskEditorPage;
-import org.eclipse.mylyn.internal.provisional.tasks.core.TasksUtil;
-import org.eclipse.mylyn.internal.tasks.ui.editors.ToolBarButtonContribution;
-import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal;
-import org.eclipse.mylyn.reviews.core.ReviewConstants;
-import org.eclipse.mylyn.reviews.core.ReviewsUtil;
-import org.eclipse.mylyn.reviews.core.model.review.Review;
-import org.eclipse.mylyn.reviews.ui.Images;
-import org.eclipse.mylyn.reviews.ui.ReviewCommentTaskAttachmentSource;
-import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
-import org.eclipse.mylyn.tasks.core.TaskRepository;
-import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
-import org.eclipse.mylyn.tasks.core.data.TaskData;
-import org.eclipse.mylyn.tasks.core.data.TaskDataModel;
-import org.eclipse.mylyn.tasks.core.sync.SubmitJob;
-import org.eclipse.mylyn.tasks.ui.TasksUi;
-import org.eclipse.mylyn.tasks.ui.TasksUiUtil;
-import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPage;
-import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart;
-import org.eclipse.mylyn.tasks.ui.editors.TaskEditor;
-import org.eclipse.mylyn.tasks.ui.editors.TaskEditorPartDescriptor;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Listener;
-
-/*
- * @author Kilian Matt
- */
-public class ReviewTaskEditorPage extends BugzillaTaskEditorPage {
- private static final String PAGE_ID = "org.eclipse.mylyn.reviews.ui.editors.ReviewTaskEditorPage"; //$NON-NLS-1$
- private Review review;
- private boolean dirty;
-
- public ReviewTaskEditorPage(TaskEditor editor) {
- super(editor);
- }
-
- @Override
- protected Set<TaskEditorPartDescriptor> createPartDescriptors() {
- Set<TaskEditorPartDescriptor> originalTaskDescriptors = super
- .createPartDescriptors();
- Set<TaskEditorPartDescriptor> taskDescriptors = new HashSet<TaskEditorPartDescriptor>();
- List<String> blockedPaths = Arrays.asList(
- AbstractTaskEditorPage.PATH_ATTRIBUTES,
- AbstractTaskEditorPage.PATH_COMMENTS,
- AbstractTaskEditorPage.PATH_ATTACHMENTS,
- AbstractTaskEditorPage.PATH_PLANNING);
- for (TaskEditorPartDescriptor descriptor : originalTaskDescriptors) {
- if (!blockedPaths.contains(descriptor.getPath())) {
- taskDescriptors.add(descriptor);
- }
- }
- try {
- TaskData data = TasksUi.getTaskDataManager().getTaskData(getTask());
- if (data != null) {
- taskDescriptors.add(new TaskEditorPartDescriptor(
- DelegateReviewTaskEditorPart.ID_PART_REVIEW) {
- @Override
- public AbstractTaskEditorPart createPart() {
- return new DelegateReviewTaskEditorPart();
- }
-
- });
- taskDescriptors.add(new TaskEditorPartDescriptor(
- ReviewTaskEditorPart.ID_PART_REVIEW) {
- @Override
- public AbstractTaskEditorPart createPart() {
- return new ReviewTaskEditorPart();
- }
-
- });
- }
- } catch (CoreException e) {
- e.printStackTrace();
- }
-
- return taskDescriptors;
- }
-
- @Override
- public void doSubmit() {
- super.doSubmit();
- if (dirty) {
- TaskRepository taskRepository = getModel().getTaskRepository();
- AbstractRepositoryConnector connector = TasksUi
- .getRepositoryConnector(taskRepository.getConnectorKind());
-
- final TaskDataModel model = getModel();
- Review review = getReview();
- TaskAttribute attachmentAttribute = model.getTaskData()
- .getAttributeMapper()
- .createTaskAttachment(model.getTaskData());
-
- final byte[] attachmentBytes = createAttachment(model, review);
-
- ReviewCommentTaskAttachmentSource attachment = new ReviewCommentTaskAttachmentSource(
- attachmentBytes);
-
- if (connector != null) {
- TasksUiInternal
- .getJobFactory()
- .createSubmitTaskAttachmentJob(connector,
- model.getTaskRepository(), model.getTask(),
- attachment, "review result",
- attachmentAttribute).schedule();
- }
- dirty = false;
- }
- }
-
- private byte[] createAttachment(TaskDataModel model, Review review) {
- try {
- ResourceSet resourceSet = new ResourceSetImpl();
-
- Resource resource = resourceSet.createResource(URI
- .createFileURI("")); //$NON-NLS-1$
-
- resource.getContents().add(review);
- resource.getContents().add(review.getScope().get(0));
- if (review.getResult() != null)
- resource.getContents().add(review.getResult());
- ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
- ZipOutputStream outputStream = new ZipOutputStream(
- byteArrayOutputStream);
- outputStream.putNextEntry(new ZipEntry(
- ReviewConstants.REVIEW_DATA_FILE));
- resource.save(outputStream, null);
- outputStream.closeEntry();
- outputStream.close();
- return byteArrayOutputStream.toByteArray();
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException(e);
- }
-
- }
-
- @Override
- public void fillToolBar(IToolBarManager toolBarManager) {
- super.fillToolBar(toolBarManager);
- }
-
- public Review getReview() {
- if (review == null) {
- try {
- final TaskDataModel model = getModel();
- List<Review> reviews = ReviewsUtil.getReviewAttachmentFromTask(
- TasksUi.getTaskDataManager(),
- TasksUi.getRepositoryModel(), model.getTask());
-
- if (reviews.size() > 0) {
- review = reviews.get(0);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- return review;
- }
-
- public void setDirty() {
- this.dirty = true;
- }
-
- @Override
- public boolean isDirty() {
- return dirty || super.isDirty();
- }
-}
diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java
index 619a513d..0e174cba 100644
--- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java
+++ b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java
@@ -27,9 +27,11 @@
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.mylyn.reviews.core.ReviewData;
import org.eclipse.mylyn.reviews.core.model.review.Patch;
import org.eclipse.mylyn.reviews.ui.Images;
import org.eclipse.mylyn.reviews.ui.ReviewDiffModel;
+import org.eclipse.mylyn.reviews.ui.ReviewsUiPlugin;
import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
@@ -160,9 +162,7 @@ public void selectionChanged(SelectionChangedEvent event) {
}
}
});
-
- fileList.setInput((getTaskEditorPage().getReview().getScope().get(0)));
-
+ setInput();
CompareConfiguration configuration = new CompareConfiguration();
configuration.setLeftEditable(false);
configuration.setRightEditable(false);
@@ -190,16 +190,17 @@ public void selectionChanged(SelectionChangedEvent event) {
setSection(toolkit, section);
}
+ private void setInput() {
+ ReviewData rd = ReviewsUiPlugin.getDataManager().getReviewData(getModel().getTask());
+ if(rd!=null) {
+ fileList.setInput((rd.getReview().getScope().get(0)));
+ }
+ }
private DiffNode getDiffEditorNullInput() {
return new DiffNode(new DiffNode(SWT.LEFT),new DiffNode(SWT.RIGHT));
}
- @Override
- public ReviewTaskEditorPage getTaskEditorPage() {
- return (ReviewTaskEditorPage)super.getTaskEditorPage();
- }
-
private GridLayout createSectionClientLayout() {
GridLayout layout = new GridLayout(2,false);
layout.marginHeight = 0;
diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java
new file mode 100644
index 00000000..9144414c
--- /dev/null
+++ b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java
@@ -0,0 +1,52 @@
+package org.eclipse.mylyn.reviews.ui.editors;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.eclipse.mylyn.reviews.core.ReviewConstants;
+import org.eclipse.mylyn.reviews.core.ReviewDataManager;
+import org.eclipse.mylyn.reviews.ui.ReviewsUiPlugin;
+import org.eclipse.mylyn.tasks.core.ITask;
+import org.eclipse.mylyn.tasks.ui.TasksUiUtil;
+import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPage;
+import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart;
+import org.eclipse.mylyn.tasks.ui.editors.ITaskEditorPartDescriptorAdvisor;
+import org.eclipse.mylyn.tasks.ui.editors.TaskEditorPartDescriptor;
+
+public class ReviewTaskEditorPartAdvisor implements
+ ITaskEditorPartDescriptorAdvisor {
+
+ public boolean canCustomize(ITask task) {
+ boolean isReview = Boolean.parseBoolean(task.getAttribute(ReviewConstants.ATTR_REVIEW_FLAG));
+ return isReview;
+ }
+
+ public Set<String> getBlockingIds(ITask task) {
+ return Collections.emptySet();
+ }
+
+ public Set<String> getBlockingPaths(ITask task) {
+ Set<String> blockedPaths = new HashSet<String>();
+ blockedPaths.add(AbstractTaskEditorPage.PATH_ATTRIBUTES);
+ blockedPaths.add(AbstractTaskEditorPage.PATH_COMMENTS);
+ blockedPaths.add(AbstractTaskEditorPage.PATH_ATTACHMENTS);
+ blockedPaths.add(AbstractTaskEditorPage.PATH_PLANNING);
+
+ return blockedPaths;
+ }
+
+ public Set<TaskEditorPartDescriptor> getPartContributions(ITask task) {
+ Set<TaskEditorPartDescriptor> parts = new HashSet<TaskEditorPartDescriptor>();
+ parts.add(new TaskEditorPartDescriptor(
+ ReviewTaskEditorPart.ID_PART_REVIEW) {
+
+ @Override
+ public AbstractTaskEditorPart createPart() {
+ return new ReviewTaskEditorPart();
+ }
+ });
+ return parts;
+ }
+
+}
diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/wizard/CreateReviewWizard.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/wizard/CreateReviewWizard.java
index 2624732e..ede73888 100644
--- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/wizard/CreateReviewWizard.java
+++ b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/wizard/CreateReviewWizard.java
@@ -1,21 +1,27 @@
package org.eclipse.mylyn.reviews.ui.wizard;
import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.jobs.IJobChangeEvent;
-import org.eclipse.core.runtime.jobs.JobChangeAdapter;
+import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.wizard.Wizard;
+import org.eclipse.mylyn.internal.tasks.core.data.TaskDataManager;
+import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal;
+import org.eclipse.mylyn.reviews.core.ReviewConstants;
+import org.eclipse.mylyn.reviews.core.ReviewDataManager;
import org.eclipse.mylyn.reviews.core.model.review.Review;
import org.eclipse.mylyn.reviews.core.model.review.ReviewFactory;
import org.eclipse.mylyn.reviews.core.model.review.ScopeItem;
-import org.eclipse.mylyn.reviews.ui.CreateTask;
-import org.eclipse.mylyn.reviews.ui.ReviewStatus;
-import org.eclipse.mylyn.tasks.core.ITaskAttachment;
+import org.eclipse.mylyn.reviews.ui.ReviewsUiPlugin;
+import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
+import org.eclipse.mylyn.tasks.core.ITask;
+import org.eclipse.mylyn.tasks.core.ITaskMapping;
+import org.eclipse.mylyn.tasks.core.TaskRepository;
+import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
+import org.eclipse.mylyn.tasks.core.data.TaskData;
import org.eclipse.mylyn.tasks.core.data.TaskDataModel;
-import org.eclipse.mylyn.tasks.ui.TasksUi;
+import org.eclipse.mylyn.tasks.core.data.TaskMapper;
import org.eclipse.mylyn.tasks.ui.TasksUiUtil;
-import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.commands.Priority;
public class CreateReviewWizard extends Wizard {
@@ -52,38 +58,26 @@ public boolean performFinish() {
try {
Review review = ReviewFactory.eINSTANCE.createReview();
review.getScope().add(getScope());
-
- CreateTask createTask = new CreateTask(model, review,
- assignmentsPage.getReviewer());
-
- createTask.schedule();
- if (assignmentsPage.isOpenReviewOnFinish()) {
-
- createTask.addJobChangeListener(new JobChangeAdapter() {
- @Override
- public void done(IJobChangeEvent event) {
- super.done(event);
- IStatus result = event.getResult();
- if (result instanceof ReviewStatus) {
- final ReviewStatus reviewResult = (ReviewStatus) result;
- Display.getDefault().asyncExec(new Runnable() {
-
- public void run() {
- TasksUiInternal.synchronizeTaskInBackground(
- TasksUi.getRepositoryConnector(reviewResult
- .getTask()
- .getConnectorKind()),
- reviewResult.getTask());
- // TODO
- TasksUiUtil.openTask(reviewResult.getTask());
-
- }
- });
-
- }
- }
- });
- }
+ TaskRepository taskRepository=model.getTaskRepository();
+ ITask newTask = TasksUiUtil.createOutgoingNewTask(taskRepository.getConnectorKind(), taskRepository.getRepositoryUrl());
+
+ newTask.setAttribute(ReviewConstants.ATTR_REVIEW_FLAG, Boolean.TRUE.toString());
+ TaskMapper initializationData=new TaskMapper(model.getTaskData());
+ TaskData taskData = TasksUiInternal.createTaskData(taskRepository, initializationData, null,
+ new NullProgressMonitor());
+ AbstractRepositoryConnector connector=TasksUiPlugin.getConnector(taskRepository.getConnectorKind());
+ connector.getTaskDataHandler().initializeSubTaskData(
+ taskRepository, taskData, model.getTaskData(),
+ new NullProgressMonitor());
+ String reviewer = assignmentsPage.getReviewer();
+
+ taskData.getRoot().getMappedAttribute(TaskAttribute.SUMMARY).setValue("Review of " + model.getTask().getSummary());
+ taskData.getRoot().getMappedAttribute(TaskAttribute.USER_ASSIGNED).setValue(reviewer);
+
+ ReviewsUiPlugin.getDataManager().storeOutgoingTask(newTask, review);
+
+
+ TasksUiInternal.createAndOpenNewTask(newTask, taskData);
} catch (CoreException e1) {
throw new RuntimeException(e1);
}
@@ -103,4 +97,10 @@ public TaskDataModel getModel() {
return model;
}
+
+ private TaskAttribute createAttribute( TaskData taskData, String mappedAttributeName, String value) {
+ TaskAttribute attribute = taskData.getRoot().createMappedAttribute(mappedAttributeName);
+ attribute.setValue(value);
+ return attribute;
+ }
}
\ No newline at end of file
diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/wizard/ReviewAssignmentPage.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/wizard/ReviewAssignmentPage.java
index 72ed3264..5683c786 100644
--- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/wizard/ReviewAssignmentPage.java
+++ b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/wizard/ReviewAssignmentPage.java
@@ -14,7 +14,7 @@
public class ReviewAssignmentPage extends WizardPage {
private Text reviewerText;
- private Button openOnFinish;
+// private Button openOnFinish;
protected ReviewAssignmentPage() {
super("ReviewAssignmentPage");
@@ -43,8 +43,8 @@ public void modifyText(ModifyEvent e) {
}
});
createLabel(composite, "");
- openOnFinish = new Button(composite, SWT.CHECK);
- openOnFinish.setText("Open review task on finish");
+// openOnFinish = new Button(composite, SWT.CHECK);
+// openOnFinish.setText("Open review task on finish");
setControl(composite);
}
@@ -57,6 +57,6 @@ public String getReviewer() {
return reviewerText.getText();
}
public boolean isOpenReviewOnFinish() {
- return openOnFinish.getSelection();
+ return true; //openOnFinish.getSelection();
}
}
|
b3bab12e6135d7c792c297d6f46b032ce496c18d
|
intellij-community
|
IDEA-80573 GitCheckoutOperation: sleep a bit to- let file watcher report all changes for small repositories where refresh is- too fast.--
|
c
|
https://github.com/JetBrains/intellij-community
|
diff --git a/plugins/git4idea/src/git4idea/branch/GitCheckoutOperation.java b/plugins/git4idea/src/git4idea/branch/GitCheckoutOperation.java
index e3530b19e040f..7eda20eda6871 100644
--- a/plugins/git4idea/src/git4idea/branch/GitCheckoutOperation.java
+++ b/plugins/git4idea/src/git4idea/branch/GitCheckoutOperation.java
@@ -231,8 +231,22 @@ private boolean checkoutOrNotify(@NotNull List<GitRepository> repositories,
private static void refresh(GitRepository... repositories) {
for (GitRepository repository : repositories) {
+ // If repository is small, everything can happen so fast, that FileWatcher wouldn't report the change before refresh() handles it.
+ // Performing a fair total refresh would be an overhead, so just waiting a bit to let file watcher report the change.
+ // This is a hack, but other solutions would be either performance or programming overhead.
+ // See http://youtrack.jetbrains.com/issue/IDEA-80573
+ sleepABit();
refreshRoot(repository);
// repository state will be auto-updated with this VFS refresh => no need to call GitRepository#update().
}
}
+
+ private static void sleepABit() {
+ try {
+ Thread.sleep(50);
+ }
+ catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
}
|
3b68aaa84cfa714a4d1b5ef0c615d924e75d2be0
|
kotlin
|
JS: fix rhino 64k issue--
|
c
|
https://github.com/JetBrains/kotlin
|
diff --git a/js/js.tests/test/org/jetbrains/kotlin/js/test/rhino/RhinoUtils.java b/js/js.tests/test/org/jetbrains/kotlin/js/test/rhino/RhinoUtils.java
index fe73f3f5c0419..ebe8d8b21ffbf 100644
--- a/js/js.tests/test/org/jetbrains/kotlin/js/test/rhino/RhinoUtils.java
+++ b/js/js.tests/test/org/jetbrains/kotlin/js/test/rhino/RhinoUtils.java
@@ -109,6 +109,7 @@ private static void runFileWithRhino(@NotNull String inputFile,
catch (IOException e) {
throw new RuntimeException(e);
}
+ context.setOptimizationLevel(-1);
context.evaluateString(scope, result, inputFile, 1, null);
}
|
02668af08bebc5266b321ab1df2f45dfe656c813
|
duracloud$duracloud
|
First part of https://jira.duraspace.org/browse/DURACLOUD-525: Creates the DuraBoss application by breaking out DuraReport into the webapp (which is now DuraBoss) and a new Reporter project. There are no functionality changes in this commit, just re-naming and re-organization. Note that your init.properties will need to change, "durareport" should be replaced with "duraboss".
git-svn-id: https://svn.duraspace.org/duracloud/trunk@833 1005ed41-97cd-4a8f-848c-be5b5fe45bcb
|
p
|
https://github.com/duracloud/duracloud
|
diff --git a/app-config/src/main/java/org/duracloud/appconfig/ApplicationInitializer.java b/app-config/src/main/java/org/duracloud/appconfig/ApplicationInitializer.java
index 695a706e6..69ccf19d6 100644
--- a/app-config/src/main/java/org/duracloud/appconfig/ApplicationInitializer.java
+++ b/app-config/src/main/java/org/duracloud/appconfig/ApplicationInitializer.java
@@ -11,7 +11,7 @@
import org.duracloud.appconfig.domain.Application;
import org.duracloud.appconfig.domain.BaseConfig;
import org.duracloud.appconfig.domain.DuradminConfig;
-import org.duracloud.appconfig.domain.DurareportConfig;
+import org.duracloud.appconfig.domain.DurabossConfig;
import org.duracloud.appconfig.domain.DuraserviceConfig;
import org.duracloud.appconfig.domain.DurastoreConfig;
import org.duracloud.appconfig.domain.SecurityConfig;
@@ -46,7 +46,7 @@ public class ApplicationInitializer extends BaseConfig {
private static final String duradminKey = "duradmin";
private static final String duraserviceKey = "duraservice";
private static final String durastoreKey = "durastore";
- private static final String durareportKey = "durareport";
+ private static final String durabossKey = "duraboss";
protected static final String hostKey = "host";
protected static final String portKey = "port";
@@ -62,9 +62,9 @@ public class ApplicationInitializer extends BaseConfig {
private String durastoreHost;
private String durastorePort;
private String durastoreContext;
- private String durareportHost;
- private String durareportPort;
- private String durareportContext;
+ private String durabossHost;
+ private String durabossPort;
+ private String durabossContext;
private SecurityConfig securityConfig = new SecurityConfig();
private Map<String, ApplicationWithConfig> appsWithConfigs =
@@ -88,7 +88,7 @@ public ApplicationInitializer(File propsFile) throws IOException {
/**
* This method sets the configuration of duradmin, durastore, duraservice,
- * durareport, and application security from the provided props.
+ * duraboss, and application security from the provided props.
* Note: this method is called by the constructor, so generally is should
* not be needed publicly.
*
@@ -145,17 +145,17 @@ private void createApplications() {
log.warn("durastore endpoint !loaded");
}
- if (durareportEndpointLoad()) {
- app = new Application(durareportHost,
- durareportPort,
- durareportContext);
+ if (durabossEndpointLoad()) {
+ app = new Application(durabossHost,
+ durabossPort,
+ durabossContext);
- appWithConfig = new ApplicationWithConfig(durareportKey);
+ appWithConfig = new ApplicationWithConfig(durabossKey);
appWithConfig.setApplication(app);
- appWithConfig.setConfig(new DurareportConfig());
+ appWithConfig.setConfig(new DurabossConfig());
appsWithConfigs.put(appWithConfig.getName(), appWithConfig);
} else {
- log.warn("durareport endpoint not !loaded");
+ log.warn("duraboss endpoint not !loaded");
}
}
@@ -174,9 +174,9 @@ private boolean durastoreEndpointLoad() {
null != durastoreContext;
}
- private boolean durareportEndpointLoad() {
- return null != durareportHost && null != durareportPort &&
- null != durareportContext;
+ private boolean durabossEndpointLoad() {
+ return null != durabossHost && null != durabossPort &&
+ null != durabossContext;
}
protected String getQualifier() {
@@ -196,14 +196,14 @@ protected void loadProperty(String key, String value) {
} else if (prefix.equalsIgnoreCase(DuraserviceConfig.QUALIFIER)) {
loadDuraservice(suffix, value);
- } else if (prefix.equalsIgnoreCase(DurareportConfig.QUALIFIER)) {
- loadDurareport(suffix, value);
+ } else if (prefix.equalsIgnoreCase(DurabossConfig.QUALIFIER)) {
+ loadDuraboss(suffix, value);
} else if (prefix.equalsIgnoreCase(wildcardKey)) {
loadDuradmin(suffix, value);
loadDurastore(suffix, value);
loadDuraservice(suffix, value);
- loadDurareport(suffix, value);
+ loadDuraboss(suffix, value);
} else {
String msg = "unknown key: " + key + " (" + value + ")";
@@ -266,16 +266,16 @@ private void loadDuraservice(String key, String value) {
}
}
- private void loadDurareport(String key, String value) {
+ private void loadDuraboss(String key, String value) {
String prefix = getPrefix(key);
if (prefix.equalsIgnoreCase(hostKey)) {
- this.durareportHost = value;
+ this.durabossHost = value;
} else if (prefix.equalsIgnoreCase(portKey)) {
- this.durareportPort = value;
+ this.durabossPort = value;
} else if (prefix.equalsIgnoreCase(contextKey)) {
- this.durareportContext = value;
+ this.durabossContext = value;
} else {
String msg = "unknown key: " + key + " (" + value + ")";
@@ -296,8 +296,8 @@ public RestHttpHelper.HttpResponse initialize() {
response = initApp(appsWithConfigs.get(durastoreKey));
response = initApp(appsWithConfigs.get(duraserviceKey));
response = initApp(appsWithConfigs.get(duradminKey));
- if (durareportEndpointLoad()) {
- response = initApp(appsWithConfigs.get(durareportKey));
+ if (durabossEndpointLoad()) {
+ response = initApp(appsWithConfigs.get(durabossKey));
}
return response;
@@ -389,7 +389,7 @@ public Application getDuraservice() {
return appsWithConfigs.get(duraserviceKey).getApplication();
}
- public Application getDurareport() {
- return appsWithConfigs.get(durareportKey).getApplication();
+ public Application getDuraboss() {
+ return appsWithConfigs.get(durabossKey).getApplication();
}
}
diff --git a/app-config/src/main/java/org/duracloud/appconfig/domain/BaseConfig.java b/app-config/src/main/java/org/duracloud/appconfig/domain/BaseConfig.java
index 3e5c77730..58016abf5 100644
--- a/app-config/src/main/java/org/duracloud/appconfig/domain/BaseConfig.java
+++ b/app-config/src/main/java/org/duracloud/appconfig/domain/BaseConfig.java
@@ -16,7 +16,7 @@
/**
* This class collects the common functionality needed by durastore,
- * duraservice, duradmin, durareport, and security configurations.
+ * duraservice, duradmin, duraboss, and security configurations.
*
* @author Andrew Woods
* Date: Apr 20, 2010
diff --git a/app-config/src/main/java/org/duracloud/appconfig/domain/DurareportConfig.java b/app-config/src/main/java/org/duracloud/appconfig/domain/DurabossConfig.java
similarity index 92%
rename from app-config/src/main/java/org/duracloud/appconfig/domain/DurareportConfig.java
rename to app-config/src/main/java/org/duracloud/appconfig/domain/DurabossConfig.java
index 8d952f946..9675d65e1 100644
--- a/app-config/src/main/java/org/duracloud/appconfig/domain/DurareportConfig.java
+++ b/app-config/src/main/java/org/duracloud/appconfig/domain/DurabossConfig.java
@@ -7,7 +7,7 @@
*/
package org.duracloud.appconfig.domain;
-import org.duracloud.appconfig.xml.DurareportInitDocumentBinding;
+import org.duracloud.appconfig.xml.DurabossInitDocumentBinding;
import java.util.Collection;
import java.util.HashMap;
@@ -17,9 +17,9 @@
* @author: Bill Branan
* Date: 5/12/11
*/
-public class DurareportConfig extends DuradminConfig {
+public class DurabossConfig extends DuradminConfig {
- public static final String QUALIFIER = "durareport";
+ public static final String QUALIFIER = "duraboss";
public static final String notificationKey = "notification";
public static final String notificationTypeKey = "type";
public static final String notificationUsernameKey = "username";
@@ -82,7 +82,7 @@ protected boolean isSupported(String key) {
@Override
public String asXml() {
- return DurareportInitDocumentBinding.createDocumentFrom(this);
+ return DurabossInitDocumentBinding.createDocumentFrom(this);
}
/**
diff --git a/app-config/src/main/java/org/duracloud/appconfig/domain/DuradminConfig.java b/app-config/src/main/java/org/duracloud/appconfig/domain/DuradminConfig.java
index 7124e760b..f49a1901b 100644
--- a/app-config/src/main/java/org/duracloud/appconfig/domain/DuradminConfig.java
+++ b/app-config/src/main/java/org/duracloud/appconfig/domain/DuradminConfig.java
@@ -28,7 +28,7 @@ public class DuradminConfig extends BaseConfig implements AppConfig {
public static final String duraServiceHostKey = "duraservice-host";
public static final String duraServicePortKey = "duraservice-port";
public static final String duraServiceContextKey = "duraservice-context";
- public static final String duraReportContextKey = "durareport-context";
+ public static final String duraBossContextKey = "duraboss-context";
public static final String amaUrlKey = "ama-url";
@@ -38,7 +38,7 @@ public class DuradminConfig extends BaseConfig implements AppConfig {
private String duraserviceHost;
private String duraservicePort;
private String duraserviceContext;
- private String durareportContext;
+ private String durabossContext;
private String amaUrl;
@@ -74,8 +74,8 @@ protected void loadProperty(String key, String value) {
} else if (key.equalsIgnoreCase(duraServiceContextKey)) {
this.duraserviceContext = value;
- } else if (key.equalsIgnoreCase(duraReportContextKey)) {
- this.durareportContext = value;
+ } else if (key.equalsIgnoreCase(duraBossContextKey)) {
+ this.durabossContext = value;
} else if (key.equalsIgnoreCase(amaUrlKey)) {
this.amaUrl = value;
@@ -149,11 +149,11 @@ public void setAmaUrl(String amaUrl) {
this.amaUrl = amaUrl;
}
- public String getDurareportContext() {
- return durareportContext;
+ public String getDurabossContext() {
+ return durabossContext;
}
- public void setDurareportContext(String durareportContext) {
- this.durareportContext = durareportContext;
+ public void setDurabossContext(String durabossContext) {
+ this.durabossContext = durabossContext;
}
}
diff --git a/app-config/src/main/java/org/duracloud/appconfig/xml/DurareportInitDocumentBinding.java b/app-config/src/main/java/org/duracloud/appconfig/xml/DurabossInitDocumentBinding.java
similarity index 80%
rename from app-config/src/main/java/org/duracloud/appconfig/xml/DurareportInitDocumentBinding.java
rename to app-config/src/main/java/org/duracloud/appconfig/xml/DurabossInitDocumentBinding.java
index 39c053910..24a1af67a 100644
--- a/app-config/src/main/java/org/duracloud/appconfig/xml/DurareportInitDocumentBinding.java
+++ b/app-config/src/main/java/org/duracloud/appconfig/xml/DurabossInitDocumentBinding.java
@@ -7,7 +7,7 @@
*/
package org.duracloud.appconfig.xml;
-import org.duracloud.appconfig.domain.DurareportConfig;
+import org.duracloud.appconfig.domain.DurabossConfig;
import org.duracloud.appconfig.domain.NotificationConfig;
import org.duracloud.common.error.DuraCloudRuntimeException;
import org.duracloud.common.util.EncryptionUtil;
@@ -27,10 +27,10 @@
* @author: Bill Branan
* Date: 5/12/11
*/
-public class DurareportInitDocumentBinding {
+public class DurabossInitDocumentBinding {
private static final Logger log = LoggerFactory
- .getLogger(DurareportInitDocumentBinding.class);
+ .getLogger(DurabossInitDocumentBinding.class);
private static EncryptionUtil encryptionUtil;
@@ -44,13 +44,13 @@ public class DurareportInitDocumentBinding {
/**
- * This method deserializes the provided xml into a durareport config object.
+ * This method deserializes the provided xml into a duraboss config object.
*
* @param xml
* @return
*/
- public static DurareportConfig createDurareportConfigFrom(InputStream xml) {
- DurareportConfig config = new DurareportConfig();
+ public static DurabossConfig createDurabossConfigFrom(InputStream xml) {
+ DurabossConfig config = new DurabossConfig();
try {
SAXBuilder builder = new SAXBuilder();
@@ -84,7 +84,7 @@ public static DurareportConfig createDurareportConfigFrom(InputStream xml) {
}
} catch (Exception e) {
String error = "Error encountered attempting to parse " +
- "Durareport configuration xml: " + e.getMessage();
+ "Duraboss configuration xml: " + e.getMessage();
log.error(error);
throw new DuraCloudRuntimeException(error, e);
}
@@ -93,23 +93,23 @@ public static DurareportConfig createDurareportConfigFrom(InputStream xml) {
}
/**
- * This method serializes the provide durareport configuration into xml.
+ * This method serializes the provide duraboss configuration into xml.
*
- * @param durareportConfig
+ * @param durabossConfig
* @return
*/
- public static String createDocumentFrom(DurareportConfig durareportConfig) {
+ public static String createDocumentFrom(DurabossConfig durabossConfig) {
StringBuilder xml = new StringBuilder();
- if (null != durareportConfig) {
- String durastoreHost = durareportConfig.getDurastoreHost();
- String durastorePort = durareportConfig.getDurastorePort();
- String durastoreContext = durareportConfig.getDurastoreContext();
- String duraserviceHost = durareportConfig.getDuraserviceHost();
- String duraservicePort = durareportConfig.getDuraservicePort();
- String duraserviceContext = durareportConfig.getDuraserviceContext();
+ if (null != durabossConfig) {
+ String durastoreHost = durabossConfig.getDurastoreHost();
+ String durastorePort = durabossConfig.getDurastorePort();
+ String durastoreContext = durabossConfig.getDurastoreContext();
+ String duraserviceHost = durabossConfig.getDuraserviceHost();
+ String duraservicePort = durabossConfig.getDuraservicePort();
+ String duraserviceContext = durabossConfig.getDuraserviceContext();
- xml.append("<durareportConfig>");
+ xml.append("<durabossConfig>");
xml.append(" <durastoreHost>" + durastoreHost);
xml.append("</durastoreHost>");
xml.append(" <durastorePort>" + durastorePort);
@@ -124,7 +124,7 @@ public static String createDocumentFrom(DurareportConfig durareportConfig) {
xml.append("</duraserviceContext>");
Collection<NotificationConfig> notificationConfigs =
- durareportConfig.getNotificationConfigs();
+ durabossConfig.getNotificationConfigs();
if(null != notificationConfigs) {
for(NotificationConfig config : notificationConfigs) {
String encUsername = encrypt(config.getUsername());
@@ -142,7 +142,7 @@ public static String createDocumentFrom(DurareportConfig durareportConfig) {
}
}
- xml.append("</durareportConfig>");
+ xml.append("</durabossConfig>");
}
return xml.toString();
}
diff --git a/app-config/src/main/java/org/duracloud/appconfig/xml/DuradminInitDocumentBinding.java b/app-config/src/main/java/org/duracloud/appconfig/xml/DuradminInitDocumentBinding.java
index 800a7e4c4..27e7d2f46 100644
--- a/app-config/src/main/java/org/duracloud/appconfig/xml/DuradminInitDocumentBinding.java
+++ b/app-config/src/main/java/org/duracloud/appconfig/xml/DuradminInitDocumentBinding.java
@@ -47,7 +47,7 @@ public static DuradminConfig createDuradminConfigFrom(InputStream xml) {
config.setDuraserviceHost(root.getChildText("duraserviceHost"));
config.setDuraservicePort(root.getChildText("duraservicePort"));
config.setDuraserviceContext(root.getChildText("duraserviceContext"));
- config.setDurareportContext(root.getChildText("durareportContext"));
+ config.setDurabossContext(root.getChildText("durabossContext"));
config.setAmaUrl(root.getChildText("amaUrl"));
} catch (Exception e) {
diff --git a/app-config/src/main/resources/init.properties b/app-config/src/main/resources/init.properties
index 8cea7fdba..faa77c231 100644
--- a/app-config/src/main/resources/init.properties
+++ b/app-config/src/main/resources/init.properties
@@ -6,7 +6,7 @@ app.*.port=8080
app.durastore.context=durastore
app.duraservice.context=duraservice
app.duradmin.context=duradmin
-app.durareport.context=durareport
+app.duraboss.context=duraboss
###
# defines durastore accts
@@ -67,12 +67,12 @@ duradmin.duraservice-port=8080
duradmin.duraservice-context=duraservice
###
-# defines notification requirements, for durareport
+# defines notification requirements, for duraboss
###
-durareport.notification.0.type=EMAIL
-durareport.notification.0.username=[username]
-durareport.notification.0.password=[password]
-durareport.notification.0.originator=[from email address]
+duraboss.notification.0.type=EMAIL
+duraboss.notification.0.username=[username]
+duraboss.notification.0.password=[password]
+duraboss.notification.0.originator=[from email address]
###
# defines new users
diff --git a/app-config/src/test/java/org/duracloud/appconfig/ApplicationInitializerTest.java b/app-config/src/test/java/org/duracloud/appconfig/ApplicationInitializerTest.java
index ad2b19212..62306a860 100644
--- a/app-config/src/test/java/org/duracloud/appconfig/ApplicationInitializerTest.java
+++ b/app-config/src/test/java/org/duracloud/appconfig/ApplicationInitializerTest.java
@@ -9,7 +9,7 @@
import org.duracloud.appconfig.domain.Application;
import org.duracloud.appconfig.domain.DuradminConfig;
-import org.duracloud.appconfig.domain.DurareportConfig;
+import org.duracloud.appconfig.domain.DurabossConfig;
import org.duracloud.appconfig.domain.DuraserviceConfig;
import org.duracloud.appconfig.domain.DurastoreConfig;
import org.junit.Assert;
@@ -32,8 +32,8 @@ public class ApplicationInitializerTest {
private String durastoreContext = "durastoreContext";
private String duraservicePort = "duraservicePort";
private String duraserviceContext = "duraserviceContext";
- private String durareportPort = "durareportPort";
- private String durareportContext = "durareportContext";
+ private String durabossPort = "durabossPort";
+ private String durabossContext = "durabossContext";
private String allHost = "allHost";
@Test
@@ -56,7 +56,7 @@ private Properties createProps() {
String pAdm = p + DuradminConfig.QUALIFIER + dot;
String pStr = p + DurastoreConfig.QUALIFIER + dot;
String pSrv = p + DuraserviceConfig.QUALIFIER + dot;
- String pRpt = p + DurareportConfig.QUALIFIER + dot;
+ String pRpt = p + DurabossConfig.QUALIFIER + dot;
String pWild = p + ApplicationInitializer.wildcardKey + dot;
String host = ApplicationInitializer.hostKey;
@@ -66,11 +66,11 @@ private Properties createProps() {
props.put(pAdm + port, duradminPort);
props.put(pStr + port, durastorePort);
props.put(pSrv + port, duraservicePort);
- props.put(pRpt + port, durareportPort);
+ props.put(pRpt + port, durabossPort);
props.put(pAdm + context, duradminContext);
props.put(pStr + context, durastoreContext);
props.put(pSrv + context, duraserviceContext);
- props.put(pRpt + context, durareportContext);
+ props.put(pRpt + context, durabossContext);
props.put(pWild + host, allHost);
return props;
@@ -80,12 +80,12 @@ private void verifyApplicationInitializer(ApplicationInitializer config) {
Application duradmin = config.getDuradmin();
Application durastore = config.getDurastore();
Application duraservice = config.getDuraservice();
- Application durareport = config.getDurareport();
+ Application duraboss = config.getDuraboss();
Assert.assertNotNull(duradmin);
Assert.assertNotNull(durastore);
Assert.assertNotNull(duraservice);
- Assert.assertNotNull(durareport);
+ Assert.assertNotNull(duraboss);
String adminHost = duradmin.getHost();
String adminPort = duradmin.getPort();
@@ -96,9 +96,9 @@ private void verifyApplicationInitializer(ApplicationInitializer config) {
String serviceHost = duraservice.getHost();
String servicePort = duraservice.getPort();
String serviceContext = duraservice.getContext();
- String reportHost = durareport.getHost();
- String reportPort = durareport.getPort();
- String reportContext = durareport.getContext();
+ String reportHost = duraboss.getHost();
+ String reportPort = duraboss.getPort();
+ String reportContext = duraboss.getContext();
Assert.assertNotNull(adminHost);
Assert.assertNotNull(adminPort);
@@ -123,8 +123,8 @@ private void verifyApplicationInitializer(ApplicationInitializer config) {
Assert.assertEquals(duraservicePort, servicePort);
Assert.assertEquals(duraserviceContext, serviceContext);
Assert.assertEquals(allHost, reportHost);
- Assert.assertEquals(durareportPort, reportPort);
- Assert.assertEquals(durareportContext, reportContext);
+ Assert.assertEquals(durabossPort, reportPort);
+ Assert.assertEquals(durabossContext, reportContext);
}
}
diff --git a/app-config/src/test/java/org/duracloud/appconfig/domain/DurareportConfigTest.java b/app-config/src/test/java/org/duracloud/appconfig/domain/DurabossConfigTest.java
similarity index 68%
rename from app-config/src/test/java/org/duracloud/appconfig/domain/DurareportConfigTest.java
rename to app-config/src/test/java/org/duracloud/appconfig/domain/DurabossConfigTest.java
index 9e98fd29e..045fd19ee 100644
--- a/app-config/src/test/java/org/duracloud/appconfig/domain/DurareportConfigTest.java
+++ b/app-config/src/test/java/org/duracloud/appconfig/domain/DurabossConfigTest.java
@@ -18,7 +18,7 @@
* @author: Bill Branan
* Date: 5/12/11
*/
-public class DurareportConfigTest {
+public class DurabossConfigTest {
private String durastoreHost = "durastoreHost";
private String durastorePort = "durastorePort";
@@ -34,40 +34,40 @@ public class DurareportConfigTest {
@Test
public void testLoad() {
- DurareportConfig config = new DurareportConfig();
+ DurabossConfig config = new DurabossConfig();
config.load(createProps());
- verifyDurareportConfig(config);
+ verifyDurabossConfig(config);
}
private Map<String, String> createProps() {
Map<String, String> props = new HashMap<String, String>();
- String p = DurareportConfig.QUALIFIER + ".";
+ String p = DurabossConfig.QUALIFIER + ".";
- props.put(p + DurareportConfig.duraStoreHostKey, durastoreHost);
- props.put(p + DurareportConfig.duraStorePortKey, durastorePort);
- props.put(p + DurareportConfig.duraStoreContextKey, durastoreContext);
- props.put(p + DurareportConfig.duraServiceHostKey, duraserviceHost);
- props.put(p + DurareportConfig.duraServicePortKey, duraservicePort);
- props.put(p + DurareportConfig.duraServiceContextKey, duraserviceContext);
+ props.put(p + DurabossConfig.duraStoreHostKey, durastoreHost);
+ props.put(p + DurabossConfig.duraStorePortKey, durastorePort);
+ props.put(p + DurabossConfig.duraStoreContextKey, durastoreContext);
+ props.put(p + DurabossConfig.duraServiceHostKey, duraserviceHost);
+ props.put(p + DurabossConfig.duraServicePortKey, duraservicePort);
+ props.put(p + DurabossConfig.duraServiceContextKey, duraserviceContext);
- props.put(p + DurareportConfig.notificationKey + ".0." +
- DurareportConfig.notificationTypeKey,
+ props.put(p + DurabossConfig.notificationKey + ".0." +
+ DurabossConfig.notificationTypeKey,
notifyType);
- props.put(p + DurareportConfig.notificationKey + ".0." +
- DurareportConfig.notificationUsernameKey,
+ props.put(p + DurabossConfig.notificationKey + ".0." +
+ DurabossConfig.notificationUsernameKey,
notifyUsername);
- props.put(p + DurareportConfig.notificationKey + ".0." +
- DurareportConfig.notificationPasswordKey,
+ props.put(p + DurabossConfig.notificationKey + ".0." +
+ DurabossConfig.notificationPasswordKey,
notifyPassword);
- props.put(p + DurareportConfig.notificationKey + ".0." +
- DurareportConfig.notificationOriginatorKey,
+ props.put(p + DurabossConfig.notificationKey + ".0." +
+ DurabossConfig.notificationOriginatorKey,
notifyOriginator);
return props;
}
- private void verifyDurareportConfig(DurareportConfig config) {
+ private void verifyDurabossConfig(DurabossConfig config) {
Assert.assertNotNull(config.getDurastoreHost());
Assert.assertNotNull(config.getDurastorePort());
diff --git a/app-config/src/test/java/org/duracloud/appconfig/domain/DuradminConfigTest.java b/app-config/src/test/java/org/duracloud/appconfig/domain/DuradminConfigTest.java
index af63b2362..ac02bef55 100644
--- a/app-config/src/test/java/org/duracloud/appconfig/domain/DuradminConfigTest.java
+++ b/app-config/src/test/java/org/duracloud/appconfig/domain/DuradminConfigTest.java
@@ -28,7 +28,7 @@ public class DuradminConfigTest {
private String duraserviceHost = "duraserviceHost";
private String duraservicePort = "duraservicePort";
private String duraserviceContext = "duraserviceContext";
- private String durareportContext = "durareportContext";
+ private String durabossContext = "durabossContext";
private String amaUrl = "amaUrl";
@@ -54,7 +54,7 @@ private Map<String, String> createProps() {
props.put(p + DuradminConfig.duraServiceHostKey, duraserviceHost);
props.put(p + DuradminConfig.duraServicePortKey, duraservicePort);
props.put(p + DuradminConfig.duraServiceContextKey, duraserviceContext);
- props.put(p + DuradminConfig.duraReportContextKey, durareportContext);
+ props.put(p + DuradminConfig.duraBossContextKey, durabossContext);
props.put(p + DuradminConfig.amaUrlKey, amaUrl);
return props;
@@ -68,7 +68,7 @@ private void verifyDuradminConfig(DuradminConfig config) {
Assert.assertNotNull(config.getDuraserviceHost());
Assert.assertNotNull(config.getDuraservicePort());
Assert.assertNotNull(config.getDuraserviceContext());
- Assert.assertNotNull(config.getDurareportContext());
+ Assert.assertNotNull(config.getDurabossContext());
Assert.assertNotNull(config.getAmaUrl());
@@ -78,7 +78,7 @@ private void verifyDuradminConfig(DuradminConfig config) {
Assert.assertEquals(duraserviceHost, config.getDuraserviceHost());
Assert.assertEquals(duraservicePort, config.getDuraservicePort());
Assert.assertEquals(duraserviceContext, config.getDuraserviceContext());
- Assert.assertEquals(durareportContext, config.getDurareportContext());
+ Assert.assertEquals(durabossContext, config.getDurabossContext());
Assert.assertEquals(amaUrl, config.getAmaUrl());
}
diff --git a/app-config/src/test/java/org/duracloud/appconfig/xml/DurareportInitDocumentBindingTest.java b/app-config/src/test/java/org/duracloud/appconfig/xml/DurabossInitDocumentBindingTest.java
similarity index 88%
rename from app-config/src/test/java/org/duracloud/appconfig/xml/DurareportInitDocumentBindingTest.java
rename to app-config/src/test/java/org/duracloud/appconfig/xml/DurabossInitDocumentBindingTest.java
index 4de42443e..ce77c04c1 100644
--- a/app-config/src/test/java/org/duracloud/appconfig/xml/DurareportInitDocumentBindingTest.java
+++ b/app-config/src/test/java/org/duracloud/appconfig/xml/DurabossInitDocumentBindingTest.java
@@ -7,7 +7,7 @@
*/
package org.duracloud.appconfig.xml;
-import org.duracloud.appconfig.domain.DurareportConfig;
+import org.duracloud.appconfig.domain.DurabossConfig;
import org.duracloud.appconfig.domain.NotificationConfig;
import org.junit.Test;
@@ -24,7 +24,7 @@
* @author: Bill Branan
* Date: 12/6/11
*/
-public class DurareportInitDocumentBindingTest {
+public class DurabossInitDocumentBindingTest {
private String durastoreHost = "durastoreHost";
private String durastorePort = "durastorePort";
@@ -41,7 +41,7 @@ public class DurareportInitDocumentBindingTest {
@Test
public void testXmlRoundTrip() throws Exception {
// Create config
- DurareportConfig config = new DurareportConfig();
+ DurabossConfig config = new DurabossConfig();
config.setDurastoreHost(durastoreHost);
config.setDurastorePort(durastorePort);
config.setDurastoreContext(durastoreContext);
@@ -60,12 +60,12 @@ public void testXmlRoundTrip() throws Exception {
config.setNotificationConfigs(notifyConfigMap);
// Run round trip
- String xml = DurareportInitDocumentBinding.createDocumentFrom(config);
+ String xml = DurabossInitDocumentBinding.createDocumentFrom(config);
assertNotNull(xml);
InputStream xmlStream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
- DurareportConfig trippedConfig =
- DurareportInitDocumentBinding.createDurareportConfigFrom(xmlStream);
+ DurabossConfig trippedConfig =
+ DurabossInitDocumentBinding.createDurabossConfigFrom(xmlStream);
// Verify results
assertEquals(config.getDurastoreHost(),
diff --git a/duraboss/pom.xml b/duraboss/pom.xml
new file mode 100644
index 000000000..d85ee2233
--- /dev/null
+++ b/duraboss/pom.xml
@@ -0,0 +1,96 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.duracloud</groupId>
+ <artifactId>duraboss</artifactId>
+ <packaging>war</packaging>
+ <version>1.4.0-SNAPSHOT</version>
+ <name>DuraCloud DuraBoss</name>
+ <url>http://localhost:8080/${artifactId}</url>
+
+ <parent>
+ <groupId>org.duracloud</groupId>
+ <artifactId>duracloud</artifactId>
+ <version>1.4.0-SNAPSHOT</version>
+ <relativePath>../pom.xml</relativePath>
+ </parent>
+
+ <build>
+
+ <plugins>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <version>2.3.1</version>
+ <executions>
+ <execution>
+ <phase>package</phase>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ <configuration>
+ <classifier>for-integration-test</classifier>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+
+ </plugins>
+
+ </build>
+
+ <dependencies>
+
+ <!-- internal projects -->
+ <dependency>
+ <groupId>org.duracloud</groupId>
+ <artifactId>common</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.duracloud</groupId>
+ <artifactId>common-rest</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.duracloud</groupId>
+ <artifactId>security</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.duracloud</groupId>
+ <artifactId>reporter</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <!-- for Spring -->
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-core</artifactId>
+ <scope>compile</scope>
+ </dependency>
+
+ <!-- for Jersey -->
+ <dependency>
+ <groupId>com.sun.jersey</groupId>
+ <artifactId>jersey-server</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.sun.jersey.contribs</groupId>
+ <artifactId>jersey-spring</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.sun.xml.bind</groupId>
+ <artifactId>jaxb-impl</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>javax.mail</groupId>
+ <artifactId>mail</artifactId>
+ </dependency>
+
+ </dependencies>
+
+</project>
diff --git a/durareport/src/main/java/org/duracloud/durareport/rest/BaseRest.java b/duraboss/src/main/java/org/duracloud/duraboss/rest/BaseRest.java
similarity index 95%
rename from durareport/src/main/java/org/duracloud/durareport/rest/BaseRest.java
rename to duraboss/src/main/java/org/duracloud/duraboss/rest/BaseRest.java
index 624034ffd..d1333389b 100644
--- a/durareport/src/main/java/org/duracloud/durareport/rest/BaseRest.java
+++ b/duraboss/src/main/java/org/duracloud/duraboss/rest/BaseRest.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.rest;
+package org.duracloud.duraboss.rest;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Context;
@@ -35,7 +35,7 @@ public class BaseRest {
MediaType.APPLICATION_XML_TYPE;
public static final MediaType TEXT_PLAIN = MediaType.TEXT_PLAIN_TYPE;
- public static final String APP_NAME = "DuraReport";
+ public static final String APP_NAME = "DuraBoss";
protected Response responseOk(String text) {
return Response.ok(text, TEXT_PLAIN).build();
diff --git a/durareport/src/main/java/org/duracloud/durareport/rest/InitRest.java b/duraboss/src/main/java/org/duracloud/duraboss/rest/InitRest.java
similarity index 92%
rename from durareport/src/main/java/org/duracloud/durareport/rest/InitRest.java
rename to duraboss/src/main/java/org/duracloud/duraboss/rest/InitRest.java
index 00a1c02e2..213b019a8 100644
--- a/durareport/src/main/java/org/duracloud/durareport/rest/InitRest.java
+++ b/duraboss/src/main/java/org/duracloud/duraboss/rest/InitRest.java
@@ -5,17 +5,17 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.rest;
+package org.duracloud.duraboss.rest;
-import org.duracloud.appconfig.domain.DurareportConfig;
-import org.duracloud.appconfig.xml.DurareportInitDocumentBinding;
+import org.duracloud.appconfig.domain.DurabossConfig;
+import org.duracloud.appconfig.xml.DurabossInitDocumentBinding;
import org.duracloud.client.ContentStoreManager;
import org.duracloud.client.ContentStoreManagerImpl;
import org.duracloud.client.ServicesManagerImpl;
import org.duracloud.common.model.Credential;
import org.duracloud.common.rest.RestUtil;
import org.duracloud.common.util.InitUtil;
-import org.duracloud.durareport.notification.NotificationManager;
+import org.duracloud.reporter.notification.NotificationManager;
import org.duracloud.security.context.SecurityContextUtil;
import org.duracloud.security.error.NoUserLoggedInException;
import org.duracloud.serviceapi.ServicesManager;
@@ -67,7 +67,7 @@ public InitRest(StorageReportResource storageResource,
}
/**
- * Initializes DuraReport
+ * Initializes DuraBoss
*
* @return 200 response with text indicating success
*/
@@ -87,8 +87,8 @@ public Response initialize(){
}
private void doInitialize(InputStream xml) throws NoUserLoggedInException {
- DurareportConfig config =
- DurareportInitDocumentBinding.createDurareportConfigFrom(xml);
+ DurabossConfig config =
+ DurabossInitDocumentBinding.createDurabossConfigFrom(xml);
Credential credential = securityContextUtil.getCurrentUser();
diff --git a/durareport/src/main/java/org/duracloud/durareport/rest/SecurityRest.java b/duraboss/src/main/java/org/duracloud/duraboss/rest/SecurityRest.java
similarity index 97%
rename from durareport/src/main/java/org/duracloud/durareport/rest/SecurityRest.java
rename to duraboss/src/main/java/org/duracloud/duraboss/rest/SecurityRest.java
index 85ba538e8..52c489c5e 100644
--- a/durareport/src/main/java/org/duracloud/durareport/rest/SecurityRest.java
+++ b/duraboss/src/main/java/org/duracloud/duraboss/rest/SecurityRest.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.rest;
+package org.duracloud.duraboss.rest;
import org.duracloud.common.rest.RestUtil;
import org.duracloud.security.DuracloudUserDetailsService;
diff --git a/durareport/src/main/java/org/duracloud/durareport/rest/ServiceReportResource.java b/duraboss/src/main/java/org/duracloud/duraboss/rest/ServiceReportResource.java
similarity index 91%
rename from durareport/src/main/java/org/duracloud/durareport/rest/ServiceReportResource.java
rename to duraboss/src/main/java/org/duracloud/duraboss/rest/ServiceReportResource.java
index 1e7089c6d..75132c985 100644
--- a/durareport/src/main/java/org/duracloud/durareport/rest/ServiceReportResource.java
+++ b/duraboss/src/main/java/org/duracloud/duraboss/rest/ServiceReportResource.java
@@ -5,10 +5,10 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.rest;
+package org.duracloud.duraboss.rest;
-import org.duracloud.durareport.service.ServiceNotificationMonitor;
-import org.duracloud.durareport.service.ServiceReportBuilder;
+import org.duracloud.reporter.service.ServiceNotificationMonitor;
+import org.duracloud.reporter.service.ServiceReportBuilder;
import org.duracloud.servicemonitor.ServiceMonitor;
import org.duracloud.servicemonitor.ServiceSummarizer;
import org.duracloud.servicemonitor.ServiceSummaryDirectory;
@@ -75,7 +75,7 @@ public InputStream getCompletedServicesReport(String reportId)
public void checkInitialized() {
if(null == reportBuilder) {
- throw new RuntimeException("DuraReport must be initialized.");
+ throw new RuntimeException("DuraBoss must be initialized.");
}
}
diff --git a/durareport/src/main/java/org/duracloud/durareport/rest/ServiceReportRest.java b/duraboss/src/main/java/org/duracloud/duraboss/rest/ServiceReportRest.java
similarity index 98%
rename from durareport/src/main/java/org/duracloud/durareport/rest/ServiceReportRest.java
rename to duraboss/src/main/java/org/duracloud/duraboss/rest/ServiceReportRest.java
index 774540d7b..bc97aa4a2 100644
--- a/durareport/src/main/java/org/duracloud/durareport/rest/ServiceReportRest.java
+++ b/duraboss/src/main/java/org/duracloud/duraboss/rest/ServiceReportRest.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.rest;
+package org.duracloud.duraboss.rest;
import org.duracloud.servicemonitor.error.ServiceSummaryNotFoundException;
import org.slf4j.Logger;
@@ -23,7 +23,7 @@
* @author: Bill Branan
* Date: 5/12/11
*/
-@Path("/servicereport")
+@Path("/report/service")
public class ServiceReportRest extends BaseRest {
private ServiceReportResource resource;
diff --git a/durareport/src/main/java/org/duracloud/durareport/rest/StorageReportResource.java b/duraboss/src/main/java/org/duracloud/duraboss/rest/StorageReportResource.java
similarity index 96%
rename from durareport/src/main/java/org/duracloud/durareport/rest/StorageReportResource.java
rename to duraboss/src/main/java/org/duracloud/duraboss/rest/StorageReportResource.java
index b1dce70ac..a866a702a 100644
--- a/durareport/src/main/java/org/duracloud/durareport/rest/StorageReportResource.java
+++ b/duraboss/src/main/java/org/duracloud/duraboss/rest/StorageReportResource.java
@@ -5,13 +5,13 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.rest;
+package org.duracloud.duraboss.rest;
import org.duracloud.client.ContentStoreManager;
-import org.duracloud.durareport.error.InvalidScheduleException;
-import org.duracloud.durareport.storage.StorageReportBuilder;
-import org.duracloud.durareport.storage.StorageReportHandler;
-import org.duracloud.durareport.storage.StorageReportScheduler;
+import org.duracloud.reporter.error.InvalidScheduleException;
+import org.duracloud.reporter.storage.StorageReportBuilder;
+import org.duracloud.reporter.storage.StorageReportHandler;
+import org.duracloud.reporter.storage.StorageReportScheduler;
import org.duracloud.error.ContentStoreException;
import org.duracloud.reportdata.storage.StorageReportInfo;
import org.duracloud.reportdata.storage.StorageReportList;
@@ -247,7 +247,7 @@ public void dispose() {
private void checkInitialized() {
if(null == storeMgr) {
- throw new RuntimeException("DuraReport must be initialized.");
+ throw new RuntimeException("DuraBoss must be initialized.");
}
}
diff --git a/durareport/src/main/java/org/duracloud/durareport/rest/StorageReportRest.java b/duraboss/src/main/java/org/duracloud/duraboss/rest/StorageReportRest.java
similarity index 97%
rename from durareport/src/main/java/org/duracloud/durareport/rest/StorageReportRest.java
rename to duraboss/src/main/java/org/duracloud/duraboss/rest/StorageReportRest.java
index e1891f17b..2fb7ea2b5 100644
--- a/durareport/src/main/java/org/duracloud/durareport/rest/StorageReportRest.java
+++ b/duraboss/src/main/java/org/duracloud/duraboss/rest/StorageReportRest.java
@@ -5,9 +5,9 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.rest;
+package org.duracloud.duraboss.rest;
-import org.duracloud.durareport.error.InvalidScheduleException;
+import org.duracloud.reporter.error.InvalidScheduleException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -27,7 +27,7 @@
* @author: Bill Branan
* Date: 5/11/11
*/
-@Path("/storagereport")
+@Path("/report/storage")
public class StorageReportRest extends BaseRest {
private StorageReportResource resource;
diff --git a/durareport/src/main/resources/logback.xml b/duraboss/src/main/resources/logback.xml
similarity index 97%
rename from durareport/src/main/resources/logback.xml
rename to duraboss/src/main/resources/logback.xml
index 341dde314..8852cf7b8 100644
--- a/durareport/src/main/resources/logback.xml
+++ b/duraboss/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
<configuration debug="true" scan="true">
<jmxConfigurator/>
- <property name="LOG_FILENAME" value="${duracloud.home}/logs/duracloud-durareport.log" />
+ <property name="LOG_FILENAME" value="${duracloud.home}/logs/duracloud-duraboss.log" />
<appender name="DURACLOUD" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!--See also http://logback.qos.ch/manual/appenders.html#RollingFileAppender-->
diff --git a/durareport/src/main/webapp/WEB-INF/config/duracloud-app-config.xml b/duraboss/src/main/webapp/WEB-INF/config/duracloud-app-config.xml
similarity index 100%
rename from durareport/src/main/webapp/WEB-INF/config/duracloud-app-config.xml
rename to duraboss/src/main/webapp/WEB-INF/config/duracloud-app-config.xml
diff --git a/durareport/src/main/webapp/WEB-INF/config/messaging-config.xml b/duraboss/src/main/webapp/WEB-INF/config/messaging-config.xml
similarity index 100%
rename from durareport/src/main/webapp/WEB-INF/config/messaging-config.xml
rename to duraboss/src/main/webapp/WEB-INF/config/messaging-config.xml
diff --git a/durareport/src/main/webapp/WEB-INF/config/notification-config.xml b/duraboss/src/main/webapp/WEB-INF/config/notification-config.xml
similarity index 70%
rename from durareport/src/main/webapp/WEB-INF/config/notification-config.xml
rename to duraboss/src/main/webapp/WEB-INF/config/notification-config.xml
index c738753ee..5b327171d 100644
--- a/durareport/src/main/webapp/WEB-INF/config/notification-config.xml
+++ b/duraboss/src/main/webapp/WEB-INF/config/notification-config.xml
@@ -6,17 +6,17 @@
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="serviceNotificationMonitor"
- class="org.duracloud.durareport.service.ServiceNotificationMonitor">
+ class="org.duracloud.reporter.service.ServiceNotificationMonitor">
<constructor-arg ref="notificationManager" />
<constructor-arg ref="userDetailsSvc" />
</bean>
<bean id="notificationManager"
- class="org.duracloud.durareport.notification.NotificationManager">
+ class="org.duracloud.reporter.notification.NotificationManager">
<constructor-arg ref="emailNotifier"/>
</bean>
<bean id="emailNotifier"
- class="org.duracloud.durareport.notification.EmailNotifier"/>
+ class="org.duracloud.reporter.notification.EmailNotifier"/>
</beans>
\ No newline at end of file
diff --git a/durareport/src/main/webapp/WEB-INF/config/restapi-config.xml b/duraboss/src/main/webapp/WEB-INF/config/restapi-config.xml
similarity index 78%
rename from durareport/src/main/webapp/WEB-INF/config/restapi-config.xml
rename to duraboss/src/main/webapp/WEB-INF/config/restapi-config.xml
index 44d74ee71..e78b5c51c 100644
--- a/durareport/src/main/webapp/WEB-INF/config/restapi-config.xml
+++ b/duraboss/src/main/webapp/WEB-INF/config/restapi-config.xml
@@ -6,15 +6,15 @@
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- REST API resources -->
- <bean id="storageReportRest" class="org.duracloud.durareport.rest.StorageReportRest" >
+ <bean id="storageReportRest" class="org.duracloud.duraboss.rest.StorageReportRest" >
<constructor-arg ref="storageResource"/>
</bean>
- <bean id="serviceReportRest" class="org.duracloud.durareport.rest.ServiceReportRest" >
+ <bean id="serviceReportRest" class="org.duracloud.duraboss.rest.ServiceReportRest" >
<constructor-arg ref="serviceResource"/>
</bean>
- <bean id="initRest" class="org.duracloud.durareport.rest.InitRest" >
+ <bean id="initRest" class="org.duracloud.duraboss.rest.InitRest" >
<constructor-arg ref="storageResource"/>
<constructor-arg ref="serviceResource"/>
<constructor-arg ref="summaryDirectory"/>
@@ -24,19 +24,19 @@
<constructor-arg ref="notificationManager"/>
</bean>
- <bean id="securityRest" class="org.duracloud.durareport.rest.SecurityRest">
+ <bean id="securityRest" class="org.duracloud.duraboss.rest.SecurityRest">
<constructor-arg ref="userDetailsSvc" />
<constructor-arg ref="restUtil"/>
</bean>
<!-- Support beans -->
- <bean id="storageResource" class="org.duracloud.durareport.rest.StorageReportResource"
+ <bean id="storageResource" class="org.duracloud.duraboss.rest.StorageReportResource"
destroy-method="dispose">
<constructor-arg value="report/storage-report-"/>
<constructor-arg value="report/error-log-storage-report.txt"/>
</bean>
- <bean id="serviceResource" class="org.duracloud.durareport.rest.ServiceReportResource" >
+ <bean id="serviceResource" class="org.duracloud.duraboss.rest.ServiceReportResource" >
<constructor-arg ref="serviceMonitor"/>
<constructor-arg ref="serviceNotificationMonitor"/>
</bean>
diff --git a/durareport/src/main/webapp/WEB-INF/config/security-config.xml b/duraboss/src/main/webapp/WEB-INF/config/security-config.xml
similarity index 100%
rename from durareport/src/main/webapp/WEB-INF/config/security-config.xml
rename to duraboss/src/main/webapp/WEB-INF/config/security-config.xml
diff --git a/durareport/src/main/webapp/WEB-INF/web.xml b/duraboss/src/main/webapp/WEB-INF/web.xml
similarity index 97%
rename from durareport/src/main/webapp/WEB-INF/web.xml
rename to duraboss/src/main/webapp/WEB-INF/web.xml
index 77fd06a45..af7fb1d7e 100644
--- a/durareport/src/main/webapp/WEB-INF/web.xml
+++ b/duraboss/src/main/webapp/WEB-INF/web.xml
@@ -18,7 +18,7 @@
</listener>
<servlet>
- <servlet-name>durareport</servlet-name>
+ <servlet-name>duraboss</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
diff --git a/durareport/src/main/webapp/index.jsp b/duraboss/src/main/webapp/index.jsp
similarity index 60%
rename from durareport/src/main/webapp/index.jsp
rename to duraboss/src/main/webapp/index.jsp
index 4bf1fd442..0867daa04 100644
--- a/durareport/src/main/webapp/index.jsp
+++ b/duraboss/src/main/webapp/index.jsp
@@ -1,6 +1,6 @@
<html>
<head>
<%-- Redirected because we can't set the welcome page to a virtual URL. --%>
- <meta http-equiv="refresh" content="0; url=/durareport/storagereport">
+ <meta http-equiv="refresh" content="0; url=/duraboss/report/storage">
</head>
</html>
\ No newline at end of file
diff --git a/durareport/src/test/java/org/duracloud/durareport/rest/InitRestTest.java b/duraboss/src/test/java/org/duracloud/duraboss/rest/InitRestTest.java
similarity index 91%
rename from durareport/src/test/java/org/duracloud/durareport/rest/InitRestTest.java
rename to duraboss/src/test/java/org/duracloud/duraboss/rest/InitRestTest.java
index d81415a50..faf416c4a 100644
--- a/durareport/src/test/java/org/duracloud/durareport/rest/InitRestTest.java
+++ b/duraboss/src/test/java/org/duracloud/duraboss/rest/InitRestTest.java
@@ -5,10 +5,9 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.rest;
+package org.duracloud.duraboss.rest;
import org.duracloud.common.rest.RestUtil;
-import org.duracloud.durareport.notification.NotificationManager;
import org.easymock.classextension.EasyMock;
import org.junit.After;
import org.junit.Before;
diff --git a/durareport/src/test/java/org/duracloud/durareport/rest/StorageReportResourceTest.java b/duraboss/src/test/java/org/duracloud/duraboss/rest/StorageReportResourceTest.java
similarity index 94%
rename from durareport/src/test/java/org/duracloud/durareport/rest/StorageReportResourceTest.java
rename to duraboss/src/test/java/org/duracloud/duraboss/rest/StorageReportResourceTest.java
index b83a33ddb..18635b595 100644
--- a/durareport/src/test/java/org/duracloud/durareport/rest/StorageReportResourceTest.java
+++ b/duraboss/src/test/java/org/duracloud/duraboss/rest/StorageReportResourceTest.java
@@ -5,12 +5,12 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.rest;
+package org.duracloud.duraboss.rest;
import org.duracloud.client.ContentStoreManager;
-import org.duracloud.durareport.storage.StorageReportBuilder;
-import org.duracloud.durareport.storage.StorageReportHandler;
-import org.duracloud.durareport.storage.StorageReportScheduler;
+import org.duracloud.reporter.storage.StorageReportBuilder;
+import org.duracloud.reporter.storage.StorageReportHandler;
+import org.duracloud.reporter.storage.StorageReportScheduler;
import org.duracloud.reportdata.storage.StorageReportList;
import org.easymock.classextension.EasyMock;
import org.junit.After;
diff --git a/duradmin/src/main/java/org/duracloud/duradmin/config/DuradminConfig.java b/duradmin/src/main/java/org/duracloud/duradmin/config/DuradminConfig.java
index 0a9bb4244..96b63a994 100644
--- a/duradmin/src/main/java/org/duracloud/duradmin/config/DuradminConfig.java
+++ b/duradmin/src/main/java/org/duracloud/duradmin/config/DuradminConfig.java
@@ -35,7 +35,7 @@ public class DuradminConfig
private static String duraserviceContextKey = "duraserviceContext";
- private static String durareportContextKey = "durareportContext";
+ private static String durabossContextKey = "durabossContext";
private static boolean initialized = false;
@@ -128,25 +128,25 @@ private static void initFromProperties() {
config.setDuraServiceHost(getPropsHost());
config.setDuraServicePort(getPropsPort());
config.setDuraServiceContext(getPropsDuraServiceContext());
- config.setDuraReportContext(getPropsDuraReportContext());
+ config.setDuraBossContext(getPropsDuraBossContext());
config.setAmaUrl(null); // default is null.
}
- private static String getPropsDuraReportContext() {
- return getProps().getProperty(durareportContextKey, "durareport");
+ private static String getPropsDuraBossContext() {
+ return getProps().getProperty(durabossContextKey, "duraboss");
}
- public static String getDuraReportHost() {
+ public static String getDuraBossHost() {
return getPropsHost();
}
- public static String getDuraReportPort() {
+ public static String getDuraBossPort() {
return getPropsPort();
}
- public static String getDuraReportContext() {
- return getPropsDuraReportContext();
+ public static String getDuraBossContext() {
+ return getPropsDuraBossContext();
}
}
diff --git a/duradmin/src/main/java/org/duracloud/duradmin/control/InitController.java b/duradmin/src/main/java/org/duracloud/duradmin/control/InitController.java
index 596a86d2b..b314af056 100644
--- a/duradmin/src/main/java/org/duracloud/duradmin/control/InitController.java
+++ b/duradmin/src/main/java/org/duracloud/duradmin/control/InitController.java
@@ -7,18 +7,6 @@
*/
package org.duracloud.duradmin.control;
-import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
-import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
-import static javax.servlet.http.HttpServletResponse.SC_METHOD_NOT_ALLOWED;
-import static javax.servlet.http.HttpServletResponse.SC_OK;
-import static javax.servlet.http.HttpServletResponse.SC_SERVICE_UNAVAILABLE;
-import static org.duracloud.appconfig.xml.DuradminInitDocumentBinding.createDuradminConfigFrom;
-import static org.duracloud.common.util.ExceptionUtil.getStackTraceAsString;
-
-import javax.servlet.ServletInputStream;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
import org.duracloud.common.util.InitUtil;
import org.duracloud.duradmin.config.DuradminConfig;
import org.duracloud.duradmin.domain.AdminInit;
@@ -27,6 +15,18 @@
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
+import javax.servlet.ServletInputStream;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
+import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
+import static javax.servlet.http.HttpServletResponse.SC_METHOD_NOT_ALLOWED;
+import static javax.servlet.http.HttpServletResponse.SC_OK;
+import static javax.servlet.http.HttpServletResponse.SC_SERVICE_UNAVAILABLE;
+import static org.duracloud.appconfig.xml.DuradminInitDocumentBinding.createDuradminConfigFrom;
+import static org.duracloud.common.util.ExceptionUtil.getStackTraceAsString;
+
/**
* This class initializes the application based on the xml body of the
* servlet request.
@@ -87,7 +87,7 @@ private void updateInit(org.duracloud.appconfig.domain.DuradminConfig config)
init.setDuraStorePort(config.getDurastorePort());
init.setDuraStoreContext(config.getDurastoreContext());
init.setAmaUrl(config.getAmaUrl());
- init.setDuraReportContext(config.getDurareportContext());
+ init.setDuraBossContext(config.getDurabossContext());
DuradminConfig.setConfig(init);
diff --git a/duradmin/src/main/java/org/duracloud/duradmin/domain/AdminInit.java b/duradmin/src/main/java/org/duracloud/duradmin/domain/AdminInit.java
index fb2c01517..a86141417 100644
--- a/duradmin/src/main/java/org/duracloud/duradmin/domain/AdminInit.java
+++ b/duradmin/src/main/java/org/duracloud/duradmin/domain/AdminInit.java
@@ -20,7 +20,7 @@ public class AdminInit {
private String duraServicePort;
private String duraServiceContext;
private String amaUrl;
- private String duraReportContext;
+ private String duraBossContext;
public String getDuraStoreHost() {
return duraStoreHost;
@@ -78,11 +78,11 @@ public void setAmaUrl(String amaUrl) {
this.amaUrl = amaUrl;
}
- public void setDuraReportContext(String durareportContext) {
- this.duraReportContext = durareportContext;
+ public void setDuraBossContext(String durabossContext) {
+ this.duraBossContext = durabossContext;
}
- public String getDuraReportContext() {
- return duraReportContext;
+ public String getDuraBossContext() {
+ return duraBossContext;
}
}
\ No newline at end of file
diff --git a/duradmin/src/main/java/org/duracloud/duradmin/report/DuradminServiceReportManagerImpl.java b/duradmin/src/main/java/org/duracloud/duradmin/report/DuradminServiceReportManagerImpl.java
index 0ce7fed09..7ff47e0b0 100644
--- a/duradmin/src/main/java/org/duracloud/duradmin/report/DuradminServiceReportManagerImpl.java
+++ b/duradmin/src/main/java/org/duracloud/duradmin/report/DuradminServiceReportManagerImpl.java
@@ -18,9 +18,9 @@
public class DuradminServiceReportManagerImpl extends ServiceReportManagerImpl{
public DuradminServiceReportManagerImpl(){
- super(DuradminConfig.getDuraReportHost(),
- DuradminConfig.getDuraReportPort(),
- DuradminConfig.getDuraReportContext());
+ super(DuradminConfig.getDuraBossHost(),
+ DuradminConfig.getDuraBossPort(),
+ DuradminConfig.getDuraBossContext());
}
}
diff --git a/duradmin/src/main/java/org/duracloud/duradmin/report/DuradminStorageReportManagerImpl.java b/duradmin/src/main/java/org/duracloud/duradmin/report/DuradminStorageReportManagerImpl.java
index d39f2a04d..cdc306fa3 100644
--- a/duradmin/src/main/java/org/duracloud/duradmin/report/DuradminStorageReportManagerImpl.java
+++ b/duradmin/src/main/java/org/duracloud/duradmin/report/DuradminStorageReportManagerImpl.java
@@ -18,9 +18,9 @@
public class DuradminStorageReportManagerImpl extends StorageReportManagerImpl{
public DuradminStorageReportManagerImpl(){
- super(DuradminConfig.getDuraReportHost(),
- DuradminConfig.getDuraReportPort(),
- DuradminConfig.getDuraReportContext());
+ super(DuradminConfig.getDuraBossHost(),
+ DuradminConfig.getDuraBossPort(),
+ DuradminConfig.getDuraBossContext());
}
}
diff --git a/pom.xml b/pom.xml
index 38c30178a..f350a075f 100644
--- a/pom.xml
+++ b/pom.xml
@@ -85,7 +85,8 @@
<module>servicemonitor</module>
<module>duraservice</module>
<module>reportdata</module>
- <module>durareport</module>
+ <module>reporter</module>
+ <module>duraboss</module>
<module>reportclient</module>
<module>app-config</module>
<module>serviceclient</module>
diff --git a/reportclient/resources/ExampleReportClient.java b/reportclient/resources/ExampleReportClient.java
index 8916e76e7..c5bd7f30d 100644
--- a/reportclient/resources/ExampleReportClient.java
+++ b/reportclient/resources/ExampleReportClient.java
@@ -24,8 +24,8 @@
import java.util.Map;
/**
- * Example code which connects to the DuraCloud DuraReport REST API by using
- * the ReportClient.
+ * Example code which connects to the DuraCloud DuraBoss reporting REST API
+ * by using the ReportClient.
*
* @author Bill Branan
* Date: 6/2/11
@@ -36,7 +36,7 @@ public class ExampleReportClient {
private static final String PASSWORD = "upw"; // replace as necessary
private static final String HOST = "localhost"; // replace as necessary
private static final String PORT = "8080"; // replace as necessary
- private static final String CONTEXT = "durareport";
+ private static final String CONTEXT = "duraboss";
private StorageReportManager storageReportManager;
private ServiceReportManager serviceReportManager;
diff --git a/reportclient/resources/readme.txt b/reportclient/resources/readme.txt
index 71ac7f584..07ab8cc19 100644
--- a/reportclient/resources/readme.txt
+++ b/reportclient/resources/readme.txt
@@ -4,11 +4,11 @@
DuraCloud provides reporting over both storage and service functions
which occur within the DuraCloud framework. The building of these
-reports is managed by the DuraReport web application. DuraReport
+reports is managed by the DuraBoss web application. DuraBoss
is installed and running on your DuraCloud instance and can be
accessed via a REST interface. In order to aid Java developers in
-communicating with DuraReport, a Java client, called ReportClient
-was written.
+communicating with DuraBoss report features, a Java client, called
+ReportClient was written.
2. Using ReportClient
diff --git a/reportclient/src/main/java/org/duracloud/client/report/BaseReportManager.java b/reportclient/src/main/java/org/duracloud/client/report/BaseReportManager.java
index e44308ace..70553369b 100644
--- a/reportclient/src/main/java/org/duracloud/client/report/BaseReportManager.java
+++ b/reportclient/src/main/java/org/duracloud/client/report/BaseReportManager.java
@@ -25,7 +25,7 @@ public abstract class BaseReportManager implements Securable {
protected RestHttpHelper restHelper;
- private static final String DEFAULT_CONTEXT = "durareport";
+ private static final String DEFAULT_CONTEXT = "duraboss";
private String baseURL = null;
public BaseReportManager(String host, String port) {
diff --git a/reportclient/src/main/java/org/duracloud/client/report/ServiceReportManagerImpl.java b/reportclient/src/main/java/org/duracloud/client/report/ServiceReportManagerImpl.java
index da15ee2c2..6b14fd06a 100644
--- a/reportclient/src/main/java/org/duracloud/client/report/ServiceReportManagerImpl.java
+++ b/reportclient/src/main/java/org/duracloud/client/report/ServiceReportManagerImpl.java
@@ -35,7 +35,7 @@ public ServiceReportManagerImpl(String host, String port, String context) {
}
private String buildURL(String relativeURL) {
- String storageReport = "servicereport";
+ String storageReport = "report/service";
if (null == relativeURL) {
return getBaseURL() + "/" + storageReport;
}
diff --git a/reportclient/src/main/java/org/duracloud/client/report/StorageReportManager.java b/reportclient/src/main/java/org/duracloud/client/report/StorageReportManager.java
index e6ac9a3bf..a9f44d973 100644
--- a/reportclient/src/main/java/org/duracloud/client/report/StorageReportManager.java
+++ b/reportclient/src/main/java/org/duracloud/client/report/StorageReportManager.java
@@ -17,7 +17,7 @@
import java.util.List;
/**
- * Allows for communication with DuraReport
+ * Allows for communication with DuraBoss reporting
*
* @author: Bill Branan
* Date: 6/2/11
@@ -66,7 +66,7 @@ public StorageReportInfo getStorageReportInfo()
throws ReportException;
/**
- * Tells DuraReport to start running a new storage report generation
+ * Tells DuraBoss reporting to start running a new storage report generation
* process. If a report generation process is already underway, this
* call is ignored.
*
diff --git a/reportclient/src/main/java/org/duracloud/client/report/StorageReportManagerImpl.java b/reportclient/src/main/java/org/duracloud/client/report/StorageReportManagerImpl.java
index 6dc1b67b7..3a936136e 100644
--- a/reportclient/src/main/java/org/duracloud/client/report/StorageReportManagerImpl.java
+++ b/reportclient/src/main/java/org/duracloud/client/report/StorageReportManagerImpl.java
@@ -24,7 +24,7 @@
import java.util.List;
/**
- * Allows for communication with DuraReport
+ * Allows for communication with Duraboss reporting
*
* @author: Bill Branan
* Date: 6/2/11
@@ -40,7 +40,7 @@ public StorageReportManagerImpl(String host, String port, String context) {
}
private String buildURL(String relativeURL) {
- String storageReport = "storagereport";
+ String storageReport = "report/storage";
if (null == relativeURL) {
return getBaseURL() + "/" + storageReport;
}
diff --git a/reportclient/src/test/java/org/duracloud/client/report/ServiceReportManagerImplTest.java b/reportclient/src/test/java/org/duracloud/client/report/ServiceReportManagerImplTest.java
index 297c709c0..068d5ca23 100644
--- a/reportclient/src/test/java/org/duracloud/client/report/ServiceReportManagerImplTest.java
+++ b/reportclient/src/test/java/org/duracloud/client/report/ServiceReportManagerImplTest.java
@@ -47,7 +47,7 @@ public void setup() {
}
private String getBaseUrl() {
- return baseUrl + "/servicereport";
+ return baseUrl + "/report/service";
}
@Test
diff --git a/reportclient/src/test/java/org/duracloud/client/report/StorageReportManagerImplTest.java b/reportclient/src/test/java/org/duracloud/client/report/StorageReportManagerImplTest.java
index 6b6c53428..63081cfcc 100644
--- a/reportclient/src/test/java/org/duracloud/client/report/StorageReportManagerImplTest.java
+++ b/reportclient/src/test/java/org/duracloud/client/report/StorageReportManagerImplTest.java
@@ -46,7 +46,7 @@ public void setup() {
}
private String getBaseUrl() {
- return baseUrl + "/storagereport";
+ return baseUrl + "/report/storage";
}
@Test
diff --git a/durareport/.springBeans b/reporter/.springBeans
similarity index 100%
rename from durareport/.springBeans
rename to reporter/.springBeans
diff --git a/durareport/pom.xml b/reporter/pom.xml
similarity index 68%
rename from durareport/pom.xml
rename to reporter/pom.xml
index 0e1a31cb8..35d60103c 100644
--- a/durareport/pom.xml
+++ b/reporter/pom.xml
@@ -1,10 +1,10 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.duracloud</groupId>
- <artifactId>durareport</artifactId>
- <packaging>war</packaging>
+ <artifactId>reporter</artifactId>
+ <packaging>jar</packaging>
<version>1.4.0-SNAPSHOT</version>
- <name>DuraCloud DuraReport</name>
+ <name>DuraCloud Reporter</name>
<url>http://localhost:8080/${artifactId}</url>
<parent>
@@ -14,31 +14,6 @@
<relativePath>../pom.xml</relativePath>
</parent>
- <build>
-
- <plugins>
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-jar-plugin</artifactId>
- <version>2.3.1</version>
- <executions>
- <execution>
- <phase>package</phase>
- <goals>
- <goal>jar</goal>
- </goals>
- <configuration>
- <classifier>for-integration-test</classifier>
- </configuration>
- </execution>
- </executions>
- </plugin>
-
- </plugins>
-
- </build>
-
<dependencies>
<!-- internal projects -->
@@ -114,31 +89,6 @@
<version>${project.version}</version>
</dependency>
- <!-- for Spring -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-core</artifactId>
- <scope>compile</scope>
- </dependency>
-
- <!-- for Jersey -->
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-server</artifactId>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey.contribs</groupId>
- <artifactId>jersey-spring</artifactId>
- </dependency>
- <dependency>
- <groupId>com.sun.xml.bind</groupId>
- <artifactId>jaxb-impl</artifactId>
- </dependency>
- <dependency>
- <groupId>javax.mail</groupId>
- <artifactId>mail</artifactId>
- </dependency>
-
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
diff --git a/durareport/src/main/java/org/duracloud/durareport/error/InvalidScheduleException.java b/reporter/src/main/java/org/duracloud/reporter/error/InvalidScheduleException.java
similarity index 89%
rename from durareport/src/main/java/org/duracloud/durareport/error/InvalidScheduleException.java
rename to reporter/src/main/java/org/duracloud/reporter/error/InvalidScheduleException.java
index 906ae09a7..369882589 100644
--- a/durareport/src/main/java/org/duracloud/durareport/error/InvalidScheduleException.java
+++ b/reporter/src/main/java/org/duracloud/reporter/error/InvalidScheduleException.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.error;
+package org.duracloud.reporter.error;
import org.duracloud.common.error.DuraCloudRuntimeException;
diff --git a/durareport/src/main/java/org/duracloud/durareport/error/ReportBuilderException.java b/reporter/src/main/java/org/duracloud/reporter/error/ReportBuilderException.java
similarity index 90%
rename from durareport/src/main/java/org/duracloud/durareport/error/ReportBuilderException.java
rename to reporter/src/main/java/org/duracloud/reporter/error/ReportBuilderException.java
index 59e53ce29..8574cd6ee 100644
--- a/durareport/src/main/java/org/duracloud/durareport/error/ReportBuilderException.java
+++ b/reporter/src/main/java/org/duracloud/reporter/error/ReportBuilderException.java
@@ -1,26 +1,26 @@
-/*
- * The contents of this file are subject to the license and copyright
- * detailed in the LICENSE and NOTICE files at the root of the source
- * tree and available online at
- *
- * http://duracloud.org/license/
- */
-package org.duracloud.durareport.error;
-
-import org.duracloud.common.error.DuraCloudRuntimeException;
-
-/**
- * @author: Bill Branan
- * Date: 5/16/11
- */
-public class ReportBuilderException extends DuraCloudRuntimeException {
-
- public ReportBuilderException(String message) {
- super(message);
- }
-
- public ReportBuilderException(String message, Throwable throwable) {
- super(message, throwable);
- }
-
-}
+/*
+ * The contents of this file are subject to the license and copyright
+ * detailed in the LICENSE and NOTICE files at the root of the source
+ * tree and available online at
+ *
+ * http://duracloud.org/license/
+ */
+package org.duracloud.reporter.error;
+
+import org.duracloud.common.error.DuraCloudRuntimeException;
+
+/**
+ * @author: Bill Branan
+ * Date: 5/16/11
+ */
+public class ReportBuilderException extends DuraCloudRuntimeException {
+
+ public ReportBuilderException(String message) {
+ super(message);
+ }
+
+ public ReportBuilderException(String message, Throwable throwable) {
+ super(message, throwable);
+ }
+
+}
diff --git a/durareport/src/main/java/org/duracloud/durareport/error/StorageReportCancelledException.java b/reporter/src/main/java/org/duracloud/reporter/error/StorageReportCancelledException.java
similarity index 87%
rename from durareport/src/main/java/org/duracloud/durareport/error/StorageReportCancelledException.java
rename to reporter/src/main/java/org/duracloud/reporter/error/StorageReportCancelledException.java
index 9b2c47e5c..be5613029 100644
--- a/durareport/src/main/java/org/duracloud/durareport/error/StorageReportCancelledException.java
+++ b/reporter/src/main/java/org/duracloud/reporter/error/StorageReportCancelledException.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.error;
+package org.duracloud.reporter.error;
import org.duracloud.common.error.DuraCloudRuntimeException;
diff --git a/durareport/src/main/java/org/duracloud/durareport/notification/EmailNotifier.java b/reporter/src/main/java/org/duracloud/reporter/notification/EmailNotifier.java
similarity index 94%
rename from durareport/src/main/java/org/duracloud/durareport/notification/EmailNotifier.java
rename to reporter/src/main/java/org/duracloud/reporter/notification/EmailNotifier.java
index b358e039f..db5de363b 100644
--- a/durareport/src/main/java/org/duracloud/durareport/notification/EmailNotifier.java
+++ b/reporter/src/main/java/org/duracloud/reporter/notification/EmailNotifier.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.notification;
+package org.duracloud.reporter.notification;
import org.duracloud.appconfig.domain.NotificationConfig;
import org.duracloud.notification.AmazonNotificationFactory;
diff --git a/durareport/src/main/java/org/duracloud/durareport/notification/NotificationManager.java b/reporter/src/main/java/org/duracloud/reporter/notification/NotificationManager.java
similarity index 95%
rename from durareport/src/main/java/org/duracloud/durareport/notification/NotificationManager.java
rename to reporter/src/main/java/org/duracloud/reporter/notification/NotificationManager.java
index ed0307506..617b45985 100644
--- a/durareport/src/main/java/org/duracloud/durareport/notification/NotificationManager.java
+++ b/reporter/src/main/java/org/duracloud/reporter/notification/NotificationManager.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.notification;
+package org.duracloud.reporter.notification;
import org.duracloud.appconfig.domain.NotificationConfig;
diff --git a/durareport/src/main/java/org/duracloud/durareport/notification/NotificationType.java b/reporter/src/main/java/org/duracloud/reporter/notification/NotificationType.java
similarity index 84%
rename from durareport/src/main/java/org/duracloud/durareport/notification/NotificationType.java
rename to reporter/src/main/java/org/duracloud/reporter/notification/NotificationType.java
index 339d6adc1..4f5ade096 100644
--- a/durareport/src/main/java/org/duracloud/durareport/notification/NotificationType.java
+++ b/reporter/src/main/java/org/duracloud/reporter/notification/NotificationType.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.notification;
+package org.duracloud.reporter.notification;
/**
* Defines the supported types of notification.
diff --git a/durareport/src/main/java/org/duracloud/durareport/notification/Notifier.java b/reporter/src/main/java/org/duracloud/reporter/notification/Notifier.java
similarity index 93%
rename from durareport/src/main/java/org/duracloud/durareport/notification/Notifier.java
rename to reporter/src/main/java/org/duracloud/reporter/notification/Notifier.java
index 61f31669d..c1e6895d4 100644
--- a/durareport/src/main/java/org/duracloud/durareport/notification/Notifier.java
+++ b/reporter/src/main/java/org/duracloud/reporter/notification/Notifier.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.notification;
+package org.duracloud.reporter.notification;
import org.duracloud.appconfig.domain.NotificationConfig;
diff --git a/durareport/src/main/java/org/duracloud/durareport/service/ServiceNotificationMonitor.java b/reporter/src/main/java/org/duracloud/reporter/service/ServiceNotificationMonitor.java
similarity index 92%
rename from durareport/src/main/java/org/duracloud/durareport/service/ServiceNotificationMonitor.java
rename to reporter/src/main/java/org/duracloud/reporter/service/ServiceNotificationMonitor.java
index 93d9917c7..b61f6020b 100644
--- a/durareport/src/main/java/org/duracloud/durareport/service/ServiceNotificationMonitor.java
+++ b/reporter/src/main/java/org/duracloud/reporter/service/ServiceNotificationMonitor.java
@@ -5,10 +5,10 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.service;
+package org.duracloud.reporter.service;
-import org.duracloud.durareport.notification.NotificationManager;
-import org.duracloud.durareport.notification.NotificationType;
+import org.duracloud.reporter.notification.NotificationManager;
+import org.duracloud.reporter.notification.NotificationType;
import org.duracloud.security.DuracloudUserDetailsService;
import org.duracloud.security.domain.SecurityUserBean;
import org.duracloud.serviceconfig.ServiceSummary;
diff --git a/durareport/src/main/java/org/duracloud/durareport/service/ServiceReportBuilder.java b/reporter/src/main/java/org/duracloud/reporter/service/ServiceReportBuilder.java
similarity index 94%
rename from durareport/src/main/java/org/duracloud/durareport/service/ServiceReportBuilder.java
rename to reporter/src/main/java/org/duracloud/reporter/service/ServiceReportBuilder.java
index 351655670..d1e642615 100644
--- a/durareport/src/main/java/org/duracloud/durareport/service/ServiceReportBuilder.java
+++ b/reporter/src/main/java/org/duracloud/reporter/service/ServiceReportBuilder.java
@@ -5,11 +5,11 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.service;
+package org.duracloud.reporter.service;
import org.duracloud.common.util.IOUtil;
-import org.duracloud.durareport.error.ReportBuilderException;
-import org.duracloud.durareport.storage.StorageReportScheduler;
+import org.duracloud.reporter.error.ReportBuilderException;
+import org.duracloud.reporter.storage.StorageReportScheduler;
import org.duracloud.serviceconfig.ServiceReportList;
import org.duracloud.serviceconfig.ServiceSummariesDocument;
import org.duracloud.serviceconfig.ServiceSummary;
diff --git a/durareport/src/main/java/org/duracloud/durareport/storage/StorageReportBuilder.java b/reporter/src/main/java/org/duracloud/reporter/storage/StorageReportBuilder.java
similarity index 94%
rename from durareport/src/main/java/org/duracloud/durareport/storage/StorageReportBuilder.java
rename to reporter/src/main/java/org/duracloud/reporter/storage/StorageReportBuilder.java
index 806081a85..f084f9d2d 100644
--- a/durareport/src/main/java/org/duracloud/durareport/storage/StorageReportBuilder.java
+++ b/reporter/src/main/java/org/duracloud/reporter/storage/StorageReportBuilder.java
@@ -1,289 +1,289 @@
-/*
- * The contents of this file are subject to the license and copyright
- * detailed in the LICENSE and NOTICE files at the root of the source
- * tree and available online at
- *
- * http://duracloud.org/license/
- */
-package org.duracloud.durareport.storage;
-
-import org.duracloud.client.ContentStore;
-import org.duracloud.client.ContentStoreManager;
-import org.duracloud.common.error.DuraCloudCheckedException;
-import org.duracloud.durareport.error.ReportBuilderException;
-import org.duracloud.durareport.error.StorageReportCancelledException;
-import org.duracloud.durareport.storage.metrics.DuraStoreMetricsCollector;
-import org.duracloud.error.ContentStoreException;
-import org.duracloud.reportdata.storage.StorageReport;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Builder to be run in a thread to generate metrics reports.
- *
- * @author: Bill Branan
- * Date: 5/12/11
- */
-public class StorageReportBuilder implements Runnable {
-
- public static enum Status {CREATED, RUNNING, COMPLETE, CANCELLED, ERROR};
- private final Logger log =
- LoggerFactory.getLogger(StorageReportBuilder.class);
- public static final int maxRetries = 20;
-
- private ContentStoreManager storeMgr = null;
- private StorageReportHandler reportHandler;
-
- private Status status;
- private String error;
- private long startTime;
- private long stopTime;
- private long elapsedTime;
- private boolean run;
-
- private DuraStoreMetricsCollector durastoreMetrics;
-
- public StorageReportBuilder(ContentStoreManager storeMgr,
- StorageReportHandler reportHandler) {
- this.storeMgr = storeMgr;
- this.reportHandler = reportHandler;
- this.status = Status.CREATED;
- this.error = null;
- this.startTime = 0;
- this.stopTime = 0;
- this.elapsedTime = 0;
-
- try {
- StorageReport lastReport = reportHandler.getLatestStorageReport();
- if(null != lastReport) {
- this.stopTime = lastReport.getCompletionTime();
- this.elapsedTime = lastReport.getElapsedTime();
- }
- } catch(Exception e) {
- log.warn("Unable to retrieve latest storage report due to: " +
- e.getMessage());
- }
- }
-
- @Override
- public void run() {
- run = true;
- error = null;
- startTime = System.currentTimeMillis();
- log.info("Storage Report starting at time: " + startTime);
- status = Status.RUNNING;
- try {
- collectStorageMetrics();
- stopTime = System.currentTimeMillis();
- elapsedTime = stopTime - startTime;
- reportHandler.storeReport(durastoreMetrics,
- stopTime,
- elapsedTime);
- status = Status.COMPLETE;
- log.info("Storage Report completed at time: " + stopTime);
- } catch (StorageReportCancelledException e) {
- stopTime = System.currentTimeMillis();
- log.warn("Storage Report cancelled at: " + stopTime);
- status = Status.CANCELLED;
- } catch(ReportBuilderException e) {
- stopTime = System.currentTimeMillis();
- String errMsg = "Unable to complete metrics collection due to: " +
- e.getMessage();
- error = errMsg;
- log.error(errMsg);
- reportHandler.addToErrorLog(errMsg);
- status = Status.ERROR;
- }
- }
-
- public void cancelReport() {
- new DuraCloudCheckedException(); // loads this exception type
- log.info("Cancelling Storage Report");
- run = false;
- }
-
- private void collectStorageMetrics() {
- durastoreMetrics = new DuraStoreMetricsCollector();
-
- Map<String, ContentStore> contentStores = retryGetContentStores();
- for(ContentStore contentStore : contentStores.values()) {
- checkRun();
- String storeId = contentStore.getStoreId();
- String storeType = contentStore.getStorageProviderType();
- for(String spaceId : retryGetSpaces(contentStore)) {
- checkRun();
- Iterator<String> contentIds =
- retryGetSpaceContents(contentStore, spaceId);
- while(contentIds.hasNext()) {
- checkRun();
- String contentId = contentIds.next();
- Map<String, String> contentProperties =
- retryGetContentProperties(contentStore,
- spaceId,
- contentId);
- updateMetrics(contentProperties,
- storeId,
- storeType,
- spaceId);
- }
- }
- }
- }
-
- private void updateMetrics(Map<String, String> contentProperties,
- String storeId,
- String storeType,
- String spaceId) {
- if(null != contentProperties) {
- String mimetype =
- contentProperties.get(ContentStore.CONTENT_MIMETYPE);
- long size =
- convert(contentProperties.get(ContentStore.CONTENT_SIZE));
- durastoreMetrics.update(storeId, storeType, spaceId, mimetype, size);
- }
- }
-
- private Map<String, ContentStore> retryGetContentStores() {
- for(int i=0; i<maxRetries; i++) {
- checkRun();
- try {
- return storeMgr.getContentStores();
- } catch (ContentStoreException e) {
- log.warn("Exception attempting to retrieve content " +
- "stores list: " + e.getMessage());
- wait(i);
- }
- }
- throw new ReportBuilderException("Exceeded retries attempting to " +
- "retrieve content stores list");
- }
-
- private List<String> retryGetSpaces(ContentStore contentStore) {
- for(int i=0; i<maxRetries; i++) {
- checkRun();
- try {
- return contentStore.getSpaces();
- } catch (ContentStoreException e) {
- String store = getStoreInfo(contentStore);
- log.warn("Exception attempting to retrieve spaces list for " +
- "store: " + store + " due to: " + e.getMessage());
- wait(i);
- }
- }
- throw new ReportBuilderException("Exceeded retries attempting to " +
- "retrieve spaces list");
- }
-
- private Iterator<String> retryGetSpaceContents(ContentStore contentStore,
- String spaceId) {
- for(int i=0; i<maxRetries; i++) {
- checkRun();
- try {
- return contentStore.getSpaceContents(spaceId);
- } catch (ContentStoreException e) {
- String store = getStoreInfo(contentStore);
- log.warn("Exception attempting to retrieve space contents " +
- "list (for " + spaceId + " in store " + store +
- "): " + e.getMessage());
- wait(i);
- }
- }
- throw new ReportBuilderException("Exceeded retries attempting to " +
- "retrieve space contents list " +
- "(for " + spaceId + ")");
- }
-
- private Map<String, String> retryGetContentProperties(ContentStore contentStore,
- String spaceId,
- String contentId) {
- for(int i=0; i<maxRetries; i++) {
- checkRun();
- try {
- return contentStore.getContentProperties(spaceId, contentId);
- } catch (ContentStoreException e) {
- String store = getStoreInfo(contentStore);
- log.warn("Exception attempting to retrieve content properties " +
- "(for " + spaceId + ":" + contentId + " in store " +
- store + "): " + e.getMessage());
- wait(i);
- }
- }
- log.error("Exceeded retries attempting to retrieve content properties " +
- "(for " + spaceId + ":" + contentId + "). Skipping item.");
- return null;
- }
-
- private String getStoreInfo(ContentStore contentStore) {
- return contentStore.getStoreId() + "(" +
- contentStore.getStorageProviderType() + ")";
- }
-
- private long convert(String sizeStr) {
- try {
- return Long.valueOf(sizeStr);
- } catch(NumberFormatException e) {
- return 0;
- }
- }
-
- private void wait(int index) {
- checkRun();
- try {
- Thread.sleep(1000 * index);
- } catch(InterruptedException e) {
- }
- }
-
- private void checkRun() {
- if(!run) {
- throw new StorageReportCancelledException();
- }
- }
-
- /**
- * Gets the current status of the report builder
- */
- public Status getStatus() {
- return status;
- }
-
- /**
- * Gets the text of the last error which occurred (if any)
- */
- public String getError() {
- return error;
- }
-
- /**
- * Gets the current count for the in-process report builder run
- */
- public long getCurrentCount() {
- return durastoreMetrics.getTotalItems();
- }
-
- /**
- * Gets the stop time (in millis) of the most recent report builder run
- */
- public long getStopTime() {
- return stopTime;
- }
-
- /**
- * Gets the starting time (in millis) of the most recent report builder run
- */
- public long getStartTime() {
- return startTime;
- }
-
- /**
- * Gets the time (in millis) required to complete the most recent
- * report builder run
- */
- public long getElapsedTime() {
- return elapsedTime;
- }
+/*
+ * The contents of this file are subject to the license and copyright
+ * detailed in the LICENSE and NOTICE files at the root of the source
+ * tree and available online at
+ *
+ * http://duracloud.org/license/
+ */
+package org.duracloud.reporter.storage;
+
+import org.duracloud.client.ContentStore;
+import org.duracloud.client.ContentStoreManager;
+import org.duracloud.common.error.DuraCloudCheckedException;
+import org.duracloud.reporter.error.ReportBuilderException;
+import org.duracloud.reporter.error.StorageReportCancelledException;
+import org.duracloud.reporter.storage.metrics.DuraStoreMetricsCollector;
+import org.duracloud.error.ContentStoreException;
+import org.duracloud.reportdata.storage.StorageReport;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Builder to be run in a thread to generate metrics reports.
+ *
+ * @author: Bill Branan
+ * Date: 5/12/11
+ */
+public class StorageReportBuilder implements Runnable {
+
+ public static enum Status {CREATED, RUNNING, COMPLETE, CANCELLED, ERROR};
+ private final Logger log =
+ LoggerFactory.getLogger(StorageReportBuilder.class);
+ public static final int maxRetries = 20;
+
+ private ContentStoreManager storeMgr = null;
+ private StorageReportHandler reportHandler;
+
+ private Status status;
+ private String error;
+ private long startTime;
+ private long stopTime;
+ private long elapsedTime;
+ private boolean run;
+
+ private DuraStoreMetricsCollector durastoreMetrics;
+
+ public StorageReportBuilder(ContentStoreManager storeMgr,
+ StorageReportHandler reportHandler) {
+ this.storeMgr = storeMgr;
+ this.reportHandler = reportHandler;
+ this.status = Status.CREATED;
+ this.error = null;
+ this.startTime = 0;
+ this.stopTime = 0;
+ this.elapsedTime = 0;
+
+ try {
+ StorageReport lastReport = reportHandler.getLatestStorageReport();
+ if(null != lastReport) {
+ this.stopTime = lastReport.getCompletionTime();
+ this.elapsedTime = lastReport.getElapsedTime();
+ }
+ } catch(Exception e) {
+ log.warn("Unable to retrieve latest storage report due to: " +
+ e.getMessage());
+ }
+ }
+
+ @Override
+ public void run() {
+ run = true;
+ error = null;
+ startTime = System.currentTimeMillis();
+ log.info("Storage Report starting at time: " + startTime);
+ status = Status.RUNNING;
+ try {
+ collectStorageMetrics();
+ stopTime = System.currentTimeMillis();
+ elapsedTime = stopTime - startTime;
+ reportHandler.storeReport(durastoreMetrics,
+ stopTime,
+ elapsedTime);
+ status = Status.COMPLETE;
+ log.info("Storage Report completed at time: " + stopTime);
+ } catch (StorageReportCancelledException e) {
+ stopTime = System.currentTimeMillis();
+ log.warn("Storage Report cancelled at: " + stopTime);
+ status = Status.CANCELLED;
+ } catch(ReportBuilderException e) {
+ stopTime = System.currentTimeMillis();
+ String errMsg = "Unable to complete metrics collection due to: " +
+ e.getMessage();
+ error = errMsg;
+ log.error(errMsg);
+ reportHandler.addToErrorLog(errMsg);
+ status = Status.ERROR;
+ }
+ }
+
+ public void cancelReport() {
+ new DuraCloudCheckedException(); // loads this exception type
+ log.info("Cancelling Storage Report");
+ run = false;
+ }
+
+ private void collectStorageMetrics() {
+ durastoreMetrics = new DuraStoreMetricsCollector();
+
+ Map<String, ContentStore> contentStores = retryGetContentStores();
+ for(ContentStore contentStore : contentStores.values()) {
+ checkRun();
+ String storeId = contentStore.getStoreId();
+ String storeType = contentStore.getStorageProviderType();
+ for(String spaceId : retryGetSpaces(contentStore)) {
+ checkRun();
+ Iterator<String> contentIds =
+ retryGetSpaceContents(contentStore, spaceId);
+ while(contentIds.hasNext()) {
+ checkRun();
+ String contentId = contentIds.next();
+ Map<String, String> contentProperties =
+ retryGetContentProperties(contentStore,
+ spaceId,
+ contentId);
+ updateMetrics(contentProperties,
+ storeId,
+ storeType,
+ spaceId);
+ }
+ }
+ }
+ }
+
+ private void updateMetrics(Map<String, String> contentProperties,
+ String storeId,
+ String storeType,
+ String spaceId) {
+ if(null != contentProperties) {
+ String mimetype =
+ contentProperties.get(ContentStore.CONTENT_MIMETYPE);
+ long size =
+ convert(contentProperties.get(ContentStore.CONTENT_SIZE));
+ durastoreMetrics.update(storeId, storeType, spaceId, mimetype, size);
+ }
+ }
+
+ private Map<String, ContentStore> retryGetContentStores() {
+ for(int i=0; i<maxRetries; i++) {
+ checkRun();
+ try {
+ return storeMgr.getContentStores();
+ } catch (ContentStoreException e) {
+ log.warn("Exception attempting to retrieve content " +
+ "stores list: " + e.getMessage());
+ wait(i);
+ }
+ }
+ throw new ReportBuilderException("Exceeded retries attempting to " +
+ "retrieve content stores list");
+ }
+
+ private List<String> retryGetSpaces(ContentStore contentStore) {
+ for(int i=0; i<maxRetries; i++) {
+ checkRun();
+ try {
+ return contentStore.getSpaces();
+ } catch (ContentStoreException e) {
+ String store = getStoreInfo(contentStore);
+ log.warn("Exception attempting to retrieve spaces list for " +
+ "store: " + store + " due to: " + e.getMessage());
+ wait(i);
+ }
+ }
+ throw new ReportBuilderException("Exceeded retries attempting to " +
+ "retrieve spaces list");
+ }
+
+ private Iterator<String> retryGetSpaceContents(ContentStore contentStore,
+ String spaceId) {
+ for(int i=0; i<maxRetries; i++) {
+ checkRun();
+ try {
+ return contentStore.getSpaceContents(spaceId);
+ } catch (ContentStoreException e) {
+ String store = getStoreInfo(contentStore);
+ log.warn("Exception attempting to retrieve space contents " +
+ "list (for " + spaceId + " in store " + store +
+ "): " + e.getMessage());
+ wait(i);
+ }
+ }
+ throw new ReportBuilderException("Exceeded retries attempting to " +
+ "retrieve space contents list " +
+ "(for " + spaceId + ")");
+ }
+
+ private Map<String, String> retryGetContentProperties(ContentStore contentStore,
+ String spaceId,
+ String contentId) {
+ for(int i=0; i<maxRetries; i++) {
+ checkRun();
+ try {
+ return contentStore.getContentProperties(spaceId, contentId);
+ } catch (ContentStoreException e) {
+ String store = getStoreInfo(contentStore);
+ log.warn("Exception attempting to retrieve content properties " +
+ "(for " + spaceId + ":" + contentId + " in store " +
+ store + "): " + e.getMessage());
+ wait(i);
+ }
+ }
+ log.error("Exceeded retries attempting to retrieve content properties " +
+ "(for " + spaceId + ":" + contentId + "). Skipping item.");
+ return null;
+ }
+
+ private String getStoreInfo(ContentStore contentStore) {
+ return contentStore.getStoreId() + "(" +
+ contentStore.getStorageProviderType() + ")";
+ }
+
+ private long convert(String sizeStr) {
+ try {
+ return Long.valueOf(sizeStr);
+ } catch(NumberFormatException e) {
+ return 0;
+ }
+ }
+
+ private void wait(int index) {
+ checkRun();
+ try {
+ Thread.sleep(1000 * index);
+ } catch(InterruptedException e) {
+ }
+ }
+
+ private void checkRun() {
+ if(!run) {
+ throw new StorageReportCancelledException();
+ }
+ }
+
+ /**
+ * Gets the current status of the report builder
+ */
+ public Status getStatus() {
+ return status;
+ }
+
+ /**
+ * Gets the text of the last error which occurred (if any)
+ */
+ public String getError() {
+ return error;
+ }
+
+ /**
+ * Gets the current count for the in-process report builder run
+ */
+ public long getCurrentCount() {
+ return durastoreMetrics.getTotalItems();
+ }
+
+ /**
+ * Gets the stop time (in millis) of the most recent report builder run
+ */
+ public long getStopTime() {
+ return stopTime;
+ }
+
+ /**
+ * Gets the starting time (in millis) of the most recent report builder run
+ */
+ public long getStartTime() {
+ return startTime;
+ }
+
+ /**
+ * Gets the time (in millis) required to complete the most recent
+ * report builder run
+ */
+ public long getElapsedTime() {
+ return elapsedTime;
+ }
}
\ No newline at end of file
diff --git a/durareport/src/main/java/org/duracloud/durareport/storage/StorageReportConverter.java b/reporter/src/main/java/org/duracloud/reporter/storage/StorageReportConverter.java
similarity index 88%
rename from durareport/src/main/java/org/duracloud/durareport/storage/StorageReportConverter.java
rename to reporter/src/main/java/org/duracloud/reporter/storage/StorageReportConverter.java
index 695f72286..ffea055a2 100644
--- a/durareport/src/main/java/org/duracloud/durareport/storage/StorageReportConverter.java
+++ b/reporter/src/main/java/org/duracloud/reporter/storage/StorageReportConverter.java
@@ -5,12 +5,12 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.storage;
+package org.duracloud.reporter.storage;
-import org.duracloud.durareport.storage.metrics.DuraStoreMetricsCollector;
-import org.duracloud.durareport.storage.metrics.MimetypeMetricsCollector;
-import org.duracloud.durareport.storage.metrics.SpaceMetricsCollector;
-import org.duracloud.durareport.storage.metrics.StorageProviderMetricsCollector;
+import org.duracloud.reporter.storage.metrics.DuraStoreMetricsCollector;
+import org.duracloud.reporter.storage.metrics.MimetypeMetricsCollector;
+import org.duracloud.reporter.storage.metrics.SpaceMetricsCollector;
+import org.duracloud.reporter.storage.metrics.StorageProviderMetricsCollector;
import org.duracloud.reportdata.storage.StorageReport;
import org.duracloud.reportdata.storage.metrics.MimetypeMetrics;
import org.duracloud.reportdata.storage.metrics.SpaceMetrics;
diff --git a/durareport/src/main/java/org/duracloud/durareport/storage/StorageReportHandler.java b/reporter/src/main/java/org/duracloud/reporter/storage/StorageReportHandler.java
similarity index 95%
rename from durareport/src/main/java/org/duracloud/durareport/storage/StorageReportHandler.java
rename to reporter/src/main/java/org/duracloud/reporter/storage/StorageReportHandler.java
index 1b5e87310..0f7c31a38 100644
--- a/durareport/src/main/java/org/duracloud/durareport/storage/StorageReportHandler.java
+++ b/reporter/src/main/java/org/duracloud/reporter/storage/StorageReportHandler.java
@@ -1,327 +1,327 @@
-/*
- * The contents of this file are subject to the license and copyright
- * detailed in the LICENSE and NOTICE files at the root of the source
- * tree and available online at
- *
- * http://duracloud.org/license/
- */
-package org.duracloud.durareport.storage;
-
-import org.apache.commons.io.IOUtils;
-import org.duracloud.client.ContentStore;
-import org.duracloud.client.ContentStoreManager;
-import org.duracloud.common.error.DuraCloudRuntimeException;
-import org.duracloud.common.util.ChecksumUtil;
-import org.duracloud.common.util.DateUtil;
-import org.duracloud.domain.Content;
-import org.duracloud.durareport.error.ReportBuilderException;
-import org.duracloud.durareport.storage.metrics.DuraStoreMetricsCollector;
-import org.duracloud.error.ContentStoreException;
-import org.duracloud.error.NotFoundException;
-import org.duracloud.reportdata.storage.StorageReport;
-import org.duracloud.reportdata.storage.StorageReportList;
-import org.duracloud.reportdata.storage.serialize.StorageReportSerializer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.ws.rs.core.MediaType;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.SequenceInputStream;
-import java.io.UnsupportedEncodingException;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.Map;
-
-/**
- * Handles the storage and retrieval of storage reports.
- *
- * @author: Bill Branan
- * Date: 5/13/11
- */
-public class StorageReportHandler {
-
- private final Logger log =
- LoggerFactory.getLogger(StorageReportHandler.class);
-
- private static final String REPORT_FILE_NAME_SUFFIX = ".xml";
- public static final String COMPLETION_TIME_META = "completion-time";
- public static final String ELAPSED_TIME_META = "elapsed-time";
- public static final int maxRetries = 8;
-
- protected String storageSpace;
- private ContentStore primaryStore = null;
- private String reportFileNamePrefix;
- private String reportErrorLogFileName;
-
- public StorageReportHandler(ContentStoreManager storeMgr,
- String storageSpace,
- String reportFileNamePrefix,
- String reportErrorLogFileName) {
- this.storageSpace = storageSpace;
- this.reportFileNamePrefix = reportFileNamePrefix;
- this.reportErrorLogFileName = reportErrorLogFileName;
- try {
- this.primaryStore = storeMgr.getPrimaryContentStore();
- try {
- primaryStore.getSpaceProperties(storageSpace);
- } catch(NotFoundException e) {
- primaryStore.createSpace(storageSpace, null);
- }
- } catch(ContentStoreException e) {
- throw new DuraCloudRuntimeException("Error checking metrics " +
- "storage space: " +
- e.getMessage());
- }
- }
-
- /**
- * Returns a specific storage report stream or null if the report does
- * not exist.
- *
- * @param reportId content ID of the report to retrieve
- * @return InputStream containing report
- */
- public InputStream getStorageReportStream(String reportId)
- throws ContentStoreException {
- try {
- return primaryStore.getContent(storageSpace, reportId).getStream();
- } catch(NotFoundException e) {
- return null;
- }
- }
-
- /**
- * Returns a specific storage report or null if the report does not exist.
- *
- * @param reportId content ID of the report to retrieve
- * @return StorageReport
- */
- public StorageReport getStorageReport(String reportId)
- throws ContentStoreException {
- try {
- Content content = primaryStore.getContent(storageSpace, reportId);
- return deserializeStorageReport(content);
- } catch(NotFoundException e) {
- return null;
- }
- }
-
- private StorageReport deserializeStorageReport(Content content) {
- StorageReportSerializer serializer = new StorageReportSerializer();
- return serializer.deserialize(content.getStream());
- }
-
- /**
- * Returns the latest storage report stream or null if no reports exist
- */
- public InputStream getLatestStorageReportStream()
- throws ContentStoreException {
- Content latestContent = getLatestStorageReportContent();
- if(null != latestContent) {
- return latestContent.getStream();
- } else {
- return null;
- }
- }
-
- /**
- * Returns the latest storage report or null if no reports exist
- */
- public StorageReport getLatestStorageReport() throws ContentStoreException {
- Content latestContent = getLatestStorageReportContent();
- if(null != latestContent) {
- return deserializeStorageReport(latestContent);
- } else {
- return null;
- }
- }
-
- private Content getLatestStorageReportContent()
- throws ContentStoreException {
- LinkedList<String> reportList = getSortedReportList();
- if(reportList.size() > 0) {
- String latestContentId = reportList.getFirst();
- Content latestContent =
- primaryStore.getContent(storageSpace, latestContentId);
- return latestContent;
- } else {
- return null;
- }
- }
-
- /*
- * Retrieves a list of all report lists (limited to a maximum of 5000),
- * sorted by name in descending order (i.e. the latest report will be first)
- */
- private LinkedList<String> getSortedReportList()
- throws ContentStoreException {
- Iterator<String> reports =
- primaryStore.getSpaceContents(storageSpace, reportFileNamePrefix);
-
- // Read the list of storage reports into a list, note that there is
- // the assumption here that there will not be a very large number of
- // these files.
- LinkedList<String> reportList = new LinkedList<String>();
- while(reports.hasNext() && reportList.size() < 5000) {
- reportList.add(reports.next());
- }
- if(reportList.size() > 0) {
- Collections.sort(reportList);
- Collections.reverse(reportList);
- }
- return reportList;
- }
-
- /**
- * Retrieve a sorted list of all storage reports in XML format. Sorting
- * is by name in descending order (i.e. the latest report will be first).
- *
- * @return list of storage reports
- * @throws ContentStoreException
- */
- public StorageReportList getStorageReportList() throws ContentStoreException {
- return new StorageReportList(getSortedReportList());
- }
-
- /**
- * Stores a storage report in the primary storage provider,
- * returns the content ID of the new item.
- *
- * @param metrics storage report
- * @param completionTime time report completed (in millis)
- * @param elapsedTime millis required to complete the report
- * @return contentId of the newly stored report
- */
- public String storeReport(DuraStoreMetricsCollector metrics,
- long completionTime,
- long elapsedTime) {
- String contentId = buildContentId(completionTime);
-
- StorageReportConverter converter = new StorageReportConverter();
- StorageReport report = converter.createStorageReport(contentId,
- metrics,
- completionTime,
- elapsedTime);
-
- StorageReportSerializer serializer = new StorageReportSerializer();
- String xml = serializer.serialize(report);
- byte[] metricsBytes = getXmlBytes(xml);
-
- log.info("Storing Storage Report with ID: " + contentId);
- for(int i=0; i<maxRetries; i++) {
- try {
- primaryStore.addContent(storageSpace,
- contentId,
- new ByteArrayInputStream(metricsBytes),
- metricsBytes.length,
- MediaType.APPLICATION_XML,
- getMetricsChecksum(xml),
- null);
- return contentId;
- } catch (ContentStoreException e) {
- log.warn("Exception attempting to store storage report: " +
- e.getMessage());
- wait(i);
- }
- }
- throw new ReportBuilderException("Exceeded retries attempting to " +
- "store storage report");
- }
-
- private String buildContentId(long time) {
- String date = DateUtil.convertToString(time);
- return reportFileNamePrefix + date + REPORT_FILE_NAME_SUFFIX;
- }
-
- private byte[] getXmlBytes(String xml) {
- try {
- return xml.getBytes("UTF-8");
- } catch(UnsupportedEncodingException e) {
- throw new RuntimeException(e);
- }
- }
-
- private String getMetricsChecksum(String xml) {
- ChecksumUtil util = new ChecksumUtil(ChecksumUtil.Algorithm.MD5);
- return util.generateChecksum(xml);
- }
-
- public void addToErrorLog(String errMsg) {
- InputStream existingLog = null;
- long existingLogSize = 0;
- try {
- Content errorLogContent =
- primaryStore.getContent(storageSpace, reportErrorLogFileName);
- if(null != errorLogContent) {
- existingLog = errorLogContent.getStream();
- existingLogSize = getExistingLogSize(errorLogContent);
- }
- } catch(ContentStoreException e) {
- // Could not get error log, likely because it does not yet exist
- }
-
- String logMsg = createLogMsg(errMsg);
- InputStream newMsg = createLogMsgStream(logMsg);
- InputStream newLog;
- if(null != existingLog) {
- newLog = new SequenceInputStream(newMsg, existingLog);
- } else {
- newLog = newMsg;
- }
-
- for(int i=0; i<maxRetries; i++) {
- try {
- primaryStore.addContent(storageSpace,
- reportErrorLogFileName,
- newLog,
- existingLogSize + logMsg.length(),
- MediaType.TEXT_PLAIN,
- null,
- null);
- return;
- } catch(ContentStoreException e) {
- log.warn("Exception attempting to store error log: " +
- e.getMessage());
- wait(i);
- }
- }
- log.error("Unable to store error log file!");
- }
-
- private String createLogMsg(String msg) {
- return DateUtil.now() + " " + msg + "\n";
- }
-
- private InputStream createLogMsgStream(String logMsg) {
- try {
- return IOUtils.toInputStream(logMsg, "UTF-8");
- } catch(IOException e) {
- throw new RuntimeException(e.getMessage(), e);
- }
- }
-
- private long getExistingLogSize(Content logContent) {
- Map<String, String> properties = logContent.getProperties();
- if(null != properties) {
- String logSize = properties.get(ContentStore.CONTENT_SIZE);
- if(null != logSize) {
- try {
- return Long.valueOf(logSize);
- } catch(NumberFormatException e) {
- }
- }
- }
- return 0;
- }
-
- private void wait(int index) {
- try {
- Thread.sleep(1000 * index);
- } catch(InterruptedException e) {
- }
- }
-
-}
+/*
+ * The contents of this file are subject to the license and copyright
+ * detailed in the LICENSE and NOTICE files at the root of the source
+ * tree and available online at
+ *
+ * http://duracloud.org/license/
+ */
+package org.duracloud.reporter.storage;
+
+import org.apache.commons.io.IOUtils;
+import org.duracloud.client.ContentStore;
+import org.duracloud.client.ContentStoreManager;
+import org.duracloud.common.error.DuraCloudRuntimeException;
+import org.duracloud.common.util.ChecksumUtil;
+import org.duracloud.common.util.DateUtil;
+import org.duracloud.domain.Content;
+import org.duracloud.reporter.error.ReportBuilderException;
+import org.duracloud.reporter.storage.metrics.DuraStoreMetricsCollector;
+import org.duracloud.error.ContentStoreException;
+import org.duracloud.error.NotFoundException;
+import org.duracloud.reportdata.storage.StorageReport;
+import org.duracloud.reportdata.storage.StorageReportList;
+import org.duracloud.reportdata.storage.serialize.StorageReportSerializer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.ws.rs.core.MediaType;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.SequenceInputStream;
+import java.io.UnsupportedEncodingException;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.Map;
+
+/**
+ * Handles the storage and retrieval of storage reports.
+ *
+ * @author: Bill Branan
+ * Date: 5/13/11
+ */
+public class StorageReportHandler {
+
+ private final Logger log =
+ LoggerFactory.getLogger(StorageReportHandler.class);
+
+ private static final String REPORT_FILE_NAME_SUFFIX = ".xml";
+ public static final String COMPLETION_TIME_META = "completion-time";
+ public static final String ELAPSED_TIME_META = "elapsed-time";
+ public static final int maxRetries = 8;
+
+ protected String storageSpace;
+ private ContentStore primaryStore = null;
+ private String reportFileNamePrefix;
+ private String reportErrorLogFileName;
+
+ public StorageReportHandler(ContentStoreManager storeMgr,
+ String storageSpace,
+ String reportFileNamePrefix,
+ String reportErrorLogFileName) {
+ this.storageSpace = storageSpace;
+ this.reportFileNamePrefix = reportFileNamePrefix;
+ this.reportErrorLogFileName = reportErrorLogFileName;
+ try {
+ this.primaryStore = storeMgr.getPrimaryContentStore();
+ try {
+ primaryStore.getSpaceProperties(storageSpace);
+ } catch(NotFoundException e) {
+ primaryStore.createSpace(storageSpace, null);
+ }
+ } catch(ContentStoreException e) {
+ throw new DuraCloudRuntimeException("Error checking metrics " +
+ "storage space: " +
+ e.getMessage());
+ }
+ }
+
+ /**
+ * Returns a specific storage report stream or null if the report does
+ * not exist.
+ *
+ * @param reportId content ID of the report to retrieve
+ * @return InputStream containing report
+ */
+ public InputStream getStorageReportStream(String reportId)
+ throws ContentStoreException {
+ try {
+ return primaryStore.getContent(storageSpace, reportId).getStream();
+ } catch(NotFoundException e) {
+ return null;
+ }
+ }
+
+ /**
+ * Returns a specific storage report or null if the report does not exist.
+ *
+ * @param reportId content ID of the report to retrieve
+ * @return StorageReport
+ */
+ public StorageReport getStorageReport(String reportId)
+ throws ContentStoreException {
+ try {
+ Content content = primaryStore.getContent(storageSpace, reportId);
+ return deserializeStorageReport(content);
+ } catch(NotFoundException e) {
+ return null;
+ }
+ }
+
+ private StorageReport deserializeStorageReport(Content content) {
+ StorageReportSerializer serializer = new StorageReportSerializer();
+ return serializer.deserialize(content.getStream());
+ }
+
+ /**
+ * Returns the latest storage report stream or null if no reports exist
+ */
+ public InputStream getLatestStorageReportStream()
+ throws ContentStoreException {
+ Content latestContent = getLatestStorageReportContent();
+ if(null != latestContent) {
+ return latestContent.getStream();
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Returns the latest storage report or null if no reports exist
+ */
+ public StorageReport getLatestStorageReport() throws ContentStoreException {
+ Content latestContent = getLatestStorageReportContent();
+ if(null != latestContent) {
+ return deserializeStorageReport(latestContent);
+ } else {
+ return null;
+ }
+ }
+
+ private Content getLatestStorageReportContent()
+ throws ContentStoreException {
+ LinkedList<String> reportList = getSortedReportList();
+ if(reportList.size() > 0) {
+ String latestContentId = reportList.getFirst();
+ Content latestContent =
+ primaryStore.getContent(storageSpace, latestContentId);
+ return latestContent;
+ } else {
+ return null;
+ }
+ }
+
+ /*
+ * Retrieves a list of all report lists (limited to a maximum of 5000),
+ * sorted by name in descending order (i.e. the latest report will be first)
+ */
+ private LinkedList<String> getSortedReportList()
+ throws ContentStoreException {
+ Iterator<String> reports =
+ primaryStore.getSpaceContents(storageSpace, reportFileNamePrefix);
+
+ // Read the list of storage reports into a list, note that there is
+ // the assumption here that there will not be a very large number of
+ // these files.
+ LinkedList<String> reportList = new LinkedList<String>();
+ while(reports.hasNext() && reportList.size() < 5000) {
+ reportList.add(reports.next());
+ }
+ if(reportList.size() > 0) {
+ Collections.sort(reportList);
+ Collections.reverse(reportList);
+ }
+ return reportList;
+ }
+
+ /**
+ * Retrieve a sorted list of all storage reports in XML format. Sorting
+ * is by name in descending order (i.e. the latest report will be first).
+ *
+ * @return list of storage reports
+ * @throws ContentStoreException
+ */
+ public StorageReportList getStorageReportList() throws ContentStoreException {
+ return new StorageReportList(getSortedReportList());
+ }
+
+ /**
+ * Stores a storage report in the primary storage provider,
+ * returns the content ID of the new item.
+ *
+ * @param metrics storage report
+ * @param completionTime time report completed (in millis)
+ * @param elapsedTime millis required to complete the report
+ * @return contentId of the newly stored report
+ */
+ public String storeReport(DuraStoreMetricsCollector metrics,
+ long completionTime,
+ long elapsedTime) {
+ String contentId = buildContentId(completionTime);
+
+ StorageReportConverter converter = new StorageReportConverter();
+ StorageReport report = converter.createStorageReport(contentId,
+ metrics,
+ completionTime,
+ elapsedTime);
+
+ StorageReportSerializer serializer = new StorageReportSerializer();
+ String xml = serializer.serialize(report);
+ byte[] metricsBytes = getXmlBytes(xml);
+
+ log.info("Storing Storage Report with ID: " + contentId);
+ for(int i=0; i<maxRetries; i++) {
+ try {
+ primaryStore.addContent(storageSpace,
+ contentId,
+ new ByteArrayInputStream(metricsBytes),
+ metricsBytes.length,
+ MediaType.APPLICATION_XML,
+ getMetricsChecksum(xml),
+ null);
+ return contentId;
+ } catch (ContentStoreException e) {
+ log.warn("Exception attempting to store storage report: " +
+ e.getMessage());
+ wait(i);
+ }
+ }
+ throw new ReportBuilderException("Exceeded retries attempting to " +
+ "store storage report");
+ }
+
+ private String buildContentId(long time) {
+ String date = DateUtil.convertToString(time);
+ return reportFileNamePrefix + date + REPORT_FILE_NAME_SUFFIX;
+ }
+
+ private byte[] getXmlBytes(String xml) {
+ try {
+ return xml.getBytes("UTF-8");
+ } catch(UnsupportedEncodingException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private String getMetricsChecksum(String xml) {
+ ChecksumUtil util = new ChecksumUtil(ChecksumUtil.Algorithm.MD5);
+ return util.generateChecksum(xml);
+ }
+
+ public void addToErrorLog(String errMsg) {
+ InputStream existingLog = null;
+ long existingLogSize = 0;
+ try {
+ Content errorLogContent =
+ primaryStore.getContent(storageSpace, reportErrorLogFileName);
+ if(null != errorLogContent) {
+ existingLog = errorLogContent.getStream();
+ existingLogSize = getExistingLogSize(errorLogContent);
+ }
+ } catch(ContentStoreException e) {
+ // Could not get error log, likely because it does not yet exist
+ }
+
+ String logMsg = createLogMsg(errMsg);
+ InputStream newMsg = createLogMsgStream(logMsg);
+ InputStream newLog;
+ if(null != existingLog) {
+ newLog = new SequenceInputStream(newMsg, existingLog);
+ } else {
+ newLog = newMsg;
+ }
+
+ for(int i=0; i<maxRetries; i++) {
+ try {
+ primaryStore.addContent(storageSpace,
+ reportErrorLogFileName,
+ newLog,
+ existingLogSize + logMsg.length(),
+ MediaType.TEXT_PLAIN,
+ null,
+ null);
+ return;
+ } catch(ContentStoreException e) {
+ log.warn("Exception attempting to store error log: " +
+ e.getMessage());
+ wait(i);
+ }
+ }
+ log.error("Unable to store error log file!");
+ }
+
+ private String createLogMsg(String msg) {
+ return DateUtil.now() + " " + msg + "\n";
+ }
+
+ private InputStream createLogMsgStream(String logMsg) {
+ try {
+ return IOUtils.toInputStream(logMsg, "UTF-8");
+ } catch(IOException e) {
+ throw new RuntimeException(e.getMessage(), e);
+ }
+ }
+
+ private long getExistingLogSize(Content logContent) {
+ Map<String, String> properties = logContent.getProperties();
+ if(null != properties) {
+ String logSize = properties.get(ContentStore.CONTENT_SIZE);
+ if(null != logSize) {
+ try {
+ return Long.valueOf(logSize);
+ } catch(NumberFormatException e) {
+ }
+ }
+ }
+ return 0;
+ }
+
+ private void wait(int index) {
+ try {
+ Thread.sleep(1000 * index);
+ } catch(InterruptedException e) {
+ }
+ }
+
+}
diff --git a/durareport/src/main/java/org/duracloud/durareport/storage/StorageReportScheduler.java b/reporter/src/main/java/org/duracloud/reporter/storage/StorageReportScheduler.java
similarity index 95%
rename from durareport/src/main/java/org/duracloud/durareport/storage/StorageReportScheduler.java
rename to reporter/src/main/java/org/duracloud/reporter/storage/StorageReportScheduler.java
index df855face..42e58e3c7 100644
--- a/durareport/src/main/java/org/duracloud/durareport/storage/StorageReportScheduler.java
+++ b/reporter/src/main/java/org/duracloud/reporter/storage/StorageReportScheduler.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.storage;
+package org.duracloud.reporter.storage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
diff --git a/durareport/src/main/java/org/duracloud/durareport/storage/metrics/DuraStoreMetricsCollector.java b/reporter/src/main/java/org/duracloud/reporter/storage/metrics/DuraStoreMetricsCollector.java
similarity index 94%
rename from durareport/src/main/java/org/duracloud/durareport/storage/metrics/DuraStoreMetricsCollector.java
rename to reporter/src/main/java/org/duracloud/reporter/storage/metrics/DuraStoreMetricsCollector.java
index 4d1015d85..dd2440a17 100644
--- a/durareport/src/main/java/org/duracloud/durareport/storage/metrics/DuraStoreMetricsCollector.java
+++ b/reporter/src/main/java/org/duracloud/reporter/storage/metrics/DuraStoreMetricsCollector.java
@@ -1,56 +1,56 @@
-/*
- * The contents of this file are subject to the license and copyright
- * detailed in the LICENSE and NOTICE files at the root of the source
- * tree and available online at
- *
- * http://duracloud.org/license/
- */
-package org.duracloud.durareport.storage.metrics;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Top level metrics storage data structure for DuraStore. Contains all
- * metrics information for all storage providers.
- *
- * @author: Bill Branan
- * Date: 5/12/11
- */
-public class DuraStoreMetricsCollector extends MetricsCollector {
-
- private Map<String, StorageProviderMetricsCollector> storageProviderMetrics;
-
- public DuraStoreMetricsCollector() {
- super();
- this.storageProviderMetrics =
- new HashMap<String, StorageProviderMetricsCollector>();
- }
-
- @Override
- public void update(String mimetype, long size) {
- String error = "Use update(String, String, String, long)";
- throw new UnsupportedOperationException(error);
- }
-
- public void update(String storageProviderId,
- String storageProviderType,
- String spaceId,
- String mimetype,
- long size) {
- super.update(mimetype, size);
-
- StorageProviderMetricsCollector providerMet =
- storageProviderMetrics.get(storageProviderId);
- if(null == providerMet) {
- providerMet = new StorageProviderMetricsCollector(storageProviderId,
- storageProviderType);
- storageProviderMetrics.put(storageProviderId, providerMet);
- }
- providerMet.update(spaceId, mimetype, size);
- }
-
- public Map<String, StorageProviderMetricsCollector> getStorageProviderMetrics() {
- return storageProviderMetrics;
- }
-}
+/*
+ * The contents of this file are subject to the license and copyright
+ * detailed in the LICENSE and NOTICE files at the root of the source
+ * tree and available online at
+ *
+ * http://duracloud.org/license/
+ */
+package org.duracloud.reporter.storage.metrics;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Top level metrics storage data structure for DuraStore. Contains all
+ * metrics information for all storage providers.
+ *
+ * @author: Bill Branan
+ * Date: 5/12/11
+ */
+public class DuraStoreMetricsCollector extends MetricsCollector {
+
+ private Map<String, StorageProviderMetricsCollector> storageProviderMetrics;
+
+ public DuraStoreMetricsCollector() {
+ super();
+ this.storageProviderMetrics =
+ new HashMap<String, StorageProviderMetricsCollector>();
+ }
+
+ @Override
+ public void update(String mimetype, long size) {
+ String error = "Use update(String, String, String, long)";
+ throw new UnsupportedOperationException(error);
+ }
+
+ public void update(String storageProviderId,
+ String storageProviderType,
+ String spaceId,
+ String mimetype,
+ long size) {
+ super.update(mimetype, size);
+
+ StorageProviderMetricsCollector providerMet =
+ storageProviderMetrics.get(storageProviderId);
+ if(null == providerMet) {
+ providerMet = new StorageProviderMetricsCollector(storageProviderId,
+ storageProviderType);
+ storageProviderMetrics.put(storageProviderId, providerMet);
+ }
+ providerMet.update(spaceId, mimetype, size);
+ }
+
+ public Map<String, StorageProviderMetricsCollector> getStorageProviderMetrics() {
+ return storageProviderMetrics;
+ }
+}
diff --git a/durareport/src/main/java/org/duracloud/durareport/storage/metrics/MetricsCollector.java b/reporter/src/main/java/org/duracloud/reporter/storage/metrics/MetricsCollector.java
similarity index 92%
rename from durareport/src/main/java/org/duracloud/durareport/storage/metrics/MetricsCollector.java
rename to reporter/src/main/java/org/duracloud/reporter/storage/metrics/MetricsCollector.java
index 8c00d553a..c7b139544 100644
--- a/durareport/src/main/java/org/duracloud/durareport/storage/metrics/MetricsCollector.java
+++ b/reporter/src/main/java/org/duracloud/reporter/storage/metrics/MetricsCollector.java
@@ -1,54 +1,54 @@
-/*
- * The contents of this file are subject to the license and copyright
- * detailed in the LICENSE and NOTICE files at the root of the source
- * tree and available online at
- *
- * http://duracloud.org/license/
- */
-package org.duracloud.durareport.storage.metrics;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * @author: Bill Branan
- * Date: 5/12/11
- */
-public abstract class MetricsCollector {
-
- private long totalItems;
- private long totalSize;
-
- private Map<String, MimetypeMetricsCollector> mimetypeMetrics;
-
- public MetricsCollector() {
- this.totalItems = 0;
- this.totalSize = 0;
- this.mimetypeMetrics = new HashMap<String, MimetypeMetricsCollector>();
- }
-
- public void update(String mimetype, long size) {
- ++totalItems;
- totalSize += size;
-
- MimetypeMetricsCollector mimeMet = mimetypeMetrics.get(mimetype);
- if(null == mimeMet) {
- mimeMet = new MimetypeMetricsCollector(mimetype);
- mimetypeMetrics.put(mimetype, mimeMet);
- }
- mimeMet.update(size);
- }
-
- public long getTotalItems() {
- return totalItems;
- }
-
- public long getTotalSize() {
- return totalSize;
- }
-
- public Map<String, MimetypeMetricsCollector> getMimetypeMetrics() {
- return mimetypeMetrics;
- }
-
-}
+/*
+ * The contents of this file are subject to the license and copyright
+ * detailed in the LICENSE and NOTICE files at the root of the source
+ * tree and available online at
+ *
+ * http://duracloud.org/license/
+ */
+package org.duracloud.reporter.storage.metrics;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @author: Bill Branan
+ * Date: 5/12/11
+ */
+public abstract class MetricsCollector {
+
+ private long totalItems;
+ private long totalSize;
+
+ private Map<String, MimetypeMetricsCollector> mimetypeMetrics;
+
+ public MetricsCollector() {
+ this.totalItems = 0;
+ this.totalSize = 0;
+ this.mimetypeMetrics = new HashMap<String, MimetypeMetricsCollector>();
+ }
+
+ public void update(String mimetype, long size) {
+ ++totalItems;
+ totalSize += size;
+
+ MimetypeMetricsCollector mimeMet = mimetypeMetrics.get(mimetype);
+ if(null == mimeMet) {
+ mimeMet = new MimetypeMetricsCollector(mimetype);
+ mimetypeMetrics.put(mimetype, mimeMet);
+ }
+ mimeMet.update(size);
+ }
+
+ public long getTotalItems() {
+ return totalItems;
+ }
+
+ public long getTotalSize() {
+ return totalSize;
+ }
+
+ public Map<String, MimetypeMetricsCollector> getMimetypeMetrics() {
+ return mimetypeMetrics;
+ }
+
+}
diff --git a/durareport/src/main/java/org/duracloud/durareport/storage/metrics/MimetypeMetricsCollector.java b/reporter/src/main/java/org/duracloud/reporter/storage/metrics/MimetypeMetricsCollector.java
similarity index 90%
rename from durareport/src/main/java/org/duracloud/durareport/storage/metrics/MimetypeMetricsCollector.java
rename to reporter/src/main/java/org/duracloud/reporter/storage/metrics/MimetypeMetricsCollector.java
index 3dcc3372e..52d711bab 100644
--- a/durareport/src/main/java/org/duracloud/durareport/storage/metrics/MimetypeMetricsCollector.java
+++ b/reporter/src/main/java/org/duracloud/reporter/storage/metrics/MimetypeMetricsCollector.java
@@ -1,43 +1,43 @@
-/*
- * The contents of this file are subject to the license and copyright
- * detailed in the LICENSE and NOTICE files at the root of the source
- * tree and available online at
- *
- * http://duracloud.org/license/
- */
-package org.duracloud.durareport.storage.metrics;
-
-/**
- * @author: Bill Branan
- * Date: 5/12/11
- */
-public class MimetypeMetricsCollector {
-
- private String mimetype;
- private long totalItems;
- private long totalSize;
-
- public MimetypeMetricsCollector(String mimetype) {
- this.mimetype = mimetype;
- this.totalItems = 0;
- this.totalSize = 0;
- }
-
- public void update(long size) {
- ++totalItems;
- totalSize += size;
- }
-
- public String getMimetype() {
- return mimetype;
- }
-
- public long getTotalItems() {
- return totalItems;
- }
-
- public long getTotalSize() {
- return totalSize;
- }
-
-}
+/*
+ * The contents of this file are subject to the license and copyright
+ * detailed in the LICENSE and NOTICE files at the root of the source
+ * tree and available online at
+ *
+ * http://duracloud.org/license/
+ */
+package org.duracloud.reporter.storage.metrics;
+
+/**
+ * @author: Bill Branan
+ * Date: 5/12/11
+ */
+public class MimetypeMetricsCollector {
+
+ private String mimetype;
+ private long totalItems;
+ private long totalSize;
+
+ public MimetypeMetricsCollector(String mimetype) {
+ this.mimetype = mimetype;
+ this.totalItems = 0;
+ this.totalSize = 0;
+ }
+
+ public void update(long size) {
+ ++totalItems;
+ totalSize += size;
+ }
+
+ public String getMimetype() {
+ return mimetype;
+ }
+
+ public long getTotalItems() {
+ return totalItems;
+ }
+
+ public long getTotalSize() {
+ return totalSize;
+ }
+
+}
diff --git a/durareport/src/main/java/org/duracloud/durareport/storage/metrics/SpaceMetricsCollector.java b/reporter/src/main/java/org/duracloud/reporter/storage/metrics/SpaceMetricsCollector.java
similarity index 89%
rename from durareport/src/main/java/org/duracloud/durareport/storage/metrics/SpaceMetricsCollector.java
rename to reporter/src/main/java/org/duracloud/reporter/storage/metrics/SpaceMetricsCollector.java
index c501226dc..f13a7b6b4 100644
--- a/durareport/src/main/java/org/duracloud/durareport/storage/metrics/SpaceMetricsCollector.java
+++ b/reporter/src/main/java/org/duracloud/reporter/storage/metrics/SpaceMetricsCollector.java
@@ -1,30 +1,30 @@
-/*
- * The contents of this file are subject to the license and copyright
- * detailed in the LICENSE and NOTICE files at the root of the source
- * tree and available online at
- *
- * http://duracloud.org/license/
- */
-package org.duracloud.durareport.storage.metrics;
-
-/**
- * Metrics data structure for spaces. Contains all of the metrics for a single
- * space.
- *
- * @author: Bill Branan
- * Date: 5/12/11
- */
-public class SpaceMetricsCollector extends MetricsCollector {
-
- private String spaceName;
-
- public SpaceMetricsCollector(String spaceName) {
- super();
- this.spaceName = spaceName;
- }
-
- public String getSpaceName() {
- return spaceName;
- }
-
-}
+/*
+ * The contents of this file are subject to the license and copyright
+ * detailed in the LICENSE and NOTICE files at the root of the source
+ * tree and available online at
+ *
+ * http://duracloud.org/license/
+ */
+package org.duracloud.reporter.storage.metrics;
+
+/**
+ * Metrics data structure for spaces. Contains all of the metrics for a single
+ * space.
+ *
+ * @author: Bill Branan
+ * Date: 5/12/11
+ */
+public class SpaceMetricsCollector extends MetricsCollector {
+
+ private String spaceName;
+
+ public SpaceMetricsCollector(String spaceName) {
+ super();
+ this.spaceName = spaceName;
+ }
+
+ public String getSpaceName() {
+ return spaceName;
+ }
+
+}
diff --git a/durareport/src/main/java/org/duracloud/durareport/storage/metrics/StorageProviderMetricsCollector.java b/reporter/src/main/java/org/duracloud/reporter/storage/metrics/StorageProviderMetricsCollector.java
similarity index 94%
rename from durareport/src/main/java/org/duracloud/durareport/storage/metrics/StorageProviderMetricsCollector.java
rename to reporter/src/main/java/org/duracloud/reporter/storage/metrics/StorageProviderMetricsCollector.java
index 38bb121a2..3ad548dc6 100644
--- a/durareport/src/main/java/org/duracloud/durareport/storage/metrics/StorageProviderMetricsCollector.java
+++ b/reporter/src/main/java/org/duracloud/reporter/storage/metrics/StorageProviderMetricsCollector.java
@@ -1,62 +1,62 @@
-/*
- * The contents of this file are subject to the license and copyright
- * detailed in the LICENSE and NOTICE files at the root of the source
- * tree and available online at
- *
- * http://duracloud.org/license/
- */
-package org.duracloud.durareport.storage.metrics;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Metrics data structure for storage providers. Contains all of the metrics
- * information about a single storage provider and its storage spaces.
- *
- * @author: Bill Branan
- * Date: 5/12/11
- */
-public class StorageProviderMetricsCollector extends MetricsCollector {
-
- private String storageProviderId;
- private String storageProviderType;
- private Map<String, SpaceMetricsCollector> spaceMetrics;
-
- public StorageProviderMetricsCollector(String storageProviderId,
- String storageProviderType) {
- super();
- this.storageProviderId = storageProviderId;
- this.storageProviderType = storageProviderType;
- this.spaceMetrics = new HashMap<String, SpaceMetricsCollector>();
- }
-
- @Override
- public void update(String mimetype, long size) {
- String error = "Use update(String, String, long)";
- throw new UnsupportedOperationException(error);
- }
-
- public void update(String spaceId, String mimetype, long size) {
- super.update(mimetype, size);
-
- SpaceMetricsCollector spaceMet = spaceMetrics.get(spaceId);
- if(null == spaceMet) {
- spaceMet = new SpaceMetricsCollector(spaceId);
- spaceMetrics.put(spaceId, spaceMet);
- }
- spaceMet.update(mimetype, size);
- }
-
- public String getStorageProviderId() {
- return storageProviderId;
- }
-
- public String getStorageProviderType() {
- return storageProviderType;
- }
-
- public Map<String, SpaceMetricsCollector> getSpaceMetrics() {
- return spaceMetrics;
- }
-}
+/*
+ * The contents of this file are subject to the license and copyright
+ * detailed in the LICENSE and NOTICE files at the root of the source
+ * tree and available online at
+ *
+ * http://duracloud.org/license/
+ */
+package org.duracloud.reporter.storage.metrics;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Metrics data structure for storage providers. Contains all of the metrics
+ * information about a single storage provider and its storage spaces.
+ *
+ * @author: Bill Branan
+ * Date: 5/12/11
+ */
+public class StorageProviderMetricsCollector extends MetricsCollector {
+
+ private String storageProviderId;
+ private String storageProviderType;
+ private Map<String, SpaceMetricsCollector> spaceMetrics;
+
+ public StorageProviderMetricsCollector(String storageProviderId,
+ String storageProviderType) {
+ super();
+ this.storageProviderId = storageProviderId;
+ this.storageProviderType = storageProviderType;
+ this.spaceMetrics = new HashMap<String, SpaceMetricsCollector>();
+ }
+
+ @Override
+ public void update(String mimetype, long size) {
+ String error = "Use update(String, String, long)";
+ throw new UnsupportedOperationException(error);
+ }
+
+ public void update(String spaceId, String mimetype, long size) {
+ super.update(mimetype, size);
+
+ SpaceMetricsCollector spaceMet = spaceMetrics.get(spaceId);
+ if(null == spaceMet) {
+ spaceMet = new SpaceMetricsCollector(spaceId);
+ spaceMetrics.put(spaceId, spaceMet);
+ }
+ spaceMet.update(mimetype, size);
+ }
+
+ public String getStorageProviderId() {
+ return storageProviderId;
+ }
+
+ public String getStorageProviderType() {
+ return storageProviderType;
+ }
+
+ public Map<String, SpaceMetricsCollector> getSpaceMetrics() {
+ return spaceMetrics;
+ }
+}
diff --git a/durareport/src/test/java/org/duracloud/durareport/notification/EmailNotifierTest.java b/reporter/src/test/java/org/duracloud/reporter/notification/EmailNotifierTest.java
similarity index 93%
rename from durareport/src/test/java/org/duracloud/durareport/notification/EmailNotifierTest.java
rename to reporter/src/test/java/org/duracloud/reporter/notification/EmailNotifierTest.java
index d6d54f742..33a679bfa 100644
--- a/durareport/src/test/java/org/duracloud/durareport/notification/EmailNotifierTest.java
+++ b/reporter/src/test/java/org/duracloud/reporter/notification/EmailNotifierTest.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.notification;
+package org.duracloud.reporter.notification;
import org.duracloud.notification.Emailer;
import org.easymock.classextension.EasyMock;
diff --git a/durareport/src/test/java/org/duracloud/durareport/notification/NotificationManagerTest.java b/reporter/src/test/java/org/duracloud/reporter/notification/NotificationManagerTest.java
similarity index 94%
rename from durareport/src/test/java/org/duracloud/durareport/notification/NotificationManagerTest.java
rename to reporter/src/test/java/org/duracloud/reporter/notification/NotificationManagerTest.java
index bd6969c67..094b33aa0 100644
--- a/durareport/src/test/java/org/duracloud/durareport/notification/NotificationManagerTest.java
+++ b/reporter/src/test/java/org/duracloud/reporter/notification/NotificationManagerTest.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.notification;
+package org.duracloud.reporter.notification;
import org.duracloud.appconfig.domain.NotificationConfig;
import org.easymock.classextension.EasyMock;
diff --git a/durareport/src/test/java/org/duracloud/durareport/service/ServiceNotificationMonitorTest.java b/reporter/src/test/java/org/duracloud/reporter/service/ServiceNotificationMonitorTest.java
similarity index 90%
rename from durareport/src/test/java/org/duracloud/durareport/service/ServiceNotificationMonitorTest.java
rename to reporter/src/test/java/org/duracloud/reporter/service/ServiceNotificationMonitorTest.java
index 024aedee1..695b5161f 100644
--- a/durareport/src/test/java/org/duracloud/durareport/service/ServiceNotificationMonitorTest.java
+++ b/reporter/src/test/java/org/duracloud/reporter/service/ServiceNotificationMonitorTest.java
@@ -5,10 +5,10 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.service;
+package org.duracloud.reporter.service;
-import org.duracloud.durareport.notification.NotificationManager;
-import org.duracloud.durareport.notification.NotificationType;
+import org.duracloud.reporter.notification.NotificationManager;
+import org.duracloud.reporter.notification.NotificationType;
import org.duracloud.security.DuracloudUserDetailsService;
import org.duracloud.security.domain.SecurityUserBean;
import org.duracloud.serviceconfig.ServiceSummary;
diff --git a/durareport/src/test/java/org/duracloud/durareport/service/ServiceReportBuilderTest.java b/reporter/src/test/java/org/duracloud/reporter/service/ServiceReportBuilderTest.java
similarity index 96%
rename from durareport/src/test/java/org/duracloud/durareport/service/ServiceReportBuilderTest.java
rename to reporter/src/test/java/org/duracloud/reporter/service/ServiceReportBuilderTest.java
index ab38e16f8..fa63daf29 100644
--- a/durareport/src/test/java/org/duracloud/durareport/service/ServiceReportBuilderTest.java
+++ b/reporter/src/test/java/org/duracloud/reporter/service/ServiceReportBuilderTest.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.service;
+package org.duracloud.reporter.service;
import org.duracloud.serviceapi.ServicesManager;
import org.duracloud.serviceconfig.ServiceSummary;
diff --git a/durareport/src/test/java/org/duracloud/durareport/storage/StorageReportBuilderTest.java b/reporter/src/test/java/org/duracloud/reporter/storage/StorageReportBuilderTest.java
similarity index 92%
rename from durareport/src/test/java/org/duracloud/durareport/storage/StorageReportBuilderTest.java
rename to reporter/src/test/java/org/duracloud/reporter/storage/StorageReportBuilderTest.java
index dea6bfeda..163953c6e 100644
--- a/durareport/src/test/java/org/duracloud/durareport/storage/StorageReportBuilderTest.java
+++ b/reporter/src/test/java/org/duracloud/reporter/storage/StorageReportBuilderTest.java
@@ -5,14 +5,14 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.storage;
+package org.duracloud.reporter.storage;
import org.duracloud.client.ContentStore;
import org.duracloud.client.ContentStoreManager;
-import org.duracloud.durareport.storage.metrics.DuraStoreMetricsCollector;
-import org.duracloud.durareport.storage.metrics.MimetypeMetricsCollector;
-import org.duracloud.durareport.storage.metrics.SpaceMetricsCollector;
-import org.duracloud.durareport.storage.metrics.StorageProviderMetricsCollector;
+import org.duracloud.reporter.storage.metrics.DuraStoreMetricsCollector;
+import org.duracloud.reporter.storage.metrics.MimetypeMetricsCollector;
+import org.duracloud.reporter.storage.metrics.SpaceMetricsCollector;
+import org.duracloud.reporter.storage.metrics.StorageProviderMetricsCollector;
import org.duracloud.reportdata.storage.StorageReport;
import org.easymock.Capture;
import org.easymock.IAnswer;
diff --git a/durareport/src/test/java/org/duracloud/durareport/storage/StorageReportConverterTest.java b/reporter/src/test/java/org/duracloud/reporter/storage/StorageReportConverterTest.java
similarity index 95%
rename from durareport/src/test/java/org/duracloud/durareport/storage/StorageReportConverterTest.java
rename to reporter/src/test/java/org/duracloud/reporter/storage/StorageReportConverterTest.java
index 7130d04eb..7f4606257 100644
--- a/durareport/src/test/java/org/duracloud/durareport/storage/StorageReportConverterTest.java
+++ b/reporter/src/test/java/org/duracloud/reporter/storage/StorageReportConverterTest.java
@@ -5,9 +5,9 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.storage;
+package org.duracloud.reporter.storage;
-import org.duracloud.durareport.storage.metrics.DuraStoreMetricsCollector;
+import org.duracloud.reporter.storage.metrics.DuraStoreMetricsCollector;
import org.duracloud.reportdata.storage.StorageReport;
import org.duracloud.reportdata.storage.metrics.MimetypeMetrics;
import org.duracloud.reportdata.storage.metrics.SpaceMetrics;
diff --git a/durareport/src/test/java/org/duracloud/durareport/storage/StorageReportHandlerTest.java b/reporter/src/test/java/org/duracloud/reporter/storage/StorageReportHandlerTest.java
similarity index 96%
rename from durareport/src/test/java/org/duracloud/durareport/storage/StorageReportHandlerTest.java
rename to reporter/src/test/java/org/duracloud/reporter/storage/StorageReportHandlerTest.java
index 790698b34..8860a3833 100644
--- a/durareport/src/test/java/org/duracloud/durareport/storage/StorageReportHandlerTest.java
+++ b/reporter/src/test/java/org/duracloud/reporter/storage/StorageReportHandlerTest.java
@@ -5,12 +5,12 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.storage;
+package org.duracloud.reporter.storage;
import org.duracloud.client.ContentStore;
import org.duracloud.client.ContentStoreManager;
import org.duracloud.domain.Content;
-import org.duracloud.durareport.storage.metrics.DuraStoreMetricsCollector;
+import org.duracloud.reporter.storage.metrics.DuraStoreMetricsCollector;
import org.duracloud.reportdata.storage.StorageReport;
import org.duracloud.reportdata.storage.metrics.StorageMetrics;
import org.duracloud.reportdata.storage.serialize.StorageReportSerializer;
diff --git a/durareport/src/test/java/org/duracloud/durareport/storage/StorageReportSchedulerTest.java b/reporter/src/test/java/org/duracloud/reporter/storage/StorageReportSchedulerTest.java
similarity index 94%
rename from durareport/src/test/java/org/duracloud/durareport/storage/StorageReportSchedulerTest.java
rename to reporter/src/test/java/org/duracloud/reporter/storage/StorageReportSchedulerTest.java
index 1154bfde8..82837b186 100644
--- a/durareport/src/test/java/org/duracloud/durareport/storage/StorageReportSchedulerTest.java
+++ b/reporter/src/test/java/org/duracloud/reporter/storage/StorageReportSchedulerTest.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.storage;
+package org.duracloud.reporter.storage;
import org.easymock.classextension.EasyMock;
import org.junit.After;
diff --git a/durareport/src/test/java/org/duracloud/durareport/storage/metrics/MetricsCollectorTest.java b/reporter/src/test/java/org/duracloud/reporter/storage/metrics/MetricsCollectorTest.java
similarity index 96%
rename from durareport/src/test/java/org/duracloud/durareport/storage/metrics/MetricsCollectorTest.java
rename to reporter/src/test/java/org/duracloud/reporter/storage/metrics/MetricsCollectorTest.java
index 542a7e2b2..f8258f5fc 100644
--- a/durareport/src/test/java/org/duracloud/durareport/storage/metrics/MetricsCollectorTest.java
+++ b/reporter/src/test/java/org/duracloud/reporter/storage/metrics/MetricsCollectorTest.java
@@ -1,292 +1,292 @@
-/*
- * The contents of this file are subject to the license and copyright
- * detailed in the LICENSE and NOTICE files at the root of the source
- * tree and available online at
- *
- * http://duracloud.org/license/
- */
-package org.duracloud.durareport.storage.metrics;
-
-import org.junit.Test;
-
-import java.util.Map;
-
-import static org.junit.Assert.*;
-import static org.junit.Assert.assertEquals;
-
-/**
- * @author: Bill Branan
- * Date: 5/12/11
- */
-public class MetricsCollectorTest {
-
- private String mimetype1 = "text/plain";
- private String mimetype2 = "text/xml";
- private String mimetype3 = "application/xml";
- private String spaceName1 = "space1";
- private String spaceName2 = "space2";
- private String providerId1 = "provider1";
- private String providerType1 = "AMAZON";
- private String providerId2 = "provider2";
- private String providerType2 = "RACKSPACE";
-
- @Test
- public void testMimetypeMetrics() {
- MimetypeMetricsCollector metrics = new MimetypeMetricsCollector(mimetype1);
-
- // Add data
- for(int i=1; i<=100; i++) {
- metrics.update(i);
- }
-
- // Verify totals
- assertEquals(mimetype1, metrics.getMimetype());
- assertEquals(100, metrics.getTotalItems());
- assertEquals(5050, metrics.getTotalSize());
- }
-
- @Test
- public void testSpaceMetrics() {
- SpaceMetricsCollector metrics = new SpaceMetricsCollector(spaceName1);
-
- // Add data
- for(int i=1; i<=10; i++) {
- metrics.update(mimetype1, i);
- }
- for(int i=1; i<=5; i++) {
- metrics.update(mimetype2, i);
- }
- for(int i=1; i<=3; i++) {
- metrics.update(mimetype3, i);
- }
-
- verifySpaceTotals(spaceName1, metrics);
- }
-
- private void verifySpaceTotals(String spaceName, SpaceMetricsCollector metrics) {
- // Verify space totals
- assertEquals(spaceName, metrics.getSpaceName());
- assertEquals(18, metrics.getTotalItems());
- assertEquals(76, metrics.getTotalSize());
-
- // Verify mimetype totals
- Map<String, MimetypeMetricsCollector> mimetypeMetricsMap =
- metrics.getMimetypeMetrics();
- assertEquals(3, mimetypeMetricsMap.size());
-
- MimetypeMetricsCollector mimetype1Metrics = mimetypeMetricsMap.get(mimetype1);
- assertNotNull(mimetype1Metrics);
- assertEquals(mimetype1, mimetype1Metrics.getMimetype());
- assertEquals(10, mimetype1Metrics.getTotalItems());
- assertEquals(55, mimetype1Metrics.getTotalSize());
-
- MimetypeMetricsCollector mimetype2Metrics = mimetypeMetricsMap.get(mimetype2);
- assertNotNull(mimetype2Metrics);
- assertEquals(mimetype2, mimetype2Metrics.getMimetype());
- assertEquals(5, mimetype2Metrics.getTotalItems());
- assertEquals(15, mimetype2Metrics.getTotalSize());
-
- MimetypeMetricsCollector mimetype3Metrics = mimetypeMetricsMap.get(mimetype3);
- assertNotNull(mimetype3Metrics);
- assertEquals(mimetype3, mimetype3Metrics.getMimetype());
- assertEquals(3, mimetype3Metrics.getTotalItems());
- assertEquals(6, mimetype3Metrics.getTotalSize());
- }
-
- @Test
- public void testStorageProviderMetricsError() {
- StorageProviderMetricsCollector metrics =
- new StorageProviderMetricsCollector(providerId1, providerType1);
-
- try {
- metrics.update(mimetype1, 1);
- fail("Exception expected");
- } catch(UnsupportedOperationException expected) {
- assertNotNull(expected);
- }
- }
-
- @Test
- public void testStorageProviderMetrics() {
- StorageProviderMetricsCollector metrics =
- new StorageProviderMetricsCollector(providerId1, providerType1);
-
- // Add data for space 1
- for(int i=1; i<=10; i++) {
- metrics.update(spaceName1, mimetype1, i);
- }
- for(int i=1; i<=5; i++) {
- metrics.update(spaceName1, mimetype2, i);
- }
- for(int i=1; i<=3; i++) {
- metrics.update(spaceName1, mimetype3, i);
- }
-
- // Add data for space 2
- for(int i=1; i<=10; i++) {
- metrics.update(spaceName2, mimetype1, i);
- }
- for(int i=1; i<=5; i++) {
- metrics.update(spaceName2, mimetype2, i);
- }
- for(int i=1; i<=3; i++) {
- metrics.update(spaceName2, mimetype3, i);
- }
-
- verifyStorageProviderMetrics(providerId1, metrics);
- }
-
- private void verifyStorageProviderMetrics(String providerId,
- StorageProviderMetricsCollector metrics) {
- // Verify storage provider totals
- assertEquals(providerId, metrics.getStorageProviderId());
- assertEquals(36, metrics.getTotalItems());
- assertEquals(152, metrics.getTotalSize());
-
- // Verify storage provider mimetype totals
- Map<String, MimetypeMetricsCollector> mimetypeMetricsMap =
- metrics.getMimetypeMetrics();
- assertEquals(3, mimetypeMetricsMap.size());
-
- MimetypeMetricsCollector mimetype1Metrics = mimetypeMetricsMap.get(mimetype1);
- assertNotNull(mimetype1Metrics);
- assertEquals(mimetype1, mimetype1Metrics.getMimetype());
- assertEquals(20, mimetype1Metrics.getTotalItems());
- assertEquals(110, mimetype1Metrics.getTotalSize());
-
- MimetypeMetricsCollector mimetype2Metrics = mimetypeMetricsMap.get(mimetype2);
- assertNotNull(mimetype2Metrics);
- assertEquals(mimetype2, mimetype2Metrics.getMimetype());
- assertEquals(10, mimetype2Metrics.getTotalItems());
- assertEquals(30, mimetype2Metrics.getTotalSize());
-
- MimetypeMetricsCollector mimetype3Metrics = mimetypeMetricsMap.get(mimetype3);
- assertNotNull(mimetype3Metrics);
- assertEquals(mimetype3, mimetype3Metrics.getMimetype());
- assertEquals(6, mimetype3Metrics.getTotalItems());
- assertEquals(12, mimetype3Metrics.getTotalSize());
-
- // Verify space metrics map
- Map<String, SpaceMetricsCollector> spaceMetricsMap = metrics.getSpaceMetrics();
- assertNotNull(spaceMetricsMap);
- assertEquals(2, spaceMetricsMap.size());
-
- // Verify space 1 totals
- SpaceMetricsCollector space1Metrics = spaceMetricsMap.get(spaceName1);
- assertNotNull(space1Metrics);
- verifySpaceTotals(spaceName1, space1Metrics);
-
- // Verify space 2 totals
- SpaceMetricsCollector space2Metrics = spaceMetricsMap.get(spaceName2);
- assertNotNull(space2Metrics);
- verifySpaceTotals(spaceName2, space2Metrics);
- }
-
- @Test
- public void testDuraStoreMetricsError() {
- DuraStoreMetricsCollector metrics = new DuraStoreMetricsCollector();
-
- try {
- metrics.update(mimetype1, 1);
- fail("Exception expected");
- } catch(UnsupportedOperationException expected) {
- assertNotNull(expected);
- }
- }
-
- @Test
- public void testDuraStoreMetrics() {
- DuraStoreMetricsCollector metrics = new DuraStoreMetricsCollector();
-
- // Add data
-
- // Provider 1, Space 1
- for(int i=1; i<=10; i++) {
- metrics.update(providerId1, providerType1, spaceName1, mimetype1, i);
- }
- for(int i=1; i<=5; i++) {
- metrics.update(providerId1, providerType1, spaceName1, mimetype2, i);
- }
- for(int i=1; i<=3; i++) {
- metrics.update(providerId1, providerType1, spaceName1, mimetype3, i);
- }
-
- // Provider 1, Space 2
- for(int i=1; i<=10; i++) {
- metrics.update(providerId1, providerType1, spaceName2, mimetype1, i);
- }
- for(int i=1; i<=5; i++) {
- metrics.update(providerId1, providerType1, spaceName2, mimetype2, i);
- }
- for(int i=1; i<=3; i++) {
- metrics.update(providerId1, providerType1, spaceName2, mimetype3, i);
- }
-
- // Provider 2, Space 1
- for(int i=1; i<=10; i++) {
- metrics.update(providerId2, providerType2, spaceName1, mimetype1, i);
- }
- for(int i=1; i<=5; i++) {
- metrics.update(providerId2, providerType2, spaceName1, mimetype2, i);
- }
- for(int i=1; i<=3; i++) {
- metrics.update(providerId2, providerType2, spaceName1, mimetype3, i);
- }
-
- // Provider 2, Space 2
- for(int i=1; i<=10; i++) {
- metrics.update(providerId2, providerType2, spaceName2, mimetype1, i);
- }
- for(int i=1; i<=5; i++) {
- metrics.update(providerId2, providerType2, spaceName2, mimetype2, i);
- }
- for(int i=1; i<=3; i++) {
- metrics.update(providerId2, providerType2, spaceName2, mimetype3, i);
- }
-
- // Verify durastore totals
- assertEquals(72, metrics.getTotalItems());
- assertEquals(304, metrics.getTotalSize());
-
- // Verify durastore mimetype totals
- Map<String, MimetypeMetricsCollector> mimetypeMetricsMap =
- metrics.getMimetypeMetrics();
- assertEquals(3, mimetypeMetricsMap.size());
-
- MimetypeMetricsCollector mimetype1Metrics = mimetypeMetricsMap.get(mimetype1);
- assertNotNull(mimetype1Metrics);
- assertEquals(mimetype1, mimetype1Metrics.getMimetype());
- assertEquals(40, mimetype1Metrics.getTotalItems());
- assertEquals(220, mimetype1Metrics.getTotalSize());
-
- MimetypeMetricsCollector mimetype2Metrics = mimetypeMetricsMap.get(mimetype2);
- assertNotNull(mimetype2Metrics);
- assertEquals(mimetype2, mimetype2Metrics.getMimetype());
- assertEquals(20, mimetype2Metrics.getTotalItems());
- assertEquals(60, mimetype2Metrics.getTotalSize());
-
- MimetypeMetricsCollector mimetype3Metrics = mimetypeMetricsMap.get(mimetype3);
- assertNotNull(mimetype3Metrics);
- assertEquals(mimetype3, mimetype3Metrics.getMimetype());
- assertEquals(12, mimetype3Metrics.getTotalItems());
- assertEquals(24, mimetype3Metrics.getTotalSize());
-
- // Verify storage provider metrics map
- Map<String, StorageProviderMetricsCollector> storageProviderMetricsMap =
- metrics.getStorageProviderMetrics();
- assertNotNull(storageProviderMetricsMap);
- assertEquals(2, storageProviderMetricsMap.size());
-
- // Verify storage provider 1 totals
- StorageProviderMetricsCollector spMetrics1 =
- storageProviderMetricsMap.get(providerId1);
- assertNotNull(spMetrics1);
- verifyStorageProviderMetrics(providerId1, spMetrics1);
-
- // Verify storage provider 2 totals
- StorageProviderMetricsCollector spMetrics2 =
- storageProviderMetricsMap.get(providerId2);
- assertNotNull(spMetrics2);
- verifyStorageProviderMetrics(providerId2, spMetrics2);
- }
-}
+/*
+ * The contents of this file are subject to the license and copyright
+ * detailed in the LICENSE and NOTICE files at the root of the source
+ * tree and available online at
+ *
+ * http://duracloud.org/license/
+ */
+package org.duracloud.reporter.storage.metrics;
+
+import org.junit.Test;
+
+import java.util.Map;
+
+import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+
+/**
+ * @author: Bill Branan
+ * Date: 5/12/11
+ */
+public class MetricsCollectorTest {
+
+ private String mimetype1 = "text/plain";
+ private String mimetype2 = "text/xml";
+ private String mimetype3 = "application/xml";
+ private String spaceName1 = "space1";
+ private String spaceName2 = "space2";
+ private String providerId1 = "provider1";
+ private String providerType1 = "AMAZON";
+ private String providerId2 = "provider2";
+ private String providerType2 = "RACKSPACE";
+
+ @Test
+ public void testMimetypeMetrics() {
+ MimetypeMetricsCollector metrics = new MimetypeMetricsCollector(mimetype1);
+
+ // Add data
+ for(int i=1; i<=100; i++) {
+ metrics.update(i);
+ }
+
+ // Verify totals
+ assertEquals(mimetype1, metrics.getMimetype());
+ assertEquals(100, metrics.getTotalItems());
+ assertEquals(5050, metrics.getTotalSize());
+ }
+
+ @Test
+ public void testSpaceMetrics() {
+ SpaceMetricsCollector metrics = new SpaceMetricsCollector(spaceName1);
+
+ // Add data
+ for(int i=1; i<=10; i++) {
+ metrics.update(mimetype1, i);
+ }
+ for(int i=1; i<=5; i++) {
+ metrics.update(mimetype2, i);
+ }
+ for(int i=1; i<=3; i++) {
+ metrics.update(mimetype3, i);
+ }
+
+ verifySpaceTotals(spaceName1, metrics);
+ }
+
+ private void verifySpaceTotals(String spaceName, SpaceMetricsCollector metrics) {
+ // Verify space totals
+ assertEquals(spaceName, metrics.getSpaceName());
+ assertEquals(18, metrics.getTotalItems());
+ assertEquals(76, metrics.getTotalSize());
+
+ // Verify mimetype totals
+ Map<String, MimetypeMetricsCollector> mimetypeMetricsMap =
+ metrics.getMimetypeMetrics();
+ assertEquals(3, mimetypeMetricsMap.size());
+
+ MimetypeMetricsCollector mimetype1Metrics = mimetypeMetricsMap.get(mimetype1);
+ assertNotNull(mimetype1Metrics);
+ assertEquals(mimetype1, mimetype1Metrics.getMimetype());
+ assertEquals(10, mimetype1Metrics.getTotalItems());
+ assertEquals(55, mimetype1Metrics.getTotalSize());
+
+ MimetypeMetricsCollector mimetype2Metrics = mimetypeMetricsMap.get(mimetype2);
+ assertNotNull(mimetype2Metrics);
+ assertEquals(mimetype2, mimetype2Metrics.getMimetype());
+ assertEquals(5, mimetype2Metrics.getTotalItems());
+ assertEquals(15, mimetype2Metrics.getTotalSize());
+
+ MimetypeMetricsCollector mimetype3Metrics = mimetypeMetricsMap.get(mimetype3);
+ assertNotNull(mimetype3Metrics);
+ assertEquals(mimetype3, mimetype3Metrics.getMimetype());
+ assertEquals(3, mimetype3Metrics.getTotalItems());
+ assertEquals(6, mimetype3Metrics.getTotalSize());
+ }
+
+ @Test
+ public void testStorageProviderMetricsError() {
+ StorageProviderMetricsCollector metrics =
+ new StorageProviderMetricsCollector(providerId1, providerType1);
+
+ try {
+ metrics.update(mimetype1, 1);
+ fail("Exception expected");
+ } catch(UnsupportedOperationException expected) {
+ assertNotNull(expected);
+ }
+ }
+
+ @Test
+ public void testStorageProviderMetrics() {
+ StorageProviderMetricsCollector metrics =
+ new StorageProviderMetricsCollector(providerId1, providerType1);
+
+ // Add data for space 1
+ for(int i=1; i<=10; i++) {
+ metrics.update(spaceName1, mimetype1, i);
+ }
+ for(int i=1; i<=5; i++) {
+ metrics.update(spaceName1, mimetype2, i);
+ }
+ for(int i=1; i<=3; i++) {
+ metrics.update(spaceName1, mimetype3, i);
+ }
+
+ // Add data for space 2
+ for(int i=1; i<=10; i++) {
+ metrics.update(spaceName2, mimetype1, i);
+ }
+ for(int i=1; i<=5; i++) {
+ metrics.update(spaceName2, mimetype2, i);
+ }
+ for(int i=1; i<=3; i++) {
+ metrics.update(spaceName2, mimetype3, i);
+ }
+
+ verifyStorageProviderMetrics(providerId1, metrics);
+ }
+
+ private void verifyStorageProviderMetrics(String providerId,
+ StorageProviderMetricsCollector metrics) {
+ // Verify storage provider totals
+ assertEquals(providerId, metrics.getStorageProviderId());
+ assertEquals(36, metrics.getTotalItems());
+ assertEquals(152, metrics.getTotalSize());
+
+ // Verify storage provider mimetype totals
+ Map<String, MimetypeMetricsCollector> mimetypeMetricsMap =
+ metrics.getMimetypeMetrics();
+ assertEquals(3, mimetypeMetricsMap.size());
+
+ MimetypeMetricsCollector mimetype1Metrics = mimetypeMetricsMap.get(mimetype1);
+ assertNotNull(mimetype1Metrics);
+ assertEquals(mimetype1, mimetype1Metrics.getMimetype());
+ assertEquals(20, mimetype1Metrics.getTotalItems());
+ assertEquals(110, mimetype1Metrics.getTotalSize());
+
+ MimetypeMetricsCollector mimetype2Metrics = mimetypeMetricsMap.get(mimetype2);
+ assertNotNull(mimetype2Metrics);
+ assertEquals(mimetype2, mimetype2Metrics.getMimetype());
+ assertEquals(10, mimetype2Metrics.getTotalItems());
+ assertEquals(30, mimetype2Metrics.getTotalSize());
+
+ MimetypeMetricsCollector mimetype3Metrics = mimetypeMetricsMap.get(mimetype3);
+ assertNotNull(mimetype3Metrics);
+ assertEquals(mimetype3, mimetype3Metrics.getMimetype());
+ assertEquals(6, mimetype3Metrics.getTotalItems());
+ assertEquals(12, mimetype3Metrics.getTotalSize());
+
+ // Verify space metrics map
+ Map<String, SpaceMetricsCollector> spaceMetricsMap = metrics.getSpaceMetrics();
+ assertNotNull(spaceMetricsMap);
+ assertEquals(2, spaceMetricsMap.size());
+
+ // Verify space 1 totals
+ SpaceMetricsCollector space1Metrics = spaceMetricsMap.get(spaceName1);
+ assertNotNull(space1Metrics);
+ verifySpaceTotals(spaceName1, space1Metrics);
+
+ // Verify space 2 totals
+ SpaceMetricsCollector space2Metrics = spaceMetricsMap.get(spaceName2);
+ assertNotNull(space2Metrics);
+ verifySpaceTotals(spaceName2, space2Metrics);
+ }
+
+ @Test
+ public void testDuraStoreMetricsError() {
+ DuraStoreMetricsCollector metrics = new DuraStoreMetricsCollector();
+
+ try {
+ metrics.update(mimetype1, 1);
+ fail("Exception expected");
+ } catch(UnsupportedOperationException expected) {
+ assertNotNull(expected);
+ }
+ }
+
+ @Test
+ public void testDuraStoreMetrics() {
+ DuraStoreMetricsCollector metrics = new DuraStoreMetricsCollector();
+
+ // Add data
+
+ // Provider 1, Space 1
+ for(int i=1; i<=10; i++) {
+ metrics.update(providerId1, providerType1, spaceName1, mimetype1, i);
+ }
+ for(int i=1; i<=5; i++) {
+ metrics.update(providerId1, providerType1, spaceName1, mimetype2, i);
+ }
+ for(int i=1; i<=3; i++) {
+ metrics.update(providerId1, providerType1, spaceName1, mimetype3, i);
+ }
+
+ // Provider 1, Space 2
+ for(int i=1; i<=10; i++) {
+ metrics.update(providerId1, providerType1, spaceName2, mimetype1, i);
+ }
+ for(int i=1; i<=5; i++) {
+ metrics.update(providerId1, providerType1, spaceName2, mimetype2, i);
+ }
+ for(int i=1; i<=3; i++) {
+ metrics.update(providerId1, providerType1, spaceName2, mimetype3, i);
+ }
+
+ // Provider 2, Space 1
+ for(int i=1; i<=10; i++) {
+ metrics.update(providerId2, providerType2, spaceName1, mimetype1, i);
+ }
+ for(int i=1; i<=5; i++) {
+ metrics.update(providerId2, providerType2, spaceName1, mimetype2, i);
+ }
+ for(int i=1; i<=3; i++) {
+ metrics.update(providerId2, providerType2, spaceName1, mimetype3, i);
+ }
+
+ // Provider 2, Space 2
+ for(int i=1; i<=10; i++) {
+ metrics.update(providerId2, providerType2, spaceName2, mimetype1, i);
+ }
+ for(int i=1; i<=5; i++) {
+ metrics.update(providerId2, providerType2, spaceName2, mimetype2, i);
+ }
+ for(int i=1; i<=3; i++) {
+ metrics.update(providerId2, providerType2, spaceName2, mimetype3, i);
+ }
+
+ // Verify durastore totals
+ assertEquals(72, metrics.getTotalItems());
+ assertEquals(304, metrics.getTotalSize());
+
+ // Verify durastore mimetype totals
+ Map<String, MimetypeMetricsCollector> mimetypeMetricsMap =
+ metrics.getMimetypeMetrics();
+ assertEquals(3, mimetypeMetricsMap.size());
+
+ MimetypeMetricsCollector mimetype1Metrics = mimetypeMetricsMap.get(mimetype1);
+ assertNotNull(mimetype1Metrics);
+ assertEquals(mimetype1, mimetype1Metrics.getMimetype());
+ assertEquals(40, mimetype1Metrics.getTotalItems());
+ assertEquals(220, mimetype1Metrics.getTotalSize());
+
+ MimetypeMetricsCollector mimetype2Metrics = mimetypeMetricsMap.get(mimetype2);
+ assertNotNull(mimetype2Metrics);
+ assertEquals(mimetype2, mimetype2Metrics.getMimetype());
+ assertEquals(20, mimetype2Metrics.getTotalItems());
+ assertEquals(60, mimetype2Metrics.getTotalSize());
+
+ MimetypeMetricsCollector mimetype3Metrics = mimetypeMetricsMap.get(mimetype3);
+ assertNotNull(mimetype3Metrics);
+ assertEquals(mimetype3, mimetype3Metrics.getMimetype());
+ assertEquals(12, mimetype3Metrics.getTotalItems());
+ assertEquals(24, mimetype3Metrics.getTotalSize());
+
+ // Verify storage provider metrics map
+ Map<String, StorageProviderMetricsCollector> storageProviderMetricsMap =
+ metrics.getStorageProviderMetrics();
+ assertNotNull(storageProviderMetricsMap);
+ assertEquals(2, storageProviderMetricsMap.size());
+
+ // Verify storage provider 1 totals
+ StorageProviderMetricsCollector spMetrics1 =
+ storageProviderMetricsMap.get(providerId1);
+ assertNotNull(spMetrics1);
+ verifyStorageProviderMetrics(providerId1, spMetrics1);
+
+ // Verify storage provider 2 totals
+ StorageProviderMetricsCollector spMetrics2 =
+ storageProviderMetricsMap.get(providerId2);
+ assertNotNull(spMetrics2);
+ verifyStorageProviderMetrics(providerId2, spMetrics2);
+ }
+}
diff --git a/resources/readme.txt b/resources/readme.txt
index e6b67eccb..b87a442ab 100644
--- a/resources/readme.txt
+++ b/resources/readme.txt
@@ -6,7 +6,7 @@ This package should include the following:
a. war files
-- durastore.war
-- duraservice.war
--- durareport.war
+-- duraboss.war
-- duradmin.war
b. services
|
4a1d547c823016965040237c038832468984fd05
|
intellij-community
|
plugins: tooltip for plugins with newer version- (IDEA-75998)--
|
a
|
https://github.com/JetBrains/intellij-community
|
diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsTableModel.java b/platform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsTableModel.java
index 840b8e1ccc43d..00b7d1672b357 100644
--- a/platform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsTableModel.java
+++ b/platform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsTableModel.java
@@ -514,6 +514,7 @@ public Component getTableCellRendererComponent(JTable table, Object value, boole
else if (hasNewerVersion(myPluginDescriptor.getPluginId()) ||
PluginManagerUISettings.getInstance().myOutdatedPlugins.contains(idString)) {
myNameLabel.setIcon(IconLoader.getIcon("/nodes/pluginobsolete.png"));
+ myPanel.setToolTipText("Newer version of the plugin is available");
}
else {
myNameLabel.setIcon(IconLoader.getIcon("/nodes/plugin.png"));
|
a4bb3485393b2bcf68379420d45dff7203583245
|
genericworkflownodes$genericknimenodes
|
Functionality moved to PluginXmlTemplate
New file package
|
p
|
https://github.com/genericworkflownodes/genericknimenodes
|
diff --git a/src/org/ballproject/knime/nodegeneration/NodeGenerator.java b/src/org/ballproject/knime/nodegeneration/NodeGenerator.java
index 77715219..dbe18016 100644
--- a/src/org/ballproject/knime/nodegeneration/NodeGenerator.java
+++ b/src/org/ballproject/knime/nodegeneration/NodeGenerator.java
@@ -50,19 +50,18 @@
import org.ballproject.knime.nodegeneration.model.PluginXmlTemplate;
import org.ballproject.knime.nodegeneration.model.directories.NodesBuildDirectory;
import org.ballproject.knime.nodegeneration.model.directories.NodesSourceDirectory;
+import org.ballproject.knime.nodegeneration.model.directories.source.DescriptorsDirectory;
+import org.ballproject.knime.nodegeneration.model.files.CtdFile;
import org.ballproject.knime.nodegeneration.model.mime.MimeType;
import org.ballproject.knime.nodegeneration.templates.TemplateResources;
-import org.dom4j.Document;
import org.dom4j.DocumentException;
-import org.dom4j.Element;
-import org.dom4j.Node;
import org.eclipse.core.commands.ExecutionException;
import org.jaxen.JaxenException;
public class NodeGenerator {
private static final String PLUGIN_PROPERTIES = "plugin.properties";
- static Logger logger = Logger.getLogger(NodeGenerator.class
+ public static Logger logger = Logger.getLogger(NodeGenerator.class
.getCanonicalName());
private NodesSourceDirectory srcDir;
@@ -82,22 +81,24 @@ public NodeGenerator(File pluginDir) throws IOException,
logger.info("Creating KNIME plugin sources in: " + buildDir.getPath());
- Document pluginXML = PluginXmlTemplate.getFromTemplate();
+ PluginXmlTemplate pluginXML = new PluginXmlTemplate();
createMimeFileCellFactoryFile(meta.getName(), srcDir.getMimeTypes(),
new File(buildDir.getKnimeNodesDirectory(), "mimetypes"
+ File.separator + "MimeFileCellFactory.java"));
+ // TODO: hier weiter machen
+ // Plugin zum laufen bekommen
Set<String> node_names = new HashSet<String>();
Set<String> ext_tools = new HashSet<String>();
processDescriptors(
node_names,
ext_tools,
pluginXML,
- (dynamicCTDs) ? srcDir.getExecutablesDirectory() : srcDir
- .getDescriptorsDirectory(), meta.getPackageRoot(),
- meta.getName(), this.buildDir.getKnimeNodesDirectory(),
- meta.getPackageRoot());
+ (dynamicCTDs) ? new DescriptorsDirectory(srcDir
+ .getExecutablesDirectory()) : srcDir
+ .getDescriptorsDirectory(),
+ this.buildDir.getKnimeNodesDirectory(), meta);
// TODO
// this.installIcon();
@@ -109,7 +110,7 @@ public NodeGenerator(File pluginDir) throws IOException,
this.buildDir.getKnimeNodesDirectory(),
srcDir.getPayloadDirectory(), node_names, ext_tools);
- PluginXmlTemplate.saveTo(pluginXML, buildDir.getPluginXml());
+ pluginXML.saveTo(buildDir.getPluginXml());
createManifest(meta, buildDir.getManifestMf());
}
@@ -214,30 +215,27 @@ private static void createMimeFileCellFactoryFile(String packageName,
}
private static void processDescriptors(Set<String> node_names,
- Set<String> ext_tools, Document pluginXML,
- File descriptorDirectory, String nodeRepositoryRoot,
- String pluginName, File destinationFQNNodeDirectory,
- String packageName) throws IOException, DuplicateNodeNameException,
+ Set<String> ext_tools, PluginXmlTemplate pluginXML,
+ DescriptorsDirectory descriptorDirectory,
+ File destinationFQNNodeDirectory, KNIMEPluginMeta pluginMeta)
+ throws IOException, DuplicateNodeNameException,
InvalidNodeNameException, CTDNodeConfigurationReaderException,
UnknownMimeTypeException {
+
Set<String> categories = new HashSet<String>();
- for (File file : descriptorDirectory.listFiles()) {
- if (file.getName().endsWith(".ctd")) {
- logger.info("start processing node " + file);
- processNode(pluginXML, file, node_names, ext_tools,
- nodeRepositoryRoot, pluginName,
- destinationFQNNodeDirectory, categories, packageName);
- }
+ for (CtdFile ctdFile : descriptorDirectory.getCtdFiles()) {
+ logger.info("Start processing node: " + ctdFile);
+ processNode(pluginMeta, pluginXML, ctdFile, node_names, ext_tools,
+ destinationFQNNodeDirectory, categories);
}
}
- public static void processNode(Document pluginXML, File ctdFile,
- Set<String> node_names, Set<String> ext_tools,
- String nodeRepositoryRoot, String pluginName,
- File destinationFQNNodeDirectory, Set<String> categories,
- String packageName) throws IOException, DuplicateNodeNameException,
- InvalidNodeNameException, CTDNodeConfigurationReaderException,
- UnknownMimeTypeException {
+ public static void processNode(KNIMEPluginMeta pluginMeta,
+ PluginXmlTemplate pluginXML, File ctdFile, Set<String> node_names,
+ Set<String> ext_tools, File destinationFQNNodeDirectory,
+ Set<String> categories) throws IOException,
+ DuplicateNodeNameException, InvalidNodeNameException,
+ CTDNodeConfigurationReaderException, UnknownMimeTypeException {
logger.info("## processing Node " + ctdFile.getName());
@@ -279,8 +277,8 @@ public static void processNode(Document pluginXML, File ctdFile,
}
}
- String cur_cat = new File("/" + nodeRepositoryRoot + "/" + pluginName,
- config.getCategory()).getPath();
+ String cur_cat = new File("/" + pluginMeta.getNodeRepositoryRoot()
+ + "/" + pluginMeta.getName(), config.getCategory()).getPath();
File nodeConfigDir = new File(destinationFQNNodeDirectory
+ File.separator + nodeName + File.separator + "config");
@@ -290,16 +288,19 @@ public static void processNode(Document pluginXML, File ctdFile,
+ File.separator + nodeName + File.separator + "config"
+ File.separator + "config.xml"));
- registerPath(cur_cat, pluginXML, categories);
+ pluginXML.registerPath(cur_cat);
- createFactory(nodeName, destinationFQNNodeDirectory, packageName);
+ createFactory(nodeName, destinationFQNNodeDirectory,
+ pluginMeta.getPackageRoot());
- createDialog(nodeName, destinationFQNNodeDirectory, packageName);
+ createDialog(nodeName, destinationFQNNodeDirectory,
+ pluginMeta.getPackageRoot());
- createView(nodeName, destinationFQNNodeDirectory, packageName);
+ createView(nodeName, destinationFQNNodeDirectory,
+ pluginMeta.getPackageRoot());
TemplateFiller curmodel_tf = createModel(nodeName,
- destinationFQNNodeDirectory, packageName);
+ destinationFQNNodeDirectory, pluginMeta.getPackageRoot());
fillMimeTypes(config, curmodel_tf);
@@ -309,46 +310,9 @@ public static void processNode(Document pluginXML, File ctdFile,
writeModel(nodeName, destinationFQNNodeDirectory, curmodel_tf);
- registerNode(packageName + ".knime.nodes." + nodeName + "." + nodeName
- + "NodeFactory", cur_cat, pluginXML, categories);
-
- }
-
- public static void registerPath(String path, Document pluginXML,
- Set<String> categories) {
- List<String> prefixes = Utils.getPathPrefixes(path);
- for (String prefix : prefixes) {
- registerPathPrefix(prefix, pluginXML, categories);
- }
- }
-
- public static void registerPathPrefix(String path, Document pluginXML,
- Set<String> categories) {
- // do not register any top level or root path
- if (path.equals("/") || new File(path).getParent().equals("/"))
- return;
+ pluginXML.registerNode(pluginMeta.getPackageRoot() + ".knime.nodes."
+ + nodeName + "." + nodeName + "NodeFactory", cur_cat);
- if (categories.contains(path))
- return;
-
- logger.info("registering path prefix " + path);
-
- categories.add(path);
-
- String cat_name = Utils.getPathSuffix(path);
- String path_prefix = Utils.getPathPrefix(path);
-
- Node node = pluginXML
- .selectSingleNode("/plugin/extension[@point='org.knime.workbench.repository.categories']");
-
- Element elem = (Element) node;
- logger.info("name=" + cat_name);
-
- elem.addElement("category").addAttribute("description", path)
- .addAttribute("icon", "icons/category.png")
- .addAttribute("path", path_prefix)
- .addAttribute("name", cat_name)
- .addAttribute("level-id", cat_name);
}
public static void createFactory(String nodeName,
@@ -581,19 +545,6 @@ public static void createOutClazzezModel(String clazzez,
curmodel_tf.replace("__OUTCLAZZEZ__", clazzez);
}
- public static void registerNode(String clazz, String path,
- Document pluginXML, Set<String> categories) {
- logger.info("registering Node " + clazz);
- registerPath(path, pluginXML, categories);
-
- Node node = pluginXML
- .selectSingleNode("/plugin/extension[@point='org.knime.workbench.repository.nodes']");
- Element elem = (Element) node;
-
- elem.addElement("node").addAttribute("factory-class", clazz)
- .addAttribute("id", clazz).addAttribute("category-path", path);
- }
-
public static void post(String packageName, File destinationFQNDirectory,
File destinationFQNNodeDirectory, File payloadDirectory,
Set<String> node_names, Set<String> ext_tools) throws IOException {
diff --git a/src/org/ballproject/knime/nodegeneration/Utils.java b/src/org/ballproject/knime/nodegeneration/Utils.java
index 61d53c34..fd035e40 100644
--- a/src/org/ballproject/knime/nodegeneration/Utils.java
+++ b/src/org/ballproject/knime/nodegeneration/Utils.java
@@ -13,7 +13,7 @@ public class Utils {
/**
* returns all prefix paths of a given path.
*
- * /foo/bar/baz --> [/foo/bar/,/foo/,/]
+ * /foo/bar/baz --> [/foo/bar, /foo, /]
*
* @param path
* @return
diff --git a/src/org/ballproject/knime/nodegeneration/model/PluginXmlTemplate.java b/src/org/ballproject/knime/nodegeneration/model/PluginXmlTemplate.java
index ad29710f..da02ada6 100644
--- a/src/org/ballproject/knime/nodegeneration/model/PluginXmlTemplate.java
+++ b/src/org/ballproject/knime/nodegeneration/model/PluginXmlTemplate.java
@@ -4,27 +4,41 @@
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.logging.Logger;
import org.ballproject.knime.base.util.Helper;
+import org.ballproject.knime.nodegeneration.NodeGenerator;
+import org.ballproject.knime.nodegeneration.Utils;
import org.ballproject.knime.nodegeneration.templates.TemplateResources;
import org.dom4j.Document;
import org.dom4j.DocumentException;
+import org.dom4j.Element;
+import org.dom4j.Node;
import org.dom4j.dom.DOMDocumentFactory;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class PluginXmlTemplate {
+
+ private static final Logger LOGGER = Logger
+ .getLogger(PluginXmlTemplate.class.getCanonicalName());
+
+ private Document doc;
+ private Set<String> registeredPrefixed = new HashSet<String>();
+
/**
- * Prepares a new copy of a template plugin.xml and returns its
+ * Constructs a new copy of a template plugin.xml and returns its
* {@link Document} representation.
*
* @return
* @throws DocumentException
* @throws IOException
*/
- public static Document getFromTemplate() throws DocumentException,
- IOException {
+ public PluginXmlTemplate() throws DocumentException, IOException {
File temp = File.createTempFile("plugin", "xml");
temp.deleteOnExit();
Helper.copyStream(TemplateResources.class
@@ -33,7 +47,7 @@ public static Document getFromTemplate() throws DocumentException,
SAXReader reader = new SAXReader();
reader.setDocumentFactory(new DOMDocumentFactory());
- return reader.read(new FileInputStream(temp));
+ this.doc = reader.read(new FileInputStream(temp));
}
/**
@@ -43,10 +57,62 @@ public static Document getFromTemplate() throws DocumentException,
* @param dest
* @throws IOException
*/
- public static void saveTo(Document pluginXml, File dest) throws IOException {
+ public void saveTo(File dest) throws IOException {
XMLWriter writer = new XMLWriter(new FileWriter(dest),
OutputFormat.createPrettyPrint());
- writer.write(pluginXml);
+ writer.write(this.doc);
writer.close();
}
+
+ // TODO: documentation
+ public void registerPath(String path) {
+ System.out.println(path);
+ List<String> prefixes = Utils.getPathPrefixes(path);
+ for (String prefix : prefixes) {
+ this.registerPathPrefix(prefix);
+ }
+ }
+
+ // TODO: documentation
+ private void registerPathPrefix(String path) {
+ // do not register any top level or root path
+ // TODO: why?
+ if (path.equals("/") || new File(path).getParent().equals("/"))
+ return;
+
+ if (this.registeredPrefixed.contains(path))
+ return;
+
+ LOGGER.info("Registering path prefix: " + path);
+
+ this.registeredPrefixed.add(path);
+
+ String categoryName = Utils.getPathSuffix(path);
+ String categoryPath = Utils.getPathPrefix(path);
+
+ Node node = this.doc
+ .selectSingleNode("/plugin/extension[@point='org.knime.workbench.repository.categories']");
+
+ Element elem = (Element) node;
+ LOGGER.info("name=" + categoryName);
+
+ elem.addElement("category").addAttribute("description", path)
+ .addAttribute("icon", "icons/category.png")
+ .addAttribute("path", categoryPath)
+ .addAttribute("name", categoryName)
+ .addAttribute("level-id", categoryName);
+ }
+
+ // TODO: documentation
+ public void registerNode(String clazz, String path) {
+ NodeGenerator.logger.info("registering Node " + clazz);
+ this.registerPath(path);
+
+ Node node = this.doc
+ .selectSingleNode("/plugin/extension[@point='org.knime.workbench.repository.nodes']");
+ Element elem = (Element) node;
+
+ elem.addElement("node").addAttribute("factory-class", clazz)
+ .addAttribute("id", clazz).addAttribute("category-path", path);
+ }
}
diff --git a/src/org/ballproject/knime/nodegeneration/model/directories/NodesSourceDirectory.java b/src/org/ballproject/knime/nodegeneration/model/directories/NodesSourceDirectory.java
index 2dddc113..01ed2fab 100644
--- a/src/org/ballproject/knime/nodegeneration/model/directories/NodesSourceDirectory.java
+++ b/src/org/ballproject/knime/nodegeneration/model/directories/NodesSourceDirectory.java
@@ -9,11 +9,10 @@
import org.ballproject.knime.nodegeneration.model.directories.source.DescriptorsDirectory;
import org.ballproject.knime.nodegeneration.model.directories.source.ExecutablesDirectory;
-import org.ballproject.knime.nodegeneration.model.directories.source.MimeTypesFile;
import org.ballproject.knime.nodegeneration.model.directories.source.PayloadDirectory;
+import org.ballproject.knime.nodegeneration.model.files.CtdFile;
import org.ballproject.knime.nodegeneration.model.mime.MimeType;
import org.dom4j.DocumentException;
-import org.jaxen.JaxenException;
public class NodesSourceDirectory extends Directory {
@@ -22,7 +21,6 @@ public class NodesSourceDirectory extends Directory {
private ExecutablesDirectory executablesDirectory = null;
private PayloadDirectory payloadDirectory = null;
private Properties properties = null;
- private MimeTypesFile mimeTypesFile;
public NodesSourceDirectory(File nodeSourceDirectory) throws IOException,
DocumentException {
@@ -61,14 +59,6 @@ public NodesSourceDirectory(File nodeSourceDirectory) throws IOException,
} catch (IOException e) {
throw new IOException("Could not load property file", e);
}
-
- File mimeTypeFile = new File(descriptorsDirectory, "mimetypes.xml");
- try {
- this.mimeTypesFile = new MimeTypesFile(mimeTypeFile);
- } catch (JaxenException e) {
- throw new IOException("Error reading MIME types from "
- + mimeTypeFile.getPath());
- }
}
public DescriptorsDirectory getDescriptorsDirectory() {
@@ -87,7 +77,11 @@ public Properties getProperties() {
return properties;
}
+ public List<CtdFile> getCtdFiles() {
+ return this.descriptorsDirectory.getCtdFiles();
+ }
+
public List<MimeType> getMimeTypes() {
- return this.mimeTypesFile.getMimeTypes();
+ return this.descriptorsDirectory.getMimeTypesFile().getMimeTypes();
}
}
diff --git a/src/org/ballproject/knime/nodegeneration/model/directories/source/DescriptorsDirectory.java b/src/org/ballproject/knime/nodegeneration/model/directories/source/DescriptorsDirectory.java
index 05ae4c3e..ac742f71 100644
--- a/src/org/ballproject/knime/nodegeneration/model/directories/source/DescriptorsDirectory.java
+++ b/src/org/ballproject/knime/nodegeneration/model/directories/source/DescriptorsDirectory.java
@@ -1,17 +1,49 @@
package org.ballproject.knime.nodegeneration.model.directories.source;
import java.io.File;
-import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.LinkedList;
+import java.util.List;
import org.ballproject.knime.nodegeneration.model.directories.Directory;
+import org.ballproject.knime.nodegeneration.model.files.CtdFile;
+import org.ballproject.knime.nodegeneration.model.files.MimeTypesFile;
+import org.dom4j.DocumentException;
+import org.jaxen.JaxenException;
public class DescriptorsDirectory extends Directory {
private static final long serialVersionUID = -3535393317046918930L;
+ private List<CtdFile> ctdFiles;
+ private MimeTypesFile mimeTypesFile;
- public DescriptorsDirectory(File sourcesDirectory) throws FileNotFoundException {
+ public DescriptorsDirectory(File sourcesDirectory) throws IOException {
super(sourcesDirectory);
- // TODO Auto-generated constructor stub
+
+ File mimeTypeFile = new File(this, "mimetypes.xml");
+ try {
+ this.mimeTypesFile = new MimeTypesFile(mimeTypeFile);
+ } catch (JaxenException e) {
+ throw new IOException("Error reading MIME types from "
+ + mimeTypeFile.getPath());
+ } catch (DocumentException e) {
+ throw new IOException("Error reading MIME types from "
+ + mimeTypeFile.getPath());
+ }
+
+ ctdFiles = new LinkedList<CtdFile>();
+ for (File file : this.listFiles()) {
+ if (file.getName().endsWith(".ctd"))
+ ctdFiles.add(new CtdFile(file));
+ }
+ }
+
+ public List<CtdFile> getCtdFiles() {
+ return ctdFiles;
+ }
+
+ public MimeTypesFile getMimeTypesFile() {
+ return mimeTypesFile;
}
}
diff --git a/src/org/ballproject/knime/nodegeneration/model/directories/source/MimeTypesFile.java b/src/org/ballproject/knime/nodegeneration/model/directories/source/MimeTypesFile.java
deleted file mode 100644
index 11dceaab..00000000
--- a/src/org/ballproject/knime/nodegeneration/model/directories/source/MimeTypesFile.java
+++ /dev/null
@@ -1,81 +0,0 @@
-package org.ballproject.knime.nodegeneration.model.directories.source;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.ballproject.knime.base.schemas.SchemaProvider;
-import org.ballproject.knime.base.schemas.SchemaValidator;
-import org.ballproject.knime.nodegeneration.model.mime.MimeType;
-import org.dom4j.Document;
-import org.dom4j.DocumentException;
-import org.dom4j.Element;
-import org.dom4j.Node;
-import org.dom4j.dom.DOMDocumentFactory;
-import org.dom4j.io.SAXReader;
-import org.jaxen.JaxenException;
-import org.jaxen.SimpleNamespaceContext;
-import org.jaxen.dom4j.Dom4jXPath;
-
-public class MimeTypesFile extends File {
-
- private static final long serialVersionUID = -1620704972604551679L;
-
- public static void validate(File file) throws DocumentException {
- SchemaValidator val = new SchemaValidator();
- val.addSchema(SchemaProvider.class.getResourceAsStream("mimetypes.xsd"));
- if (!val.validates(file.getPath()))
- throw new DocumentException("Supplied \"" + file.getPath()
- + "\" does not conform to schema " + val.getErrorReport());
- }
-
- public static Document createDocument(File file)
- throws FileNotFoundException, DocumentException {
- DOMDocumentFactory factory = new DOMDocumentFactory();
- SAXReader reader = new SAXReader();
- reader.setDocumentFactory(factory);
- return reader.read(new FileInputStream(file));
- }
-
- public static List<MimeType> readMimeTypes(Document doc)
- throws JaxenException {
- Map<String, String> map = new HashMap<String, String>();
- map.put("bp", "http://www.ball-project.org/mimetypes"); // TODO
-
- Dom4jXPath xpath = new Dom4jXPath("//bp:mimetype");
- xpath.setNamespaceContext(new SimpleNamespaceContext(map));
- @SuppressWarnings("unchecked")
- List<Node> nodes = xpath.selectNodes(doc);
- List<MimeType> mimeTypes = new ArrayList<MimeType>();
- for (Node node : nodes) {
- Element element = (Element) node;
- mimeTypes.add(new MimeType(element));
- }
- return mimeTypes;
- }
-
- private List<MimeType> mimeTypes;
-
- public MimeTypesFile(File file) throws IOException, DocumentException,
- JaxenException {
- super(file.getPath());
-
- if (file == null || !file.canRead())
- throw new IOException("Invalid MIME types file: " + file.getPath());
-
- validate(file);
-
- Document doc = createDocument(file);
- this.mimeTypes = readMimeTypes(doc);
- }
-
- public List<MimeType> getMimeTypes() {
- return mimeTypes;
- }
-
-}
|
7181fa35a35a4aa8e2f1bf8d2db39fa87a81e69d
|
hbase
|
HBASE-8062 Replace HBaseFsck.debugLsr() in- TestFlushSnapshotFromClient with FSUtils.logFileSystemState()--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1463646 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/hbase
|
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/snapshot/TestFlushSnapshotFromClient.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/snapshot/TestFlushSnapshotFromClient.java
index 456df24d6593..7f1308e7ef7c 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/snapshot/TestFlushSnapshotFromClient.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/snapshot/TestFlushSnapshotFromClient.java
@@ -55,7 +55,6 @@
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.FSTableDescriptors;
import org.apache.hadoop.hbase.util.FSUtils;
-import org.apache.hadoop.hbase.util.HBaseFsck;
import org.apache.hadoop.hbase.util.JVMClusterUtil.RegionServerThread;
import org.apache.log4j.Level;
import org.junit.After;
@@ -233,14 +232,16 @@ public void testAsyncFlushSnapshot() throws Exception {
HMaster master = UTIL.getMiniHBaseCluster().getMaster();
SnapshotTestingUtils.waitForSnapshotToComplete(master, snapshot, 200);
LOG.info(" === Async Snapshot Completed ===");
- HBaseFsck.debugLsr(UTIL.getHBaseCluster().getConfiguration(), FSUtils.getRootDir(UTIL.getConfiguration()));
+ FSUtils.logFileSystemState(UTIL.getTestFileSystem(),
+ FSUtils.getRootDir(UTIL.getConfiguration()), LOG);
// make sure we get the snapshot
SnapshotTestingUtils.assertOneSnapshotThatMatches(admin, snapshot);
// test that we can delete the snapshot
admin.deleteSnapshot(snapshot.getName());
LOG.info(" === Async Snapshot Deleted ===");
- HBaseFsck.debugLsr(UTIL.getHBaseCluster().getConfiguration(), FSUtils.getRootDir(UTIL.getConfiguration()));
+ FSUtils.logFileSystemState(UTIL.getTestFileSystem(),
+ FSUtils.getRootDir(UTIL.getConfiguration()), LOG);
// make sure we don't have any snapshots
SnapshotTestingUtils.assertNoSnapshots(admin);
LOG.info(" === Async Snapshot Test Completed ===");
@@ -278,7 +279,7 @@ public void testFlushCreateListDestroy() throws Exception {
Path rootDir = UTIL.getHBaseCluster().getMaster().getMasterFileSystem().getRootDir();
Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshots.get(0), rootDir);
assertTrue(fs.exists(snapshotDir));
- HBaseFsck.debugLsr(UTIL.getHBaseCluster().getConfiguration(), snapshotDir);
+ FSUtils.logFileSystemState(UTIL.getTestFileSystem(), snapshotDir, LOG);
Path snapshotinfo = new Path(snapshotDir, SnapshotDescriptionUtils.SNAPSHOTINFO_FILE);
assertTrue(fs.exists(snapshotinfo));
@@ -304,7 +305,8 @@ public void testFlushCreateListDestroy() throws Exception {
// test that we can delete the snapshot
admin.deleteSnapshot(snapshotName);
- HBaseFsck.debugLsr(UTIL.getHBaseCluster().getConfiguration(), FSUtils.getRootDir(UTIL.getConfiguration()));
+ FSUtils.logFileSystemState(UTIL.getTestFileSystem(),
+ FSUtils.getRootDir(UTIL.getConfiguration()), LOG);
// make sure we don't have any snapshots
SnapshotTestingUtils.assertNoSnapshots(admin);
|
72894b26c24b1ea31c6dda4634cfde67e7dc3050
|
spring-framework
|
Fix conversion of Message<?> payload for replies--If a custom MessageConverter is set
|
c
|
https://github.com/spring-projects/spring-framework
|
diff --git a/spring-jms/src/main/java/org/springframework/jms/listener/adapter/AbstractAdaptableMessageListener.java b/spring-jms/src/main/java/org/springframework/jms/listener/adapter/AbstractAdaptableMessageListener.java
index f910fd430828..cd0516de6d57 100644
--- a/spring-jms/src/main/java/org/springframework/jms/listener/adapter/AbstractAdaptableMessageListener.java
+++ b/spring-jms/src/main/java/org/springframework/jms/listener/adapter/AbstractAdaptableMessageListener.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2014 the original author or authors.
+ * Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -396,6 +396,15 @@ private class MessagingMessageConverterAdapter extends MessagingMessageConverter
protected Object extractPayload(Message message) throws JMSException {
return extractMessage(message);
}
+
+ @Override
+ protected Message createMessageForPayload(Object payload, Session session) throws JMSException {
+ MessageConverter converter = getMessageConverter();
+ if (converter != null) {
+ return converter.toMessage(payload, session);
+ }
+ throw new IllegalStateException("No message converter, cannot handle '" + payload + "'");
+ }
}
diff --git a/spring-jms/src/main/java/org/springframework/jms/support/converter/MessagingMessageConverter.java b/spring-jms/src/main/java/org/springframework/jms/support/converter/MessagingMessageConverter.java
index aefa45877e47..a4db74313e9c 100644
--- a/spring-jms/src/main/java/org/springframework/jms/support/converter/MessagingMessageConverter.java
+++ b/spring-jms/src/main/java/org/springframework/jms/support/converter/MessagingMessageConverter.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2014 the original author or authors.
+ * Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -93,7 +93,7 @@ public javax.jms.Message toMessage(Object object, Session session) throws JMSExc
Message.class.getName() + "] is handled by this converter");
}
Message<?> input = (Message<?>) object;
- javax.jms.Message reply = this.payloadConverter.toMessage(input.getPayload(), session);
+ javax.jms.Message reply = createMessageForPayload(input.getPayload(), session);
this.headerMapper.fromHeaders(input.getHeaders(), reply);
return reply;
}
@@ -119,4 +119,12 @@ protected Object extractPayload(javax.jms.Message message) throws JMSException {
return this.payloadConverter.fromMessage(message);
}
+ /**
+ * Create a JMS message for the specified payload.
+ * @see MessageConverter#toMessage(Object, Session)
+ */
+ protected javax.jms.Message createMessageForPayload(Object payload, Session session) throws JMSException {
+ return this.payloadConverter.toMessage(payload, session);
+ }
+
}
diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java
index 5fc400e8bb0d..f5f38d787d33 100644
--- a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java
+++ b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2014 the original author or authors.
+ * Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,8 @@
package org.springframework.jms.listener.adapter;
import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Session;
@@ -28,6 +30,7 @@
import org.springframework.beans.factory.support.StaticListableBeanFactory;
import org.springframework.jms.StubTextMessage;
import org.springframework.jms.support.JmsHeaders;
+import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.messaging.Message;
import org.springframework.messaging.converter.MessageConversionException;
import org.springframework.messaging.handler.annotation.support.DefaultMessageHandlerMethodFactory;
@@ -111,6 +114,38 @@ public void exceptionInInvocation() {
}
}
+ @Test
+ public void incomingMessageUsesMessageConverter() throws JMSException {
+ javax.jms.Message jmsMessage = mock(javax.jms.Message.class);
+ Session session = mock(Session.class);
+ MessageConverter messageConverter = mock(MessageConverter.class);
+ given(messageConverter.fromMessage(jmsMessage)).willReturn("FooBar");
+ MessagingMessageListenerAdapter listener = getSimpleInstance("simple", Message.class);
+ listener.setMessageConverter(messageConverter);
+ listener.onMessage(jmsMessage, session);
+ verify(messageConverter, times(1)).fromMessage(jmsMessage);
+ assertEquals(1, sample.simples.size());
+ assertEquals("FooBar", sample.simples.get(0).getPayload());
+ }
+
+ @Test
+ public void replyUsesMessageConverterForPayload() throws JMSException {
+ Session session = mock(Session.class);
+ MessageConverter messageConverter = mock(MessageConverter.class);
+ given(messageConverter.toMessage("Response", session)).willReturn(new StubTextMessage("Response"));
+
+ Message<String> result = MessageBuilder.withPayload("Response")
+ .build();
+
+ MessagingMessageListenerAdapter listener = getSimpleInstance("echo", Message.class);
+ listener.setMessageConverter(messageConverter);
+ javax.jms.Message replyMessage = listener.buildMessage(session, result);
+
+ verify(messageConverter, times(1)).toMessage("Response", session);
+ assertNotNull("reply should never be null", replyMessage);
+ assertEquals("Response", ((TextMessage) replyMessage).getText());
+ }
+
protected MessagingMessageListenerAdapter getSimpleInstance(String methodName, Class... parameterTypes) {
Method m = ReflectionUtils.findMethod(SampleBean.class, methodName, parameterTypes);
return createInstance(m);
@@ -131,6 +166,12 @@ private void initializeFactory(DefaultMessageHandlerMethodFactory factory) {
@SuppressWarnings("unused")
private static class SampleBean {
+ public final List<Message<String>> simples = new ArrayList<>();
+
+ public void simple(Message<String> input) {
+ simples.add(input);
+ }
+
public Message<String> echo(Message<String> input) {
return MessageBuilder.withPayload(input.getPayload())
.setHeader(JmsHeaders.TYPE, "reply")
|
d65ee9688799a2766e3121e779ff4fd17c48fe8a
|
Vala
|
gtk+-2.0: Make GtkContainer::set_focus_child's argument nullable
Fixes bug 611492.
|
c
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/gtk+-2.0.vapi b/vapi/gtk+-2.0.vapi
index 8b3b951bfe..66c9d6894e 100644
--- a/vapi/gtk+-2.0.vapi
+++ b/vapi/gtk+-2.0.vapi
@@ -1101,7 +1101,7 @@ namespace Gtk {
[HasEmitter]
public virtual signal void remove (Gtk.Widget widget);
[HasEmitter]
- public virtual signal void set_focus_child (Gtk.Widget widget);
+ public virtual signal void set_focus_child (Gtk.Widget? widget);
}
[CCode (cheader_filename = "gtk/gtk.h")]
public class Curve : Gtk.DrawingArea, Atk.Implementor, Gtk.Buildable {
diff --git a/vapi/packages/gtk+-2.0/gtk+-2.0.metadata b/vapi/packages/gtk+-2.0/gtk+-2.0.metadata
index ada4ef5ff4..1210297d66 100644
--- a/vapi/packages/gtk+-2.0/gtk+-2.0.metadata
+++ b/vapi/packages/gtk+-2.0/gtk+-2.0.metadata
@@ -122,6 +122,7 @@ GtkContainer::add has_emitter="1"
GtkContainer::check_resize has_emitter="1"
GtkContainer::remove has_emitter="1"
GtkContainer::set_focus_child has_emitter="1"
+GtkContainer::set_focus_child.widget nullable="1"
gtk_container_forall.callback_data hidden="1"
gtk_container_foreach.callback_data hidden="1"
gtk_container_get_children transfer_ownership="1" type_arguments="unowned Widget"
|
65991ccc26feda4b15faeb03707123b9795de1df
|
Vala
|
glib-2.0: add GLib.FileUtils.get/set_data methods
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/glib-2.0.vapi b/vapi/glib-2.0.vapi
index b864b34eaa..404dc7abb1 100644
--- a/vapi/glib-2.0.vapi
+++ b/vapi/glib-2.0.vapi
@@ -2600,6 +2600,10 @@ namespace GLib {
namespace FileUtils {
public static bool get_contents (string filename, out string contents, out size_t length = null) throws FileError;
public static bool set_contents (string filename, string contents, ssize_t length = -1) throws FileError;
+ [CCode (cname = "g_file_get_contents")]
+ public static bool get_data (string filename, [CCode (type = "gchar**", array_length_type = "size_t")] out uint8[] contents) throws FileError;
+ [CCode (cname = "g_file_set_contents")]
+ public static bool set_data (string filename, [CCode (type = "const char*", array_length_type = "size_t")] uint8[] contents) throws FileError;
public static bool test (string filename, FileTest test);
public static int open_tmp (string tmpl, out string name_used) throws FileError;
public static string read_link (string filename) throws FileError;
|
43162699924ee9295b47e1fecf6068e6fe4b4ad8
|
Vala
|
Support XOR operation for booleans
Fixes bug 729907
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/tests/Makefile.am b/tests/Makefile.am
index ee5bbfeab8..8143bda83f 100644
--- a/tests/Makefile.am
+++ b/tests/Makefile.am
@@ -37,6 +37,7 @@ TESTS = \
basic-types/bug659975.vala \
basic-types/bug678791.vala \
basic-types/bug686336.vala \
+ basic-types/bug729907.vala \
namespaces.vala \
methods/lambda.vala \
methods/closures.vala \
diff --git a/tests/basic-types/bug729907.vala b/tests/basic-types/bug729907.vala
new file mode 100644
index 0000000000..fbbebb2107
--- /dev/null
+++ b/tests/basic-types/bug729907.vala
@@ -0,0 +1,5 @@
+void main () {
+ assert (false ^ true == true);
+ assert (true ^ true == false);
+ assert (false ^ false == false);
+}
\ No newline at end of file
diff --git a/vala/valabinaryexpression.vala b/vala/valabinaryexpression.vala
index 8ccddba0d7..0c9bf32431 100644
--- a/vala/valabinaryexpression.vala
+++ b/vala/valabinaryexpression.vala
@@ -355,8 +355,7 @@ public class Vala.BinaryExpression : Expression {
}
} else if (operator == BinaryOperator.MOD
|| operator == BinaryOperator.SHIFT_LEFT
- || operator == BinaryOperator.SHIFT_RIGHT
- || operator == BinaryOperator.BITWISE_XOR) {
+ || operator == BinaryOperator.SHIFT_RIGHT) {
left.target_type.nullable = false;
right.target_type.nullable = false;
@@ -433,7 +432,8 @@ public class Vala.BinaryExpression : Expression {
value_type = context.analyzer.bool_type;
} else if (operator == BinaryOperator.BITWISE_AND
- || operator == BinaryOperator.BITWISE_OR) {
+ || operator == BinaryOperator.BITWISE_OR
+ || operator == BinaryOperator.BITWISE_XOR) {
// integer type or flags type
left.target_type.nullable = false;
right.target_type.nullable = false;
|
f8a5053d2b51dd72cb46ab32e776957443a3dd88
|
drools
|
JBRULES-527: adding primitive support to alpha- hashing code--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@7150 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
|
a
|
https://github.com/kiegroup/drools
|
diff --git a/drools-core/src/main/java/org/drools/base/ValueType.java b/drools-core/src/main/java/org/drools/base/ValueType.java
index bd4f9bc24bb..ed7712339f1 100644
--- a/drools-core/src/main/java/org/drools/base/ValueType.java
+++ b/drools-core/src/main/java/org/drools/base/ValueType.java
@@ -212,8 +212,35 @@ public boolean isBoolean() {
}
public boolean isNumber() {
- return (Number.class.isAssignableFrom( this.classType )) || (this.classType == Byte.TYPE) || (this.classType == Short.TYPE) || (this.classType == Integer.TYPE) || (this.classType == Long.TYPE) || (this.classType == Float.TYPE)
- || (this.classType == Double.TYPE);
+ return (this.classType == Integer.TYPE) ||
+ (this.classType == Long.TYPE) ||
+ (this.classType == Float.TYPE) ||
+ (this.classType == Double.TYPE) ||
+ (this.classType == Byte.TYPE) ||
+ (this.classType == Short.TYPE) ||
+ (this.classType == Character.TYPE) ||
+ (this.classType == Character.class) ||
+ (Number.class.isAssignableFrom( this.classType ));
+ }
+
+ public boolean isIntegerNumber() {
+ return (this.classType == Integer.TYPE) ||
+ (this.classType == Long.TYPE) ||
+ (this.classType == Integer.class) ||
+ (this.classType == Long.class) ||
+ (this.classType == Character.class) ||
+ (this.classType == Character.TYPE) ||
+ (this.classType == Byte.TYPE) ||
+ (this.classType == Short.TYPE) ||
+ (this.classType == Byte.class) ||
+ (this.classType == Short.class);
+ }
+
+ public boolean isFloatNumber() {
+ return (this.classType == Float.TYPE) ||
+ (this.classType == Double.TYPE) ||
+ (this.classType == Float.class) ||
+ (this.classType == Double.class);
}
public boolean isChar() {
diff --git a/drools-core/src/main/java/org/drools/base/field/BooleanFieldImpl.java b/drools-core/src/main/java/org/drools/base/field/BooleanFieldImpl.java
index 11fcbefca1b..33bd1bc15e7 100755
--- a/drools-core/src/main/java/org/drools/base/field/BooleanFieldImpl.java
+++ b/drools-core/src/main/java/org/drools/base/field/BooleanFieldImpl.java
@@ -90,4 +90,20 @@ public int hashCode() {
return this.value ? 1 : 0;
}
+ public boolean isBooleanField() {
+ return true;
+ }
+
+ public boolean isFloatNumberField() {
+ return false;
+ }
+
+ public boolean isIntegerNumberField() {
+ return false;
+ }
+
+ public boolean isObjectField() {
+ return false;
+ }
+
}
diff --git a/drools-core/src/main/java/org/drools/base/field/DoubleFieldImpl.java b/drools-core/src/main/java/org/drools/base/field/DoubleFieldImpl.java
index a5e9ad8ffe5..86f92fcaea7 100755
--- a/drools-core/src/main/java/org/drools/base/field/DoubleFieldImpl.java
+++ b/drools-core/src/main/java/org/drools/base/field/DoubleFieldImpl.java
@@ -70,4 +70,20 @@ public int hashCode() {
return (int) this.value;
}
+ public boolean isBooleanField() {
+ return false;
+ }
+
+ public boolean isFloatNumberField() {
+ return true;
+ }
+
+ public boolean isIntegerNumberField() {
+ return false;
+ }
+
+ public boolean isObjectField() {
+ return false;
+ }
+
}
diff --git a/drools-core/src/main/java/org/drools/base/field/LongFieldImpl.java b/drools-core/src/main/java/org/drools/base/field/LongFieldImpl.java
index e29ceb6ab54..4cd2563c166 100755
--- a/drools-core/src/main/java/org/drools/base/field/LongFieldImpl.java
+++ b/drools-core/src/main/java/org/drools/base/field/LongFieldImpl.java
@@ -69,4 +69,20 @@ public boolean equals(final Object object) {
public int hashCode() {
return (int) this.value;
}
+
+ public boolean isBooleanField() {
+ return false;
+ }
+
+ public boolean isFloatNumberField() {
+ return false;
+ }
+
+ public boolean isIntegerNumberField() {
+ return true;
+ }
+
+ public boolean isObjectField() {
+ return false;
+ }
}
diff --git a/drools-core/src/main/java/org/drools/base/field/ObjectFieldImpl.java b/drools-core/src/main/java/org/drools/base/field/ObjectFieldImpl.java
index add6bf9297e..a9ae0922d95 100644
--- a/drools-core/src/main/java/org/drools/base/field/ObjectFieldImpl.java
+++ b/drools-core/src/main/java/org/drools/base/field/ObjectFieldImpl.java
@@ -113,4 +113,20 @@ public int hashCode() {
return 0;
}
}
+
+ public boolean isBooleanField() {
+ return false;
+ }
+
+ public boolean isFloatNumberField() {
+ return false;
+ }
+
+ public boolean isIntegerNumberField() {
+ return false;
+ }
+
+ public boolean isObjectField() {
+ return true;
+ }
}
\ No newline at end of file
diff --git a/drools-core/src/main/java/org/drools/reteoo/CompositeObjectSinkAdapter.java b/drools-core/src/main/java/org/drools/reteoo/CompositeObjectSinkAdapter.java
index 787805080f6..ce63267c935 100644
--- a/drools-core/src/main/java/org/drools/reteoo/CompositeObjectSinkAdapter.java
+++ b/drools-core/src/main/java/org/drools/reteoo/CompositeObjectSinkAdapter.java
@@ -4,13 +4,16 @@
import java.util.ArrayList;
import java.util.List;
+import org.drools.base.ValueType;
import org.drools.base.evaluators.Operator;
import org.drools.common.InternalFactHandle;
import org.drools.common.InternalWorkingMemory;
import org.drools.rule.LiteralConstraint;
import org.drools.spi.AlphaNodeFieldConstraint;
import org.drools.spi.Evaluator;
+import org.drools.spi.Extractor;
import org.drools.spi.FieldExtractor;
+import org.drools.spi.FieldValue;
import org.drools.spi.PropagationContext;
import org.drools.util.Iterator;
import org.drools.util.LinkedList;
@@ -22,21 +25,20 @@ public class CompositeObjectSinkAdapter
implements
ObjectSinkPropagator {
-
-
/** You can override this property via a system property (eg -Ddrools.hashThreshold=4) */
public static final String HASH_THRESHOLD_SYSTEM_PROPERTY = "drools.hashThreshold";
/** The threshold for when hashing kicks in */
- public static final int THRESHOLD_TO_HASH = Integer.parseInt( System.getProperty( HASH_THRESHOLD_SYSTEM_PROPERTY, "3" ));
-
- private static final long serialVersionUID = 2192568791644369227L;
- ObjectSinkNodeList otherSinks;
- ObjectSinkNodeList hashableSinks;
+ public static final int THRESHOLD_TO_HASH = Integer.parseInt( System.getProperty( HASH_THRESHOLD_SYSTEM_PROPERTY,
+ "3" ) );
- LinkedList hashedFieldIndexes;
+ private static final long serialVersionUID = 2192568791644369227L;
+ ObjectSinkNodeList otherSinks;
+ ObjectSinkNodeList hashableSinks;
- ObjectHashMap hashedSinkMap;
+ LinkedList hashedFieldIndexes;
+
+ ObjectHashMap hashedSinkMap;
private HashKey hashKey;
@@ -56,18 +58,18 @@ public void addObjectSink(final ObjectSink sink) {
if ( evaluator.getOperator() == Operator.EQUAL ) {
final int index = literalConstraint.getFieldExtractor().getIndex();
final FieldIndex fieldIndex = registerFieldIndex( index,
- literalConstraint.getFieldExtractor() );
+ literalConstraint.getFieldExtractor() );
if ( fieldIndex.getCount() >= THRESHOLD_TO_HASH ) {
if ( !fieldIndex.isHashed() ) {
hashSinks( fieldIndex );
}
- final Object value = literalConstraint.getField().getValue();
+ final FieldValue value = literalConstraint.getField();
// no need to check, we know the sink does not exist
this.hashedSinkMap.put( new HashKey( index,
- value ),
- sink,
- false );
+ value ),
+ sink,
+ false );
} else {
if ( this.hashableSinks == null ) {
this.hashableSinks = new ObjectSinkNodeList();
@@ -95,15 +97,14 @@ public void removeObjectSink(final ObjectSink sink) {
if ( fieldConstraint.getClass() == LiteralConstraint.class ) {
final LiteralConstraint literalConstraint = (LiteralConstraint) fieldConstraint;
final Evaluator evaluator = literalConstraint.getEvaluator();
- final Object value = literalConstraint.getField().getValue();
+ final FieldValue value = literalConstraint.getField();
if ( evaluator.getOperator() == Operator.EQUAL ) {
final int index = literalConstraint.getFieldExtractor().getIndex();
final FieldIndex fieldIndex = unregisterFieldIndex( index );
if ( fieldIndex.isHashed() ) {
- this.hashKey.setIndex( index );
- this.hashKey.setValue( value );
+ this.hashKey.setValue( index, value );
this.hashedSinkMap.remove( this.hashKey );
if ( fieldIndex.getCount() <= THRESHOLD_TO_HASH - 1 ) {
// we have less than three so unhash
@@ -144,11 +145,11 @@ public void hashSinks(final FieldIndex fieldIndex) {
final LiteralConstraint literalConstraint = (LiteralConstraint) fieldConstraint;
final Evaluator evaluator = literalConstraint.getEvaluator();
if ( evaluator.getOperator() == Operator.EQUAL && index == literalConstraint.getFieldExtractor().getIndex() ) {
- final Object value = literalConstraint.getField().getValue();
+ final FieldValue value = literalConstraint.getField();
list.add( sink );
this.hashedSinkMap.put( new HashKey( index,
- value ),
- sink );
+ value ),
+ sink );
}
}
@@ -167,17 +168,16 @@ public void hashSinks(final FieldIndex fieldIndex) {
public void unHashSinks(final FieldIndex fieldIndex) {
final int index = fieldIndex.getIndex();
-
List sinks = new ArrayList();
-
+
//iterate twice as custom iterator is immutable
Iterator mapIt = this.hashedSinkMap.iterator();
- for(ObjectHashMap.ObjectEntry e = (ObjectHashMap.ObjectEntry) mapIt.next(); e != null; ) {
+ for ( ObjectHashMap.ObjectEntry e = (ObjectHashMap.ObjectEntry) mapIt.next(); e != null; ) {
sinks.add( e.getValue() );
e = (ObjectHashMap.ObjectEntry) mapIt.next();
}
-
+
for ( java.util.Iterator iter = sinks.iterator(); iter.hasNext(); ) {
AlphaNode sink = (AlphaNode) iter.next();
final AlphaNode alphaNode = (AlphaNode) sink;
@@ -185,16 +185,15 @@ public void unHashSinks(final FieldIndex fieldIndex) {
final LiteralConstraint literalConstraint = (LiteralConstraint) fieldConstraint;
final Evaluator evaluator = literalConstraint.getEvaluator();
if ( evaluator.getOperator() == Operator.EQUAL && index == literalConstraint.getFieldExtractor().getIndex() ) {
- final Object value = literalConstraint.getField().getValue();
- if (this.hashableSinks == null) {
+ final FieldValue value = literalConstraint.getField();
+ if ( this.hashableSinks == null ) {
this.hashableSinks = new ObjectSinkNodeList();
}
this.hashableSinks.add( sink );
- this.hashedSinkMap.remove( new HashKey(index, value) );
+ this.hashedSinkMap.remove( new HashKey( index,
+ value ) );
};
}
-
-
if ( this.hashedSinkMap.isEmpty() ) {
this.hashedSinkMap = null;
@@ -276,14 +275,13 @@ public void propagateAssertObject(final InternalFactHandle handle,
if ( this.hashedFieldIndexes != null ) {
// Iterate the FieldIndexes to see if any are hashed
for ( FieldIndex fieldIndex = (FieldIndex) this.hashedFieldIndexes.getFirst(); fieldIndex != null; fieldIndex = (FieldIndex) fieldIndex.getNext() ) {
- if ( !fieldIndex.isHashed() ) {
+ if ( !fieldIndex.isHashed() ) {
continue;
}
// this field is hashed so set the existing hashKey and see if there is a sink for it
final int index = fieldIndex.getIndex();
final FieldExtractor extractor = fieldIndex.getFieldExtactor();
- this.hashKey.setIndex( index );
- this.hashKey.setValue( extractor.getValue( object ) );
+ this.hashKey.setValue( index, object, extractor );
final ObjectSink sink = (ObjectSink) this.hashedSinkMap.get( this.hashKey );
if ( sink != null ) {
// The sink exists so propagate
@@ -324,14 +322,13 @@ public void propagateRetractObject(final InternalFactHandle handle,
// Iterate the FieldIndexes to see if any are hashed
for ( FieldIndex fieldIndex = (FieldIndex) this.hashedFieldIndexes.getFirst(); fieldIndex != null; fieldIndex = (FieldIndex) fieldIndex.getNext() ) {
// this field is hashed so set the existing hashKey and see if there is a sink for it
- if ( ! fieldIndex.isHashed() ) {
+ if ( !fieldIndex.isHashed() ) {
continue;
}
-
+
final int index = fieldIndex.getIndex();
final FieldExtractor extractor = fieldIndex.getFieldExtactor();
- this.hashKey.setIndex( index );
- this.hashKey.setValue( extractor.getValue( object ) );
+ this.hashKey.setValue( index, object, extractor );
final ObjectSink sink = (ObjectSink) this.hashedSinkMap.get( this.hashKey );
if ( sink != null ) {
// The sink exists so propagate
@@ -397,56 +394,117 @@ public ObjectSink[] getSinks() {
}
public int size() {
- int size = 0;
- size += ( ( otherSinks != null ) ? otherSinks.size() : 0);
- size += ( ( hashableSinks != null ) ? hashableSinks.size() : 0);
- size += ( ( hashedSinkMap != null ) ? hashedSinkMap.size() : 0);
+ int size = 0;
+ size += ((otherSinks != null) ? otherSinks.size() : 0);
+ size += ((hashableSinks != null) ? hashableSinks.size() : 0);
+ size += ((hashedSinkMap != null) ? hashedSinkMap.size() : 0);
return size;
}
- public static class HashKey implements Serializable {
- private int index;
- private Object value;
+ public static class HashKey
+ implements
+ Serializable {
+ private static final long serialVersionUID = 1949191240975565186L;
+
+ private static final byte OBJECT = 1;
+ private static final byte LONG = 2;
+ private static final byte DOUBLE = 3;
+ private static final byte BOOL = 4;
+ private int index;
+
+ private byte type;
+ private Object ovalue;
+ private long lvalue;
+ private boolean bvalue;
+ private double dvalue;
+
+ private int hashCode;
+
public HashKey() {
+ }
+ public HashKey(final int index,
+ final FieldValue value ) {
+ this.setValue( index, value );
}
public HashKey(final int index,
- final Object value) {
- super();
- this.index = index;
- this.value = value;
+ final Object value,
+ final Extractor extractor) {
+ this.setValue( index, value, extractor );
}
public int getIndex() {
return this.index;
}
- public void setIndex(final int index) {
+ public void setValue(final int index, final Object value, final Extractor extractor) {
this.index = index;
+ ValueType vtype = extractor.getValueType();
+ if( vtype.isBoolean() ) {
+ this.bvalue = extractor.getBooleanValue( value );
+ this.type = BOOL;
+ this.setHashCode( this.bvalue ? 1231 : 1237 );
+ } else if( vtype.isIntegerNumber() ) {
+ this.lvalue = extractor.getLongValue( value );
+ this.type = LONG;
+ this.setHashCode( (int) ( this.lvalue ^ ( this.lvalue >>> 32 ) ) );
+ } else if( vtype.isFloatNumber() ) {
+ this.dvalue = extractor.getDoubleValue( value );
+ this.type = DOUBLE;
+ long temp = Double.doubleToLongBits( this.dvalue );
+ this.setHashCode( (int) ( temp ^ ( temp >>> 32 )));
+ } else {
+ this.ovalue = extractor.getValue( value );
+ this.type = OBJECT;
+ this.setHashCode( this.ovalue.hashCode() );
+ }
}
-
- public Object getValue() {
- return this.value;
- }
-
- public void setValue(final Object value) {
- this.value = value;
+
+ public void setValue(final int index, final FieldValue value) {
+ this.index = index;
+ if( value.isBooleanField() ) {
+ this.bvalue = value.getBooleanValue();
+ this.type = BOOL;
+ this.setHashCode( this.bvalue ? 1231 : 1237 );
+ } else if( value.isIntegerNumberField() ) {
+ this.lvalue = value.getLongValue();
+ this.type = LONG;
+ this.setHashCode( (int) ( this.lvalue ^ ( this.lvalue >>> 32 ) ) );
+ } else if( value.isFloatNumberField() ) {
+ this.dvalue = value.getDoubleValue();
+ this.type = DOUBLE;
+ long temp = Double.doubleToLongBits( this.dvalue );
+ this.setHashCode( (int) ( temp ^ ( temp >>> 32 )));
+ } else {
+ this.ovalue = value.getValue();
+ this.type = OBJECT;
+ this.setHashCode( this.ovalue.hashCode() );
+ }
}
-
- public int hashCode() {
+
+ private void setHashCode(int hashSeed) {
final int PRIME = 31;
int result = 1;
+ result = PRIME * result + hashSeed;
result = PRIME * result + this.index;
- result = PRIME * result + ((this.value == null) ? 0 : this.value.hashCode());
- return result;
+ this.hashCode = result;
+ }
+
+ public int hashCode() {
+ return this.hashCode;
}
public boolean equals(final Object object) {
final HashKey other = (HashKey) object;
- return this.index == other.index && this.value.equals( other.value );
+ return this.index == other.index &&
+ this.type == other.type &&
+ ( ((this.type == BOOL) && (this.bvalue == other.bvalue)) ||
+ ((this.type == LONG) && (this.lvalue == other.lvalue)) ||
+ ((this.type == DOUBLE) && (this.dvalue == other.dvalue)) ||
+ ((this.type == OBJECT) && (this.ovalue.equals( other.ovalue ))) );
}
}
@@ -455,15 +513,15 @@ public static class FieldIndex
implements
LinkedListNode {
private static final long serialVersionUID = 3853708964744065172L;
- private final int index;
- private FieldExtractor fieldExtactor;
+ private final int index;
+ private FieldExtractor fieldExtactor;
- private int count;
+ private int count;
- private boolean hashed;
+ private boolean hashed;
- private LinkedListNode previous;
- private LinkedListNode next;
+ private LinkedListNode previous;
+ private LinkedListNode next;
public FieldIndex(final int index,
final FieldExtractor fieldExtractor) {
diff --git a/drools-core/src/main/java/org/drools/reteoo/ObjectTypeNode.java b/drools-core/src/main/java/org/drools/reteoo/ObjectTypeNode.java
index 02c8f1791a6..8332c509bee 100644
--- a/drools-core/src/main/java/org/drools/reteoo/ObjectTypeNode.java
+++ b/drools-core/src/main/java/org/drools/reteoo/ObjectTypeNode.java
@@ -19,6 +19,7 @@
import java.io.Serializable;
import org.drools.RuleBaseConfiguration;
+import org.drools.base.ClassObjectType;
import org.drools.base.ShadowProxy;
import org.drools.common.BaseNode;
import org.drools.common.InternalFactHandle;
diff --git a/drools-core/src/main/java/org/drools/spi/FieldValue.java b/drools-core/src/main/java/org/drools/spi/FieldValue.java
index 515f9af5ab0..18aeab09583 100644
--- a/drools-core/src/main/java/org/drools/spi/FieldValue.java
+++ b/drools-core/src/main/java/org/drools/spi/FieldValue.java
@@ -39,5 +39,13 @@ public interface FieldValue
public double getDoubleValue();
public boolean getBooleanValue();
+
+ public boolean isBooleanField();
+
+ public boolean isIntegerNumberField();
+
+ public boolean isFloatNumberField();
+
+ public boolean isObjectField();
}
\ No newline at end of file
|
d2111faa385e670d577f9fd05d378481aceb336a
|
hunterhacker$jdom
|
Put in support for most of the anticipated StAX functionality.
Put in tests for it too.
But...
StAX is poorly specified, does not support DocTypes properly, has loose
specifications for lots of things. Makes it very hard to do the right
thing.
|
p
|
https://github.com/hunterhacker/jdom
|
diff --git a/core/src/java/org/jdom2/input/StAXStreamBuilder.java b/core/src/java/org/jdom2/input/StAXStreamBuilder.java
index 660625c3d..775167216 100644
--- a/core/src/java/org/jdom2/input/StAXStreamBuilder.java
+++ b/core/src/java/org/jdom2/input/StAXStreamBuilder.java
@@ -65,7 +65,6 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
import org.jdom2.AttributeType;
import org.jdom2.Content;
import org.jdom2.DefaultJDOMFactory;
-import org.jdom2.DocType;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
@@ -128,7 +127,6 @@ private static final Document process(final JDOMFactory factory,
final Document document = factory.document(null);
-
while (state != XMLStreamConstants.END_DOCUMENT) {
switch (state) {
@@ -144,9 +142,8 @@ private static final Document process(final JDOMFactory factory,
break;
case DTD:
- final DocType dtype = DTDParser.parse(
- stream.getText(), factory);
- document.setDocType(dtype);
+ document.setDocType(DTDParser.parse(
+ stream.getText(), factory));
break;
case START_ELEMENT:
diff --git a/core/src/java/org/jdom2/output/AbstractStAXEventProcessor.java b/core/src/java/org/jdom2/output/AbstractStAXEventProcessor.java
new file mode 100644
index 000000000..219172d75
--- /dev/null
+++ b/core/src/java/org/jdom2/output/AbstractStAXEventProcessor.java
@@ -0,0 +1,1385 @@
+package org.jdom2.output;
+
+import java.io.StringWriter;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+
+import javax.xml.stream.XMLEventFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.util.XMLEventConsumer;
+
+import org.jdom2.Attribute;
+import org.jdom2.CDATA;
+import org.jdom2.Comment;
+import org.jdom2.Content;
+import org.jdom2.DocType;
+import org.jdom2.Document;
+import org.jdom2.Element;
+import org.jdom2.EntityRef;
+import org.jdom2.Namespace;
+import org.jdom2.NamespaceStack;
+import org.jdom2.ProcessingInstruction;
+import org.jdom2.Text;
+import org.jdom2.Verifier;
+import org.jdom2.output.Format.TextMode;
+
+/**
+ * This class provides a concrete implementation of {@link StAXEventProcessor}
+ * for supporting the {@link StAXEventOutputter}.
+ * <p>
+ * <h2>Overview</h2>
+ * <p>
+ * This class is marked abstract even though all methods are fully implemented.
+ * The <code>process*(...)</code> methods are public because they match the
+ * StAXEventProcessor interface but the remaining methods are all protected.
+ * <p>
+ * People who want to create a custom StAXEventProcessor for StAXEventOutputter are
+ * able to extend this class and modify any functionality they want. Before
+ * sub-classing this you should first check to see if the {@link Format} class
+ * can get you the results you want.
+ * <p>
+ * <b><i>Subclasses of this should have reentrant methods.</i></b> This is
+ * easiest to accomplish simply by not allowing any instance fields. If your
+ * sub-class has an instance field/variable, then it's probably broken.
+ * <p>
+ * <h2>The Stacks</h2>
+ * <p>
+ * One significant feature of this implementation is that it creates and
+ * maintains both a {@link NamespaceStack} and {@link FormatStack} that are
+ * managed in the
+ * {@link #printElement(XMLEventConsumer, FormatStack, NamespaceStack, XMLEventFactory, Element)} method.
+ * The stacks are pushed and popped in that method only. They significantly
+ * improve the performance and readability of the code.
+ * <p>
+ * The NamespaceStack is only sent through to the
+ * {@link #printElement(XMLEventConsumer, FormatStack, NamespaceStack, XMLEventFactory, Element)} and
+ * {@link #printContent(XMLEventConsumer, FormatStack, NamespaceStack, XMLEventFactory, List)} methods, but
+ * the FormatStack is pushed through to all print* Methods.
+ * <p>
+ * <h2>Text Processing</h2>
+ * <p>
+ * In XML the concept of 'Text' can be loosely defined as anything that can be
+ * found between an Element's start and end tags, excluding Comments and
+ * Processing Instructions. When considered from a JDOM perspective, this means
+ * {@link Text}, {@link CDATA} and {@link EntityRef} content. This will be
+ * referred to as 'text-type content'
+ * <p>
+ * In the context of StAXEventOutputter, {@link EntityRef} content is considered to be
+ * text-type content. This happens because when XML is parsed the embedded
+ * entity reference tokens are (normally) expanded to their replacement text. If
+ * an EntityRef content has survived to this output stage it means that it
+ * cannot (or should not) be expanded. As a result, it should simply be output
+ * as it's escaped name in the form <code>&refname;</code>.
+ * <p>
+ * Consecutive text-type JDOM content is an especially hard problem because the
+ * complete set of consecutive values should be considered together. For
+ * example, there is a significant difference between the 'trimmed' result of
+ * two individual Text contents and the trimmed result of the same Text contents
+ * which are combined before trimming: consider two consecutive Text contents
+ * " X " and " Y " which (trimmed) should be output as:
+ * "X Y" not "XY".
+ * <p>
+ * As a result, this class differentiates between stand-alone and consecutive
+ * text-type JDOM Content. If the content is determined to be stand-alone, it is
+ * fed to one of the {@link #printEntityRef(XMLEventConsumer, FormatStack, XMLEventFactory, EntityRef)},
+ * {@link #printCDATA(XMLEventConsumer, FormatStack, XMLEventFactory, CDATA)}, or
+ * {@link #printText(XMLEventConsumer, FormatStack, XMLEventFactory, Text)} methods. If there is
+ * consecutive text-type content it is all fed together to the
+ * {@link #printTextConsecutive(XMLEventConsumer, FormatStack, XMLEventFactory, List, int, int)} method.
+ * <p>
+ * The above 4 methods for printing text-type content will all use the various
+ * <code>text*(...)</code> methods to produce output to the XMLEventConsumer.
+ * <p>
+ * <b>Note:</b> If the Format's TextMode is PRESERVE then all text-type content
+ * is considered to be stand-alone. In other words, printTextConsecutive() will
+ * never be called when the TextMode is PRESERVE.
+ * <p>
+ * <h2>Non-Text Content</h2>
+ * <p>
+ * Non-text content is processed via the respective print* methods. The usage
+ * should be logical based on the method name.
+ * <p>
+ * The general observations are:
+ * <ul>
+ * <li>printElement - maintains the Stacks, prints the element open tags, with
+ * attributes and namespaces. It checks to see whether the Element is text-only,
+ * or has non-text content. If it is text-only there is no indent/newline
+ * handling and it delegates to the correct text-type print method, otherwise it
+ * delegates to printContent.
+ * <li>printContent is called if there is a 'mixed' content list to output. It
+ * will always wrap each respective content call (one of a text-type print, a
+ * printTextConsecutive, or a non-text type print) with an indent and a newline.
+ * </ul>
+ * <p>
+ * There are two 'helper' methods which are simply there to reduce some code
+ * redundancy in the class. They do nothing more than that. Have a look at the
+ * source-code to see what they do. If you need them they may prove useful.
+ *
+ * @see StAXEventOutputter
+ * @see StAXEventProcessor
+ * @author Rolf Lear
+ */
+public abstract class AbstractStAXEventProcessor implements StAXEventProcessor {
+
+ private static final class NSIterator implements Iterator<javax.xml.stream.events.Namespace> {
+ private final Iterator<Namespace> source;
+ private final XMLEventFactory fac;
+
+ public NSIterator(Iterator<Namespace> source, XMLEventFactory fac) {
+ super();
+ this.source = source;
+ this.fac = fac;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return source.hasNext();
+ }
+
+ @Override
+ public javax.xml.stream.events.Namespace next() {
+ Namespace ns = source.next();
+ return fac.createNamespace(ns.getPrefix(), ns.getURI());
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException("Cannot remove Namespaces");
+
+ }
+
+ }
+ private static final class AttIterator implements Iterator<javax.xml.stream.events.Attribute> {
+ private final Iterator<Attribute> source;
+ private final XMLEventFactory fac;
+
+ public AttIterator(Iterator<Attribute> source, XMLEventFactory fac) {
+ super();
+ this.source = source;
+ this.fac = fac;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return source.hasNext();
+ }
+
+ @Override
+ public javax.xml.stream.events.Attribute next() {
+ Attribute att = source.next();
+ final Namespace ns = att.getNamespace();
+ if (ns == Namespace.NO_NAMESPACE) {
+ return fac.createAttribute(att.getName(), att.getValue());
+ }
+ return fac.createAttribute(ns.getPrefix(), ns.getURI(),
+ att.getName(), att.getValue());
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException("Cannot remove attributes");
+
+ }
+
+ }
+
+
+
+ /* *******************************************
+ * StAXEventProcessor implementation.
+ * *******************************************
+ */
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jdom2.output.StAXEventProcessor#process(java.io.XMLEventConsumer,
+ * org.jdom2.Document, org.jdom2.output.Format)
+ */
+ @Override
+ public void process(final XMLEventConsumer out, final Format format,
+ final XMLEventFactory eventfactory, final Document doc) throws XMLStreamException {
+ printDocument(out, new FormatStack(format), new NamespaceStack(), eventfactory, doc);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jdom2.output.StAXEventProcessor#process(java.io.XMLEventConsumer,
+ * org.jdom2.DocType, org.jdom2.output.Format)
+ */
+ @Override
+ public void process(final XMLEventConsumer out, final Format format,
+ final XMLEventFactory eventfactory, final DocType doctype) throws XMLStreamException {
+ printDocType(out, new FormatStack(format), eventfactory, doctype);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jdom2.output.StAXEventProcessor#process(java.io.XMLEventConsumer,
+ * org.jdom2.Element, org.jdom2.output.Format)
+ */
+ @Override
+ public void process(final XMLEventConsumer out, final Format format,
+ final XMLEventFactory eventfactory, final Element element) throws XMLStreamException {
+ // If this is the root element we could pre-initialize the
+ // namespace stack with the namespaces
+ printElement(out, new FormatStack(format), new NamespaceStack(),
+ eventfactory, element);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jdom2.output.StAXEventProcessor#process(java.io.XMLEventConsumer,
+ * java.util.List, org.jdom2.output.Format)
+ */
+ @Override
+ public void process(final XMLEventConsumer out, final Format format,
+ final XMLEventFactory eventfactory, final List<? extends Content> list)
+ throws XMLStreamException {
+ printContent(out, new FormatStack(format), new NamespaceStack(), eventfactory, list);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jdom2.output.StAXEventProcessor#process(java.io.XMLEventConsumer,
+ * org.jdom2.CDATA, org.jdom2.output.Format)
+ */
+ @Override
+ public void process(final XMLEventConsumer out, final Format format,
+ final XMLEventFactory eventfactory, final CDATA cdata) throws XMLStreamException {
+ printCDATA(out, new FormatStack(format), eventfactory, cdata);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jdom2.output.StAXEventProcessor#process(java.io.XMLEventConsumer,
+ * org.jdom2.Text, org.jdom2.output.Format)
+ */
+ @Override
+ public void process(final XMLEventConsumer out, final Format format,
+ final XMLEventFactory eventfactory, final Text text) throws XMLStreamException {
+ printText(out, new FormatStack(format), eventfactory, text);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jdom2.output.StAXEventProcessor#process(java.io.XMLEventConsumer,
+ * org.jdom2.Comment, org.jdom2.output.Format)
+ */
+ @Override
+ public void process(final XMLEventConsumer out, final Format format,
+ final XMLEventFactory eventfactory, final Comment comment) throws XMLStreamException {
+ printComment(out, new FormatStack(format), eventfactory, comment);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jdom2.output.StAXEventProcessor#process(java.io.XMLEventConsumer,
+ * org.jdom2.ProcessingInstruction, org.jdom2.output.Format)
+ */
+ @Override
+ public void process(final XMLEventConsumer out, final Format format,
+ final XMLEventFactory eventfactory, final ProcessingInstruction pi) throws XMLStreamException {
+ FormatStack fstack = new FormatStack(format);
+ // Output PI verbatim, disregarding TrAX escaping PIs.
+ fstack.setIgnoreTrAXEscapingPIs(true);
+ printProcessingInstruction(out, fstack, eventfactory, pi);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jdom2.output.StAXEventProcessor#process(java.io.XMLEventConsumer,
+ * org.jdom2.EntityRef, org.jdom2.output.Format)
+ */
+ @Override
+ public void process(final XMLEventConsumer out, final Format format,
+ final XMLEventFactory eventfactory, final EntityRef entity) throws XMLStreamException {
+ printEntityRef(out, new FormatStack(format), eventfactory, entity);
+ }
+
+ /*
+ * ========================================================================
+ * Support methods for Text-content formatting. Should all be protected. The
+ * following are used when printing Text-based data. Because of complicated
+ * multi-sequential text sometimes the requirements are odd. All Text
+ * content will be output using these methods, which is why there is the Raw
+ * version.
+ * ========================================================================
+ */
+
+ /**
+ * Write a CDATA's value to the destination. The value will first be
+ * compacted (all leading and trailing whitespace will be removed and all
+ * internal whitespace will be be represented with a single ' ' character).
+ * If the CDATA contains only whitespace then nothing is output.
+ * <p>
+ * The results (if any) will be wrapped in the <code><![CDATA[</code> and
+ * <code>]]></code> delimiters.
+ *
+ * @param str
+ * the CDATA's value.
+ * @return The input String in a compact form
+ */
+ protected String textCompact(final String str) {
+ final char[] chars = str.toCharArray();
+ int right = chars.length - 1;
+ while (right >= 0 && Verifier.isXMLWhitespace(chars[right])) {
+ right--;
+ }
+ if (right < 0) {
+ return "";
+ }
+
+ int left = 0;
+ while (Verifier.isXMLWhitespace(chars[left])) {
+ // we do not need to check left < right because
+ // we know we will find some non-white char first.
+ left++;
+ }
+
+ int from = left;
+ boolean wspace = false;
+ left++;
+ int ip = left;
+ while (left <= right) {
+ if (Verifier.isXMLWhitespace(chars[left])) {
+ if (!wspace) {
+ chars[ip++] = ' ';
+ }
+ wspace = true;
+ } else {
+ chars[ip++] = chars[left];
+ wspace = false;
+ }
+ left++;
+ }
+
+ return String.valueOf(chars, from, ip - from);
+ }
+
+ /**
+ * Write a CDATA's value to the destination. The value will first be
+ * inspected. If the CDATA contains only whitespace then nothing is output,
+ * otherwise the entire input <code>str</code> will be wrapped in the
+ * <code><![CDATA[</code> and <code>]]></code> delimiters.
+ *
+ * @param str
+ * the CDATA's value.
+ * @return the input str if there's at least one non-whitespace char in it.
+ * otherwise returns ""
+ */
+ protected String textTrimFullWhite(final String str) {
+ int right = str.length();
+ while (--right >= 0 && Verifier.isXMLWhitespace(str.charAt(right))) {
+ right--;
+ }
+ if (right < 0) {
+ return "";
+ }
+
+ return str;
+ }
+
+ /**
+ * Write a CDATA's value to the destination. The value will first be trimmed
+ * (all leading and trailing whitespace will be removed). If the CDATA
+ * contains only whitespace then nothing is output. The results (if any)
+ * will be wrapped in the <code><![CDATA[</code> and <code>]]></code>
+ * delimiters.
+ *
+ * @param str
+ * the CDATA's value.
+ * @return the input str value trimmed left and right.
+ */
+ protected String textTrimBoth(final String str) {
+ int right = str.length() - 1;
+ while (right >= 0 && Verifier.isXMLWhitespace(str.charAt(right))) {
+ right--;
+ }
+ if (right < 0) {
+ return "";
+ }
+
+ int left = 0;
+ while (Verifier.isXMLWhitespace(str.charAt(left))) {
+ // we do not need to check left < right because
+ // we know we will find some non-white char first.
+ left++;
+ }
+ return str.substring(left, right + 1);
+ }
+
+ /**
+ * Write a CDATA's value to the destination. The value will first be
+ * right-trimmed (all trailing whitespace will be removed). If the CDATA
+ * contains only whitespace then nothing is output. The results (if any)
+ * will be wrapped in the <code><![CDATA[</code> and <code>]]></code>
+ * delimiters.
+ *
+ * @param str
+ * the CDATA's value.
+ * @return the input str trimmed on the right.
+ */
+ protected String textTrimRight(final String str) {
+ int right = str.length() - 1;
+ while (right >= 0 && Verifier.isXMLWhitespace(str.charAt(right))) {
+ right--;
+ }
+ if (right < 0) {
+ return "";
+ }
+
+ return str.substring(0, right + 1);
+ }
+
+ /**
+ * Write a CDATA's value to the destination. The value will first be
+ * left-trimmed (all leading whitespace will be removed). If the CDATA
+ * contains only whitespace then nothing is output. The results (if any)
+ * will be wrapped in the <code><![CDATA[</code> and <code>]]></code>
+ * delimiters.
+ *
+ * @param str
+ * the CDATA's value.
+ * @return the input str trimmed on the left.
+ */
+ protected String textTrimLeft(final String str) {
+ final int right = str.length();
+ int left = 0;
+ while (left < right && Verifier.isXMLWhitespace(str.charAt(left))) {
+ left++;
+ }
+ if (left >= right) {
+ return "";
+ }
+
+ return str.substring(left, right);
+ }
+
+ /* *******************************************
+ * Support methods for output. Should all be protected. All content-type
+ * print methods have a FormatStack. Only printContent is responsible for
+ * outputting appropriate indenting and newlines, which are easily available
+ * using the FormatStack.getLevelIndent() and FormatStack.getLevelEOL().
+ * *******************************************
+ */
+
+ /**
+ * This will handle printing of a {@link Document}.
+ *
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @param fstack
+ * the FormatStack
+ * @param nstack
+ * the NamespaceStack
+ * @param eventfactory
+ * The XMLEventFactory for creating XMLEvents
+ * @param doc
+ * <code>Document</code> to write.
+ * @throws XMLStreamException
+ * if the destination XMLEventConsumer fails
+ */
+ protected void printDocument(final XMLEventConsumer out, final FormatStack fstack,
+ final NamespaceStack nstack, final XMLEventFactory eventfactory, final Document doc) throws XMLStreamException {
+
+ if (fstack.isOmitDeclaration()) {
+ // this actually writes the declaration as version 1, UTF-8
+ out.add(eventfactory.createStartDocument());
+ } else if (fstack.isOmitEncoding()) {
+ out.add(eventfactory.createStartDocument("1.0"));
+ } else {
+ out.add(eventfactory.createStartDocument(fstack.getEncoding(), "1.0"));
+ }
+
+ printContent(out, fstack, nstack, eventfactory, doc.getContent());
+
+ out.add(eventfactory.createEndDocument());
+
+ }
+
+ /**
+ * This will handle printing of a {@link DocType}.
+ *
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @param fstack
+ * the FormatStack
+ * @param eventfactory
+ * The XMLEventFactory for creating XMLEvents
+ * @param docType
+ * <code>DocType</code> to write.
+ * @throws XMLStreamException
+ * if the destination XMLEventConsumer fails
+ */
+ protected void printDocType(final XMLEventConsumer out, final FormatStack fstack,
+ final XMLEventFactory eventfactory, final DocType docType) throws XMLStreamException {
+
+ final String publicID = docType.getPublicID();
+ final String systemID = docType.getSystemID();
+ final String internalSubset = docType.getInternalSubset();
+ boolean hasPublic = false;
+
+ // Declaration is never indented.
+ // write(out, fstack.getLevelIndent());
+
+ StringWriter sw = new StringWriter();
+
+ sw.write("<!DOCTYPE ");
+ sw.write(docType.getElementName());
+ if (publicID != null) {
+ sw.write(" PUBLIC \"");
+ sw.write(publicID);
+ sw.write("\"");
+ hasPublic = true;
+ }
+ if (systemID != null) {
+ if (!hasPublic) {
+ sw.write(" SYSTEM");
+ }
+ sw.write(" \"");
+ sw.write(systemID);
+ sw.write("\"");
+ }
+ if ((internalSubset != null) && (!internalSubset.equals(""))) {
+ sw.write(" [");
+ sw.write(fstack.getLineSeparator());
+ sw.write(docType.getInternalSubset());
+ sw.write("]");
+ }
+ sw.write(">");
+
+ // DocType does not write it's own EOL
+ // for compatibility reasons. Only
+ // when output from inside a Content set.
+ // write(out, fstack.getLineSeparator());
+ out.add(eventfactory.createDTD(sw.toString()));
+ }
+
+ /**
+ * This will handle printing of a {@link ProcessingInstruction}.
+ *
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @param fstack
+ * the FormatStack
+ * @param eventfactory
+ * The XMLEventFactory for creating XMLEvents
+ * @param pi
+ * <code>ProcessingInstruction</code> to write.
+ * @throws XMLStreamException
+ * if the destination XMLEventConsumer fails
+ */
+ protected void printProcessingInstruction(final XMLEventConsumer out,
+ final FormatStack fstack, final XMLEventFactory eventfactory, final ProcessingInstruction pi)
+ throws XMLStreamException {
+ String target = pi.getTarget();
+ String rawData = pi.getData();
+ if (rawData != null && rawData.trim().length() > 0) {
+ out.add(eventfactory.createProcessingInstruction(target, rawData));
+ } else {
+ out.add(eventfactory.createProcessingInstruction(target, ""));
+ }
+ }
+
+ /**
+ * This will handle printing of a {@link Comment}.
+ *
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @param fstack
+ * the FormatStack
+ * @param eventfactory
+ * The XMLEventFactory for creating XMLEvents
+ * @param comment
+ * <code>Comment</code> to write.
+ * @throws XMLStreamException
+ * if the destination XMLEventConsumer fails
+ */
+ protected void printComment(final XMLEventConsumer out, final FormatStack fstack,
+ final XMLEventFactory eventfactory, final Comment comment) throws XMLStreamException {
+ out.add(eventfactory.createComment(comment.getText()));
+ }
+
+ /**
+ * This will handle printing of an {@link EntityRef}.
+ *
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @param fstack
+ * the FormatStack
+ * @param eventfactory
+ * The XMLEventFactory for creating XMLEvents
+ * @param entity
+ * <code>EntotyRef</code> to write.
+ * @throws XMLStreamException
+ * if the destination XMLEventConsumer fails
+ */
+ protected void printEntityRef(final XMLEventConsumer out, final FormatStack fstack,
+ final XMLEventFactory eventfactory, final EntityRef entity) throws XMLStreamException {
+ out.add(eventfactory.createEntityReference(entity.getName(), null));
+ }
+
+ /**
+ * This will handle printing of a {@link CDATA}.
+ *
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @param fstack
+ * the FormatStack
+ * @param eventfactory
+ * The XMLEventFactory for creating XMLEvents
+ * @param cdata
+ * <code>CDATA</code> to write.
+ * @throws XMLStreamException
+ * if the destination XMLEventConsumer fails
+ */
+ protected void printCDATA(final XMLEventConsumer out, final FormatStack fstack,
+ final XMLEventFactory eventfactory, final CDATA cdata) throws XMLStreamException {
+ // CDATAs are treated like text, not indented/newline content.
+ String text = cdata.getText();
+ switch (fstack.getTextMode()) {
+ case PRESERVE:
+ break;
+ case NORMALIZE:
+ text = textCompact(text);
+ break;
+ case TRIM:
+ text = textTrimBoth(text);
+ break;
+ case TRIM_FULL_WHITE:
+ text = textTrimFullWhite(text);
+ break;
+ }
+ out.add(eventfactory.createCData(text));
+ }
+
+ /**
+ * This will handle printing of a {@link Text}.
+ *
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @param fstack
+ * the FormatStack
+ * @param eventfactory
+ * The XMLEventFactory for creating XMLEvents
+ * @param text
+ * <code>Text</code> to write.
+ * @throws XMLStreamException
+ * if the destination XMLEventConsumer fails
+ */
+ protected void printText(final XMLEventConsumer out, final FormatStack fstack,
+ final XMLEventFactory eventfactory, final Text text) throws XMLStreamException {
+ String str = text.getText();
+ switch (fstack.getTextMode()) {
+ case PRESERVE:
+ break;
+ case NORMALIZE:
+ str = textCompact(str);
+ break;
+ case TRIM:
+ str = textTrimBoth(str);
+ break;
+ case TRIM_FULL_WHITE:
+ str = textTrimFullWhite(str);
+ break;
+ }
+ out.add(eventfactory.createCharacters(str));
+ }
+
+ /**
+ * This will handle printing of an {@link Element}.
+ * <p>
+ * This method arranges for outputting the Element infrastructure including
+ * Namespace Declarations and Attributes.
+ * <p>
+ * There has to be a fair amount of inspection to determine whether there is
+ * any content and whether it is all text-type content, and based on the
+ * required Format output, how to deal with the content. Alternatives (in
+ * 'fall-through' order) are:
+ * <ol>
+ * <li>There is no content, then output just an empty element (depending on
+ * settings this may be either <code><element /></code> or
+ * <code><element></element></code>).
+ * <li>There is only text-type content and the current Format settings would
+ * condense the text-type content to nothing, then output just an empty
+ * element (depending on settings this may be either
+ * <code><element /></code> or <code><element></element></code>
+ * ).
+ * <li>There is just a single text-type content then delegate to that
+ * content's print method
+ * <li>There is only text-type content (more than one though) then delegate
+ * to {@link #printTextConsecutive(XMLEventConsumer, FormatStack, XMLEventFactory, List, int, int)}
+ * <li>There is content other than just text-type content, then delegate to
+ * {@link #printContent(XMLEventConsumer, FormatStack, NamespaceStack, XMLEventFactory, List)}
+ * </ol>
+ * <p>
+ *
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @param fstack
+ * the FormatStack
+ * @param nstack
+ * the NamespaceStack
+ * @param eventfactory
+ * The XMLEventFactory for creating XMLEvents
+ * @param element
+ * <code>Element</code> to write.
+ * @throws XMLStreamException
+ * if the destination XMLEventConsumer fails
+ */
+ protected void printElement(final XMLEventConsumer out, final FormatStack fstack,
+ final NamespaceStack nstack, final XMLEventFactory eventfactory,
+ final Element element) throws XMLStreamException {
+
+ nstack.push(element);
+ try {
+
+ TextMode textmode = fstack.getTextMode();
+
+ // Check for xml:space and adjust format settings
+ final String space = element.getAttributeValue("space",
+ Namespace.XML_NAMESPACE);
+
+ if ("default".equals(space)) {
+ textmode = fstack.getDefaultMode();
+ }
+ else if ("preserve".equals(space)) {
+ textmode = TextMode.PRESERVE;
+ }
+
+ final List<Content> content = element.getContent();
+
+ // Three conditions that determine the required output.
+ // do we have an expanded element( <emt></emt> or an single <emt />
+ // if there is any printable content, or if expandempty is set
+ // then we must expand.
+ boolean expandit = fstack.isExpandEmptyElements();
+
+ // is there only text content
+ // text content is Text/CDATA/EntityRef
+ boolean textonly = true;
+ // is the text content only whitespace.
+ // whiteonly is obvious....
+ boolean whiteonly = true;
+
+ for (Content k : content) {
+ if (k instanceof Text) {
+ if (whiteonly) {
+ if (textmode == TextMode.PRESERVE) {
+ expandit = true;
+ whiteonly = false;
+ } else {
+ // look for non-whitespace.
+ String val = k.getValue();
+ int cc = val.length();
+ while (--cc >= 0) {
+ if (!Verifier.isXMLWhitespace(val.charAt(cc))) {
+ // found non-whitespace;
+ expandit = true;
+ whiteonly = false;
+ break;
+ }
+ }
+ }
+ }
+ } else {
+ expandit = true;
+ whiteonly = false;
+ if (!(k instanceof EntityRef)) {
+ textonly = false;
+ // we know everything we need.
+ break;
+ }
+ }
+ if (expandit && !whiteonly && !textonly) {
+ break;
+ }
+ }
+
+
+ Namespace ns = element.getNamespace();
+ if (ns == Namespace.NO_NAMESPACE) {
+ out.add(eventfactory.createStartElement("", "", element.getName(),
+ new AttIterator(element.getAttributes().iterator(), eventfactory),
+ new NSIterator(nstack.addedForward().iterator(), eventfactory)));
+ } else if ("".equals(ns.getPrefix())) {
+ out.add(eventfactory.createStartElement("", ns.getURI(), element.getName(),
+ new AttIterator(element.getAttributes().iterator(), eventfactory),
+ new NSIterator(nstack.addedForward().iterator(), eventfactory)));
+ } else {
+ out.add(eventfactory.createStartElement(ns.getPrefix(), ns.getURI(), element.getName(),
+ new AttIterator(element.getAttributes().iterator(), eventfactory),
+ new NSIterator(nstack.addedForward().iterator(), eventfactory)));
+ }
+
+ if (expandit) {
+
+ // OK, now we print out the meat of the Element
+ if (!content.isEmpty()) {
+ if (textonly) {
+ if (!whiteonly) {
+ fstack.push();
+ try {
+ fstack.setTextMode(textmode);
+ helperTextType(out, fstack, eventfactory, content, 0, content.size());
+ } finally {
+ fstack.pop();
+ }
+ }
+ } else {
+ fstack.push();
+ try {
+ fstack.setTextMode(textmode);
+
+ printContent(out, fstack, nstack, eventfactory, content);
+
+ } finally {
+ fstack.pop();
+ }
+ }
+ }
+
+ }
+
+
+ out.add(eventfactory.createEndElement(element.getNamespacePrefix(),
+ element.getNamespaceURI(), element.getName(),
+ new NSIterator(nstack.addedReverse().iterator(), eventfactory)));
+
+
+ } finally {
+ nstack.pop();
+ }
+ }
+
+ /**
+ * This will handle printing of a List of {@link Content}.
+ * <p>
+ * The list of Content is basically processed as one of three types of
+ * content
+ * <ol>
+ * <li>Consecutive text-type (Text, CDATA, and EntityRef) content
+ * <li>Stand-alone text-type content
+ * <li>Non-text-type content.
+ * </ol>
+ * Although the code looks complex, the theory is conceptually simple:
+ * <ol>
+ * <li>identify one of the three types (consecutive, stand-alone, non-text)
+ * <li>do indent if any is specified.
+ * <li>send the type to the respective print* handler (e.g.
+ * {@link #printTextConsecutive(XMLEventConsumer, FormatStack, XMLEventFactory, List, int, int)},
+ * {@link #printCDATA(XMLEventConsumer, FormatStack, XMLEventFactory, CDATA)}, or
+ * {@link #printComment(XMLEventConsumer, FormatStack, XMLEventFactory, Comment)},
+ * <li>do a newline if one is specified.
+ * <li>loop back to 1. until there's no more content to process.
+ * </ol>
+ *
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @param fstack
+ * the FormatStack
+ * @param nstack
+ * the NamespaceStack
+ * @param eventfactory
+ * The XMLEventFactory for creating XMLEvents
+ * @param content
+ * <code>List</code> of <code>Content</code> to write.
+ * @throws XMLStreamException
+ * if the destination XMLEventConsumer fails
+ */
+ protected void printContent(final XMLEventConsumer out,
+ final FormatStack fstack, final NamespaceStack nstack,
+ final XMLEventFactory eventfactory, final List<? extends Content> content)
+ throws XMLStreamException {
+
+ // Basic theory of operation is as follows:
+ // 0. raw-print for PRESERVE.
+ // 1. print any non-Text content
+ // 2. Accumulate all sequential text content and print them together
+ // Do not do any newlines before or after content.
+ if (fstack.getTextMode() == TextMode.PRESERVE) {
+ for (Content c : content) {
+ helperContentDispatcher(out, fstack, nstack, eventfactory, c);
+ }
+ return;
+ }
+
+ int txti = -1;
+ int index = 0;
+ for (final Content c : content) {
+ switch (c.getCType()) {
+ case Text:
+ case CDATA:
+ case EntityRef:
+ //
+ // Handle consecutive CDATA, Text, and EntityRef nodes all
+ // at once
+ //
+ if (txti < 0) {
+ txti = index;
+ }
+ break;
+ default:
+ if (txti >= 0) {
+ // we have text content we need to print.
+ // we also know that we are 'mixed' content
+ // so the text content should be indented.
+ // but, since we have no PRESERVE content, only the
+ // 'trimming' variants, if it is all whitespace we do
+ // not want to even print the indent/newline.
+ if (!isAllWhiteSpace(content, txti, index - txti)) {
+ helperTextType(out, fstack, eventfactory, content, txti, index - txti);
+ }
+ }
+ txti = -1;
+
+ helperContentDispatcher(out, fstack, nstack, eventfactory, c);
+ }
+ index++;
+ }
+ if (txti >= 0) {
+ // we have text content we need to print.
+ // we also know that we are 'mixed' content
+ // so the text content should be indented.
+ // but, since we have no PRESERVE content, only the
+ // 'trimming' variants, if it is all whitespace we do
+ // not want to even print the indent/newline.
+ if (!isAllWhiteSpace(content, txti, index - txti)) {
+ helperTextType(out, fstack, eventfactory, content, txti, index - txti);
+ }
+ }
+
+ }
+
+ /**
+ * This will handle printing of a consecutive sequence of text-type
+ * {@link Content} (<code>{@link CDATA}</code> <code>{@link Text}</code>, or
+ * <code>{@link EntityRef}</code>) nodes. It is an error (unspecified
+ * Exception or unspecified behaviour) to pass this method any other type of
+ * node.
+ * <p>
+ * It is a requirement for this method that at least one of the specified
+ * text-type instances has non-whitespace, or, put the other way, if all
+ * specified text-type values are all white-space only, then you may
+ * get odd looking XML (empty lines).
+ *
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @param fstack
+ * the FormatStack
+ * @param eventfactory
+ * The XMLEventFactory for creating XMLEvents
+ * @param content
+ * <code>List</code> of <code>Content</code> to write.
+ * @param offset
+ * index of first content node (inclusive).
+ * @param len
+ * number of nodes that are text-type.
+ * @throws XMLStreamException
+ * if the destination XMLEventConsumer fails
+ */
+ protected void printTextConsecutive(final XMLEventConsumer out, FormatStack fstack,
+ final XMLEventFactory eventfactory, final List<? extends Content> content,
+ final int offset, final int len) throws XMLStreamException {
+
+ // we are guaranteed that len >= 2
+ assert len >= 2 : "Need at least two text-types to be 'Consecutive'";
+
+ // here we have a sequence of Text nodes to print.
+ // we follow the TextMode rules for it.
+ // also guaranteed is that at least one of the nodes has some real text.
+
+ final TextMode mode = fstack.getTextMode();
+
+ // Right, at this point it is complex.
+ // we have multiple nodes to output, and it could be in one of three
+ // modes, TRIM, TRIM_FULL_WHITE, or NORMALIZE
+ // we aggregate the text together, and dump it
+
+ // Let's get TRIM_FULL_WHITE out of the way.
+ // in this mode, if there is any real text content, we print it all.
+ // otherwise we print nothing
+ // since it is a requirement for this method that there has to be some
+ // non-whitespace text, we can just print everything.
+ if (TextMode.TRIM_FULL_WHITE == mode) {
+ // Right, if we find text, we print it all.
+ // If we don't we print nothing.
+ int cnt = len;
+ for (ListIterator<? extends Content> li =
+ content.listIterator(offset); cnt > 0; cnt--) {
+ helperRawTextType(out, fstack, eventfactory, li.next());
+ }
+ return;
+ }
+
+ // OK, now we are left with just TRIM and NORMALIZE
+ // Normalize is now actually easier.
+ if (TextMode.NORMALIZE == mode) {
+ boolean dospace = false;
+ // we know there's at least 2 content nodes...
+ // we process the 'gaps' to see if we need spaces, and print
+ // all the content in NORMALIZED form.
+ boolean first = true;
+ int cnt = len;
+ for (Iterator<? extends Content> li = content.listIterator(offset); cnt > 0; cnt--) {
+ boolean endspace = false;
+ final Content c = li.next();
+ if (c instanceof Text) {
+ final String val = ((Text) c).getValue();
+ if (val.length() == 0) {
+ // ignore empty text.
+ continue;
+ }
+ if (isAllWhitespace(val)) {
+ // we skip all whitespace.
+ // but record the space
+ if (!first) {
+ dospace = true;
+ }
+ continue;
+ }
+ if (!first && !dospace &&
+ Verifier.isXMLWhitespace(val.charAt(0))) {
+ // we are between content, and need to put in a space.
+ dospace = true;
+ }
+ endspace = Verifier.isXMLWhitespace(val.charAt(val.length() - 1));
+ }
+ first = false;
+ if (dospace) {
+ out.add(eventfactory.createCharacters(" "));
+ }
+
+ switch (c.getCType()) {
+ case Text:
+ out.add(eventfactory.createCharacters(textCompact(((Text) c).getText())));
+ break;
+ case CDATA:
+ out.add(eventfactory.createCData(textCompact(((Text) c).getText())));
+ break;
+ case EntityRef:
+ printEntityRef(out, fstack, eventfactory, (EntityRef) c);
+ default:
+ // do nothing
+ }
+ dospace = endspace;
+ }
+ return;
+ }
+
+ // All that's left now is multi-content that needs to be trimmed.
+ // For this, we do a cheat....
+ // we trim the left and right content, and print any middle content
+ // as raw.
+ // we have to preserve the right-whitespace of the left content, and the
+ // left whitespace of the right content.
+ // no need to check the mode, it can only be TRIM.
+ if (TextMode.TRIM == fstack.getTextMode()) {
+
+ int lcnt = 0;
+ while (lcnt < len) {
+ Content node = content.get(offset + lcnt);
+ if (!(node instanceof Text) || !isAllWhitespace(node.getValue())) {
+ break;
+ }
+ lcnt++;
+ }
+
+ if (lcnt == len) {
+ return;
+ }
+
+
+ final int left = offset + lcnt;
+ int rcnt = len - 1;
+ while (rcnt > lcnt) {
+ Content node = content.get(offset + rcnt);
+ if (!(node instanceof Text) || !isAllWhitespace(node.getValue())) {
+ break;
+ }
+ rcnt--;
+ }
+ final int right = offset + rcnt;
+
+ if (left == right) {
+ // came down to just one value to output.
+ final Content node = content.get(left);
+ switch (node.getCType()) {
+ case Text:
+ out.add(eventfactory.createCharacters(textTrimBoth(((Text) node).getText())));
+ break;
+ case CDATA:
+ out.add(eventfactory.createCData(textTrimBoth(((CDATA) node).getText())));
+ break;
+ case EntityRef:
+ printEntityRef(out, fstack, eventfactory, (EntityRef) node);
+ default:
+ // do nothing
+ }
+ return;
+ }
+ final Content leftc = content.get(left);
+ switch (leftc.getCType()) {
+ case Text:
+ out.add(eventfactory.createCharacters(textTrimLeft(((Text) leftc).getText())));
+ break;
+ case CDATA:
+ out.add(eventfactory.createCData(textTrimLeft(((CDATA) leftc).getText())));
+ break;
+ case EntityRef:
+ printEntityRef(out, fstack, eventfactory, (EntityRef) leftc);
+ default:
+ // do nothing
+ }
+
+ int cnt = right - left - 1;
+ for (ListIterator<? extends Content> li =
+ content.listIterator(left + 1); cnt > 0; cnt--) {
+ helperRawTextType(out, fstack, eventfactory, li.next());
+ }
+
+ final Content rightc = content.get(right);
+ switch (rightc.getCType()) {
+ case Text:
+ out.add(eventfactory.createCharacters(textTrimRight(((Text) rightc).getText())));
+ break;
+ case CDATA:
+ out.add(eventfactory.createCData(textTrimRight(((CDATA) rightc).getText())));
+ break;
+ case EntityRef:
+ printEntityRef(out, fstack, eventfactory, (EntityRef) rightc);
+ default:
+ // do nothing
+ }
+ return;
+ }
+ // For when there's just one thing to print, or in RAW mode we just
+ // print the contents...
+ // ... its the simplest mode.
+ // so simple, in fact that it is dealt with differently as a special
+ // case.
+ for (int i = 0; i < len; i++) {
+ final Content rightc = content.get(offset + i);
+ switch (rightc.getCType()) {
+ case Text:
+ out.add(eventfactory.createCharacters(((Text) rightc).getText()));
+ break;
+ case CDATA:
+ out.add(eventfactory.createCData(((CDATA) rightc).getText()));
+ break;
+ case EntityRef:
+ printEntityRef(out, fstack, eventfactory, (EntityRef) rightc);
+ default:
+ // do nothing
+ }
+ }
+ //assert TextMode.PRESERVE != mode : "PRESERVE text-types are not Consecutive";
+ }
+
+ /**
+ * This method contains code which is reused in a number of places. It
+ * simply determines what content is passed in, and dispatches it to the
+ * correct print* method.
+ *
+ * @param out
+ * The destination to write to.
+ * @param fstack
+ * The current FormatStack
+ * @param nstack
+ * the NamespaceStack
+ * @param eventfactory
+ * The XMLEventFactory for creating XMLEvents
+ * @param content
+ * The content to dispatch
+ * @throws XMLStreamException
+ * if the output fails
+ */
+ protected void helperContentDispatcher(final XMLEventConsumer out,
+ final FormatStack fstack, final NamespaceStack nstack,
+ final XMLEventFactory eventfactory, final Content content) throws XMLStreamException {
+ switch (content.getCType()) {
+ case CDATA:
+ printCDATA(out, fstack, eventfactory, (CDATA) content);
+ break;
+ case Comment:
+ printComment(out, fstack, eventfactory, (Comment) content);
+ break;
+ case Element:
+ printElement(out, fstack, nstack, eventfactory, (Element) content);
+ break;
+ case EntityRef:
+ printEntityRef(out, fstack, eventfactory, (EntityRef) content);
+ break;
+ case ProcessingInstruction:
+ printProcessingInstruction(out, fstack, eventfactory,
+ (ProcessingInstruction) content);
+ break;
+ case Text:
+ printText(out, fstack, eventfactory, (Text) content);
+ break;
+ case DocType:
+ printDocType(out, fstack, eventfactory, (DocType) content);
+ if (fstack.getLineSeparator() != null) {
+ out.add(eventfactory.createCharacters(fstack.getLineSeparator()));
+ }
+ break;
+ default:
+ throw new IllegalStateException(
+ "Unexpected Content " + content.getCType());
+ }
+ }
+
+ /**
+ * This helper determines how much text-type content there is to print. If
+ * there is a single node only, then it is dispatched to the respective
+ * print* method, otherwise it is dispatched to the printTextConsecutive
+ * method.
+ * <p>
+ * It is a requirement for this method that at least one of the specified
+ * text-type instances has non-whitespace, or, put the other way, if all
+ * specified text-type values are all white-space only, then you may
+ * get odd looking XML (empty lines).
+ * <p>
+ * Odd things can happen too if the len is <= 0;
+ *
+ * @param out
+ * where to write
+ * @param fstack
+ * the current FormatStack
+ * @param eventfactory
+ * The XMLEventFactory for creating XMLEvents
+ * @param content
+ * The list of Content to process
+ * @param offset
+ * The offset of the first text-type content in the sequence
+ * @param len
+ * the number of text-type content in the sequence
+ * @throws XMLStreamException
+ * if the output fails.
+ */
+ protected final void helperTextType(final XMLEventConsumer out,
+ final FormatStack fstack, final XMLEventFactory eventfactory,
+ final List<? extends Content> content,
+ final int offset, final int len) throws XMLStreamException {
+
+ assert len > 0 : "All calls to this should have *some* content.";
+
+ if (len == 1) {
+ final Content node = content.get(offset);
+ // Print the node
+ switch (node.getCType()) {
+ case Text:
+ printText(out, fstack, eventfactory, (Text) node);
+ break;
+ case CDATA:
+ printCDATA(out, fstack, eventfactory, (CDATA) node);
+ break;
+ case EntityRef:
+ printEntityRef(out, fstack, eventfactory, (EntityRef) node);
+ default:
+ // do nothing
+ }
+ } else {
+ // we have text content we need to print.
+ // we also know that we are 'mixed' content
+ // so the text content should be indented.
+ // Additionally
+ printTextConsecutive(out, fstack, eventfactory, content, offset, len);
+ }
+ }
+
+ /**
+ * This method contains code which is reused in a number of places. It
+ * simply determines which of the text-type content is passed in, and
+ * dispatches it to the correct text method (textEscapeRaw, textCDATARaw, or
+ * textEntityRef).
+ *
+ * @param out
+ * The destination to write to.
+ * @param fstack
+ * The current FormatStack
+ * @param eventfactory
+ * The XMLEventFactory for creating XMLEvents
+ * @param content
+ * The content to dispatch
+ * @throws XMLStreamException
+ * if the output fails
+ */
+ protected final void helperRawTextType(final XMLEventConsumer out,
+ final FormatStack fstack, final XMLEventFactory eventfactory,
+ final Content content) throws XMLStreamException {
+ switch (content.getCType()) {
+ case Text:
+ out.add(eventfactory.createCharacters(((Text) content).getText()));
+ break;
+ case CDATA:
+ out.add(eventfactory.createCData(((CDATA) content).getText()));
+ break;
+ case EntityRef:
+ printEntityRef(out, fstack, eventfactory, (EntityRef) content);
+ default:
+ // do nothing
+ }
+ }
+
+ /**
+ * Inspect the specified content range of text-type for any that have actual
+ * text.
+ * @param content a <code>List</code> containing Content.
+ * @param offset the start offset to check
+ * @param len how much content to check
+ * @return true if there's no actual text in the specified content range.
+ */
+ protected boolean isAllWhiteSpace(final List<? extends Content> content,
+ final int offset, final int len) {
+ for (int i = offset + len - 1; i >= offset; i--) {
+ // do the harder check for non-whitespace.
+ final Content c = content.get(i);
+ switch (c.getCType()) {
+ case CDATA:
+ case Text:
+ // both return the text as getValue()
+ for (char ch : c.getValue().toCharArray()) {
+ if (!Verifier.isXMLWhitespace(ch)) {
+ return false;
+ }
+ }
+ break;
+ case EntityRef:
+ return false;
+ default:
+ throw new IllegalStateException(
+ "isWhiteSpace was given a " + c.getCType() +
+ " to check, which is illegal");
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Inspect the input String for whitespace characters.
+ *
+ * @param value
+ * The value to inspect
+ * @return true if all characters in the input value are all whitespace
+ */
+ protected boolean isAllWhitespace(final String value) {
+ for (char ch : value.toCharArray()) {
+ if (!Verifier.isXMLWhitespace(ch)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+}
diff --git a/core/src/java/org/jdom2/output/AbstractStAXStreamProcessor.java b/core/src/java/org/jdom2/output/AbstractStAXStreamProcessor.java
new file mode 100644
index 000000000..b9e87ae32
--- /dev/null
+++ b/core/src/java/org/jdom2/output/AbstractStAXStreamProcessor.java
@@ -0,0 +1,1416 @@
+package org.jdom2.output;
+
+import java.io.StringWriter;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+
+import org.jdom2.Attribute;
+import org.jdom2.CDATA;
+import org.jdom2.Comment;
+import org.jdom2.Content;
+import org.jdom2.DocType;
+import org.jdom2.Document;
+import org.jdom2.Element;
+import org.jdom2.EntityRef;
+import org.jdom2.Namespace;
+import org.jdom2.NamespaceStack;
+import org.jdom2.ProcessingInstruction;
+import org.jdom2.Text;
+import org.jdom2.Verifier;
+import org.jdom2.output.Format.TextMode;
+
+/**
+ * This class provides a concrete implementation of {@link StAXStreamProcessor}
+ * for supporting the {@link StAXStreamOutputter}.
+ * <p>
+ * <h2>Overview</h2>
+ * <p>
+ * This class is marked abstract even though all methods are fully implemented.
+ * The <code>process*(...)</code> methods are public because they match the
+ * StAXStreamProcessor interface but the remaining methods are all protected.
+ * <p>
+ * People who want to create a custom StAXStreamProcessor for StAXStreamOutputter are
+ * able to extend this class and modify any functionality they want. Before
+ * sub-classing this you should first check to see if the {@link Format} class
+ * can get you the results you want.
+ * <p>
+ * <b><i>Subclasses of this should have reentrant methods.</i></b> This is
+ * easiest to accomplish simply by not allowing any instance fields. If your
+ * sub-class has an instance field/variable, then it's probably broken.
+ * <p>
+ * <h2>The Stacks</h2>
+ * <p>
+ * One significant feature of this implementation is that it creates and
+ * maintains both a {@link NamespaceStack} and {@link FormatStack} that are
+ * managed in the
+ * {@link #printElement(XMLStreamWriter, FormatStack, NamespaceStack, Element)} method.
+ * The stacks are pushed and popped in that method only. They significantly
+ * improve the performance and readability of the code.
+ * <p>
+ * The NamespaceStack is only sent through to the
+ * {@link #printElement(XMLStreamWriter, FormatStack, NamespaceStack, Element)} and
+ * {@link #printContent(XMLStreamWriter, FormatStack, NamespaceStack, List)} methods, but
+ * the FormatStack is pushed through to all print* Methods.
+ * <p>
+ * <h2>Text Processing</h2>
+ * <p>
+ * In XML the concept of 'Text' can be loosely defined as anything that can be
+ * found between an Element's start and end tags, excluding Comments and
+ * Processing Instructions. When considered from a JDOM perspective, this means
+ * {@link Text}, {@link CDATA} and {@link EntityRef} content. This will be
+ * referred to as 'text-type content'
+ * <p>
+ * In the context of StAXStreamOutputter, {@link EntityRef} content is considered to be
+ * text-type content. This happens because when XML is parsed the embedded
+ * entity reference tokens are (normally) expanded to their replacement text. If
+ * an EntityRef content has survived to this output stage it means that it
+ * cannot (or should not) be expanded. As a result, it should simply be output
+ * as it's escaped name in the form <code>&refname;</code>.
+ * <p>
+ * Consecutive text-type JDOM content is an especially hard problem because the
+ * complete set of consecutive values should be considered together. For
+ * example, there is a significant difference between the 'trimmed' result of
+ * two individual Text contents and the trimmed result of the same Text contents
+ * which are combined before trimming: consider two consecutive Text contents
+ * " X " and " Y " which (trimmed) should be output as:
+ * "X Y" not "XY".
+ * <p>
+ * As a result, this class differentiates between stand-alone and consecutive
+ * text-type JDOM Content. If the content is determined to be stand-alone, it is
+ * fed to one of the {@link #printEntityRef(XMLStreamWriter, FormatStack, EntityRef)},
+ * {@link #printCDATA(XMLStreamWriter, FormatStack, CDATA)}, or
+ * {@link #printText(XMLStreamWriter, FormatStack, Text)} methods. If there is
+ * consecutive text-type content it is all fed together to the
+ * {@link #printTextConsecutive(XMLStreamWriter, FormatStack, List, int, int)} method.
+ * <p>
+ * The above 4 methods for printing text-type content will all use the various
+ * <code>text*(...)</code> methods to produce output to the XMLStreamWriter.
+ * <p>
+ * <b>Note:</b> If the Format's TextMode is PRESERVE then all text-type content
+ * is considered to be stand-alone. In other words, printTextConsecutive() will
+ * never be called when the TextMode is PRESERVE.
+ * <p>
+ * <h2>Non-Text Content</h2>
+ * <p>
+ * Non-text content is processed via the respective print* methods. The usage
+ * should be logical based on the method name.
+ * <p>
+ * The general observations are:
+ * <ul>
+ * <li>printElement - maintains the Stacks, prints the element open tags, with
+ * attributes and namespaces. It checks to see whether the Element is text-only,
+ * or has non-text content. If it is text-only there is no indent/newline
+ * handling and it delegates to the correct text-type print method, otherwise it
+ * delegates to printContent.
+ * <li>printContent is called if there is a 'mixed' content list to output. It
+ * will always wrap each respective content call (one of a text-type print, a
+ * printTextConsecutive, or a non-text type print) with an indent and a newline.
+ * </ul>
+ * <p>
+ * There are two 'helper' methods which are simply there to reduce some code
+ * redundancy in the class. They do nothing more than that. Have a look at the
+ * source-code to see what they do. If you need them they may prove useful.
+ *
+ * @see StAXStreamOutputter
+ * @see StAXStreamProcessor
+ * @author Rolf Lear
+ */
+public abstract class AbstractStAXStreamProcessor implements StAXStreamProcessor {
+
+
+
+ /* *******************************************
+ * StAXStreamProcessor implementation.
+ * *******************************************
+ */
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jdom2.output.StAXStreamProcessor#process(java.io.XMLStreamWriter,
+ * org.jdom2.Document, org.jdom2.output.Format)
+ */
+ @Override
+ public void process(final XMLStreamWriter out, final Format format,
+ final Document doc) throws XMLStreamException {
+ printDocument(out, new FormatStack(format), new NamespaceStack(), doc);
+ out.flush();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jdom2.output.StAXStreamProcessor#process(java.io.XMLStreamWriter,
+ * org.jdom2.DocType, org.jdom2.output.Format)
+ */
+ @Override
+ public void process(final XMLStreamWriter out, final Format format,
+ final DocType doctype) throws XMLStreamException {
+ printDocType(out, new FormatStack(format), doctype);
+ out.flush();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jdom2.output.StAXStreamProcessor#process(java.io.XMLStreamWriter,
+ * org.jdom2.Element, org.jdom2.output.Format)
+ */
+ @Override
+ public void process(final XMLStreamWriter out, final Format format,
+ final Element element) throws XMLStreamException {
+ // If this is the root element we could pre-initialize the
+ // namespace stack with the namespaces
+ printElement(out, new FormatStack(format), new NamespaceStack(),
+ element);
+ out.flush();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jdom2.output.StAXStreamProcessor#process(java.io.XMLStreamWriter,
+ * java.util.List, org.jdom2.output.Format)
+ */
+ @Override
+ public void process(final XMLStreamWriter out, final Format format,
+ final List<? extends Content> list)
+ throws XMLStreamException {
+ printContent(out, new FormatStack(format), new NamespaceStack(), list);
+ out.flush();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jdom2.output.StAXStreamProcessor#process(java.io.XMLStreamWriter,
+ * org.jdom2.CDATA, org.jdom2.output.Format)
+ */
+ @Override
+ public void process(final XMLStreamWriter out, final Format format,
+ final CDATA cdata) throws XMLStreamException {
+ printCDATA(out, new FormatStack(format), cdata);
+ out.flush();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jdom2.output.StAXStreamProcessor#process(java.io.XMLStreamWriter,
+ * org.jdom2.Text, org.jdom2.output.Format)
+ */
+ @Override
+ public void process(final XMLStreamWriter out, final Format format,
+ final Text text) throws XMLStreamException {
+ printText(out, new FormatStack(format), text);
+ out.flush();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jdom2.output.StAXStreamProcessor#process(java.io.XMLStreamWriter,
+ * org.jdom2.Comment, org.jdom2.output.Format)
+ */
+ @Override
+ public void process(final XMLStreamWriter out, final Format format,
+ final Comment comment) throws XMLStreamException {
+ printComment(out, new FormatStack(format), comment);
+ out.flush();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jdom2.output.StAXStreamProcessor#process(java.io.XMLStreamWriter,
+ * org.jdom2.ProcessingInstruction, org.jdom2.output.Format)
+ */
+ @Override
+ public void process(final XMLStreamWriter out, final Format format,
+ final ProcessingInstruction pi) throws XMLStreamException {
+ FormatStack fstack = new FormatStack(format);
+ // Output PI verbatim, disregarding TrAX escaping PIs.
+ fstack.setIgnoreTrAXEscapingPIs(true);
+ printProcessingInstruction(out, fstack, pi);
+ out.flush();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jdom2.output.StAXStreamProcessor#process(java.io.XMLStreamWriter,
+ * org.jdom2.EntityRef, org.jdom2.output.Format)
+ */
+ @Override
+ public void process(final XMLStreamWriter out, final Format format,
+ final EntityRef entity) throws XMLStreamException {
+ printEntityRef(out, new FormatStack(format), entity);
+ out.flush();
+ }
+
+ /*
+ * ========================================================================
+ * Support methods for Text-content formatting. Should all be protected. The
+ * following are used when printing Text-based data. Because of complicated
+ * multi-sequential text sometimes the requirements are odd. All Text
+ * content will be output using these methods, which is why there is the Raw
+ * version.
+ * ========================================================================
+ */
+
+ /**
+ * Write a CDATA's value to the destination. The value will first be
+ * compacted (all leading and trailing whitespace will be removed and all
+ * internal whitespace will be be represented with a single ' ' character).
+ * If the CDATA contains only whitespace then nothing is output.
+ * <p>
+ * The results (if any) will be wrapped in the <code><![CDATA[</code> and
+ * <code>]]></code> delimiters.
+ *
+ * @param str
+ * the CDATA's value.
+ * @return The input String in a compact form
+ */
+ protected String textCompact(final String str) {
+ final char[] chars = str.toCharArray();
+ int right = chars.length - 1;
+ while (right >= 0 && Verifier.isXMLWhitespace(chars[right])) {
+ right--;
+ }
+ if (right < 0) {
+ return "";
+ }
+
+ int left = 0;
+ while (Verifier.isXMLWhitespace(chars[left])) {
+ // we do not need to check left < right because
+ // we know we will find some non-white char first.
+ left++;
+ }
+
+ int from = left;
+ boolean wspace = false;
+ left++;
+ int ip = left;
+ while (left <= right) {
+ if (Verifier.isXMLWhitespace(chars[left])) {
+ if (!wspace) {
+ chars[ip++] = ' ';
+ }
+ wspace = true;
+ } else {
+ chars[ip++] = chars[left];
+ wspace = false;
+ }
+ left++;
+ }
+
+ return String.valueOf(chars, from, ip - from);
+ }
+
+ /**
+ * Write a CDATA's value to the destination. The value will first be
+ * inspected. If the CDATA contains only whitespace then nothing is output,
+ * otherwise the entire input <code>str</code> will be wrapped in the
+ * <code><![CDATA[</code> and <code>]]></code> delimiters.
+ *
+ * @param str
+ * the CDATA's value.
+ * @return the input str if there's at least one non-whitespace char in it.
+ * otherwise returns ""
+ */
+ protected String textTrimFullWhite(final String str) {
+ int right = str.length();
+ while (--right >= 0 && Verifier.isXMLWhitespace(str.charAt(right))) {
+ right--;
+ }
+ if (right < 0) {
+ return "";
+ }
+
+ return str;
+ }
+
+ /**
+ * Write a CDATA's value to the destination. The value will first be trimmed
+ * (all leading and trailing whitespace will be removed). If the CDATA
+ * contains only whitespace then nothing is output. The results (if any)
+ * will be wrapped in the <code><![CDATA[</code> and <code>]]></code>
+ * delimiters.
+ *
+ * @param str
+ * the CDATA's value.
+ * @return the input str value trimmed left and right.
+ */
+ protected String textTrimBoth(final String str) {
+ int right = str.length() - 1;
+ while (right >= 0 && Verifier.isXMLWhitespace(str.charAt(right))) {
+ right--;
+ }
+ if (right < 0) {
+ return "";
+ }
+
+ int left = 0;
+ while (Verifier.isXMLWhitespace(str.charAt(left))) {
+ // we do not need to check left < right because
+ // we know we will find some non-white char first.
+ left++;
+ }
+ return str.substring(left, right + 1);
+ }
+
+ /**
+ * Write a CDATA's value to the destination. The value will first be
+ * right-trimmed (all trailing whitespace will be removed). If the CDATA
+ * contains only whitespace then nothing is output. The results (if any)
+ * will be wrapped in the <code><![CDATA[</code> and <code>]]></code>
+ * delimiters.
+ *
+ * @param str
+ * the CDATA's value.
+ * @return the input str trimmed on the right.
+ */
+ protected String textTrimRight(final String str) {
+ int right = str.length() - 1;
+ while (right >= 0 && Verifier.isXMLWhitespace(str.charAt(right))) {
+ right--;
+ }
+ if (right < 0) {
+ return "";
+ }
+
+ return str.substring(0, right + 1);
+ }
+
+ /**
+ * Write a CDATA's value to the destination. The value will first be
+ * left-trimmed (all leading whitespace will be removed). If the CDATA
+ * contains only whitespace then nothing is output. The results (if any)
+ * will be wrapped in the <code><![CDATA[</code> and <code>]]></code>
+ * delimiters.
+ *
+ * @param str
+ * the CDATA's value.
+ * @return the input str trimmed on the left.
+ */
+ protected String textTrimLeft(final String str) {
+ final int right = str.length();
+ int left = 0;
+ while (left < right && Verifier.isXMLWhitespace(str.charAt(left))) {
+ left++;
+ }
+ if (left >= right) {
+ return "";
+ }
+
+ return str.substring(left, right);
+ }
+
+ /* *******************************************
+ * Support methods for output. Should all be protected. All content-type
+ * print methods have a FormatStack. Only printContent is responsible for
+ * outputting appropriate indenting and newlines, which are easily available
+ * using the FormatStack.getLevelIndent() and FormatStack.getLevelEOL().
+ * *******************************************
+ */
+
+ /**
+ * This will handle printing of a {@link Document}.
+ *
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @param fstack
+ * the FormatStack
+ * @param nstack
+ * the NamespaceStack
+ * @param doc
+ * <code>Document</code> to write.
+ * @throws XMLStreamException
+ * if the destination XMLStreamWriter fails
+ */
+ protected void printDocument(final XMLStreamWriter out, final FormatStack fstack,
+ final NamespaceStack nstack, final Document doc) throws XMLStreamException {
+
+ if (fstack.isOmitDeclaration()) {
+ // this actually writes the declaration as version 1, UTF-8
+ out.writeStartDocument();
+ if (fstack.getLineSeparator() != null) {
+ out.writeCharacters(fstack.getLineSeparator());
+ }
+ } else if (fstack.isOmitEncoding()) {
+ out.writeStartDocument("1.0");
+ if (fstack.getLineSeparator() != null) {
+ out.writeCharacters(fstack.getLineSeparator());
+ }
+ } else {
+ out.writeStartDocument(fstack.getEncoding(), "1.0");
+ if (fstack.getLineSeparator() != null) {
+ out.writeCharacters(fstack.getLineSeparator());
+ }
+ }
+
+ printContent(out, fstack, nstack, doc.getContent());
+ // Output final line separator
+ // We output this no matter what the newline flags say
+ if (fstack.getIndent() == null && fstack.getLineSeparator() != null) {
+ out.writeCharacters(fstack.getLineSeparator());
+ }
+
+ out.writeEndDocument();
+
+ }
+
+ /**
+ * This will handle printing of a {@link DocType}.
+ *
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @param fstack
+ * the FormatStack
+ * @param docType
+ * <code>DocType</code> to write.
+ * @throws XMLStreamException
+ * if the destination XMLStreamWriter fails
+ */
+ protected void printDocType(final XMLStreamWriter out, final FormatStack fstack,
+ final DocType docType) throws XMLStreamException {
+
+ final String publicID = docType.getPublicID();
+ final String systemID = docType.getSystemID();
+ final String internalSubset = docType.getInternalSubset();
+ boolean hasPublic = false;
+
+ // Declaration is never indented.
+ // write(out, fstack.getLevelIndent());
+
+ StringWriter sw = new StringWriter();
+
+ sw.write("<!DOCTYPE ");
+ sw.write(docType.getElementName());
+ if (publicID != null) {
+ sw.write(" PUBLIC \"");
+ sw.write(publicID);
+ sw.write("\"");
+ hasPublic = true;
+ }
+ if (systemID != null) {
+ if (!hasPublic) {
+ sw.write(" SYSTEM");
+ }
+ sw.write(" \"");
+ sw.write(systemID);
+ sw.write("\"");
+ }
+ if ((internalSubset != null) && (!internalSubset.equals(""))) {
+ sw.write(" [");
+ sw.write(fstack.getLineSeparator());
+ sw.write(docType.getInternalSubset());
+ sw.write("]");
+ }
+ sw.write(">");
+
+ // DocType does not write it's own EOL
+ // for compatibility reasons. Only
+ // when output from inside a Content set.
+ // write(out, fstack.getLineSeparator());
+ out.writeDTD(sw.toString());
+ }
+
+ /**
+ * This will handle printing of a {@link ProcessingInstruction}.
+ *
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @param fstack
+ * the FormatStack
+ * @param pi
+ * <code>ProcessingInstruction</code> to write.
+ * @throws XMLStreamException
+ * if the destination XMLStreamWriter fails
+ */
+ protected void printProcessingInstruction(final XMLStreamWriter out,
+ final FormatStack fstack, final ProcessingInstruction pi)
+ throws XMLStreamException {
+ String target = pi.getTarget();
+ String rawData = pi.getData();
+ if (rawData != null && rawData.trim().length() > 0) {
+ out.writeProcessingInstruction(target, rawData);
+ } else {
+ out.writeProcessingInstruction(target);
+ }
+ }
+
+ /**
+ * This will handle printing of a {@link Comment}.
+ *
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @param fstack
+ * the FormatStack
+ * @param comment
+ * <code>Comment</code> to write.
+ * @throws XMLStreamException
+ * if the destination XMLStreamWriter fails
+ */
+ protected void printComment(final XMLStreamWriter out, final FormatStack fstack,
+ final Comment comment) throws XMLStreamException {
+ out.writeComment(comment.getText());
+ }
+
+ /**
+ * This will handle printing of an {@link EntityRef}.
+ *
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @param fstack
+ * the FormatStack
+ * @param entity
+ * <code>EntotyRef</code> to write.
+ * @throws XMLStreamException
+ * if the destination XMLStreamWriter fails
+ */
+ protected void printEntityRef(final XMLStreamWriter out, final FormatStack fstack,
+ final EntityRef entity) throws XMLStreamException {
+ out.writeEntityRef(entity.getName());
+ }
+
+ /**
+ * This will handle printing of a {@link CDATA}.
+ *
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @param fstack
+ * the FormatStack
+ * @param cdata
+ * <code>CDATA</code> to write.
+ * @throws XMLStreamException
+ * if the destination XMLStreamWriter fails
+ */
+ protected void printCDATA(final XMLStreamWriter out, final FormatStack fstack,
+ final CDATA cdata) throws XMLStreamException {
+ // CDATAs are treated like text, not indented/newline content.
+ String text = cdata.getText();
+ switch (fstack.getTextMode()) {
+ case PRESERVE:
+ break;
+ case NORMALIZE:
+ text = textCompact(text);
+ break;
+ case TRIM:
+ text = textTrimBoth(text);
+ break;
+ case TRIM_FULL_WHITE:
+ text = textTrimFullWhite(text);
+ break;
+ }
+ out.writeCData(text);
+ }
+
+ /**
+ * This will handle printing of a {@link Text}.
+ *
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @param fstack
+ * the FormatStack
+ * @param text
+ * <code>Text</code> to write.
+ * @throws XMLStreamException
+ * if the destination XMLStreamWriter fails
+ */
+ protected void printText(final XMLStreamWriter out, final FormatStack fstack,
+ final Text text) throws XMLStreamException {
+ String str = text.getText();
+ switch (fstack.getTextMode()) {
+ case PRESERVE:
+ break;
+ case NORMALIZE:
+ str = textCompact(str);
+ break;
+ case TRIM:
+ str = textTrimBoth(str);
+ break;
+ case TRIM_FULL_WHITE:
+ str = textTrimFullWhite(str);
+ break;
+ }
+ out.writeCharacters(str);
+ }
+
+ /**
+ * This will handle printing of an {@link Element}.
+ * <p>
+ * This method arranges for outputting the Element infrastructure including
+ * Namespace Declarations and Attributes.
+ * <p>
+ * There has to be a fair amount of inspection to determine whether there is
+ * any content and whether it is all text-type content, and based on the
+ * required Format output, how to deal with the content. Alternatives (in
+ * 'fall-through' order) are:
+ * <ol>
+ * <li>There is no content, then output just an empty element (depending on
+ * settings this may be either <code><element /></code> or
+ * <code><element></element></code>).
+ * <li>There is only text-type content and the current Format settings would
+ * condense the text-type content to nothing, then output just an empty
+ * element (depending on settings this may be either
+ * <code><element /></code> or <code><element></element></code>
+ * ).
+ * <li>There is just a single text-type content then delegate to that
+ * content's print method
+ * <li>There is only text-type content (more than one though) then delegate
+ * to {@link #printTextConsecutive(XMLStreamWriter, FormatStack, List, int, int)}
+ * <li>There is content other than just text-type content, then delegate to
+ * {@link #printContent(XMLStreamWriter, FormatStack, NamespaceStack, List)}
+ * </ol>
+ * <p>
+ *
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @param fstack
+ * the FormatStack
+ * @param nstack
+ * the NamespaceStack
+ * @param element
+ * <code>Element</code> to write.
+ * @throws XMLStreamException
+ * if the destination XMLStreamWriter fails
+ */
+ protected void printElement(final XMLStreamWriter out, final FormatStack fstack,
+ final NamespaceStack nstack, final Element element) throws XMLStreamException {
+
+ nstack.push(element);
+ try {
+
+ TextMode textmode = fstack.getTextMode();
+
+ // Check for xml:space and adjust format settings
+ final String space = element.getAttributeValue("space",
+ Namespace.XML_NAMESPACE);
+
+ if ("default".equals(space)) {
+ textmode = fstack.getDefaultMode();
+ }
+ else if ("preserve".equals(space)) {
+ textmode = TextMode.PRESERVE;
+ }
+
+ final List<Content> content = element.getContent();
+
+ // Three conditions that determine the required output.
+ // do we have an expanded element( <emt></emt> or an single <emt />
+ // if there is any printable content, or if expandempty is set
+ // then we must expand.
+ boolean expandit = fstack.isExpandEmptyElements();
+
+ // is there only text content
+ // text content is Text/CDATA/EntityRef
+ boolean textonly = true;
+ // is the text content only whitespace.
+ // whiteonly is obvious....
+ boolean whiteonly = true;
+
+ for (Content k : content) {
+ if (k instanceof Text) {
+ if (whiteonly) {
+ if (textmode == TextMode.PRESERVE) {
+ expandit = true;
+ whiteonly = false;
+ } else {
+ // look for non-whitespace.
+ String val = k.getValue();
+ int cc = val.length();
+ while (--cc >= 0) {
+ if (!Verifier.isXMLWhitespace(val.charAt(cc))) {
+ // found non-whitespace;
+ expandit = true;
+ whiteonly = false;
+ break;
+ }
+ }
+ }
+ }
+ } else {
+ expandit = true;
+ whiteonly = false;
+ if (!(k instanceof EntityRef)) {
+ textonly = false;
+ // we know everything we need.
+ break;
+ }
+ }
+ if (expandit && !whiteonly && !textonly) {
+ break;
+ }
+ }
+ if (!expandit) {
+ // implies:
+ // fstack.isExpandEmpty... is false
+ // and content.isEmpty()
+ // or textonly == true
+ // and preserve == false
+ // and whiteonly == true
+
+ Namespace ns = element.getNamespace();
+ if (ns == Namespace.NO_NAMESPACE) {
+ out.writeEmptyElement(element.getName());
+ } else if ("".equals(ns.getPrefix())) {
+ out.writeEmptyElement("", element.getName(), ns.getURI());
+ } else {
+ out.writeEmptyElement(ns.getPrefix(), element.getName(), ns.getURI());
+ }
+
+ // Print the element's namespace, if appropriate
+ for (final Namespace nsd : nstack.addedForward()) {
+ printNamespace(out, fstack, nsd);
+ }
+
+ // Print out attributes
+ for (final Attribute attribute : element.getAttributes()) {
+ printAttribute(out, fstack, attribute);
+ }
+
+ out.writeCharacters("");
+
+ } else {
+ Namespace ns = element.getNamespace();
+ if (ns == Namespace.NO_NAMESPACE) {
+ out.writeStartElement(element.getName());
+ } else if ("".equals(ns.getPrefix())) {
+ out.writeStartElement(ns.getURI(), element.getName());
+ } else {
+ out.writeStartElement(ns.getPrefix(), element.getName(), ns.getURI());
+ }
+
+ // Print the element's namespace, if appropriate
+ for (final Namespace nsd : nstack.addedForward()) {
+ printNamespace(out, fstack, nsd);
+ }
+
+ // Print out attributes
+ for (final Attribute attribute : element.getAttributes()) {
+ printAttribute(out, fstack, attribute);
+ }
+
+ // OK, now we print out the meat of the Element
+ if (!content.isEmpty()) {
+ if (textonly) {
+ if (!whiteonly) {
+ fstack.push();
+ try {
+ fstack.setTextMode(textmode);
+ helperTextType(out, fstack, content, 0, content.size());
+ } finally {
+ fstack.pop();
+ }
+ }
+ } else {
+ fstack.push();
+ try {
+ fstack.setTextMode(textmode);
+ if (fstack.getLevelEOL() != null) {
+ out.writeCharacters(fstack.getLevelEOL());
+ }
+
+ printContent(out, fstack, nstack, content);
+
+ } finally {
+ fstack.pop();
+ }
+ if (fstack.getLevelIndent() != null) {
+ out.writeCharacters(fstack.getLevelIndent());
+ }
+ }
+ }
+
+ out.writeEndElement();
+
+
+
+ }
+
+
+
+
+ } finally {
+ nstack.pop();
+ }
+ }
+
+ /**
+ * This will handle printing of a List of {@link Content}.
+ * <p>
+ * The list of Content is basically processed as one of three types of
+ * content
+ * <ol>
+ * <li>Consecutive text-type (Text, CDATA, and EntityRef) content
+ * <li>Stand-alone text-type content
+ * <li>Non-text-type content.
+ * </ol>
+ * Although the code looks complex, the theory is conceptually simple:
+ * <ol>
+ * <li>identify one of the three types (consecutive, stand-alone, non-text)
+ * <li>do indent if any is specified.
+ * <li>send the type to the respective print* handler (e.g.
+ * {@link #printTextConsecutive(XMLStreamWriter, FormatStack, List, int, int)},
+ * {@link #printCDATA(XMLStreamWriter, FormatStack, CDATA)}, or
+ * {@link #printComment(XMLStreamWriter, FormatStack, Comment)},
+ * <li>do a newline if one is specified.
+ * <li>loop back to 1. until there's no more content to process.
+ * </ol>
+ *
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @param fstack
+ * the FormatStack
+ * @param nstack
+ * the NamespaceStack
+ * @param content
+ * <code>List</code> of <code>Content</code> to write.
+ * @throws XMLStreamException
+ * if the destination XMLStreamWriter fails
+ */
+ protected void printContent(final XMLStreamWriter out,
+ final FormatStack fstack, final NamespaceStack nstack,
+ final List<? extends Content> content)
+ throws XMLStreamException {
+
+ // Basic theory of operation is as follows:
+ // 0. raw-print for PRESERVE.
+ // 1. print any non-Text content
+ // 2. Accumulate all sequential text content and print them together
+ // Do not do any newlines before or after content.
+ if (fstack.getTextMode() == TextMode.PRESERVE) {
+ for (Content c : content) {
+ helperContentDispatcher(out, fstack, nstack, c);
+ }
+ return;
+ }
+
+ int txti = -1;
+ int index = 0;
+ for (final Content c : content) {
+ switch (c.getCType()) {
+ case Text:
+ case CDATA:
+ case EntityRef:
+ //
+ // Handle consecutive CDATA, Text, and EntityRef nodes all
+ // at once
+ //
+ if (txti < 0) {
+ txti = index;
+ }
+ break;
+ default:
+ if (txti >= 0) {
+ // we have text content we need to print.
+ // we also know that we are 'mixed' content
+ // so the text content should be indented.
+ // but, since we have no PRESERVE content, only the
+ // 'trimming' variants, if it is all whitespace we do
+ // not want to even print the indent/newline.
+ if (!isAllWhiteSpace(content, txti, index - txti)) {
+ if (fstack.getLevelIndent() != null) {
+ out.writeCharacters(fstack.getLevelIndent());
+ }
+ helperTextType(out, fstack, content, txti, index - txti);
+ if (fstack.getLevelEOL() != null) {
+ out.writeCharacters(fstack.getLevelEOL());
+ }
+ }
+ }
+ txti = -1;
+
+ if (fstack.getLevelIndent() != null) {
+ out.writeCharacters(fstack.getLevelIndent());
+ }
+ helperContentDispatcher(out, fstack, nstack, c);
+ if (fstack.getLevelEOL() != null) {
+ out.writeCharacters(fstack.getLevelEOL());
+ }
+ }
+ index++;
+ }
+ if (txti >= 0) {
+ // we have text content we need to print.
+ // we also know that we are 'mixed' content
+ // so the text content should be indented.
+ // but, since we have no PRESERVE content, only the
+ // 'trimming' variants, if it is all whitespace we do
+ // not want to even print the indent/newline.
+ if (!isAllWhiteSpace(content, txti, index - txti)) {
+ if (fstack.getLevelIndent() != null) {
+ out.writeCharacters(fstack.getLevelIndent());
+ }
+ helperTextType(out, fstack, content, txti, index - txti);
+ if (fstack.getLevelEOL() != null) {
+ out.writeCharacters(fstack.getLevelEOL());
+ }
+ }
+ }
+
+ }
+
+ /**
+ * This will handle printing of a consecutive sequence of text-type
+ * {@link Content} (<code>{@link CDATA}</code> <code>{@link Text}</code>, or
+ * <code>{@link EntityRef}</code>) nodes. It is an error (unspecified
+ * Exception or unspecified behaviour) to pass this method any other type of
+ * node.
+ * <p>
+ * It is a requirement for this method that at least one of the specified
+ * text-type instances has non-whitespace, or, put the other way, if all
+ * specified text-type values are all white-space only, then you may
+ * get odd looking XML (empty lines).
+ *
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @param fstack
+ * the FormatStack
+ * @param content
+ * <code>List</code> of <code>Content</code> to write.
+ * @param offset
+ * index of first content node (inclusive).
+ * @param len
+ * number of nodes that are text-type.
+ * @throws XMLStreamException
+ * if the destination XMLStreamWriter fails
+ */
+ protected void printTextConsecutive(final XMLStreamWriter out, FormatStack fstack,
+ final List<? extends Content> content,
+ final int offset, final int len) throws XMLStreamException {
+
+ // we are guaranteed that len >= 2
+ assert len >= 2 : "Need at least two text-types to be 'Consecutive'";
+
+ // here we have a sequence of Text nodes to print.
+ // we follow the TextMode rules for it.
+ // also guaranteed is that at least one of the nodes has some real text.
+
+ final TextMode mode = fstack.getTextMode();
+
+ // Right, at this point it is complex.
+ // we have multiple nodes to output, and it could be in one of three
+ // modes, TRIM, TRIM_FULL_WHITE, or NORMALIZE
+ // we aggregate the text together, and dump it
+
+ // Let's get TRIM_FULL_WHITE out of the way.
+ // in this mode, if there is any real text content, we print it all.
+ // otherwise we print nothing
+ // since it is a requirement for this method that there has to be some
+ // non-whitespace text, we can just print everything.
+ if (TextMode.TRIM_FULL_WHITE == mode) {
+ // Right, if we find text, we print it all.
+ // If we don't we print nothing.
+ int cnt = len;
+ for (ListIterator<? extends Content> li =
+ content.listIterator(offset); cnt > 0; cnt--) {
+ helperRawTextType(out, fstack, li.next());
+ }
+ return;
+ }
+
+ // OK, now we are left with just TRIM and NORMALIZE
+ // Normalize is now actually easier.
+ if (TextMode.NORMALIZE == mode) {
+ boolean dospace = false;
+ // we know there's at least 2 content nodes...
+ // we process the 'gaps' to see if we need spaces, and print
+ // all the content in NORMALIZED form.
+ boolean first = true;
+ int cnt = len;
+ for (Iterator<? extends Content> li = content.listIterator(offset); cnt > 0; cnt--) {
+ boolean endspace = false;
+ final Content c = li.next();
+ if (c instanceof Text) {
+ final String val = ((Text) c).getValue();
+ if (val.length() == 0) {
+ // ignore empty text.
+ continue;
+ }
+ if (isAllWhitespace(val)) {
+ // we skip all whitespace.
+ // but record the space
+ if (!first) {
+ dospace = true;
+ }
+ continue;
+ }
+ if (!first && !dospace &&
+ Verifier.isXMLWhitespace(val.charAt(0))) {
+ // we are between content, and need to put in a space.
+ dospace = true;
+ }
+ endspace = Verifier.isXMLWhitespace(val.charAt(val.length() - 1));
+ }
+ first = false;
+ if (dospace) {
+ out.writeCharacters(" ");
+ }
+
+ switch (c.getCType()) {
+ case Text:
+ out.writeCharacters(textCompact(((Text) c).getText()));
+ break;
+ case CDATA:
+ out.writeCData(textCompact(((Text) c).getText()));
+ break;
+ case EntityRef:
+ out.writeEntityRef(((EntityRef) c).getName());
+ default:
+ // do nothing
+ }
+ dospace = endspace;
+ }
+ return;
+ }
+
+ // All that's left now is multi-content that needs to be trimmed.
+ // For this, we do a cheat....
+ // we trim the left and right content, and print any middle content
+ // as raw.
+ // we have to preserve the right-whitespace of the left content, and the
+ // left whitespace of the right content.
+ // no need to check the mode, it can only be TRIM.
+ if (TextMode.TRIM == fstack.getTextMode()) {
+
+ int lcnt = 0;
+ while (lcnt < len) {
+ Content node = content.get(offset + lcnt);
+ if (!(node instanceof Text) || !isAllWhitespace(node.getValue())) {
+ break;
+ }
+ lcnt++;
+ }
+
+ if (lcnt == len) {
+ return;
+ }
+
+
+ final int left = offset + lcnt;
+ int rcnt = len - 1;
+ while (rcnt > lcnt) {
+ Content node = content.get(offset + rcnt);
+ if (!(node instanceof Text) || !isAllWhitespace(node.getValue())) {
+ break;
+ }
+ rcnt--;
+ }
+ final int right = offset + rcnt;
+
+ if (left == right) {
+ // came down to just one value to output.
+ final Content node = content.get(left);
+ switch (node.getCType()) {
+ case Text:
+ out.writeCharacters(textTrimBoth(((Text) node).getText()));
+ break;
+ case CDATA:
+ out.writeCData(textTrimBoth(((CDATA) node).getText()));
+ break;
+ case EntityRef:
+ out.writeEntityRef(((EntityRef) node).getName());
+ default:
+ // do nothing
+ }
+ return;
+ }
+ final Content leftc = content.get(left);
+ switch (leftc.getCType()) {
+ case Text:
+ out.writeCharacters(textTrimLeft(((Text) leftc).getText()));
+ break;
+ case CDATA:
+ out.writeCData(textTrimLeft(((CDATA) leftc).getText()));
+ break;
+ case EntityRef:
+ out.writeEntityRef(((EntityRef) leftc).getName());
+ default:
+ // do nothing
+ }
+
+ int cnt = right - left - 1;
+ for (ListIterator<? extends Content> li =
+ content.listIterator(left + 1); cnt > 0; cnt--) {
+ helperRawTextType(out, fstack, li.next());
+ }
+
+ final Content rightc = content.get(right);
+ switch (rightc.getCType()) {
+ case Text:
+ out.writeCharacters(textTrimRight(((Text) rightc).getText()));
+ break;
+ case CDATA:
+ out.writeCData(textTrimRight(((CDATA) rightc).getText()));
+ break;
+ case EntityRef:
+ out.writeEntityRef(((EntityRef) rightc).getName());
+ default:
+ // do nothing
+ }
+ return;
+ }
+ // For when there's just one thing to print, or in RAW mode we just
+ // print the contents...
+ // ... its the simplest mode.
+ // so simple, in fact that it is dealt with differently as a special
+ // case.
+ for (int i = 0; i < len; i++) {
+ final Content rightc = content.get(offset + i);
+ switch (rightc.getCType()) {
+ case Text:
+ out.writeCharacters(((Text) rightc).getText());
+ break;
+ case CDATA:
+ out.writeCData(((CDATA) rightc).getText());
+ break;
+ case EntityRef:
+ out.writeEntityRef(((EntityRef) rightc).getName());
+ default:
+ // do nothing
+ }
+ }
+ //assert TextMode.PRESERVE != mode : "PRESERVE text-types are not Consecutive";
+ }
+
+ /**
+ * This method contains code which is reused in a number of places. It
+ * simply determines what content is passed in, and dispatches it to the
+ * correct print* method.
+ *
+ * @param out
+ * The destination to write to.
+ * @param fstack
+ * The current FormatStack
+ * @param nstack
+ * the NamespaceStack
+ * @param content
+ * The content to dispatch
+ * @throws XMLStreamException
+ * if the output fails
+ */
+ protected void helperContentDispatcher(final XMLStreamWriter out,
+ final FormatStack fstack, final NamespaceStack nstack,
+ final Content content) throws XMLStreamException {
+ switch (content.getCType()) {
+ case CDATA:
+ printCDATA(out, fstack, (CDATA) content);
+ break;
+ case Comment:
+ printComment(out, fstack, (Comment) content);
+ break;
+ case Element:
+ printElement(out, fstack, nstack, (Element) content);
+ break;
+ case EntityRef:
+ printEntityRef(out, fstack, (EntityRef) content);
+ break;
+ case ProcessingInstruction:
+ printProcessingInstruction(out, fstack,
+ (ProcessingInstruction) content);
+ break;
+ case Text:
+ printText(out, fstack, (Text) content);
+ break;
+ case DocType:
+ printDocType(out, fstack, (DocType) content);
+ if (fstack.getLineSeparator() != null) {
+ out.writeCharacters(fstack.getLineSeparator());
+ }
+ break;
+ default:
+ throw new IllegalStateException(
+ "Unexpected Content " + content.getCType());
+ }
+ }
+
+ /**
+ * This helper determines how much text-type content there is to print. If
+ * there is a single node only, then it is dispatched to the respective
+ * print* method, otherwise it is dispatched to the printTextConsecutive
+ * method.
+ * <p>
+ * It is a requirement for this method that at least one of the specified
+ * text-type instances has non-whitespace, or, put the other way, if all
+ * specified text-type values are all white-space only, then you may
+ * get odd looking XML (empty lines).
+ * <p>
+ * Odd things can happen too if the len is <= 0;
+ *
+ * @param out
+ * where to write
+ * @param fstack
+ * the current FormatStack
+ * @param content
+ * The list of Content to process
+ * @param offset
+ * The offset of the first text-type content in the sequence
+ * @param len
+ * the number of text-type content in the sequence
+ * @throws XMLStreamException
+ * if the output fails.
+ */
+ protected final void helperTextType(final XMLStreamWriter out,
+ final FormatStack fstack, final List<? extends Content> content,
+ final int offset, final int len) throws XMLStreamException {
+
+ assert len > 0 : "All calls to this should have *some* content.";
+
+ if (len == 1) {
+ final Content node = content.get(offset);
+ // Print the node
+ switch (node.getCType()) {
+ case Text:
+ printText(out, fstack, (Text) node);
+ break;
+ case CDATA:
+ printCDATA(out, fstack, (CDATA) node);
+ break;
+ case EntityRef:
+ printEntityRef(out, fstack, (EntityRef) node);
+ default:
+ // do nothing
+ }
+ } else {
+ // we have text content we need to print.
+ // we also know that we are 'mixed' content
+ // so the text content should be indented.
+ // Additionally
+ printTextConsecutive(out, fstack, content, offset, len);
+ }
+ }
+
+ /**
+ * This method contains code which is reused in a number of places. It
+ * simply determines which of the text-type content is passed in, and
+ * dispatches it to the correct text method (textEscapeRaw, textCDATARaw, or
+ * textEntityRef).
+ *
+ * @param out
+ * The destination to write to.
+ * @param fstack
+ * The current FormatStack
+ * @param content
+ * The content to dispatch
+ * @throws XMLStreamException
+ * if the output fails
+ */
+ protected final void helperRawTextType(final XMLStreamWriter out,
+ final FormatStack fstack, final Content content) throws XMLStreamException {
+ switch (content.getCType()) {
+ case Text:
+ out.writeCharacters(((Text) content).getText());
+ break;
+ case CDATA:
+ out.writeCData(((CDATA) content).getText());
+ break;
+ case EntityRef:
+ out.writeEntityRef(((EntityRef) content).getName());
+ default:
+ // do nothing
+ }
+ }
+
+ /**
+ * This will handle printing of any needed <code>{@link Namespace}</code>
+ * declarations.
+ *
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @param fstack
+ * The current FormatStack
+ * @param ns
+ * <code>Namespace</code> to print definition of
+ * @throws XMLStreamException
+ * if the output fails
+ */
+ protected void printNamespace(final XMLStreamWriter out, final FormatStack fstack,
+ final Namespace ns) throws XMLStreamException {
+ final String prefix = ns.getPrefix();
+ final String uri = ns.getURI();
+
+ out.writeNamespace(prefix, uri);
+ }
+
+ /**
+ * This will handle printing of an <code>{@link Attribute}</code>.
+ *
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @param fstack
+ * The current FormatStack
+ * @param attribute
+ * <code>Attribute</code> to output
+ * @throws XMLStreamException
+ * if the output fails
+ */
+ protected void printAttribute(final XMLStreamWriter out, final FormatStack fstack,
+ final Attribute attribute) throws XMLStreamException {
+
+ final Namespace ns = attribute.getNamespace();
+ if (ns == Namespace.NO_NAMESPACE) {
+ out.writeAttribute(attribute.getName(), attribute.getValue());
+ } else {
+ out.writeAttribute(ns.getPrefix(), ns.getURI(),
+ attribute.getName(), attribute.getValue());
+ }
+ }
+
+ /**
+ * Inspect the specified content range of text-type for any that have actual
+ * text.
+ * @param content a <code>List</code> containing Content.
+ * @param offset the start offset to check
+ * @param len how much content to check
+ * @return true if there's no actual text in the specified content range.
+ */
+ protected boolean isAllWhiteSpace(final List<? extends Content> content,
+ final int offset, final int len) {
+ for (int i = offset + len - 1; i >= offset; i--) {
+ // do the harder check for non-whitespace.
+ final Content c = content.get(i);
+ switch (c.getCType()) {
+ case CDATA:
+ case Text:
+ // both return the text as getValue()
+ for (char ch : c.getValue().toCharArray()) {
+ if (!Verifier.isXMLWhitespace(ch)) {
+ return false;
+ }
+ }
+ break;
+ case EntityRef:
+ return false;
+ default:
+ throw new IllegalStateException(
+ "isWhiteSpace was given a " + c.getCType() +
+ " to check, which is illegal");
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Inspect the input String for whitespace characters.
+ *
+ * @param value
+ * The value to inspect
+ * @return true if all characters in the input value are all whitespace
+ */
+ protected boolean isAllWhitespace(final String value) {
+ for (char ch : value.toCharArray()) {
+ if (!Verifier.isXMLWhitespace(ch)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+}
diff --git a/core/src/java/org/jdom2/output/AbstractXMLOutputProcessor.java b/core/src/java/org/jdom2/output/AbstractXMLOutputProcessor.java
index 50fe208f6..9c9e9baeb 100644
--- a/core/src/java/org/jdom2/output/AbstractXMLOutputProcessor.java
+++ b/core/src/java/org/jdom2/output/AbstractXMLOutputProcessor.java
@@ -2,7 +2,6 @@
import java.io.IOException;
import java.io.Writer;
-import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
@@ -136,319 +135,7 @@ public abstract class AbstractXMLOutputProcessor implements XMLOutputProcessor {
/** Simple constant for a close-CDATA */
protected static final String CDATAPOST = "]]>";
- /**
- * FormatStack implements a mechanism where the formatting details can be
- * changed mid-tree, but then get reverted when that tree segment is
- * complete.
- *
- * @author rolf
- */
- protected static final class FormatStack {
-
- private int capacity = 16; // can grow if more than 16 levels in XML
- private int depth = 0; // current level in XML
-
- /*
- * ====================================================================
- * The following values cannot be changed mid-way through the output
- * ====================================================================
- */
-
- private final TextMode defaultMode; // the base/initial Text mode
-
- /** The default indent is no spaces (as original document) */
- private final String indent;
-
- /** The encoding format */
- private final String encoding;
-
- /** New line separator */
- private final String lineSeparator;
-
- /**
- * Whether or not to output the XML declaration - default is
- * <code>false</code>
- */
- private final boolean omitDeclaration;
-
- /**
- * Whether or not to output the encoding in the XML declaration -
- * default is <code>false</code>
- */
- private final boolean omitEncoding;
-
- /**
- * Whether or not to expand empty elements to
- * <tagName></tagName> - default is <code>false</code>
- */
- private final boolean expandEmptyElements;
-
- /** entity escape logic */
- private EscapeStrategy escapeStrategy;
-
- /*
- * ====================================================================
- * The following values can be changed mid-way through the output, hence
- * they are arrays.
- * ====================================================================
- */
-
- /** The 'current' accumulated indent */
- private String[] levelIndent = new String[capacity];
-
- /** The 'current' End-Of-Line */
- private String[] levelEOL = new String[capacity];
-
- /**
- * Whether TrAX output escaping disabling/enabling PIs are ignored or
- * processed - default is <code>false</code>
- */
- private boolean[] ignoreTrAXEscapingPIs = new boolean[capacity];
-
- /** text handling mode */
- private TextMode[] mode = new TextMode[capacity];
-
- /** escape Output logic - can be changed by */
- private boolean[] escapeOutput = new boolean[capacity];
-
- /**
- * Creates a new FormatStack seeded with the specified Format
- *
- * @param format
- * the Format instance to seed the stack with.
- */
- public FormatStack(Format format) {
- indent = format.getIndent();
- lineSeparator = format.getLineSeparator();
-
- encoding = format.getEncoding();
- omitDeclaration = format.getOmitDeclaration();
- omitEncoding = format.getOmitEncoding();
- expandEmptyElements = format.getExpandEmptyElements();
- escapeStrategy = format.getEscapeStrategy();
- defaultMode = format.getTextMode();
-
- levelIndent[depth] = format.getIndent() == null
- ? null : "";
- levelEOL[depth] = format.getIndent() == null
- ? null : format.getLineSeparator();
- ignoreTrAXEscapingPIs[depth] = format.getIgnoreTrAXEscapingPIs();
- mode[depth] = format.getTextMode();
- escapeOutput[depth] = true;
- }
-
- /**
- * @return the original {@link Format#getIndent()}, may be null
- */
- public String getIndent() {
- return indent;
- }
-
- /**
- * @return the original {@link Format#getLineSeparator()}
- */
- public String getLineSeparator() {
- return lineSeparator;
- }
-
- /**
- * @return the original {@link Format#getEncoding()}
- */
- public String getEncoding() {
- return encoding;
- }
-
- /**
- * @return the original {@link Format#getOmitDeclaration()}
- */
- public boolean isOmitDeclaration() {
- return omitDeclaration;
- }
-
- /**
- * @return the original {@link Format#getOmitEncoding()}
- */
- public boolean isOmitEncoding() {
- return omitEncoding;
- }
-
- /**
- * @return the original {@link Format#getExpandEmptyElements()}
- */
- public boolean isExpandEmptyElements() {
- return expandEmptyElements;
- }
-
- /**
- * @return the original {@link Format#getEscapeStrategy()}
- */
- public EscapeStrategy getEscapeStrategy() {
- return escapeStrategy;
- }
-
- /**
- * @return the current depth's {@link Format#getIgnoreTrAXEscapingPIs()}
- */
- public boolean isIgnoreTrAXEscapingPIs() {
- return ignoreTrAXEscapingPIs[depth];
- }
-
- /**
- * Set the current depth's {@link Format#getIgnoreTrAXEscapingPIs()}
- *
- * @param ignoreTrAXEscapingPIs
- * the boolean value to set.
- */
- public void setIgnoreTrAXEscapingPIs(boolean ignoreTrAXEscapingPIs) {
- this.ignoreTrAXEscapingPIs[depth] = ignoreTrAXEscapingPIs;
- }
-
- /**
- * The escapeOutput flag can be set or unset. When set, Element text and
- * Attribute values are 'escaped' so that the output is valid XML. When
- * unset, the Element text and Attribute values are not escaped.
- *
- * @return the current depth's escapeOutput flag.
- */
- public boolean getEscapeOutput() {
- return escapeOutput[depth];
- }
-
- /**
- * The escapeOutput flag can be set or unset. When set, Element text and
- * Attribute values are 'escaped' so that the output is valid XML. When
- * unset, the Element text and Attribute values are not escaped.
- *
- * @param escape
- * what to set the current level's escapeOutput flag to.
- */
- public void setEscapeOutput(boolean escape) {
- escapeOutput[depth] = escape;
- }
-
- /**
- * @return the TextMode that was originally set for this stack before
- * any modifications.
- */
- public TextMode getDefaultMode() {
- return defaultMode;
- }
-
- /**
- * @return the current depth's accumulated/maintained indent, may be
- * null
- */
- public String getLevelIndent() {
- return levelIndent[depth];
- }
-
- /**
- * Override the current depth's accumulated line indent.
- *
- * @param indent
- * the indent to set.
- */
- public void setLevelIndent(String indent) {
- this.levelIndent[depth] = indent;
- }
-
- /**
- * @return the current depth's End-Of-Line sequence, may be null
- */
- public String getLevelEOL() {
- return levelEOL[depth];
- }
-
- /**
- * Set the current depth's End-Of-Line sequence
- *
- * @param newline
- * the new End-Of-Line sequence to set.
- */
- public void setLevelEOL(String newline) {
- this.levelEOL[depth] = newline;
- }
-
- /**
- * @return the current depth's {@link Format#getTextMode()}
- */
- public TextMode getTextMode() {
- return mode[depth];
- }
-
- /**
- * Change the current level's TextMode
- *
- * @param mode
- * the new mode to set.
- */
- public void setTextMode(TextMode mode) {
- if (this.mode[depth] == mode) {
- return;
- }
- this.mode[depth] = mode;
- switch (mode) {
- case PRESERVE:
- levelEOL[depth] = null;
- levelIndent[depth] = null;
- break;
- default:
- levelEOL[depth] = lineSeparator;
- if (indent != null) {
- if (depth > 0) {
- if (levelIndent[depth - 1] == null) {
- StringBuilder sb = new StringBuilder(indent.length() * depth);
- for (int i = 0; i < depth; i++) {
- sb.append(indent);
- }
- levelIndent[depth] = sb.toString();
- } else {
- levelIndent[depth] = levelIndent[depth - 1] + indent;
- }
- } else {
- levelIndent[depth] = "";
- }
- }
- }
- }
-
- /**
- * Create a new depth level on the stack. The previous level's details
- * are copied to this level, and the accumulated indent (if any) is
- * indented further.
- */
- public void push() {
- final int prev = depth++;
- if (depth >= capacity) {
- capacity *= 2;
- levelIndent = Arrays.copyOf(levelIndent, capacity);
- levelEOL = Arrays.copyOf(levelEOL, capacity);
- ignoreTrAXEscapingPIs = Arrays.copyOf(ignoreTrAXEscapingPIs, capacity);
- mode = Arrays.copyOf(mode, capacity);
- escapeOutput = Arrays.copyOf(escapeOutput, capacity);
- }
- levelIndent[depth] = indent == null
- ? null
- : (levelIndent[prev] + indent);
- levelEOL[depth] = indent == null
- ? null : lineSeparator;
- ignoreTrAXEscapingPIs[depth] = ignoreTrAXEscapingPIs[prev];
- mode[depth] = mode[prev];
- escapeOutput[depth] = escapeOutput[prev];
- }
-
- /**
- * Move back a level on the stack.
- */
- public void pop() {
- // no need to clear previously used members in the stack.
- // the stack is short-lived, and does not create new instances for
- // the depth levels, in other words, it does not affect GC and does
- // not save memory to clear the stack.
- depth--;
- }
-
- }
+
/* *******************************************
* XMLOutputProcessor implementation.
diff --git a/core/src/java/org/jdom2/output/FormatStack.java b/core/src/java/org/jdom2/output/FormatStack.java
new file mode 100644
index 000000000..c38d1e413
--- /dev/null
+++ b/core/src/java/org/jdom2/output/FormatStack.java
@@ -0,0 +1,327 @@
+package org.jdom2.output;
+
+import java.util.Arrays;
+
+import org.jdom2.output.Format.TextMode;
+
+/**
+ * FormatStack implements a mechanism where the formatting details can be
+ * changed mid-tree, but then get reverted when that tree segment is
+ * complete.
+ * <p>
+ * This class is intended as a working-class for in the various outputter
+ * implementations. It is inly public so that people extending the
+ * Abstract*Processor classes can take advantage of it's functionality.
+ * <p>
+ * The value this class adds is:
+ * <ul>
+ * <li>Fast -
+ * </ul>
+ *
+ * @author Rolf Lear
+ */
+public final class FormatStack {
+
+ private int capacity = 16; // can grow if more than 16 levels in XML
+ private int depth = 0; // current level in XML
+
+ /*
+ * ====================================================================
+ * The following values cannot be changed mid-way through the output
+ * ====================================================================
+ */
+
+ private final TextMode defaultMode; // the base/initial Text mode
+
+ /** The default indent is no spaces (as original document) */
+ private final String indent;
+
+ /** The encoding format */
+ private final String encoding;
+
+ /** New line separator */
+ private final String lineSeparator;
+
+ /**
+ * Whether or not to output the XML declaration - default is
+ * <code>false</code>
+ */
+ private final boolean omitDeclaration;
+
+ /**
+ * Whether or not to output the encoding in the XML declaration -
+ * default is <code>false</code>
+ */
+ private final boolean omitEncoding;
+
+ /**
+ * Whether or not to expand empty elements to
+ * <tagName></tagName> - default is <code>false</code>
+ */
+ private final boolean expandEmptyElements;
+
+ /** entity escape logic */
+ private EscapeStrategy escapeStrategy;
+
+ /*
+ * ====================================================================
+ * The following values can be changed mid-way through the output, hence
+ * they are arrays.
+ * ====================================================================
+ */
+
+ /** The 'current' accumulated indent */
+ private String[] levelIndent = new String[capacity];
+
+ /** The 'current' End-Of-Line */
+ private String[] levelEOL = new String[capacity];
+
+ /**
+ * Whether TrAX output escaping disabling/enabling PIs are ignored or
+ * processed - default is <code>false</code>
+ */
+ private boolean[] ignoreTrAXEscapingPIs = new boolean[capacity];
+
+ /** text handling mode */
+ private TextMode[] mode = new TextMode[capacity];
+
+ /** escape Output logic - can be changed by */
+ private boolean[] escapeOutput = new boolean[capacity];
+
+ /**
+ * Creates a new FormatStack seeded with the specified Format
+ *
+ * @param format
+ * the Format instance to seed the stack with.
+ */
+ public FormatStack(Format format) {
+ indent = format.getIndent();
+ lineSeparator = format.getLineSeparator();
+
+ encoding = format.getEncoding();
+ omitDeclaration = format.getOmitDeclaration();
+ omitEncoding = format.getOmitEncoding();
+ expandEmptyElements = format.getExpandEmptyElements();
+ escapeStrategy = format.getEscapeStrategy();
+ defaultMode = format.getTextMode();
+
+ levelIndent[depth] = format.getIndent() == null
+ ? null : "";
+ levelEOL[depth] = format.getIndent() == null
+ ? null : format.getLineSeparator();
+ ignoreTrAXEscapingPIs[depth] = format.getIgnoreTrAXEscapingPIs();
+ mode[depth] = format.getTextMode();
+ escapeOutput[depth] = true;
+ }
+
+ /**
+ * @return the original {@link Format#getIndent()}, may be null
+ */
+ public String getIndent() {
+ return indent;
+ }
+
+ /**
+ * @return the original {@link Format#getLineSeparator()}
+ */
+ public String getLineSeparator() {
+ return lineSeparator;
+ }
+
+ /**
+ * @return the original {@link Format#getEncoding()}
+ */
+ public String getEncoding() {
+ return encoding;
+ }
+
+ /**
+ * @return the original {@link Format#getOmitDeclaration()}
+ */
+ public boolean isOmitDeclaration() {
+ return omitDeclaration;
+ }
+
+ /**
+ * @return the original {@link Format#getOmitEncoding()}
+ */
+ public boolean isOmitEncoding() {
+ return omitEncoding;
+ }
+
+ /**
+ * @return the original {@link Format#getExpandEmptyElements()}
+ */
+ public boolean isExpandEmptyElements() {
+ return expandEmptyElements;
+ }
+
+ /**
+ * @return the original {@link Format#getEscapeStrategy()}
+ */
+ public EscapeStrategy getEscapeStrategy() {
+ return escapeStrategy;
+ }
+
+ /**
+ * @return the current depth's {@link Format#getIgnoreTrAXEscapingPIs()}
+ */
+ public boolean isIgnoreTrAXEscapingPIs() {
+ return ignoreTrAXEscapingPIs[depth];
+ }
+
+ /**
+ * Set the current depth's {@link Format#getIgnoreTrAXEscapingPIs()}
+ *
+ * @param ignoreTrAXEscapingPIs
+ * the boolean value to set.
+ */
+ public void setIgnoreTrAXEscapingPIs(boolean ignoreTrAXEscapingPIs) {
+ this.ignoreTrAXEscapingPIs[depth] = ignoreTrAXEscapingPIs;
+ }
+
+ /**
+ * The escapeOutput flag can be set or unset. When set, Element text and
+ * Attribute values are 'escaped' so that the output is valid XML. When
+ * unset, the Element text and Attribute values are not escaped.
+ *
+ * @return the current depth's escapeOutput flag.
+ */
+ public boolean getEscapeOutput() {
+ return escapeOutput[depth];
+ }
+
+ /**
+ * The escapeOutput flag can be set or unset. When set, Element text and
+ * Attribute values are 'escaped' so that the output is valid XML. When
+ * unset, the Element text and Attribute values are not escaped.
+ *
+ * @param escape
+ * what to set the current level's escapeOutput flag to.
+ */
+ public void setEscapeOutput(boolean escape) {
+ escapeOutput[depth] = escape;
+ }
+
+ /**
+ * @return the TextMode that was originally set for this stack before
+ * any modifications.
+ */
+ public TextMode getDefaultMode() {
+ return defaultMode;
+ }
+
+ /**
+ * @return the current depth's accumulated/maintained indent, may be null
+ */
+ public String getLevelIndent() {
+ return levelIndent[depth];
+ }
+
+ /**
+ * Override the current depth's accumulated line indent.
+ *
+ * @param indent
+ * the indent to set.
+ */
+ public void setLevelIndent(String indent) {
+ this.levelIndent[depth] = indent;
+ }
+
+ /**
+ * @return the current depth's End-Of-Line sequence, may be null
+ */
+ public String getLevelEOL() {
+ return levelEOL[depth];
+ }
+
+ /**
+ * Set the current depth's End-Of-Line sequence
+ *
+ * @param newline
+ * the new End-Of-Line sequence to set.
+ */
+ public void setLevelEOL(String newline) {
+ this.levelEOL[depth] = newline;
+ }
+
+ /**
+ * @return the current depth's {@link Format#getTextMode()}
+ */
+ public TextMode getTextMode() {
+ return mode[depth];
+ }
+
+ /**
+ * Change the current level's TextMode
+ *
+ * @param mode
+ * the new mode to set.
+ */
+ public void setTextMode(TextMode mode) {
+ if (this.mode[depth] == mode) {
+ return;
+ }
+ this.mode[depth] = mode;
+ switch (mode) {
+ case PRESERVE:
+ levelEOL[depth] = null;
+ levelIndent[depth] = null;
+ break;
+ default:
+ levelEOL[depth] = lineSeparator;
+ if (indent != null) {
+ if (depth > 0) {
+ if (levelIndent[depth - 1] == null) {
+ StringBuilder sb = new StringBuilder(indent.length() * depth);
+ for (int i = 0; i < depth; i++) {
+ sb.append(indent);
+ }
+ levelIndent[depth] = sb.toString();
+ } else {
+ levelIndent[depth] = levelIndent[depth - 1] + indent;
+ }
+ } else {
+ levelIndent[depth] = "";
+ }
+ }
+ }
+ }
+
+ /**
+ * Create a new depth level on the stack. The previous level's details
+ * are copied to this level, and the accumulated indent (if any) is
+ * indented further.
+ */
+ public void push() {
+ final int prev = depth++;
+ if (depth >= capacity) {
+ capacity *= 2;
+ levelIndent = Arrays.copyOf(levelIndent, capacity);
+ levelEOL = Arrays.copyOf(levelEOL, capacity);
+ ignoreTrAXEscapingPIs = Arrays.copyOf(ignoreTrAXEscapingPIs, capacity);
+ mode = Arrays.copyOf(mode, capacity);
+ escapeOutput = Arrays.copyOf(escapeOutput, capacity);
+ }
+ levelIndent[depth] = indent == null
+ ? null
+ : (levelIndent[prev] + indent);
+ levelEOL[depth] = indent == null
+ ? null : lineSeparator;
+ ignoreTrAXEscapingPIs[depth] = ignoreTrAXEscapingPIs[prev];
+ mode[depth] = mode[prev];
+ escapeOutput[depth] = escapeOutput[prev];
+ }
+
+ /**
+ * Move back a level on the stack.
+ */
+ public void pop() {
+ // no need to clear previously used members in the stack.
+ // the stack is short-lived, and does not create new instances for
+ // the depth levels, in other words, it does not affect GC and does
+ // not save memory to clear the stack.
+ depth--;
+ }
+
+}
\ No newline at end of file
diff --git a/core/src/java/org/jdom2/output/StAXEventOutputter.java b/core/src/java/org/jdom2/output/StAXEventOutputter.java
new file mode 100644
index 000000000..191a43d31
--- /dev/null
+++ b/core/src/java/org/jdom2/output/StAXEventOutputter.java
@@ -0,0 +1,575 @@
+/*--
+
+ Copyright (C) 2000-2007 Jason Hunter & Brett McLaughlin.
+ 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 disclaimer that follows
+ these conditions in the documentation and/or other materials
+ provided with the distribution.
+
+ 3. The name "JDOM" must not be used to endorse or promote products
+ derived from this software without prior written permission. For
+ written permission, please contact <request_AT_jdom_DOT_org>.
+
+ 4. Products derived from this software may not be called "JDOM", nor
+ may "JDOM" appear in their name, without prior written permission
+ from the JDOM Project Management <request_AT_jdom_DOT_org>.
+
+ In addition, we request (but do not require) that you include in the
+ end-user documentation provided with the redistribution and/or in the
+ software itself an acknowledgement equivalent to the following:
+ "This product includes software developed by the
+ JDOM Project (http://www.jdom.org/)."
+ Alternatively, the acknowledgment may be graphical using the logos
+ available at http://www.jdom.org/images/logos.
+
+ 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 JDOM AUTHORS OR THE PROJECT
+ 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 JDOM Project and was originally
+ created by Jason Hunter <jhunter_AT_jdom_DOT_org> and
+ Brett McLaughlin <brett_AT_jdom_DOT_org>. For more information
+ on the JDOM Project, please see <http://www.jdom.org/>.
+
+ */
+
+package org.jdom2.output;
+
+import java.util.List;
+
+import javax.xml.stream.XMLEventFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.util.XMLEventConsumer;
+
+import org.jdom2.Attribute;
+import org.jdom2.CDATA;
+import org.jdom2.Comment;
+import org.jdom2.Content;
+import org.jdom2.DocType;
+import org.jdom2.Document;
+import org.jdom2.Element;
+import org.jdom2.EntityRef;
+import org.jdom2.ProcessingInstruction;
+import org.jdom2.Text;
+
+/**
+ * Outputs a JDOM document as a StAX XMLEventConsumer of bytes.
+ * <p>
+ * The StAXStreamOutputter can manage many styles of document formatting, from
+ * untouched to 'pretty' printed. The default is to output the document content
+ * exactly as created, but this can be changed by setting a new Format object:
+ * <ul>
+ * <li>For pretty-print output, use
+ * <code>{@link Format#getPrettyFormat()}</code>.
+ * <li>For whitespace-normalised output, use
+ * <code>{@link Format#getCompactFormat()}</code>.
+ * <li>For unmodified-format output, use
+ * <code>{@link Format#getRawFormat()}</code>.
+ * </ul>
+ * <p>
+ * <b>All</b> of the <code>output*(...)</code> methods will flush the
+ * destination XMLEventConsumer before returning, and <b>none</b> of them
+ * will <code>close()</code> the destination.
+ * <p>
+ * To omit output of the declaration use
+ * <code>{@link Format#setOmitDeclaration}</code>. To omit printing of the
+ * encoding in the declaration use <code>{@link Format#setOmitEncoding}</code>.
+ * <p>
+ * If changing the {@link Format} settings are insufficient for your output
+ * needs you can customise this StAXStreamOutputter further by setting a different
+ * {@link StAXEventProcessor} with the
+ * {@link #setStAXEventProcessor(StAXEventProcessor)} method or an appropriate
+ * constructor. A fully-enabled Abstract class
+ * {@link AbstractStAXEventProcessor} is available to be further extended to
+ * your needs if all you want to do is tweak some details.
+ *
+ * @author Rolf Lear
+ */
+
+public final class StAXEventOutputter implements Cloneable {
+
+ /*
+ * =====================================================================
+ * Static content.
+ * =====================================================================
+ */
+
+ /**
+ * Create a final and static instance of the AbstractStAXEventProcessor The
+ * final part is important because it improves performance.
+ * <p>
+ * The JDOM user can change the actual XMLOutputProcessor with the
+ * {@link StAXEventOutputter#setStAXEventProcessor(StAXEventProcessor)} method.
+ *
+ * @author rolf
+ */
+ private static final class DefaultStAXEventProcessor
+ extends AbstractStAXEventProcessor {
+ // nothing
+ }
+
+ /**
+ * This constant StAXEventProcessor is used for all non-customised
+ * StAXStreamOutputters
+ */
+ private static final DefaultStAXEventProcessor DEFAULTPROCESSOR =
+ new DefaultStAXEventProcessor();
+
+ /**
+ * This constant StAXEventProcessor is used for all non-customised
+ * StAXStreamOutputters
+ */
+ private static final XMLEventFactory DEFAULTEVENTFACTORY =
+ XMLEventFactory.newInstance();
+
+ /*
+ * =====================================================================
+ * Instance content.
+ * =====================================================================
+ */
+
+ // For normal output
+ private Format myFormat = null;
+
+ // The actual StAXEventProcessor to delegate to.
+ private StAXEventProcessor myProcessor = null;
+
+ private XMLEventFactory myEventFactory = null;
+
+ /*
+ * =====================================================================
+ * Constructors
+ * =====================================================================
+ */
+
+ /**
+ * This will create an <code>StAXStreamOutputter</code> with the specified format
+ * characteristics.
+ * <p>
+ * <b>Note:</b> the format object is cloned internally before use. If you
+ * want to modify the Format after constructing the StAXStreamOutputter you can
+ * modify the Format instance {@link #getFormat()} returns.
+ *
+ * @param format
+ * The Format instance to use. This instance will be cloned() and as
+ * a consequence, changes made to the specified format instance
+ * <b>will not</b> be reflected in this StAXStreamOutputter. A null input
+ * format indicates that StAXStreamOutputter should use the default
+ * {@link Format#getRawFormat()}
+ * @param processor
+ * The XMLOutputProcessor to delegate output to. If null the
+ * StAXStreamOutputter will use the default XMLOutputProcessor.
+ * @param eventfactory
+ * The factory to use to create XMLEvent instances.
+ */
+ public StAXEventOutputter(Format format, StAXEventProcessor processor, XMLEventFactory eventfactory) {
+ myFormat = format == null ? Format.getRawFormat() : format.clone();
+ myProcessor = processor == null ? DEFAULTPROCESSOR : processor;
+ myEventFactory = eventfactory == null ? DEFAULTEVENTFACTORY : eventfactory;
+ }
+
+ /**
+ * This will create an <code>StAXStreamOutputter</code> with a default
+ * {@link Format} and {@link XMLOutputProcessor}.
+ */
+ public StAXEventOutputter() {
+ this(null, null, null);
+ }
+
+ /**
+ * This will create an <code>StAXStreamOutputter</code> with the specified format
+ * characteristics.
+ * <p>
+ * <b>Note:</b> the format object is cloned internally before use.
+ *
+ * @param format
+ * The Format instance to use. This instance will be cloned() and as
+ * a consequence, changes made to the specified format instance
+ * <b>will not</b> be reflected in this StAXStreamOutputter. A null input
+ * format indicates that StAXStreamOutputter should use the default
+ * {@link Format#getRawFormat()}
+ */
+ public StAXEventOutputter(Format format) {
+ this(format, null, null);
+ }
+
+ /**
+ * This will create an <code>StAXStreamOutputter</code> with the specified
+ * XMLOutputProcessor.
+ *
+ * @param processor
+ * The XMLOutputProcessor to delegate output to. If null the
+ * StAXStreamOutputter will use the default XMLOutputProcessor.
+ */
+ public StAXEventOutputter(StAXEventProcessor processor) {
+ this(null, processor, null);
+ }
+
+ /**
+ * This will create an <code>StAXStreamOutputter</code> with the specified
+ * XMLOutputProcessor.
+ *
+ * @param eventfactory
+ * The XMLEventFactory to use to create XMLEvent instances.
+ */
+ public StAXEventOutputter(XMLEventFactory eventfactory) {
+ this(null, null, eventfactory);
+ }
+
+ /*
+ * =======================================================================
+ * API - Settings...
+ * =======================================================================
+ */
+
+ /**
+ * Sets the new format logic for the StAXStreamOutputter. Note the Format object is
+ * cloned internally before use.
+ *
+ * @see #getFormat()
+ * @param newFormat
+ * the format to use for subsequent output
+ */
+ public void setFormat(Format newFormat) {
+ this.myFormat = newFormat.clone();
+ }
+
+ /**
+ * Returns the current format in use by the StAXStreamOutputter. Note the Format
+ * object returned is <b>not</b> a clone of the one used internally, thus,
+ * an StAXStreamOutputter instance is able to have it's Format changed by changing
+ * the settings on the Format instance returned by this method.
+ *
+ * @return the current Format instance used by this StAXStreamOutputter.
+ */
+ public Format getFormat() {
+ return myFormat;
+ }
+
+ /**
+ * Returns the current XMLOutputProcessor instance in use by the
+ * StAXStreamOutputter.
+ *
+ * @return the current XMLOutputProcessor instance.
+ */
+ public StAXEventProcessor getStAXStream() {
+ return myProcessor;
+ }
+
+ /**
+ * Sets a new XMLOutputProcessor instance for this StAXStreamOutputter. Note the
+ * processor object is expected to be thread-safe.
+ *
+ * @param processor
+ * the new XMLOutputProcesor to use for output
+ */
+ public void setStAXEventProcessor(StAXEventProcessor processor) {
+ this.myProcessor = processor;
+ }
+
+
+
+ /**
+ * @return the current XMLEventFactory used by this StAXEventOutputter
+ */
+ public XMLEventFactory getEventFactory() {
+ return myEventFactory;
+ }
+
+ /**
+ * @param myEventFactory the XMLEventFactory to use for subsequent output.
+ */
+ public void setEventFactory(XMLEventFactory myEventFactory) {
+ this.myEventFactory = myEventFactory;
+ }
+
+ /*
+ * ========================================================================
+ * API - Output to XMLEventConsumer Methods ... These are the core methods that the
+ * Stream and String output methods call. On the other hand, these methods
+ * defer to the protected/override methods. These methods flush the writer.
+ * ========================================================================
+ */
+
+ /**
+ * This will print the <code>Document</code> to the given Writer.
+ * <p>
+ * Warning: using your own Writer may cause the outputter's preferred
+ * character encoding to be ignored. If you use encodings other than UTF-8,
+ * we recommend using the method that takes an OutputStream instead.
+ * </p>
+ *
+ * @param doc
+ * <code>Document</code> to format.
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @throws XMLStreamException
+ * - if there's any problem writing.
+ * @throws NullPointerException
+ * if the specified content is null.
+ */
+ public final void output(Document doc, XMLEventConsumer out) throws XMLStreamException {
+ myProcessor.process(out, myFormat, myEventFactory, doc);
+ //out.flush();
+ }
+
+ /**
+ * Print out the <code>{@link DocType}</code>.
+ *
+ * @param doctype
+ * <code>DocType</code> to output.
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @throws XMLStreamException
+ * - if there's any problem writing.
+ * @throws NullPointerException
+ * if the specified content is null.
+ */
+ public final void output(DocType doctype, XMLEventConsumer out) throws XMLStreamException {
+ myProcessor.process(out, myFormat, myEventFactory, doctype);
+ //out.flush();
+ }
+
+ /**
+ * Print out an <code>{@link Element}</code>, including its
+ * <code>{@link Attribute}</code>s, and all contained (child) elements, etc.
+ *
+ * @param element
+ * <code>Element</code> to output.
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @throws XMLStreamException
+ * - if there's any problem writing.
+ * @throws NullPointerException
+ * if the specified content is null.
+ */
+ public final void output(Element element, XMLEventConsumer out) throws XMLStreamException {
+ // If this is the root element we could pre-initialize the
+ // namespace stack with the namespaces
+ myProcessor.process(out, myFormat, myEventFactory, element);
+ //out.flush();
+ }
+
+ /**
+ * This will handle printing out an <code>{@link
+ * Element}</code>'s content only, not including its tag, and attributes.
+ * This can be useful for printing the content of an element that contains
+ * HTML, like "<description>JDOM is
+ * <b>fun>!</description>".
+ *
+ * @param element
+ * <code>Element</code> to output.
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @throws XMLStreamException
+ * - if there's any problem writing.
+ * @throws NullPointerException
+ * if the specified content is null.
+ */
+ public final void outputElementContent(Element element, XMLEventConsumer out)
+ throws XMLStreamException {
+ myProcessor.process(out, myFormat, myEventFactory, element.getContent());
+ //out.flush();
+ }
+
+ /**
+ * This will handle printing out a list of nodes. This can be useful for
+ * printing the content of an element that contains HTML, like
+ * "<description>JDOM is <b>fun>!</description>".
+ *
+ * @param list
+ * <code>List</code> of nodes.
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @throws XMLStreamException
+ * - if there's any problem writing.
+ * @throws NullPointerException
+ * if the specified content is null.
+ */
+ public final void output(List<? extends Content> list, XMLEventConsumer out)
+ throws XMLStreamException {
+ myProcessor.process(out, myFormat, myEventFactory, list);
+ //out.flush();
+ }
+
+ /**
+ * Print out a <code>{@link CDATA}</code> node.
+ *
+ * @param cdata
+ * <code>CDATA</code> to output.
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @throws XMLStreamException
+ * - if there's any problem writing.
+ * @throws NullPointerException
+ * if the specified content is null.
+ */
+ public final void output(CDATA cdata, XMLEventConsumer out) throws XMLStreamException {
+ myProcessor.process(out, myFormat, myEventFactory, cdata);
+ //out.flush();
+ }
+
+ /**
+ * Print out a <code>{@link Text}</code> node. Perfoms the necessary entity
+ * escaping and whitespace stripping.
+ *
+ * @param text
+ * <code>Text</code> to output.
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @throws XMLStreamException
+ * - if there's any problem writing.
+ * @throws NullPointerException
+ * if the specified content is null.
+ */
+ public final void output(Text text, XMLEventConsumer out) throws XMLStreamException {
+ myProcessor.process(out, myFormat, myEventFactory, text);
+ //out.flush();
+ }
+
+ /**
+ * Print out a <code>{@link Comment}</code>.
+ *
+ * @param comment
+ * <code>Comment</code> to output.
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @throws XMLStreamException
+ * - if there's any problem writing.
+ * @throws NullPointerException
+ * if the specified content is null.
+ */
+ public final void output(Comment comment, XMLEventConsumer out) throws XMLStreamException {
+ myProcessor.process(out, myFormat, myEventFactory, comment);
+ //out.flush();
+ }
+
+ /**
+ * Print out a <code>{@link ProcessingInstruction}</code>.
+ *
+ * @param pi
+ * <code>ProcessingInstruction</code> to output.
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @throws XMLStreamException
+ * - if there's any problem writing.
+ * @throws NullPointerException
+ * if the specified content is null.
+ */
+ public final void output(ProcessingInstruction pi, XMLEventConsumer out)
+ throws XMLStreamException {
+ myProcessor.process(out, myFormat, myEventFactory, pi);
+ //out.flush();
+ }
+
+ /**
+ * Print out an <code>{@link EntityRef}</code>.
+ *
+ * @param entity
+ * <code>EntityRef</code> to output.
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @throws XMLStreamException
+ * - if there's any problem writing.
+ * @throws NullPointerException
+ * if the specified content is null.
+ */
+ public final void output(EntityRef entity, XMLEventConsumer out) throws XMLStreamException {
+ myProcessor.process(out, myFormat, myEventFactory, entity);
+ //out.flush();
+ }
+
+ /*
+ * ========================================================================
+ * Basic Support methods.
+ * ========================================================================
+ */
+
+ /**
+ * Returns a cloned copy of this StAXStreamOutputter.
+ */
+ @Override
+ public StAXEventOutputter clone() {
+ // Implementation notes: Since all state of an StAXStreamOutputter is
+ // embodied in simple private instance variables, Object.clone
+ // can be used. Note that since Object.clone is totally
+ // broken, we must catch an exception that will never be
+ // thrown.
+ try {
+ return (StAXEventOutputter) super.clone();
+ } catch (java.lang.CloneNotSupportedException e) {
+ // even though this should never ever happen, it's still
+ // possible to fool Java into throwing a
+ // CloneNotSupportedException. If that happens, we
+ // shouldn't swallow it.
+ throw new RuntimeException(e.toString());
+ }
+ }
+
+ /**
+ * Return a string listing of the settings for this StAXStreamOutputter instance.
+ *
+ * @return a string listing the settings for this StAXStreamOutputter instance
+ */
+ @Override
+ public String toString() {
+ StringBuilder buffer = new StringBuilder();
+ buffer.append("StAXStreamOutputter[omitDeclaration = ");
+ buffer.append(myFormat.omitDeclaration);
+ buffer.append(", ");
+ buffer.append("encoding = ");
+ buffer.append(myFormat.encoding);
+ buffer.append(", ");
+ buffer.append("omitEncoding = ");
+ buffer.append(myFormat.omitEncoding);
+ buffer.append(", ");
+ buffer.append("indent = '");
+ buffer.append(myFormat.indent);
+ buffer.append("'");
+ buffer.append(", ");
+ buffer.append("expandEmptyElements = ");
+ buffer.append(myFormat.expandEmptyElements);
+ buffer.append(", ");
+ buffer.append("lineSeparator = '");
+ for (char ch : myFormat.lineSeparator.toCharArray()) {
+ switch (ch) {
+ case '\r':
+ buffer.append("\\r");
+ break;
+ case '\n':
+ buffer.append("\\n");
+ break;
+ case '\t':
+ buffer.append("\\t");
+ break;
+ default:
+ buffer.append("[" + ((int) ch) + "]");
+ break;
+ }
+ }
+ buffer.append("', ");
+ buffer.append("textMode = ");
+ buffer.append(myFormat.mode + "]");
+ return buffer.toString();
+ }
+
+}
diff --git a/core/src/java/org/jdom2/output/StAXEventProcessor.java b/core/src/java/org/jdom2/output/StAXEventProcessor.java
new file mode 100644
index 000000000..ea2e3c0dd
--- /dev/null
+++ b/core/src/java/org/jdom2/output/StAXEventProcessor.java
@@ -0,0 +1,222 @@
+package org.jdom2.output;
+
+import java.util.List;
+
+import javax.xml.stream.XMLEventFactory;
+import javax.xml.stream.util.XMLEventConsumer;
+import javax.xml.stream.XMLStreamException;
+
+import org.jdom2.Attribute;
+import org.jdom2.CDATA;
+import org.jdom2.Comment;
+import org.jdom2.Content;
+import org.jdom2.DocType;
+import org.jdom2.Document;
+import org.jdom2.Element;
+import org.jdom2.EntityRef;
+import org.jdom2.ProcessingInstruction;
+import org.jdom2.Text;
+
+/**
+ * This interface provides a base support for the {@link XMLOutputter}.
+ * <p>
+ * People who want to create a custom XMLOutputProcessor for XMLOutputter are
+ * able to implement this interface with the following notes and restrictions:
+ * <ol>
+ * <li>The XMLOutputter will call one, and only one of the <code>process(XMLEventConsumer,Format,*)</code> methods each
+ * time the XMLOutputter is requested to output some JDOM content. It is thus
+ * safe to assume that a <code>process(XMLEventConsumer,Format,*)</code> method can set up any
+ * infrastructure needed to process the content, and that the XMLOutputter will
+ * not re-call that method, or some other <code>process(XMLEventConsumer,Format,*)</code> method for the same output
+ * sequence.
+ * <li>The process methods should be thread-safe and reentrant: The same
+ * <code>process(XMLEventConsumer,Format,*)</code> method may (will) be called concurrently from different threads.
+ * </ol>
+ * <p>
+ * The {@link AbstractXMLOutputProcessor} class is a full implementation of this
+ * interface and is fully customisable. People who want a custom XMLOutputter
+ * are encouraged to extend the AbstractXMLOutputProcessor rather than do a full
+ * re-implementation of this interface.
+ *
+ * @see XMLOutputter
+ * @see AbstractXMLOutputProcessor
+ * @author Rolf Lear
+ */
+public interface StAXEventProcessor {
+
+ /**
+ * This will print the <code>{@link Document}</code> to the given XMLEventConsumer.
+ * <p>
+ * Warning: using your own XMLEventConsumer may cause the outputter's preferred
+ * character encoding to be ignored. If you use encodings other than UTF-8,
+ * we recommend using the method that takes an OutputStream instead.
+ * </p>
+ *
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @param format
+ * <code>Format</code> instance specifying output style
+ * @param eventfactory
+ * <code>XMLEventFactory</code> for creating XMLEvent instances.
+ * @param doc
+ * <code>Document</code> to format.
+ * @throws XMLStreamException
+ * if there's any problem writing.
+ * @throws NullPointerException
+ * if the input content is null
+ */
+ public abstract void process(XMLEventConsumer out, Format format, XMLEventFactory eventfactory, Document doc) throws XMLStreamException;
+
+ /**
+ * Print out the <code>{@link DocType}</code>.
+ *
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @param format
+ * <code>Format</code> instance specifying output style
+ * @param eventfactory
+ * <code>XMLEventFactory</code> for creating XMLEvent instances.
+ * @param doctype
+ * <code>DocType</code> to output.
+ * @throws XMLStreamException
+ * if there's any problem writing.
+ * @throws NullPointerException
+ * if the input content is null
+ */
+ public abstract void process(XMLEventConsumer out, Format format, XMLEventFactory eventfactory, DocType doctype) throws XMLStreamException;
+
+ /**
+ * Print out an <code>{@link Element}</code>, including its
+ * <code>{@link Attribute}</code>s, and all contained (child) elements, etc.
+ *
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @param format
+ * <code>Format</code> instance specifying output style
+ * @param eventfactory
+ * <code>XMLEventFactory</code> for creating XMLEvent instances.
+ * @param element
+ * <code>Element</code> to output.
+ * @throws XMLStreamException
+ * if there's any problem writing.
+ * @throws NullPointerException
+ * if the input content is null
+ */
+ public abstract void process(XMLEventConsumer out, Format format, XMLEventFactory eventfactory, Element element) throws XMLStreamException;
+
+ /**
+ * This will handle printing out a list of nodes. This can be useful for
+ * printing the content of an element that contains HTML, like
+ * "<description>JDOM is <b>fun>!</description>".
+ *
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @param format
+ * <code>Format</code> instance specifying output style
+ * @param eventfactory
+ * <code>XMLEventFactory</code> for creating XMLEvent instances.
+ * @param list
+ * <code>List</code> of nodes.
+ * @throws XMLStreamException
+ * if there's any problem writing.
+ * @throws NullPointerException
+ * if the input list is null or contains null members
+ * @throws ClassCastException
+ * if any of the list members are not {@link Content}
+ */
+ public abstract void process(XMLEventConsumer out, Format format, XMLEventFactory eventfactory, List<? extends Content> list)
+ throws XMLStreamException;
+
+ /**
+ * Print out a <code>{@link CDATA}</code> node.
+ *
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @param format
+ * <code>Format</code> instance specifying output style
+ * @param eventfactpry
+ * <code>XMLEventFactory</code> for creating XMLEvent instances.
+ * @param cdata
+ * <code>CDATA</code> to output.
+ * @throws XMLStreamException
+ * if there's any problem writing.
+ * @throws NullPointerException
+ * if the input content is null
+ */
+ public abstract void process(XMLEventConsumer out, Format format, XMLEventFactory eventfactpry, CDATA cdata) throws XMLStreamException;
+
+ /**
+ * Print out a <code>{@link Text}</code> node. Performs the necessary entity
+ * escaping and whitespace stripping.
+ *
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @param format
+ * <code>Format</code> instance specifying output style
+ * @param eventfactory
+ * <code>XMLEventFactory</code> for creating XMLEvent instances.
+ * @param text
+ * <code>Text</code> to output.
+ * @throws XMLStreamException
+ * if there's any problem writing.
+ * @throws NullPointerException
+ * if the input content is null
+ */
+ public abstract void process(XMLEventConsumer out, Format format, XMLEventFactory eventfactory, Text text) throws XMLStreamException;
+
+ /**
+ * Print out a <code>{@link Comment}</code>.
+ *
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @param format
+ * <code>Format</code> instance specifying output style
+ * @param eventfactory
+ * <code>XMLEventFactory</code> for creating XMLEvent instances.
+ * @param comment
+ * <code>Comment</code> to output.
+ * @throws XMLStreamException
+ * if there's any problem writing.
+ * @throws NullPointerException
+ * if the input content is null
+ */
+ public abstract void process(XMLEventConsumer out, Format format, XMLEventFactory eventfactory, Comment comment) throws XMLStreamException;
+
+ /**
+ * Print out a <code>{@link ProcessingInstruction}</code>.
+ *
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @param format
+ * <code>Format</code> instance specifying output style
+ * @param eventfactory
+ * <code>XMLEventFactory</code> for creating XMLEvent instances.
+ * @param pi
+ * <code>ProcessingInstruction</code> to output.
+ * @throws XMLStreamException
+ * if there's any problem writing.
+ * @throws NullPointerException
+ * if the input content is null
+ */
+ public abstract void process(XMLEventConsumer out, Format format, XMLEventFactory eventfactory, ProcessingInstruction pi)
+ throws XMLStreamException;
+
+ /**
+ * Print out a <code>{@link EntityRef}</code>.
+ *
+ * @param out
+ * <code>XMLEventConsumer</code> to use.
+ * @param format
+ * <code>Format</code> instance specifying output style
+ * @param eventfactory
+ * <code>XMLEventFactory</code> for creating XMLEvent instances.
+ * @param entity
+ * <code>EntityRef</code> to output.
+ * @throws XMLStreamException
+ * if there's any problem writing.
+ * @throws NullPointerException
+ * if the input content is null
+ */
+ public abstract void process(XMLEventConsumer out, Format format, XMLEventFactory eventfactory, EntityRef entity) throws XMLStreamException;
+
+}
\ No newline at end of file
diff --git a/core/src/java/org/jdom2/output/StAXStreamOutputter.java b/core/src/java/org/jdom2/output/StAXStreamOutputter.java
new file mode 100644
index 000000000..9d222f6cc
--- /dev/null
+++ b/core/src/java/org/jdom2/output/StAXStreamOutputter.java
@@ -0,0 +1,535 @@
+/*--
+
+ Copyright (C) 2000-2007 Jason Hunter & Brett McLaughlin.
+ 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 disclaimer that follows
+ these conditions in the documentation and/or other materials
+ provided with the distribution.
+
+ 3. The name "JDOM" must not be used to endorse or promote products
+ derived from this software without prior written permission. For
+ written permission, please contact <request_AT_jdom_DOT_org>.
+
+ 4. Products derived from this software may not be called "JDOM", nor
+ may "JDOM" appear in their name, without prior written permission
+ from the JDOM Project Management <request_AT_jdom_DOT_org>.
+
+ In addition, we request (but do not require) that you include in the
+ end-user documentation provided with the redistribution and/or in the
+ software itself an acknowledgement equivalent to the following:
+ "This product includes software developed by the
+ JDOM Project (http://www.jdom.org/)."
+ Alternatively, the acknowledgment may be graphical using the logos
+ available at http://www.jdom.org/images/logos.
+
+ 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 JDOM AUTHORS OR THE PROJECT
+ 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 JDOM Project and was originally
+ created by Jason Hunter <jhunter_AT_jdom_DOT_org> and
+ Brett McLaughlin <brett_AT_jdom_DOT_org>. For more information
+ on the JDOM Project, please see <http://www.jdom.org/>.
+
+ */
+
+package org.jdom2.output;
+
+import java.util.List;
+
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+
+import org.jdom2.Attribute;
+import org.jdom2.CDATA;
+import org.jdom2.Comment;
+import org.jdom2.Content;
+import org.jdom2.DocType;
+import org.jdom2.Document;
+import org.jdom2.Element;
+import org.jdom2.EntityRef;
+import org.jdom2.ProcessingInstruction;
+import org.jdom2.Text;
+
+/**
+ * Outputs a JDOM document as a StAX XMLStreamWriter of bytes.
+ * <p>
+ * The StAXStreamOutputter can manage many styles of document formatting, from
+ * untouched to 'pretty' printed. The default is to output the document content
+ * exactly as created, but this can be changed by setting a new Format object:
+ * <ul>
+ * <li>For pretty-print output, use
+ * <code>{@link Format#getPrettyFormat()}</code>.
+ * <li>For whitespace-normalised output, use
+ * <code>{@link Format#getCompactFormat()}</code>.
+ * <li>For unmodified-format output, use
+ * <code>{@link Format#getRawFormat()}</code>.
+ * </ul>
+ * <p>
+ * <b>All</b> of the <code>output*(...)</code> methods will flush the
+ * destination XMLStreamWriter before returning, and <b>none</b> of them
+ * will <code>close()</code> the destination.
+ * <p>
+ * To omit output of the declaration use
+ * <code>{@link Format#setOmitDeclaration}</code>. To omit printing of the
+ * encoding in the declaration use <code>{@link Format#setOmitEncoding}</code>.
+ * <p>
+ * If changing the {@link Format} settings are insufficient for your output
+ * needs you can customise this StAXStreamOutputter further by setting a different
+ * {@link StAXStreamProcessor} with the
+ * {@link #setStAXStreamProcessor(StAXStreamProcessor)} method or an appropriate
+ * constructor. A fully-enabled Abstract class
+ * {@link AbstractStAXStreamProcessor} is available to be further extended to
+ * your needs if all you want to do is tweak some details.
+ *
+ * @author Rolf Lear
+ */
+
+public final class StAXStreamOutputter implements Cloneable {
+
+ /*
+ * =====================================================================
+ * Static content.
+ * =====================================================================
+ */
+
+ /**
+ * Create a final and static instance of the AbstractStAXStreamProcessor The
+ * final part is important because it improves performance.
+ * <p>
+ * The JDOM user can change the actual XMLOutputProcessor with the
+ * {@link StAXStreamOutputter#setStAXStreamProcessor(StAXStreamProcessor)} method.
+ *
+ * @author rolf
+ */
+ private static final class DefaultStAXStreamProcessor
+ extends AbstractStAXStreamProcessor {
+ // nothing
+ }
+
+ /**
+ * This constant StAXStreamProcessor is used for all non-customised
+ * StAXStreamOutputters
+ */
+ private static final DefaultStAXStreamProcessor DEFAULTPROCESSOR =
+ new DefaultStAXStreamProcessor();
+
+ /*
+ * =====================================================================
+ * Instance content.
+ * =====================================================================
+ */
+
+ // For normal output
+ private Format myFormat = null;
+
+ // The actual StAXStreamProcessor to delegate to.
+ private StAXStreamProcessor myProcessor = null;
+
+ /*
+ * =====================================================================
+ * Constructors
+ * =====================================================================
+ */
+
+ /**
+ * This will create an <code>StAXStreamOutputter</code> with the specified format
+ * characteristics.
+ * <p>
+ * <b>Note:</b> the format object is cloned internally before use. If you
+ * want to modify the Format after constructing the StAXStreamOutputter you can
+ * modify the Format instance {@link #getFormat()} returns.
+ *
+ * @param format
+ * The Format instance to use. This instance will be cloned() and as
+ * a consequence, changes made to the specified format instance
+ * <b>will not</b> be reflected in this StAXStreamOutputter. A null input
+ * format indicates that StAXStreamOutputter should use the default
+ * {@link Format#getRawFormat()}
+ * @param processor
+ * The XMLOutputProcessor to delegate output to. If null the
+ * StAXStreamOutputter will use the default XMLOutputProcessor.
+ */
+ public StAXStreamOutputter(Format format, StAXStreamProcessor processor) {
+ myFormat = format == null ? Format.getRawFormat() : format.clone();
+ myProcessor = processor == null ? DEFAULTPROCESSOR : processor;
+ }
+
+ /**
+ * This will create an <code>StAXStreamOutputter</code> with a default
+ * {@link Format} and {@link XMLOutputProcessor}.
+ */
+ public StAXStreamOutputter() {
+ this(null, null);
+ }
+
+ /**
+ * This will create an <code>StAXStreamOutputter</code> with the specified format
+ * characteristics.
+ * <p>
+ * <b>Note:</b> the format object is cloned internally before use.
+ *
+ * @param format
+ * The Format instance to use. This instance will be cloned() and as
+ * a consequence, changes made to the specified format instance
+ * <b>will not</b> be reflected in this StAXStreamOutputter. A null input
+ * format indicates that StAXStreamOutputter should use the default
+ * {@link Format#getRawFormat()}
+ */
+ public StAXStreamOutputter(Format format) {
+ this(format, null);
+ }
+
+ /**
+ * This will create an <code>StAXStreamOutputter</code> with the specified
+ * XMLOutputProcessor.
+ *
+ * @param processor
+ * The XMLOutputProcessor to delegate output to. If null the
+ * StAXStreamOutputter will use the default XMLOutputProcessor.
+ */
+ public StAXStreamOutputter(StAXStreamProcessor processor) {
+ this(null, processor);
+ }
+
+ /*
+ * =======================================================================
+ * API - Settings...
+ * =======================================================================
+ */
+
+ /**
+ * Sets the new format logic for the StAXStreamOutputter. Note the Format object is
+ * cloned internally before use.
+ *
+ * @see #getFormat()
+ * @param newFormat
+ * the format to use for subsequent output
+ */
+ public void setFormat(Format newFormat) {
+ this.myFormat = newFormat.clone();
+ }
+
+ /**
+ * Returns the current format in use by the StAXStreamOutputter. Note the Format
+ * object returned is <b>not</b> a clone of the one used internally, thus,
+ * an StAXStreamOutputter instance is able to have it's Format changed by changing
+ * the settings on the Format instance returned by this method.
+ *
+ * @return the current Format instance used by this StAXStreamOutputter.
+ */
+ public Format getFormat() {
+ return myFormat;
+ }
+
+ /**
+ * Returns the current XMLOutputProcessor instance in use by the
+ * StAXStreamOutputter.
+ *
+ * @return the current XMLOutputProcessor instance.
+ */
+ public StAXStreamProcessor getStAXStream() {
+ return myProcessor;
+ }
+
+ /**
+ * Sets a new XMLOutputProcessor instance for this StAXStreamOutputter. Note the
+ * processor object is expected to be thread-safe.
+ *
+ * @param processor
+ * the new XMLOutputProcesor to use for output
+ */
+ public void setStAXStreamProcessor(StAXStreamProcessor processor) {
+ this.myProcessor = processor;
+ }
+
+ /*
+ * ========================================================================
+ * API - Output to XMLStreamWriter Methods ... These are the core methods that the
+ * Stream and String output methods call. On the other hand, these methods
+ * defer to the protected/override methods. These methods flush the writer.
+ * ========================================================================
+ */
+
+ /**
+ * This will print the <code>Document</code> to the given Writer.
+ * <p>
+ * Warning: using your own Writer may cause the outputter's preferred
+ * character encoding to be ignored. If you use encodings other than UTF-8,
+ * we recommend using the method that takes an OutputStream instead.
+ * </p>
+ *
+ * @param doc
+ * <code>Document</code> to format.
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @throws XMLStreamException
+ * - if there's any problem writing.
+ * @throws NullPointerException
+ * if the specified content is null.
+ */
+ public final void output(Document doc, XMLStreamWriter out) throws XMLStreamException {
+ myProcessor.process(out, myFormat, doc);
+ out.flush();
+ }
+
+ /**
+ * Print out the <code>{@link DocType}</code>.
+ *
+ * @param doctype
+ * <code>DocType</code> to output.
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @throws XMLStreamException
+ * - if there's any problem writing.
+ * @throws NullPointerException
+ * if the specified content is null.
+ */
+ public final void output(DocType doctype, XMLStreamWriter out) throws XMLStreamException {
+ myProcessor.process(out, myFormat, doctype);
+ out.flush();
+ }
+
+ /**
+ * Print out an <code>{@link Element}</code>, including its
+ * <code>{@link Attribute}</code>s, and all contained (child) elements, etc.
+ *
+ * @param element
+ * <code>Element</code> to output.
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @throws XMLStreamException
+ * - if there's any problem writing.
+ * @throws NullPointerException
+ * if the specified content is null.
+ */
+ public final void output(Element element, XMLStreamWriter out) throws XMLStreamException {
+ // If this is the root element we could pre-initialize the
+ // namespace stack with the namespaces
+ myProcessor.process(out, myFormat, element);
+ out.flush();
+ }
+
+ /**
+ * This will handle printing out an <code>{@link
+ * Element}</code>'s content only, not including its tag, and attributes.
+ * This can be useful for printing the content of an element that contains
+ * HTML, like "<description>JDOM is
+ * <b>fun>!</description>".
+ *
+ * @param element
+ * <code>Element</code> to output.
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @throws XMLStreamException
+ * - if there's any problem writing.
+ * @throws NullPointerException
+ * if the specified content is null.
+ */
+ public final void outputElementContent(Element element, XMLStreamWriter out)
+ throws XMLStreamException {
+ myProcessor.process(out, myFormat, element.getContent());
+ out.flush();
+ }
+
+ /**
+ * This will handle printing out a list of nodes. This can be useful for
+ * printing the content of an element that contains HTML, like
+ * "<description>JDOM is <b>fun>!</description>".
+ *
+ * @param list
+ * <code>List</code> of nodes.
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @throws XMLStreamException
+ * - if there's any problem writing.
+ * @throws NullPointerException
+ * if the specified content is null.
+ */
+ public final void output(List<? extends Content> list, XMLStreamWriter out)
+ throws XMLStreamException {
+ myProcessor.process(out, myFormat, list);
+ out.flush();
+ }
+
+ /**
+ * Print out a <code>{@link CDATA}</code> node.
+ *
+ * @param cdata
+ * <code>CDATA</code> to output.
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @throws XMLStreamException
+ * - if there's any problem writing.
+ * @throws NullPointerException
+ * if the specified content is null.
+ */
+ public final void output(CDATA cdata, XMLStreamWriter out) throws XMLStreamException {
+ myProcessor.process(out, myFormat, cdata);
+ out.flush();
+ }
+
+ /**
+ * Print out a <code>{@link Text}</code> node. Perfoms the necessary entity
+ * escaping and whitespace stripping.
+ *
+ * @param text
+ * <code>Text</code> to output.
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @throws XMLStreamException
+ * - if there's any problem writing.
+ * @throws NullPointerException
+ * if the specified content is null.
+ */
+ public final void output(Text text, XMLStreamWriter out) throws XMLStreamException {
+ myProcessor.process(out, myFormat, text);
+ out.flush();
+ }
+
+ /**
+ * Print out a <code>{@link Comment}</code>.
+ *
+ * @param comment
+ * <code>Comment</code> to output.
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @throws XMLStreamException
+ * - if there's any problem writing.
+ * @throws NullPointerException
+ * if the specified content is null.
+ */
+ public final void output(Comment comment, XMLStreamWriter out) throws XMLStreamException {
+ myProcessor.process(out, myFormat, comment);
+ out.flush();
+ }
+
+ /**
+ * Print out a <code>{@link ProcessingInstruction}</code>.
+ *
+ * @param pi
+ * <code>ProcessingInstruction</code> to output.
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @throws XMLStreamException
+ * - if there's any problem writing.
+ * @throws NullPointerException
+ * if the specified content is null.
+ */
+ public final void output(ProcessingInstruction pi, XMLStreamWriter out)
+ throws XMLStreamException {
+ myProcessor.process(out, myFormat, pi);
+ out.flush();
+ }
+
+ /**
+ * Print out an <code>{@link EntityRef}</code>.
+ *
+ * @param entity
+ * <code>EntityRef</code> to output.
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @throws XMLStreamException
+ * - if there's any problem writing.
+ * @throws NullPointerException
+ * if the specified content is null.
+ */
+ public final void output(EntityRef entity, XMLStreamWriter out) throws XMLStreamException {
+ myProcessor.process(out, myFormat, entity);
+ out.flush();
+ }
+
+ /*
+ * ========================================================================
+ * Basic Support methods.
+ * ========================================================================
+ */
+
+ /**
+ * Returns a cloned copy of this StAXStreamOutputter.
+ */
+ @Override
+ public StAXStreamOutputter clone() {
+ // Implementation notes: Since all state of an StAXStreamOutputter is
+ // embodied in simple private instance variables, Object.clone
+ // can be used. Note that since Object.clone is totally
+ // broken, we must catch an exception that will never be
+ // thrown.
+ try {
+ return (StAXStreamOutputter) super.clone();
+ } catch (java.lang.CloneNotSupportedException e) {
+ // even though this should never ever happen, it's still
+ // possible to fool Java into throwing a
+ // CloneNotSupportedException. If that happens, we
+ // shouldn't swallow it.
+ throw new RuntimeException(e.toString());
+ }
+ }
+
+ /**
+ * Return a string listing of the settings for this StAXStreamOutputter instance.
+ *
+ * @return a string listing the settings for this StAXStreamOutputter instance
+ */
+ @Override
+ public String toString() {
+ StringBuilder buffer = new StringBuilder();
+ buffer.append("StAXStreamOutputter[omitDeclaration = ");
+ buffer.append(myFormat.omitDeclaration);
+ buffer.append(", ");
+ buffer.append("encoding = ");
+ buffer.append(myFormat.encoding);
+ buffer.append(", ");
+ buffer.append("omitEncoding = ");
+ buffer.append(myFormat.omitEncoding);
+ buffer.append(", ");
+ buffer.append("indent = '");
+ buffer.append(myFormat.indent);
+ buffer.append("'");
+ buffer.append(", ");
+ buffer.append("expandEmptyElements = ");
+ buffer.append(myFormat.expandEmptyElements);
+ buffer.append(", ");
+ buffer.append("lineSeparator = '");
+ for (char ch : myFormat.lineSeparator.toCharArray()) {
+ switch (ch) {
+ case '\r':
+ buffer.append("\\r");
+ break;
+ case '\n':
+ buffer.append("\\n");
+ break;
+ case '\t':
+ buffer.append("\\t");
+ break;
+ default:
+ buffer.append("[" + ((int) ch) + "]");
+ break;
+ }
+ }
+ buffer.append("', ");
+ buffer.append("textMode = ");
+ buffer.append(myFormat.mode + "]");
+ return buffer.toString();
+ }
+
+}
diff --git a/core/src/java/org/jdom2/output/StAXStreamProcessor.java b/core/src/java/org/jdom2/output/StAXStreamProcessor.java
new file mode 100644
index 000000000..0ab67cc2a
--- /dev/null
+++ b/core/src/java/org/jdom2/output/StAXStreamProcessor.java
@@ -0,0 +1,203 @@
+package org.jdom2.output;
+
+import java.util.List;
+
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+
+import org.jdom2.Attribute;
+import org.jdom2.CDATA;
+import org.jdom2.Comment;
+import org.jdom2.Content;
+import org.jdom2.DocType;
+import org.jdom2.Document;
+import org.jdom2.Element;
+import org.jdom2.EntityRef;
+import org.jdom2.ProcessingInstruction;
+import org.jdom2.Text;
+
+/**
+ * This interface provides a base support for the {@link XMLOutputter}.
+ * <p>
+ * People who want to create a custom XMLOutputProcessor for XMLOutputter are
+ * able to implement this interface with the following notes and restrictions:
+ * <ol>
+ * <li>The XMLOutputter will call one, and only one of the <code>process(XMLStreamWriter,Format,*)</code> methods each
+ * time the XMLOutputter is requested to output some JDOM content. It is thus
+ * safe to assume that a <code>process(XMLStreamWriter,Format,*)</code> method can set up any
+ * infrastructure needed to process the content, and that the XMLOutputter will
+ * not re-call that method, or some other <code>process(XMLStreamWriter,Format,*)</code> method for the same output
+ * sequence.
+ * <li>The process methods should be thread-safe and reentrant: The same
+ * <code>process(XMLStreamWriter,Format,*)</code> method may (will) be called concurrently from different threads.
+ * </ol>
+ * <p>
+ * The {@link AbstractXMLOutputProcessor} class is a full implementation of this
+ * interface and is fully customisable. People who want a custom XMLOutputter
+ * are encouraged to extend the AbstractXMLOutputProcessor rather than do a full
+ * re-implementation of this interface.
+ *
+ * @see XMLOutputter
+ * @see AbstractXMLOutputProcessor
+ * @author Rolf Lear
+ */
+public interface StAXStreamProcessor {
+
+ /**
+ * This will print the <code>{@link Document}</code> to the given XMLStreamWriter.
+ * <p>
+ * Warning: using your own XMLStreamWriter may cause the outputter's preferred
+ * character encoding to be ignored. If you use encodings other than UTF-8,
+ * we recommend using the method that takes an OutputStream instead.
+ * </p>
+ *
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @param format
+ * <code>Format</code> instance specifying output style
+ * @param doc
+ * <code>Document</code> to format.
+ * @throws XMLStreamException
+ * if there's any problem writing.
+ * @throws NullPointerException
+ * if the input content is null
+ */
+ public abstract void process(XMLStreamWriter out, Format format, Document doc) throws XMLStreamException;
+
+ /**
+ * Print out the <code>{@link DocType}</code>.
+ *
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @param format
+ * <code>Format</code> instance specifying output style
+ * @param doctype
+ * <code>DocType</code> to output.
+ * @throws XMLStreamException
+ * if there's any problem writing.
+ * @throws NullPointerException
+ * if the input content is null
+ */
+ public abstract void process(XMLStreamWriter out, Format format, DocType doctype) throws XMLStreamException;
+
+ /**
+ * Print out an <code>{@link Element}</code>, including its
+ * <code>{@link Attribute}</code>s, and all contained (child) elements, etc.
+ *
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @param format
+ * <code>Format</code> instance specifying output style
+ * @param element
+ * <code>Element</code> to output.
+ * @throws XMLStreamException
+ * if there's any problem writing.
+ * @throws NullPointerException
+ * if the input content is null
+ */
+ public abstract void process(XMLStreamWriter out, Format format, Element element) throws XMLStreamException;
+
+ /**
+ * This will handle printing out a list of nodes. This can be useful for
+ * printing the content of an element that contains HTML, like
+ * "<description>JDOM is <b>fun>!</description>".
+ *
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @param format
+ * <code>Format</code> instance specifying output style
+ * @param list
+ * <code>List</code> of nodes.
+ * @throws XMLStreamException
+ * if there's any problem writing.
+ * @throws NullPointerException
+ * if the input list is null or contains null members
+ * @throws ClassCastException
+ * if any of the list members are not {@link Content}
+ */
+ public abstract void process(XMLStreamWriter out, Format format, List<? extends Content> list)
+ throws XMLStreamException;
+
+ /**
+ * Print out a <code>{@link CDATA}</code> node.
+ *
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @param format
+ * <code>Format</code> instance specifying output style
+ * @param cdata
+ * <code>CDATA</code> to output.
+ * @throws XMLStreamException
+ * if there's any problem writing.
+ * @throws NullPointerException
+ * if the input content is null
+ */
+ public abstract void process(XMLStreamWriter out, Format format, CDATA cdata) throws XMLStreamException;
+
+ /**
+ * Print out a <code>{@link Text}</code> node. Perfoms the necessary entity
+ * escaping and whitespace stripping.
+ *
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @param format
+ * <code>Format</code> instance specifying output style
+ * @param text
+ * <code>Text</code> to output.
+ * @throws XMLStreamException
+ * if there's any problem writing.
+ * @throws NullPointerException
+ * if the input content is null
+ */
+ public abstract void process(XMLStreamWriter out, Format format, Text text) throws XMLStreamException;
+
+ /**
+ * Print out a <code>{@link Comment}</code>.
+ *
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @param format
+ * <code>Format</code> instance specifying output style
+ * @param comment
+ * <code>Comment</code> to output.
+ * @throws XMLStreamException
+ * if there's any problem writing.
+ * @throws NullPointerException
+ * if the input content is null
+ */
+ public abstract void process(XMLStreamWriter out, Format format, Comment comment) throws XMLStreamException;
+
+ /**
+ * Print out a <code>{@link ProcessingInstruction}</code>.
+ *
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @param format
+ * <code>Format</code> instance specifying output style
+ * @param pi
+ * <code>ProcessingInstruction</code> to output.
+ * @throws XMLStreamException
+ * if there's any problem writing.
+ * @throws NullPointerException
+ * if the input content is null
+ */
+ public abstract void process(XMLStreamWriter out, Format format, ProcessingInstruction pi)
+ throws XMLStreamException;
+
+ /**
+ * Print out a <code>{@link EntityRef}</code>.
+ *
+ * @param out
+ * <code>XMLStreamWriter</code> to use.
+ * @param format
+ * <code>Format</code> instance specifying output style
+ * @param entity
+ * <code>EntityRef</code> to output.
+ * @throws XMLStreamException
+ * if there's any problem writing.
+ * @throws NullPointerException
+ * if the input content is null
+ */
+ public abstract void process(XMLStreamWriter out, Format format, EntityRef entity) throws XMLStreamException;
+
+}
\ No newline at end of file
diff --git a/test/resources/DOMBuilder/doctypesimple.xml b/test/resources/DOMBuilder/doctypesimple.xml
new file mode 100644
index 000000000..c95a0a2d2
--- /dev/null
+++ b/test/resources/DOMBuilder/doctypesimple.xml
@@ -0,0 +1,3 @@
+<?xml version="1.0" ?>
+<!DOCTYPE root [] >
+<root />
\ No newline at end of file
diff --git a/test/src/java/org/jdom2/test/cases/input/TestStAXEventBuilder.java b/test/src/java/org/jdom2/test/cases/input/TestStAXEventBuilder.java
index 3166538d5..290c62b6a 100644
--- a/test/src/java/org/jdom2/test/cases/input/TestStAXEventBuilder.java
+++ b/test/src/java/org/jdom2/test/cases/input/TestStAXEventBuilder.java
@@ -14,14 +14,18 @@
import javax.xml.stream.XMLInputFactory;
import javax.xml.transform.stream.StreamSource;
-import org.jdom2.*;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import org.jdom2.DefaultJDOMFactory;
+import org.jdom2.DocType;
+import org.jdom2.Document;
+import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.input.StAXEventBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.test.util.UnitTestUtil;
-import org.junit.Ignore;
-import org.junit.Test;
@SuppressWarnings("javadoc")
public class TestStAXEventBuilder {
@@ -59,10 +63,16 @@ public void testNamespaceDocumentExpand() {
@Test
@Ignore
+ // TODO
public void testDocTypeDocumentExpand() {
checkStAX("test/resources/DOMBuilder/doctype.xml", true);
}
+ @Test
+ public void testDocTypeDocumentSimpleExpand() {
+ checkStAX("test/resources/DOMBuilder/doctypesimple.xml", true);
+ }
+
@Test
public void testComplexDocumentExpand() {
checkStAX("test/resources/DOMBuilder/complex.xml", true);
@@ -93,6 +103,11 @@ public void testDocTypeDocument() {
checkStAX("test/resources/DOMBuilder/doctype.xml", false);
}
+ @Test
+ public void testDocTypeSimpleDocument() {
+ checkStAX("test/resources/DOMBuilder/doctypesimple.xml", false);
+ }
+
@Test
public void testComplexDocument() {
checkStAX("test/resources/DOMBuilder/complex.xml", false);
diff --git a/test/src/java/org/jdom2/test/cases/input/TestStAXStreamBuilder.java b/test/src/java/org/jdom2/test/cases/input/TestStAXStreamBuilder.java
index 6dcb90cee..47e68011c 100644
--- a/test/src/java/org/jdom2/test/cases/input/TestStAXStreamBuilder.java
+++ b/test/src/java/org/jdom2/test/cases/input/TestStAXStreamBuilder.java
@@ -4,7 +4,6 @@
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import java.io.CharArrayWriter;
import java.io.File;
@@ -15,15 +14,20 @@
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.stream.StreamSource;
-import org.jdom2.*;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import org.jdom2.Content;
+import org.jdom2.DefaultJDOMFactory;
+import org.jdom2.DocType;
+import org.jdom2.Document;
+import org.jdom2.Element;
import org.jdom2.input.DefaultStAXFilter;
import org.jdom2.input.SAXBuilder;
import org.jdom2.input.StAXStreamBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.test.util.UnitTestUtil;
-import org.junit.Ignore;
-import org.junit.Test;
@SuppressWarnings("javadoc")
public class TestStAXStreamBuilder {
@@ -65,6 +69,12 @@ public void testDocTypeDocumentExpand() {
checkStAX("test/resources/DOMBuilder/doctype.xml", true);
}
+ @Test
+ @Ignore
+ public void testDocTypeDocumentSimpleExpand() {
+ checkStAX("test/resources/DOMBuilder/doctypesimple.xml", true);
+ }
+
@Test
public void testComplexDocumentExpand() {
checkStAX("test/resources/DOMBuilder/complex.xml", true);
@@ -95,6 +105,11 @@ public void testDocTypeDocument() {
checkStAX("test/resources/DOMBuilder/doctype.xml", false);
}
+ @Test
+ public void testDocTypeSimpleDocument() {
+ checkStAX("test/resources/DOMBuilder/doctypesimple.xml", false);
+ }
+
@Test
public void testComplexDocument() {
checkStAX("test/resources/DOMBuilder/complex.xml", false);
@@ -137,8 +152,7 @@ private void checkStAX(String filename, boolean expand) {
assertEquals("ROOT SAX to StAXReader FragmentList", toString(saxroot), toString(fragroot));
} catch (Exception e) {
- e.printStackTrace();
- fail("Could not parse file '" + filename + "': " + e.getMessage());
+ UnitTestUtil.failException("Could not parse file '" + filename + "': " + e.getMessage(), e);
}
}
diff --git a/test/src/java/org/jdom2/test/cases/output/TestStAXEventOutputter.java b/test/src/java/org/jdom2/test/cases/output/TestStAXEventOutputter.java
new file mode 100644
index 000000000..00ea051da
--- /dev/null
+++ b/test/src/java/org/jdom2/test/cases/output/TestStAXEventOutputter.java
@@ -0,0 +1,1300 @@
+package org.jdom2.test.cases.output;
+
+import static org.jdom2.test.util.UnitTestUtil.failException;
+import static org.jdom2.test.util.UnitTestUtil.normalizeAttributes;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.ByteArrayOutputStream;
+import java.io.CharArrayReader;
+import java.io.CharArrayWriter;
+import java.io.IOException;
+import java.io.StringReader;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.stream.XMLEventWriter;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamConstants;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.stream.XMLStreamWriter;
+import javax.xml.stream.events.XMLEvent;
+import javax.xml.stream.util.XMLEventConsumer;
+import javax.xml.transform.Result;
+
+import org.junit.Ignore;
+import org.junit.Test;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+import org.xml.sax.ext.DefaultHandler2;
+
+import org.jdom2.Attribute;
+import org.jdom2.AttributeType;
+import org.jdom2.CDATA;
+import org.jdom2.Comment;
+import org.jdom2.Content;
+import org.jdom2.DocType;
+import org.jdom2.Document;
+import org.jdom2.Element;
+import org.jdom2.EntityRef;
+import org.jdom2.IllegalDataException;
+import org.jdom2.JDOMException;
+import org.jdom2.Namespace;
+import org.jdom2.Parent;
+import org.jdom2.ProcessingInstruction;
+import org.jdom2.Text;
+import org.jdom2.UncheckedJDOMFactory;
+import org.jdom2.input.DefaultStAXFilter;
+import org.jdom2.input.SAXBuilder;
+import org.jdom2.input.SAXHandler;
+import org.jdom2.input.StAXStreamBuilder;
+import org.jdom2.output.AbstractStAXEventProcessor;
+import org.jdom2.output.Format;
+import org.jdom2.output.Format.TextMode;
+import org.jdom2.output.SAXOutputter;
+import org.jdom2.output.StAXEventOutputter;
+import org.jdom2.output.StAXEventProcessor;
+import org.jdom2.output.XMLOutputter;
+
+@SuppressWarnings("javadoc")
+public final class TestStAXEventOutputter {
+
+ private final static XMLOutputFactory soutfactory = XMLOutputFactory.newInstance();
+ private final static XMLInputFactory sinfactory = XMLInputFactory.newInstance();
+
+ private static final class EventStore implements XMLEventConsumer {
+ private final ArrayList<XMLEvent> store = new ArrayList<XMLEvent>();
+ private final String encoding;
+
+ EventStore(String enc) {
+ encoding = enc;
+ }
+
+ @Override
+ public void add(XMLEvent event) throws XMLStreamException {
+ store.add(event);
+ }
+
+ @Override
+ public String toString() {
+ ByteArrayOutputStream sw = new ByteArrayOutputStream();
+ try {
+ XMLEventWriter xew = soutfactory.createXMLEventWriter(sw, encoding);
+ for (XMLEvent x : store) {
+ xew.add(x);
+ }
+ xew.flush();
+ xew.close();
+ return new String(sw.toByteArray());
+ } catch (XMLStreamException e) {
+ throw new IllegalStateException("Can't get toString...", e);
+ }
+
+ }
+ }
+
+ @Test
+ public void test_HighSurrogatePair() throws XMLStreamException, IOException, JDOMException {
+ SAXBuilder builder = new SAXBuilder();
+ builder.setExpandEntities(true);
+ Document doc = builder.build(new StringReader("<?xml version=\"1.0\"?><root>𐀀 𐀀</root>"));
+
+ Format format = Format.getCompactFormat().setEncoding("ISO-8859-1");
+ StAXEventOutputter outputter = new StAXEventOutputter(format);
+ EventStore es = new EventStore("ISO-8859-1");
+ outputter.output(doc, es);
+ String xml = es.toString();
+ assertEquals("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" +
+ "<root>�� ��</root>", xml);
+ }
+
+ @Test
+ public void test_HighSurrogatePairDecimal() throws JDOMException, IOException, XMLStreamException {
+ SAXBuilder builder = new SAXBuilder();
+ builder.setExpandEntities(true);
+ Document doc = builder.build(new StringReader("<?xml version=\"1.0\"?><root>𐀀 𐀀</root>"));
+ Format format = Format.getCompactFormat().setEncoding("ISO-8859-1");
+ StAXEventOutputter outputter = new StAXEventOutputter(format);
+ EventStore es = new EventStore("ISO-8859-1");
+ outputter.output(doc, es);
+ String xml = es.toString();
+ assertEquals("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" +
+ "<root>�� ��</root>", xml);
+ }
+
+ @Test
+ public void test_HighSurrogateAttPair() throws JDOMException, IOException, XMLStreamException {
+ SAXBuilder builder = new SAXBuilder();
+ builder.setExpandEntities(true);
+ Document doc = builder.build(new StringReader("<?xml version=\"1.0\"?><root att=\"𐀀 𐀀\" />"));
+ Format format = Format.getCompactFormat().setEncoding("ISO-8859-1");
+ StAXEventOutputter outputter = new StAXEventOutputter(format);
+ EventStore es = new EventStore("ISO-8859-1");
+ outputter.output(doc, es);
+ String xml = es.toString();
+ assertEquals("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" +
+ "<root att=\"�� ��\"></root>", xml);
+ }
+
+ @Test
+ public void test_HighSurrogateAttPairDecimal() throws JDOMException, IOException, XMLStreamException {
+ SAXBuilder builder = new SAXBuilder();
+ builder.setExpandEntities(true);
+ Document doc = builder.build(new StringReader("<?xml version=\"1.0\"?><root att=\"𐀀 𐀀\" />"));
+ Format format = Format.getCompactFormat().setEncoding("ISO-8859-1");
+ StAXEventOutputter outputter = new StAXEventOutputter(format);
+ EventStore es = new EventStore("ISO-8859-1");
+ outputter.output(doc, es);
+ String xml = es.toString();
+ assertEquals("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" +
+ "<root att=\"�� ��\"></root>", xml);
+ }
+
+ // Construct a raw surrogate pair character and confirm it outputs hex escaped
+ @Test
+ public void test_RawSurrogatePair() throws JDOMException, IOException, XMLStreamException {
+ SAXBuilder builder = new SAXBuilder();
+ builder.setExpandEntities(true);
+ Document doc = builder.build(new StringReader("<?xml version=\"1.0\"?><root>\uD800\uDC00</root>"));
+ Format format = Format.getCompactFormat().setEncoding("ISO-8859-1");
+ StAXEventOutputter outputter = new StAXEventOutputter(format);
+ EventStore es = new EventStore("ISO-8859-1");
+ outputter.output(doc, es);
+ String xml = es.toString();
+ assertEquals("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" +
+ "<root>��</root>", xml);
+ }
+
+ // Construct a raw surrogate pair character and confirm it outputs hex escaped, when UTF-8 too
+ @Test
+ @Ignore
+ // TODO
+ public void test_RawSurrogatePairUTF8() throws JDOMException, IOException, XMLStreamException {
+ SAXBuilder builder = new SAXBuilder();
+ builder.setExpandEntities(true);
+ Document doc = builder.build(new StringReader("<?xml version=\"1.0\"?><root>\uD800\uDC00</root>"));
+ Format format = Format.getCompactFormat().setEncoding("UTF-8");
+ StAXEventOutputter outputter = new StAXEventOutputter(format);
+ EventStore es = new EventStore("UTF-8");
+ outputter.output(doc, es);
+ String xml = es.toString();
+ assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
+ "<root>\uD800\uDC00</root>", xml);
+ }
+
+ // Construct illegal XML and check if the parser notices
+ @Test
+ public void test_ErrorSurrogatePair() throws JDOMException, IOException {
+ SAXBuilder builder = new SAXBuilder();
+ builder.setExpandEntities(true);
+ Document doc = builder.build(new StringReader("<?xml version=\"1.0\"?><root></root>"));
+ try {
+ doc.getRootElement().setText("\uD800\uDBFF");
+ fail("Illegal surrogate pair should have thrown an exception");
+ }
+ catch (IllegalDataException e) {
+ // do nothing
+ } catch (Exception e) {
+ fail ("Unexpected exception " + e.getClass());
+ }
+ }
+
+ // Manually construct illegal XML and make sure the outputter notices
+ @Test
+ @Ignore
+ // TODO
+ public void test_ErrorSurrogatePairOutput() throws JDOMException, IOException {
+ SAXBuilder builder = new SAXBuilder();
+ builder.setExpandEntities(true);
+ Document doc = builder.build(new StringReader("<?xml version=\"1.0\"?><root></root>"));
+ Text t = new UncheckedJDOMFactory().text("\uD800\uDBFF");
+ doc.getRootElement().setContent(t);
+ Format format = Format.getCompactFormat().setEncoding("ISO-8859-1");
+ StAXEventOutputter outputter = new StAXEventOutputter(format);
+ try {
+ EventStore es = new EventStore("ISO-8859-1");
+ outputter.output(doc, es);
+ fail("Illegal surrogate pair output should have thrown an exception");
+ }
+ catch (XMLStreamException e) {
+ // do nothing
+ } catch (Exception e) {
+ fail ("Unexpected exception " + e.getClass());
+ }
+ }
+
+
+ @Test
+ public void testXMLOutputter() {
+ StAXEventOutputter out = new StAXEventOutputter();
+ TestFormat.checkEquals(out.getFormat(), Format.getRawFormat());
+ }
+
+
+ @Test
+ public void testXMLOutputterFormat() {
+ Format mine = Format.getCompactFormat();
+ mine.setEncoding("US-ASCII");
+ StAXEventOutputter out = new StAXEventOutputter(mine);
+ TestFormat.checkEquals(mine, out.getFormat());
+ }
+
+// @Test
+// public void testXMLOutputterXMLOutputter() {
+// Format mine = Format.getCompactFormat();
+// StAXEventProcessor xoutp = new StAXEventOutputter().getStAXStream();
+// mine.setEncoding("US-ASCII");
+// // double-construct it.
+// StAXEventOutputter out = new StAXEventOutputter();
+// TestFormat.checkEquals(mine, out.getFormat());
+// assertTrue(xoutp == out.getXMLOutputProcessor());
+// }
+
+ @Test
+ public void testXMLOutputterXMLOutputProcessor() {
+ StAXEventProcessor xoutp = new AbstractStAXEventProcessor() {
+ // nothing;
+ };
+ // double-constrcut it.
+ StAXEventOutputter out = new StAXEventOutputter(xoutp);
+ TestFormat.checkEquals(Format.getRawFormat(), out.getFormat());
+ assertTrue(xoutp == out.getStAXStream());
+ }
+
+ @Test
+ public void testFormat() {
+ Format mine = Format.getCompactFormat();
+ mine.setEncoding("US-ASCII");
+ // double-constcut it.
+ StAXEventOutputter out = new StAXEventOutputter();
+ TestFormat.checkEquals(Format.getRawFormat(), out.getFormat());
+ out.setFormat(mine);
+ TestFormat.checkEquals(mine, out.getFormat());
+ }
+
+ @Test
+ public void testXMLOutputProcessor() {
+ StAXEventProcessor xoutp = new AbstractStAXEventProcessor() {
+ // nothing;
+ };
+ // double-constcut it.
+ StAXEventOutputter out = new StAXEventOutputter();
+ StAXEventProcessor xop = out.getStAXStream();
+ out.setStAXEventProcessor(xoutp);
+ assertTrue(xoutp != xop);
+ assertTrue(xoutp == out.getStAXStream());
+ }
+
+ @Test
+ public void testOutputText() {
+ checkOutput(new Text(" hello there "), " hello there ", "hello there", "hello there", " hello there ");
+ }
+
+ @Test
+ public void testOutputCDATA() {
+ String indata = " hello there bozo ! ";
+ String rawcdata = "<![CDATA[ hello there bozo ! ]]>";
+ String compdata = "<![CDATA[hello there bozo !]]>";
+ String prettydata = "<![CDATA[hello there bozo !]]>";
+ String trimdata = "<![CDATA[ hello there bozo ! ]]>";
+
+ checkOutput(new CDATA(indata), rawcdata, compdata, prettydata, trimdata);
+ }
+
+ @Test
+ public void testOutputComment() {
+ String incomment = " hello there bozo ! ";
+ String outcomment = "<!--" + incomment + "-->";
+ checkOutput(new Comment(incomment), outcomment, outcomment, outcomment, outcomment);
+ }
+
+ @Test
+ public void testOutputProcessingInstructionSimple() {
+ ProcessingInstruction inpi = new ProcessingInstruction("jdomtest", "");
+ String outpi = "<?jdomtest?>";
+ checkOutput(inpi, outpi, outpi, outpi, outpi);
+ }
+
+ @Test
+ public void testOutputProcessingInstructionData() {
+ String pi = " hello there ";
+ ProcessingInstruction inpi = new ProcessingInstruction("jdomtest", pi);
+ String outpi = "<?jdomtest " + pi + "?>";
+ checkOutput(inpi, outpi, outpi, outpi, outpi);
+ }
+
+ @Test
+ public void testOutputEntityRef() {
+ checkOutput(new EntityRef("name", "publicID", "systemID"),
+ "&name;", "&name;", "&name;", "&name;");
+ }
+
+ @Test
+ public void testOutputElementSimple() {
+ String txt = "<root/>";
+ checkOutput(new Element("root"), txt, txt, txt, txt);
+ }
+
+ @Test
+ public void testOutputElementAttribute() {
+ String txt = "<root att=\"val\"/>";
+ checkOutput(new Element("root").setAttribute("att", "val"), txt, txt, txt, txt);
+ }
+
+ @Test
+ public void testOutputElementCDATA() {
+ String txt = "<root><![CDATA[xx]]></root>";
+ Element root = new Element("root");
+ root.addContent(new CDATA("xx"));
+ checkOutput(root, txt, txt, txt, txt);
+ }
+
+ @Test
+ public void testOutputElementExpandEmpty() {
+ String txt = "<root></root>";
+ FormatSetup setup = new FormatSetup() {
+ @Override
+ public void setup(Format fmt) {
+ fmt.setExpandEmptyElements(true);
+ }
+ };
+ checkOutput(new Element("root"), setup, txt, txt, txt, txt);
+ }
+
+ @Test
+ public void testOutputElementPreserveSpace() {
+ String txt = "<root xml:space=\"preserve\"> <child xml:space=\"default\">abc</child> </root>";
+ Element root = new Element("root");
+ root.setAttribute("space", "preserve", Namespace.XML_NAMESPACE);
+ root.addContent(" ");
+ Element child = new Element("child");
+ child.setAttribute("space", "default", Namespace.XML_NAMESPACE);
+ child.addContent("abc");
+ root.addContent(child);
+ root.addContent(" ");
+ checkOutput(root, txt, txt, txt, txt);
+ }
+
+ @Test
+ @Ignore
+ //TODO
+ public void testOutputElementIgnoreTrAXEscapingPIs() {
+ Element root = new Element("root");
+ root.addContent(new Text("&"));
+ root.addContent(new ProcessingInstruction(Result.PI_DISABLE_OUTPUT_ESCAPING, ""));
+ root.addContent(new Text(" && "));
+ root.addContent(new ProcessingInstruction(Result.PI_ENABLE_OUTPUT_ESCAPING, ""));
+ root.addContent(new Text("&"));
+ String expect = "<root>& && &</root>";
+ String excompact = "<root>&&&&</root>";
+ String expretty = "<root>\n &\n \n &&\n \n &\n</root>";
+ String extfw = "<root>\n &\n \n && \n \n &\n</root>";
+ checkOutput(root,
+ expect,
+ excompact,
+ expretty,
+ extfw);
+ }
+
+
+ @Test
+ public void testOutputElementMultiText() {
+ Element root = new Element("root");
+ root.addContent(new CDATA(" "));
+ root.addContent(new Text(" xx "));
+ root.addContent(new Text("yy"));
+ root.addContent(new Text(" "));
+ root.addContent(new Text("zz"));
+ root.addContent(new Text(" ww"));
+ root.addContent(new EntityRef("amp"));
+ root.addContent(new Text("vv"));
+ root.addContent(new Text(" "));
+ checkOutput(root,
+ "<root><![CDATA[ ]]> xx yy zz ww&vv </root>",
+ "<root>xx yy zz ww&vv</root>",
+ "<root>xx yy zz ww&vv</root>",
+ // This should be changed with issue #31.
+ // The real value should have one additional
+ // space at the beginning and two at the end
+ // for now we leave the broken test here because it
+ // helps with the coverage reports.
+ // the next test is added to be a failing test.
+ "<root><![CDATA[ ]]> xx yy zz ww&vv </root>");
+ }
+
+ @Test
+ public void testOutputElementMultiAllWhite() {
+ Element root = new Element("root");
+ root.addContent(new CDATA(" "));
+ root.addContent(new Text(" "));
+ root.addContent(new Text(" "));
+ root.addContent(new Text(""));
+ root.addContent(new Text(" "));
+ root.addContent(new Text(" \n \n "));
+ root.addContent(new Text(" \t "));
+ root.addContent(new Text(" "));
+ checkOutput(root,
+ "<root><![CDATA[ ]]> \n \n \t </root>",
+ "<root/>",
+ "<root/>",
+ "<root/>");
+ }
+
+ @Test
+ public void testOutputElementMultiAllWhiteExpandEmpty() {
+ Element root = new Element("root");
+ root.addContent(new CDATA(" "));
+ root.addContent(new Text(" "));
+ root.addContent(new Text(" "));
+ root.addContent(new Text(""));
+ root.addContent(new Text(" "));
+ root.addContent(new Text(" \n \n "));
+ root.addContent(new Text(" \t "));
+ root.addContent(new Text(" "));
+ FormatSetup fs = new FormatSetup() {
+ @Override
+ public void setup(Format fmt) {
+ fmt.setExpandEmptyElements(true);
+ }
+ };
+ checkOutput(root, fs,
+ "<root><![CDATA[ ]]> \n \n \t </root>",
+ "<root></root>",
+ "<root></root>",
+ "<root></root>");
+ }
+
+ @Test
+ public void testOutputElementMultiMostWhiteExpandEmpty() {
+ // this test has mixed content (text-type and not text type).
+ // and, it has a multi-text-type at the end.
+ Element root = new Element("root");
+ root.addContent(new CDATA(" "));
+ root.addContent(new Text(" "));
+ root.addContent(new Text(" "));
+ root.addContent(new Text(""));
+ root.addContent(new Text(" "));
+ root.addContent(new Text(" \n \n "));
+ root.addContent(new Comment("Boo"));
+ root.addContent(new Text(" \t "));
+ root.addContent(new Text(" "));
+ FormatSetup fs = new FormatSetup() {
+ @Override
+ public void setup(Format fmt) {
+ fmt.setExpandEmptyElements(true);
+ }
+ };
+ checkOutput(root, fs,
+ "<root><![CDATA[ ]]> \n \n <!--Boo--> \t </root>",
+ "<root><!--Boo--></root>",
+ "<root>\n <!--Boo-->\n</root>",
+ "<root>\n <!--Boo-->\n</root>");
+ }
+
+ @Test
+ public void testOutputElementMixedMultiCDATA() {
+ // this test has mixed content (text-type and not text type).
+ // and, it has a multi-text-type at the end.
+ Element root = new Element("root");
+ root.addContent(new Comment("Boo"));
+ root.addContent(new Text(" "));
+ root.addContent(new CDATA("A"));
+ FormatSetup fs = new FormatSetup() {
+ @Override
+ public void setup(Format fmt) {
+ fmt.setExpandEmptyElements(true);
+ }
+ };
+ checkOutput(root, fs,
+ "<root><!--Boo--> <![CDATA[A]]></root>",
+ "<root><!--Boo--><![CDATA[A]]></root>",
+ "<root>\n <!--Boo-->\n <![CDATA[A]]>\n</root>",
+ "<root>\n <!--Boo-->\n <![CDATA[A]]>\n</root>");
+ }
+
+ @Test
+ public void testOutputElementMixedMultiEntityRef() {
+ // this test has mixed content (text-type and not text type).
+ // and, it has a multi-text-type at the end.
+ Element root = new Element("root");
+ root.addContent(new Comment("Boo"));
+ root.addContent(new Text(" "));
+ root.addContent(new EntityRef("aer"));
+ FormatSetup fs = new FormatSetup() {
+ @Override
+ public void setup(Format fmt) {
+ fmt.setExpandEmptyElements(true);
+ }
+ };
+ checkOutput(root, fs,
+ "<root><!--Boo--> &aer;</root>",
+ "<root><!--Boo-->&aer;</root>",
+ "<root>\n <!--Boo-->\n &aer;\n</root>",
+ "<root>\n <!--Boo-->\n &aer;\n</root>");
+ }
+
+ @Test
+ public void testOutputElementMixedMultiText() {
+ // this test has mixed content (text-type and not text type).
+ // and, it has a multi-text-type at the end.
+ Element root = new Element("root");
+ root.addContent(new Comment("Boo"));
+ root.addContent(new Text(" "));
+ root.addContent(new Text("txt"));
+ FormatSetup fs = new FormatSetup() {
+ @Override
+ public void setup(Format fmt) {
+ fmt.setExpandEmptyElements(true);
+ }
+ };
+ checkOutput(root, fs,
+ "<root><!--Boo--> txt</root>",
+ "<root><!--Boo-->txt</root>",
+ "<root>\n <!--Boo-->\n txt\n</root>",
+ "<root>\n <!--Boo-->\n txt\n</root>");
+ }
+
+ @Test
+ public void testOutputElementMixedMultiZeroText() {
+ // this test has mixed content (text-type and not text type).
+ // and, it has a multi-text-type at the end.
+ Element root = new Element("root");
+ root.addContent(new Comment("Boo"));
+ root.addContent(new Text(""));
+ root.addContent(new Text(" "));
+ root.addContent(new Text(""));
+ root.addContent(new Text("txt"));
+ root.addContent(new Text(""));
+ FormatSetup fs = new FormatSetup() {
+ @Override
+ public void setup(Format fmt) {
+ fmt.setExpandEmptyElements(true);
+ fmt.setLineSeparator("\n");
+ }
+ };
+ checkOutput(root, fs,
+ "<root><!--Boo--> txt</root>",
+ "<root><!--Boo-->txt</root>",
+ "<root>\n <!--Boo-->\n txt\n</root>",
+ "<root>\n <!--Boo-->\n txt\n</root>");
+ }
+
+ @Test
+ public void testOutputElementMultiEntityLeftRight() {
+ Element root = new Element("root");
+ root.addContent(new EntityRef("erl"));
+ root.addContent(new Text(" "));
+ root.addContent(new Text(" "));
+ root.addContent(new EntityRef("err"));
+ checkOutput(root,
+ "<root>&erl; &err;</root>",
+ "<root>&erl; &err;</root>",
+ "<root>&erl; &err;</root>",
+ "<root>&erl; &err;</root>");
+ }
+
+ @Test
+ public void testOutputElementMultiTrimLeftRight() {
+ Element root = new Element("root");
+ root.addContent(new Text(" tl "));
+ root.addContent(new Text(" mid "));
+ root.addContent(new Text(" tr "));
+ checkOutput(root,
+ "<root> tl mid tr </root>",
+ "<root>tl mid tr</root>",
+ "<root>tl mid tr</root>",
+ "<root> tl mid tr </root>");
+ }
+
+ @Test
+ public void testOutputElementMultiCDATALeftRight() {
+ Element root = new Element("root");
+ root.addContent(new CDATA(" tl "));
+ root.addContent(new Text(" mid "));
+ root.addContent(new CDATA(" tr "));
+ checkOutput(root,
+ "<root><![CDATA[ tl ]]> mid <![CDATA[ tr ]]></root>",
+ "<root><![CDATA[tl]]> mid <![CDATA[tr]]></root>",
+ "<root><![CDATA[tl ]]> mid <![CDATA[ tr]]></root>",
+ "<root><![CDATA[ tl ]]> mid <![CDATA[ tr ]]></root>");
+ }
+
+ @Test
+ public void testTrimFullWhite() throws XMLStreamException {
+ // See issue #31.
+ // https://github.com/hunterhacker/jdom/issues/31
+ // This tests should pass when issue 31 is resolved.
+ Element root = new Element("root");
+ root.addContent(new Text(" "));
+ root.addContent(new Text("x"));
+ root.addContent(new Text(" "));
+ Format mf = Format.getRawFormat();
+ mf.setTextMode(TextMode.TRIM_FULL_WHITE);
+ StAXEventOutputter xout = new StAXEventOutputter(mf);
+ EventStore es = new EventStore("UTF-8");
+ xout.output(root, es);
+ assertEquals("<root> x </root>", es.toString());
+ }
+
+ @Test
+ public void testOutputElementNamespaces() {
+ String txt = "<ns:root xmlns:ns=\"myns\" xmlns:ans=\"attributens\" xmlns:two=\"two\" ans:att=\"val\"/>";
+ Element emt = new Element("root", Namespace.getNamespace("ns", "myns"));
+ Namespace ans = Namespace.getNamespace("ans", "attributens");
+ emt.setAttribute(new Attribute("att", "val", ans));
+ emt.addNamespaceDeclaration(Namespace.getNamespace("two", "two"));
+ checkOutput(emt,
+ txt, txt, txt, txt);
+ }
+
+ @Test
+ public void testOutputDocTypeSimple() {
+ checkOutput(new DocType("root"), "<!DOCTYPE root>", "<!DOCTYPE root>", "<!DOCTYPE root>", "<!DOCTYPE root>");
+ }
+
+ @Test
+ public void testOutputDocTypeInternalSubset() {
+ String dec = "<!DOCTYPE root [\ninternal]>";
+ DocType dt = new DocType("root");
+ dt.setInternalSubset("internal");
+ checkOutput(dt, dec, dec, dec, dec);
+ }
+
+ @Test
+ public void testOutputDocTypeSystem() {
+ String dec = "<!DOCTYPE root SYSTEM \"systemID\">";
+ checkOutput(new DocType("root", "systemID"), dec, dec, dec, dec);
+ }
+
+ @Test
+ public void testOutputDocTypePublic() {
+ String dec = "<!DOCTYPE root PUBLIC \"publicID\">";
+ checkOutput(new DocType("root", "publicID", null), dec, dec, dec, dec);
+ }
+
+ @Test
+ public void testOutputDocTypePublicSystem() {
+ String dec = "<!DOCTYPE root PUBLIC \"publicID\" \"systemID\">";
+ checkOutput(new DocType("root", "publicID", "systemID"), dec, dec, dec, dec);
+ }
+
+ @Test
+ public void testOutputDocumentSimple() {
+ Document doc = new Document();
+ doc.addContent(new Element("root"));
+ String xmldec = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
+ String rtdec = "<root/>";
+ checkOutput(doc,
+ xmldec + "\n" + rtdec + "\n",
+ xmldec + "\n" + rtdec + "\n",
+ xmldec + "\n" + rtdec + "\n",
+ xmldec + "\n" + rtdec + "\n");
+ }
+
+ @Test
+ public void testOutputDocumentOmitEncoding() {
+ Document doc = new Document();
+ doc.addContent(new Element("root"));
+ String xmldec = "<?xml version=\"1.0\"?>";
+ FormatSetup setup = new FormatSetup() {
+ @Override
+ public void setup(Format fmt) {
+ fmt.setOmitEncoding(true);
+ }
+ };
+ String rtdec = "<root/>";
+ checkOutput(doc, setup,
+ xmldec + "\n" + rtdec + "\n",
+ xmldec + "\n" + rtdec + "\n",
+ xmldec + "\n" + rtdec + "\n",
+ xmldec + "\n" + rtdec + "\n");
+ }
+
+ @Test
+ @Ignore
+ public void testOutputDocumentOmitDeclaration() {
+ Document doc = new Document();
+ doc.addContent(new Element("root"));
+ FormatSetup setup = new FormatSetup() {
+ @Override
+ public void setup(Format fmt) {
+ fmt.setOmitDeclaration(true);
+ }
+ };
+ String rtdec = "<root/>";
+ checkOutput(doc, setup,
+ rtdec + "\n",
+ rtdec + "\n",
+ rtdec + "\n",
+ rtdec + "\n");
+ }
+
+ @Test
+ public void testOutputDocumentFull() {
+ DocType dt = new DocType("root");
+ Comment comment = new Comment("comment");
+ ProcessingInstruction pi = new ProcessingInstruction("jdomtest", "");
+ Element root = new Element("root");
+ Document doc = new Document();
+ doc.addContent(dt);
+ doc.addContent(comment);
+ doc.addContent(pi);
+ doc.addContent(root);
+ String xmldec = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
+ String dtdec = "<!DOCTYPE root>";
+ String commentdec = "<!--comment-->";
+ String pidec = "<?jdomtest?>";
+ String rtdec = "<root/>";
+ String lf = "\n";
+ checkOutput(doc,
+ xmldec + lf + dtdec + lf + commentdec + pidec + rtdec + lf,
+ xmldec + lf + dtdec + lf + commentdec + pidec + rtdec + lf,
+ xmldec + lf + dtdec + lf + lf + commentdec + lf + pidec + lf + rtdec + lf,
+ xmldec + lf + dtdec + lf + lf + commentdec + lf + pidec + lf + rtdec + lf);
+ }
+
+ @Test
+ public void testDeepNesting() {
+ // need to get beyond 16 levels of XML.
+ DocType dt = new DocType("root");
+ Element root = new Element("root");
+ Document doc = new Document();
+ doc.addContent(dt);
+ doc.addContent(root);
+ String xmldec = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
+ String dtdec = "<!DOCTYPE root>";
+ String lf = "\n";
+
+ String base = xmldec + lf + dtdec + lf;
+ StringBuilder raw = new StringBuilder(base);
+ StringBuilder pretty = new StringBuilder(base);
+ raw.append("<root>");
+ pretty.append(lf);
+ pretty.append("<root>");
+ pretty.append(lf);
+ final int depth = 40;
+ int cnt = depth;
+ Parent parent = root;
+ StringBuilder indent = new StringBuilder();
+ while (--cnt > 0) {
+ Element emt = new Element("emt");
+ parent.getContent().add(emt);
+ parent = emt;
+ raw.append("<emt>");
+ indent.append(" ");
+ pretty.append(indent.toString());
+ pretty.append("<emt>");
+ pretty.append(lf);
+ }
+
+ parent.getContent().add(new Element("bottom"));
+ raw.append("<bottom/>");
+ pretty.append(indent.toString());
+ pretty.append(" <bottom/>");
+ pretty.append(lf);
+
+ cnt = depth;
+ while (--cnt > 0) {
+ raw.append("</emt>");
+ pretty.append(indent.toString());
+ pretty.append("</emt>");
+ indent.setLength(indent.length() - 2);
+ pretty.append(lf);
+ }
+ raw.append("</root>");
+ raw.append(lf);
+ pretty.append("</root>");
+ pretty.append(lf);
+
+ checkOutput(doc, raw.toString(), raw.toString(), pretty.toString(), pretty.toString());
+ }
+
+ @Test
+ public void testOutputElementContent() {
+ Element root = new Element("root");
+ root.addContent(new Element("child"));
+ checkOutput(root, "outputElementContent", Element.class, null, "<child/>", "<child/>", "<child/>\n", "<child/>\n");
+ }
+
+ @Test
+ public void testOutputList() {
+ List<Object> c = new ArrayList<Object>();
+ c.add(new Element("root"));
+ checkOutput(c, "output", List.class, null, "<root/>", "<root/>", "<root/>\n", "<root/>\n");
+ }
+
+ @Test
+ public void testClone() {
+ StAXEventOutputter xo = new StAXEventOutputter();
+ assertTrue(xo != xo.clone());
+ }
+
+ @Test
+ public void testToString() {
+ Format fmt = Format.getCompactFormat();
+ fmt.setLineSeparator("\n\t ");
+ StAXEventOutputter out = new StAXEventOutputter(fmt);
+ assertNotNull(out.toString());
+ }
+
+ private interface FormatSetup {
+ public void setup(Format fmt);
+ }
+
+ private void checkOutput(Object content, String raw, String compact, String pretty, String trimfw) {
+ Class<?> clazz = content.getClass();
+ checkOutput(content, "output", clazz, null, raw, compact, pretty, trimfw);
+ }
+ private void checkOutput(Object content, FormatSetup setup, String raw, String compact, String pretty, String trimfw) {
+ Class<?> clazz = content.getClass();
+ checkOutput(content, "output", clazz, setup, raw, compact, pretty, trimfw);
+ }
+
+ /**
+ * The following method will run the output data through each of the three base
+ * formatters, raw, compact, and pretty. It will also run each of those
+ * formatters as the outputString(content), output(content, OutputStream)
+ * and output(content, Writer).
+ *
+ * The expectation is that the results of the three output forms (String,
+ * OutputStream, and Writer) will be identical, and that it will match
+ * the expected value for the appropriate formatter.
+ *
+ * @param content The content to output
+ * @param methodprefix What the methods are called
+ * @param clazz The class used as the parameter for the methods.
+ * @param setup A callback mechanism to modify the formatters
+ * @param raw What we expect the content to look like with the RAW format
+ * @param compact What we expect the content to look like with the COMPACT format
+ * @param pretty What we expect the content to look like with the PRETTY format
+ * @param trimfw What we expect the content to look like with the TRIM_FULL_WHITE format
+ */
+ private void checkOutput(Object content, String methodprefix, Class<?> clazz,
+ FormatSetup setup, String raw, String compact, String pretty, String trimfw) {
+ Method mstream = getMethod(methodprefix, clazz, XMLStreamWriter.class);
+
+ String[] descn = new String[] {"Raw", "Compact", "Pretty", "TrimFullWhite"};
+ Format ftrimfw = Format.getPrettyFormat();
+ ftrimfw.setTextMode(TextMode.TRIM_FULL_WHITE);
+ Format[] formats = new Format[] {
+ getFormat(setup, Format.getRawFormat()),
+ getFormat(setup, Format.getCompactFormat()),
+ getFormat(setup, Format.getPrettyFormat()),
+ getFormat(setup, ftrimfw)};
+ String[] result = new String[] {raw, compact, pretty, trimfw};
+
+ for (int i = 0; i < 4; i++) {
+ StAXEventOutputter out = new StAXEventOutputter(formats[i]);
+ CharArrayWriter caw = new CharArrayWriter(result[i].length() + 2);
+ try {
+ if (mstream != null) {
+ XMLStreamWriter xsw = soutfactory.createXMLStreamWriter(caw);
+ mstream.invoke(out, content, xsw);
+ xsw.close();
+ String rstream = caw.toString();
+ assertEquals("output OutputStream Format " + descn[i], result[i], rstream);
+ }
+
+ } catch (Exception e) {
+ //e.printStackTrace();
+ AssertionError ae = new AssertionError("Failed to process " + descn[i] + " on content " + clazz + ": " + e.getMessage());
+ ae.initCause(e);
+ throw ae;
+ }
+ }
+ }
+
+ private Format getFormat(FormatSetup setup, Format input) {
+ input.setLineSeparator("\n");
+ if (setup == null) {
+ return input;
+ }
+ setup.setup(input);
+ return input;
+ }
+
+ private Method getMethod(String name, Class<?>...classes) {
+ try {
+ return StAXEventOutputter.class.getMethod(name, classes);
+ } catch (Exception e) {
+ // ignore.
+ System.out.println("Can't find " + name + ": " + e.getMessage());
+ }
+ return null;
+ }
+
+
+
+
+
+
+ /*
+ * The following are borrowed from the TestSAXOutputter
+ * The effect is that we compare the StAX string output with the re-parsed
+ * value of the input.
+ */
+
+ private void roundTripDocument(Document doc) {
+ StAXEventOutputter xout = new StAXEventOutputter(Format.getRawFormat());
+ // create a String representation of the input.
+ if (doc.hasRootElement()) {
+ normalizeAttributes(doc.getRootElement());
+ }
+
+ try {
+ EventStore xsw = new EventStore("UTF-8");
+ xout.output(doc, xsw);
+ String expect = xsw.toString();
+
+ // convert the input to a SAX Stream
+
+ StAXStreamBuilder sbuilder = new StAXStreamBuilder();
+
+ char[] chars = expect.toCharArray();
+ CharArrayReader car = new CharArrayReader(chars);
+ XMLStreamReader xsr = sinfactory.createXMLStreamReader(car);
+
+ Document backagain = sbuilder.build(xsr);
+ xsr.close();
+
+ // get a String representation of the round-trip.
+ if (backagain.hasRootElement()) {
+ normalizeAttributes(backagain.getRootElement());
+ }
+ xsw = new EventStore("UTF-8");
+ xout.output(backagain, xsw);
+ String actual = xsw.toString();
+
+ assertEquals(expect, actual);
+ } catch (Exception e) {
+ failException("Failed to round-trip the document with exception: "
+ + e.getMessage(), e);
+ }
+ }
+
+ private void roundTripElement(Element emt) {
+
+ try {
+ StAXEventOutputter xout = new StAXEventOutputter(Format.getRawFormat());
+
+ EventStore xsw = new EventStore("UTF-8");
+ xout.output(emt, xsw);
+ String expect = xsw.toString();
+
+ StAXStreamBuilder sbuilder = new StAXStreamBuilder();
+
+ XMLStreamReader xsr = sinfactory.createXMLStreamReader(new StringReader(expect));
+ assertTrue(xsr.getEventType() == XMLStreamConstants.START_DOCUMENT);
+ assertTrue(xsr.hasNext());
+ xsr.next();
+
+ Element backagain = (Element)sbuilder.fragment(xsr);
+
+ // convert the input to a SAX Stream
+
+ xsw = new EventStore("UTF-8");
+ xout.output(backagain, xsw);
+
+ String actual = xsw.toString();
+ assertEquals(expect, actual);
+ } catch (Exception e) {
+ failException("Failed to round-trip the document with exception: "
+ + e.getMessage(), e);
+ }
+ }
+
+ private void roundTripFragment(List<Content> content) {
+ try {
+ StAXEventOutputter xout = new StAXEventOutputter(Format.getRawFormat());
+
+ EventStore xsw = new EventStore("UTF-8");
+ xout.output(content, xsw);
+ String expect = xsw.toString();
+
+ StAXStreamBuilder sbuilder = new StAXStreamBuilder();
+
+ XMLStreamReader xsr = sinfactory.createXMLStreamReader(new StringReader(expect));
+// assertTrue(xsr.getEventType() == XMLStreamConstants.START_DOCUMENT);
+// assertTrue(xsr.hasNext());
+// xsr.next();
+
+ List<Content> backagain = sbuilder.buildFragments(xsr, new DefaultStAXFilter());
+
+ // convert the input to a SAX Stream
+
+ xsw = new EventStore("UTF-8");
+ xout.output(backagain, xsw);
+
+ String actual = xsw.toString();
+ assertEquals(expect, actual);
+ } catch (Exception e) {
+ failException("Failed to round-trip the document with exception: "
+ + e.getMessage(), e);
+ }
+
+ }
+
+ private void roundTripFragment(Content content) {
+ try {
+ StAXEventOutputter xout = new StAXEventOutputter(Format.getRawFormat());
+
+ EventStore xsw = new EventStore("UTF-8");
+ switch(content.getCType()) {
+ case CDATA :
+ xout.output((CDATA)content, xsw);
+ break;
+ case Text:
+ xout.output((Text)content, xsw);
+ break;
+ case Comment:
+ xout.output((Comment)content, xsw);
+ break;
+ case DocType:
+ xout.output((DocType)content, xsw);
+ break;
+ case Element:
+ xout.output((Element)content, xsw);
+ break;
+ case EntityRef:
+ xout.output((EntityRef)content, xsw);
+ break;
+ case ProcessingInstruction:
+ xout.output((ProcessingInstruction)content, xsw);
+ break;
+ default:
+ throw new IllegalStateException(content.getCType().toString());
+ }
+ String expect = xsw.toString();
+
+ StAXStreamBuilder sbuilder = new StAXStreamBuilder();
+
+ Content backagain = sbuilder.fragment(
+ sinfactory.createXMLStreamReader(new StringReader(expect)));
+
+ // convert the input to a SAX Stream
+
+ xsw = new EventStore("UTF-8");
+ switch(content.getCType()) {
+ case CDATA :
+ xout.output((CDATA)backagain, xsw);
+ break;
+ case Text:
+ xout.output((Text)backagain, xsw);
+ break;
+ case Comment:
+ xout.output((Comment)backagain, xsw);
+ break;
+ case DocType:
+ xout.output((DocType)backagain, xsw);
+ break;
+ case Element:
+ xout.output((Element)backagain, xsw);
+ break;
+ case EntityRef:
+ xout.output((EntityRef)backagain, xsw);
+ break;
+ case ProcessingInstruction:
+ xout.output((ProcessingInstruction)backagain, xsw);
+ break;
+ default:
+ throw new IllegalStateException(backagain.getCType().toString());
+ }
+
+ String actual = xsw.toString();
+ assertEquals(expect, actual);
+ } catch (Exception e) {
+ failException("Failed to round-trip the document with exception: "
+ + e.getMessage(), e);
+ }
+ }
+
+ @Test
+ public void testRTOutputDocumentSimple() {
+ Document doc = new Document(new Element("root"));
+ roundTripDocument(doc);
+ }
+
+ @Test
+ // TODO
+ @Ignore
+ public void testRTOutputDocumentFull() {
+ Document doc = new Document();
+ DocType dt = new DocType("root");
+ dt.setInternalSubset(" ");
+ doc.addContent(dt);
+ doc.addContent(new Comment("This is a document"));
+ doc.addContent(new ProcessingInstruction("jdomtest", ""));
+ Element e = new Element("root");
+ e.addContent(new EntityRef("ref"));
+ doc.addContent(e);
+ roundTripDocument(doc);
+ }
+
+ @Test
+ public void testOutputDocumentRootAttNS() {
+ Document doc = new Document();
+ Element e = new Element("root");
+ e.setAttribute(new Attribute("att", "val", Namespace.getNamespace("ans", "mynamespace")));
+ doc.addContent(e);
+ roundTripDocument(doc);
+ }
+
+ @Test
+ public void testOutputDocumentFullNoLexical() throws JDOMException {
+ Document doc = new Document();
+ doc.addContent(new ProcessingInstruction("jdomtest", ""));
+ Element e = new Element("root");
+ doc.addContent(e);
+ e.addContent(new Text("text"));
+ e.addContent(new EntityRef("ref"));
+
+ // the Lexical handler is what helps track comments,
+ // and identifies CDATA sections.
+ // as a result the output of CDATA structures appears as plain text.
+ // and comments are dropped....
+ e.addContent(new Text("cdata"));
+ String expect = new XMLOutputter().outputString(doc);
+ e.removeContent(2);
+ e.addContent(new CDATA("cdata"));
+ e.addContent(new Comment("This is a document"));
+
+ SAXHandler handler = new SAXHandler();
+ SAXOutputter saxout = new SAXOutputter(handler, handler, handler, handler);
+ saxout.output(doc);
+
+ Document act = handler.getDocument();
+ String actual = new XMLOutputter().outputString(act);
+
+ assertEquals(expect, actual);
+
+ }
+
+ @Test
+ public void testOutputDocumentNoErrorHandler() {
+ DefaultHandler2 handler = new DefaultHandler2() {
+ @Override
+ public void error(SAXParseException arg0) throws SAXException {
+ throw new SAXException ("foo!");
+ }
+ };
+
+ SAXOutputter saxout = new SAXOutputter(handler);
+
+ try {
+ saxout.outputFragment(new DocType("rootemt"));
+ fail("SHould have exception!");
+ } catch (JDOMException e) {
+ assertTrue(e.getMessage().indexOf("rootemt") >= 0);
+ }
+
+ saxout.setErrorHandler(handler);
+
+ try {
+ saxout.outputFragment(new DocType("rootemt"));
+ fail("SHould have exception!");
+ } catch (JDOMException e) {
+ assertTrue(e.getMessage().endsWith("foo!"));
+ }
+
+ }
+
+ @Test
+ public void testOutputDocumentAttributes() {
+ Element emt = new Element("root");
+ emt.setAttribute("att", "val");
+ Document doc = new Document(emt);
+ roundTripDocument(doc);
+ }
+
+ @Test
+ public void testOutputDocumentNamespaces() {
+ Element emt = new Element("root", Namespace.getNamespace("ns", "myns"));
+ Namespace ans = Namespace.getNamespace("ans", "attributens");
+ emt.addNamespaceDeclaration(ans);
+ emt.addNamespaceDeclaration(Namespace.getNamespace("two", "two"));
+ emt.setAttribute(new Attribute("att", "val", ans));
+ emt.addContent(new Element("child", Namespace.getNamespace("", "childuri")));
+ Document doc = new Document(emt);
+ roundTripDocument(doc);
+ }
+
+ @Test
+ public void testRTOutputList() {
+ List<Content> list = new ArrayList<Content>();
+ list.add(new ProcessingInstruction("jdomtest", ""));
+ list.add(new Comment("comment"));
+ list.add(new Element("root"));
+ roundTripFragment(list);
+ }
+
+ @Test
+ public void testOutputElementAttributes() {
+ Element emt = new Element("root");
+ emt.setAttribute("att", "val");
+ emt.setAttribute(new Attribute("attx", "valx", AttributeType.UNDECLARED));
+ roundTripElement(emt);
+ }
+
+ @Test
+ public void testRTOutputElementNamespaces() {
+ Element emt = new Element("root", Namespace.getNamespace("ns", "myns"));
+ Namespace ans = Namespace.getNamespace("ans", "attributens");
+ emt.addNamespaceDeclaration(ans);
+ emt.addNamespaceDeclaration(Namespace.getNamespace("two", "two"));
+ emt.setAttribute(new Attribute("att", "val", ans));
+ emt.addContent(new Element("child", Namespace.getNamespace("", "childns")));
+ roundTripElement(emt);
+ }
+
+ @Test
+ @Ignore
+ public void testOutputFragmentList() {
+ List<Content> list = new ArrayList<Content>();
+ list.add(new ProcessingInstruction("jdomtest", ""));
+ list.add(new Comment("comment"));
+ list.add(new CDATA("foo"));
+ list.add(new Element("root"));
+ list.add(new Text("bar"));
+ roundTripFragment(list);
+ }
+
+ @Test
+ @Ignore
+ public void testOutputFragmentContent() {
+ roundTripFragment(new ProcessingInstruction("jdomtest", ""));
+ roundTripFragment(new Comment("comment"));
+ roundTripFragment(new CDATA("foo"));
+ roundTripFragment(new Element("root"));
+ roundTripFragment(new Text("bar"));
+ }
+
+ @Test
+ public void testOutputNullContent() throws JDOMException {
+ DefaultHandler2 handler = new DefaultHandler2() {
+ @Override
+ public void startDocument() throws SAXException {
+ throw new SAXException("SHould not be reaching this, ever");
+ }
+ };
+ SAXOutputter saxout = new SAXOutputter(handler, handler, handler, handler, handler);
+
+ Document doc = null;
+ Element emt = null;
+ List<Content> list = null;
+ List<Content> empty = new ArrayList<Content>();
+ saxout.output(doc);
+ saxout.output(emt);
+ saxout.output(list);
+ saxout.output(empty);
+ saxout.outputFragment(emt);
+ saxout.outputFragment(list);
+ saxout.outputFragment(empty);
+ }
+
+
+}
diff --git a/test/src/java/org/jdom2/test/cases/output/TestStAXStreamOutputter.java b/test/src/java/org/jdom2/test/cases/output/TestStAXStreamOutputter.java
new file mode 100644
index 000000000..94a6c1fde
--- /dev/null
+++ b/test/src/java/org/jdom2/test/cases/output/TestStAXStreamOutputter.java
@@ -0,0 +1,1290 @@
+package org.jdom2.test.cases.output;
+
+import static org.jdom2.test.util.UnitTestUtil.failException;
+import static org.jdom2.test.util.UnitTestUtil.normalizeAttributes;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.ByteArrayOutputStream;
+import java.io.CharArrayReader;
+import java.io.CharArrayWriter;
+import java.io.IOException;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamConstants;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.stream.XMLStreamWriter;
+import javax.xml.transform.Result;
+
+import org.junit.Ignore;
+import org.junit.Test;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+import org.xml.sax.ext.DefaultHandler2;
+
+import org.jdom2.Attribute;
+import org.jdom2.AttributeType;
+import org.jdom2.CDATA;
+import org.jdom2.Comment;
+import org.jdom2.Content;
+import org.jdom2.DocType;
+import org.jdom2.Document;
+import org.jdom2.Element;
+import org.jdom2.EntityRef;
+import org.jdom2.IllegalDataException;
+import org.jdom2.JDOMException;
+import org.jdom2.Namespace;
+import org.jdom2.Parent;
+import org.jdom2.ProcessingInstruction;
+import org.jdom2.Text;
+import org.jdom2.UncheckedJDOMFactory;
+import org.jdom2.input.DefaultStAXFilter;
+import org.jdom2.input.SAXBuilder;
+import org.jdom2.input.SAXHandler;
+import org.jdom2.input.StAXStreamBuilder;
+import org.jdom2.output.AbstractStAXStreamProcessor;
+import org.jdom2.output.Format;
+import org.jdom2.output.Format.TextMode;
+import org.jdom2.output.SAXOutputter;
+import org.jdom2.output.StAXStreamOutputter;
+import org.jdom2.output.StAXStreamProcessor;
+import org.jdom2.output.XMLOutputter;
+
+@SuppressWarnings("javadoc")
+public final class TestStAXStreamOutputter {
+
+
+ XMLOutputFactory soutfactory = XMLOutputFactory.newInstance();
+ XMLInputFactory sinfactory = XMLInputFactory.newInstance();
+
+ @Test
+ public void test_HighSurrogatePair() throws XMLStreamException, IOException, JDOMException {
+ SAXBuilder builder = new SAXBuilder();
+ builder.setExpandEntities(true);
+ Document doc = builder.build(new StringReader("<?xml version=\"1.0\"?><root>𐀀 𐀀</root>"));
+
+ Format format = Format.getCompactFormat().setEncoding("ISO-8859-1");
+ StAXStreamOutputter outputter = new StAXStreamOutputter(format);
+ ByteArrayOutputStream sw = new ByteArrayOutputStream();
+ XMLStreamWriter xsw = soutfactory.createXMLStreamWriter(sw, "ISO-8859-1");
+ outputter.output(doc, xsw);
+ String xml = sw.toString();
+ assertEquals("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + format.getLineSeparator() +
+ "<root>�� ��</root>" + format.getLineSeparator(), xml);
+ }
+
+ @Test
+ public void test_HighSurrogatePairDecimal() throws JDOMException, IOException, XMLStreamException {
+ SAXBuilder builder = new SAXBuilder();
+ builder.setExpandEntities(true);
+ Document doc = builder.build(new StringReader("<?xml version=\"1.0\"?><root>𐀀 𐀀</root>"));
+ Format format = Format.getCompactFormat().setEncoding("ISO-8859-1");
+ StAXStreamOutputter outputter = new StAXStreamOutputter(format);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ XMLStreamWriter xsw = soutfactory.createXMLStreamWriter(baos, "ISO-8859-1");
+ outputter.output(doc, xsw);
+ String xml = baos.toString();
+ assertEquals("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + format.getLineSeparator() +
+ "<root>�� ��</root>" + format.getLineSeparator(), xml);
+ }
+
+ @Test
+ public void test_HighSurrogateAttPair() throws JDOMException, IOException, XMLStreamException {
+ SAXBuilder builder = new SAXBuilder();
+ builder.setExpandEntities(true);
+ Document doc = builder.build(new StringReader("<?xml version=\"1.0\"?><root att=\"𐀀 𐀀\" />"));
+ Format format = Format.getCompactFormat().setEncoding("ISO-8859-1");
+ StAXStreamOutputter outputter = new StAXStreamOutputter(format);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ XMLStreamWriter xsw = soutfactory.createXMLStreamWriter(baos, "ISO-8859-1");
+ outputter.output(doc, xsw);
+ String xml = baos.toString();
+ assertEquals("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + format.getLineSeparator() +
+ "<root att=\"�� ��\"/>" + format.getLineSeparator(), xml);
+ }
+
+ @Test
+ public void test_HighSurrogateAttPairDecimal() throws JDOMException, IOException, XMLStreamException {
+ SAXBuilder builder = new SAXBuilder();
+ builder.setExpandEntities(true);
+ Document doc = builder.build(new StringReader("<?xml version=\"1.0\"?><root att=\"𐀀 𐀀\" />"));
+ Format format = Format.getCompactFormat().setEncoding("ISO-8859-1");
+ StAXStreamOutputter outputter = new StAXStreamOutputter(format);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ XMLStreamWriter xsw = soutfactory.createXMLStreamWriter(baos, "ISO-8859-1");
+ outputter.output(doc, xsw);
+ String xml = baos.toString();
+ assertEquals("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + format.getLineSeparator() +
+ "<root att=\"�� ��\"/>" + format.getLineSeparator(), xml);
+ }
+
+ // Construct a raw surrogate pair character and confirm it outputs hex escaped
+ @Test
+ public void test_RawSurrogatePair() throws JDOMException, IOException, XMLStreamException {
+ SAXBuilder builder = new SAXBuilder();
+ builder.setExpandEntities(true);
+ Document doc = builder.build(new StringReader("<?xml version=\"1.0\"?><root>\uD800\uDC00</root>"));
+ Format format = Format.getCompactFormat().setEncoding("ISO-8859-1");
+ StAXStreamOutputter outputter = new StAXStreamOutputter(format);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ XMLStreamWriter xsw = soutfactory.createXMLStreamWriter(baos, "ISO-8859-1");
+ outputter.output(doc, xsw);
+ String xml = baos.toString();
+ assertEquals("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + format.getLineSeparator() +
+ "<root>��</root>" + format.getLineSeparator(), xml);
+ }
+
+ // Construct a raw surrogate pair character and confirm it outputs hex escaped, when UTF-8 too
+ @Test
+ public void test_RawSurrogatePairUTF8() throws JDOMException, IOException, XMLStreamException {
+ SAXBuilder builder = new SAXBuilder();
+ builder.setExpandEntities(true);
+ Document doc = builder.build(new StringReader("<?xml version=\"1.0\"?><root>\uD800\uDC00</root>"));
+ Format format = Format.getCompactFormat().setEncoding("UTF-8");
+ StAXStreamOutputter outputter = new StAXStreamOutputter(format);
+ StringWriter baos = new StringWriter();
+ XMLStreamWriter xsw = soutfactory.createXMLStreamWriter(baos);
+ outputter.output(doc, xsw);
+ String xml = baos.toString();
+ assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + format.getLineSeparator() +
+ "<root>\uD800\uDC00</root>" + format.getLineSeparator(), xml);
+ }
+
+ // Construct illegal XML and check if the parser notices
+ @Test
+ public void test_ErrorSurrogatePair() throws JDOMException, IOException {
+ SAXBuilder builder = new SAXBuilder();
+ builder.setExpandEntities(true);
+ Document doc = builder.build(new StringReader("<?xml version=\"1.0\"?><root></root>"));
+ try {
+ doc.getRootElement().setText("\uD800\uDBFF");
+ fail("Illegal surrogate pair should have thrown an exception");
+ }
+ catch (IllegalDataException e) {
+ // do nothing
+ } catch (Exception e) {
+ fail ("Unexpected exception " + e.getClass());
+ }
+ }
+
+ // Manually construct illegal XML and make sure the outputter notices
+ @Test
+ public void test_ErrorSurrogatePairOutput() throws JDOMException, IOException, XMLStreamException {
+ SAXBuilder builder = new SAXBuilder();
+ builder.setExpandEntities(true);
+ Document doc = builder.build(new StringReader("<?xml version=\"1.0\"?><root></root>"));
+ Text t = new UncheckedJDOMFactory().text("\uD800\uDBFF");
+ doc.getRootElement().setContent(t);
+ Format format = Format.getCompactFormat().setEncoding("ISO-8859-1");
+ StAXStreamOutputter outputter = new StAXStreamOutputter(format);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ XMLStreamWriter xsw = soutfactory.createXMLStreamWriter(baos);
+ try {
+ outputter.output(doc, xsw);
+ fail("Illegal surrogate pair output should have thrown an exception");
+ }
+ catch (XMLStreamException e) {
+ // do nothing
+ } catch (Exception e) {
+ fail ("Unexpected exception " + e.getClass());
+ }
+ }
+
+
+ @Test
+ public void testXMLOutputter() {
+ StAXStreamOutputter out = new StAXStreamOutputter();
+ TestFormat.checkEquals(out.getFormat(), Format.getRawFormat());
+ }
+
+
+ @Test
+ public void testXMLOutputterFormat() {
+ Format mine = Format.getCompactFormat();
+ mine.setEncoding("US-ASCII");
+ StAXStreamOutputter out = new StAXStreamOutputter(mine);
+ TestFormat.checkEquals(mine, out.getFormat());
+ }
+
+// @Test
+// public void testXMLOutputterXMLOutputter() {
+// Format mine = Format.getCompactFormat();
+// StAXStreamProcessor xoutp = new StAXStreamOutputter().getStAXStream();
+// mine.setEncoding("US-ASCII");
+// // double-construct it.
+// StAXStreamOutputter out = new StAXStreamOutputter();
+// TestFormat.checkEquals(mine, out.getFormat());
+// assertTrue(xoutp == out.getXMLOutputProcessor());
+// }
+
+ @Test
+ public void testXMLOutputterXMLOutputProcessor() {
+ StAXStreamProcessor xoutp = new AbstractStAXStreamProcessor() {
+ // nothing;
+ };
+ // double-constrcut it.
+ StAXStreamOutputter out = new StAXStreamOutputter(xoutp);
+ TestFormat.checkEquals(Format.getRawFormat(), out.getFormat());
+ assertTrue(xoutp == out.getStAXStream());
+ }
+
+ @Test
+ public void testFormat() {
+ Format mine = Format.getCompactFormat();
+ mine.setEncoding("US-ASCII");
+ // double-constcut it.
+ StAXStreamOutputter out = new StAXStreamOutputter();
+ TestFormat.checkEquals(Format.getRawFormat(), out.getFormat());
+ out.setFormat(mine);
+ TestFormat.checkEquals(mine, out.getFormat());
+ }
+
+ @Test
+ public void testXMLOutputProcessor() {
+ StAXStreamProcessor xoutp = new AbstractStAXStreamProcessor() {
+ // nothing;
+ };
+ // double-constcut it.
+ StAXStreamOutputter out = new StAXStreamOutputter();
+ StAXStreamProcessor xop = out.getStAXStream();
+ out.setStAXStreamProcessor(xoutp);
+ assertTrue(xoutp != xop);
+ assertTrue(xoutp == out.getStAXStream());
+ }
+
+ @Test
+ public void testOutputText() {
+ checkOutput(new Text(" hello there "), " hello there ", "hello there", "hello there", " hello there ");
+ }
+
+ @Test
+ public void testOutputCDATA() {
+ String indata = " hello there bozo ! ";
+ String rawcdata = "<![CDATA[ hello there bozo ! ]]>";
+ String compdata = "<![CDATA[hello there bozo !]]>";
+ String prettydata = "<![CDATA[hello there bozo !]]>";
+ String trimdata = "<![CDATA[ hello there bozo ! ]]>";
+
+ checkOutput(new CDATA(indata), rawcdata, compdata, prettydata, trimdata);
+ }
+
+ @Test
+ public void testOutputComment() {
+ String incomment = " hello there bozo ! ";
+ String outcomment = "<!--" + incomment + "-->";
+ checkOutput(new Comment(incomment), outcomment, outcomment, outcomment, outcomment);
+ }
+
+ @Test
+ public void testOutputProcessingInstructionSimple() {
+ ProcessingInstruction inpi = new ProcessingInstruction("jdomtest", "");
+ String outpi = "<?jdomtest?>";
+ checkOutput(inpi, outpi, outpi, outpi, outpi);
+ }
+
+ @Test
+ public void testOutputProcessingInstructionData() {
+ String pi = " hello there ";
+ ProcessingInstruction inpi = new ProcessingInstruction("jdomtest", pi);
+ String outpi = "<?jdomtest " + pi + "?>";
+ checkOutput(inpi, outpi, outpi, outpi, outpi);
+ }
+
+ @Test
+ public void testOutputEntityRef() {
+ checkOutput(new EntityRef("name", "publicID", "systemID"),
+ "&name;", "&name;", "&name;", "&name;");
+ }
+
+ @Test
+ public void testOutputElementSimple() {
+ String txt = "<root/>";
+ checkOutput(new Element("root"), txt, txt, txt, txt);
+ }
+
+ @Test
+ public void testOutputElementAttribute() {
+ String txt = "<root att=\"val\"/>";
+ checkOutput(new Element("root").setAttribute("att", "val"), txt, txt, txt, txt);
+ }
+
+ @Test
+ public void testOutputElementCDATA() {
+ String txt = "<root><![CDATA[xx]]></root>";
+ Element root = new Element("root");
+ root.addContent(new CDATA("xx"));
+ checkOutput(root, txt, txt, txt, txt);
+ }
+
+ @Test
+ public void testOutputElementExpandEmpty() {
+ String txt = "<root></root>";
+ FormatSetup setup = new FormatSetup() {
+ @Override
+ public void setup(Format fmt) {
+ fmt.setExpandEmptyElements(true);
+ }
+ };
+ checkOutput(new Element("root"), setup, txt, txt, txt, txt);
+ }
+
+ @Test
+ public void testOutputElementPreserveSpace() {
+ String txt = "<root xml:space=\"preserve\"> <child xml:space=\"default\">abc</child> </root>";
+ Element root = new Element("root");
+ root.setAttribute("space", "preserve", Namespace.XML_NAMESPACE);
+ root.addContent(" ");
+ Element child = new Element("child");
+ child.setAttribute("space", "default", Namespace.XML_NAMESPACE);
+ child.addContent("abc");
+ root.addContent(child);
+ root.addContent(" ");
+ checkOutput(root, txt, txt, txt, txt);
+ }
+
+ @Test
+ @Ignore
+ // TODO
+ public void testOutputElementIgnoreTrAXEscapingPIs() {
+ Element root = new Element("root");
+ root.addContent(new Text("&"));
+ root.addContent(new ProcessingInstruction(Result.PI_DISABLE_OUTPUT_ESCAPING, ""));
+ root.addContent(new Text(" && "));
+ root.addContent(new ProcessingInstruction(Result.PI_ENABLE_OUTPUT_ESCAPING, ""));
+ root.addContent(new Text("&"));
+ String expect = "<root>& && &</root>";
+ String excompact = "<root>&&&&</root>";
+ String expretty = "<root>\n &\n \n &&\n \n &\n</root>";
+ String extfw = "<root>\n &\n \n && \n \n &\n</root>";
+ checkOutput(root,
+ expect,
+ excompact,
+ expretty,
+ extfw);
+ }
+
+
+ @Test
+ public void testOutputElementMultiText() {
+ Element root = new Element("root");
+ root.addContent(new CDATA(" "));
+ root.addContent(new Text(" xx "));
+ root.addContent(new Text("yy"));
+ root.addContent(new Text(" "));
+ root.addContent(new Text("zz"));
+ root.addContent(new Text(" ww"));
+ root.addContent(new EntityRef("amp"));
+ root.addContent(new Text("vv"));
+ root.addContent(new Text(" "));
+ checkOutput(root,
+ "<root><![CDATA[ ]]> xx yy zz ww&vv </root>",
+ "<root>xx yy zz ww&vv</root>",
+ "<root>xx yy zz ww&vv</root>",
+ // This should be changed with issue #31.
+ // The real value should have one additional
+ // space at the beginning and two at the end
+ // for now we leave the broken test here because it
+ // helps with the coverage reports.
+ // the next test is added to be a failing test.
+ "<root><![CDATA[ ]]> xx yy zz ww&vv </root>");
+ }
+
+ @Test
+ public void testOutputElementMultiAllWhite() {
+ Element root = new Element("root");
+ root.addContent(new CDATA(" "));
+ root.addContent(new Text(" "));
+ root.addContent(new Text(" "));
+ root.addContent(new Text(""));
+ root.addContent(new Text(" "));
+ root.addContent(new Text(" \n \n "));
+ root.addContent(new Text(" \t "));
+ root.addContent(new Text(" "));
+ checkOutput(root,
+ "<root><![CDATA[ ]]> \n \n \t </root>",
+ "<root/>",
+ "<root/>",
+ "<root/>");
+ }
+
+ @Test
+ public void testOutputElementMultiAllWhiteExpandEmpty() {
+ Element root = new Element("root");
+ root.addContent(new CDATA(" "));
+ root.addContent(new Text(" "));
+ root.addContent(new Text(" "));
+ root.addContent(new Text(""));
+ root.addContent(new Text(" "));
+ root.addContent(new Text(" \n \n "));
+ root.addContent(new Text(" \t "));
+ root.addContent(new Text(" "));
+ FormatSetup fs = new FormatSetup() {
+ @Override
+ public void setup(Format fmt) {
+ fmt.setExpandEmptyElements(true);
+ }
+ };
+ checkOutput(root, fs,
+ "<root><![CDATA[ ]]> \n \n \t </root>",
+ "<root></root>",
+ "<root></root>",
+ "<root></root>");
+ }
+
+ @Test
+ public void testOutputElementMultiMostWhiteExpandEmpty() {
+ // this test has mixed content (text-type and not text type).
+ // and, it has a multi-text-type at the end.
+ Element root = new Element("root");
+ root.addContent(new CDATA(" "));
+ root.addContent(new Text(" "));
+ root.addContent(new Text(" "));
+ root.addContent(new Text(""));
+ root.addContent(new Text(" "));
+ root.addContent(new Text(" \n \n "));
+ root.addContent(new Comment("Boo"));
+ root.addContent(new Text(" \t "));
+ root.addContent(new Text(" "));
+ FormatSetup fs = new FormatSetup() {
+ @Override
+ public void setup(Format fmt) {
+ fmt.setExpandEmptyElements(true);
+ }
+ };
+ checkOutput(root, fs,
+ "<root><![CDATA[ ]]> \n \n <!--Boo--> \t </root>",
+ "<root><!--Boo--></root>",
+ "<root>\n <!--Boo-->\n</root>",
+ "<root>\n <!--Boo-->\n</root>");
+ }
+
+ @Test
+ public void testOutputElementMixedMultiCDATA() {
+ // this test has mixed content (text-type and not text type).
+ // and, it has a multi-text-type at the end.
+ Element root = new Element("root");
+ root.addContent(new Comment("Boo"));
+ root.addContent(new Text(" "));
+ root.addContent(new CDATA("A"));
+ FormatSetup fs = new FormatSetup() {
+ @Override
+ public void setup(Format fmt) {
+ fmt.setExpandEmptyElements(true);
+ }
+ };
+ checkOutput(root, fs,
+ "<root><!--Boo--> <![CDATA[A]]></root>",
+ "<root><!--Boo--><![CDATA[A]]></root>",
+ "<root>\n <!--Boo-->\n <![CDATA[A]]>\n</root>",
+ "<root>\n <!--Boo-->\n <![CDATA[A]]>\n</root>");
+ }
+
+ @Test
+ public void testOutputElementMixedMultiEntityRef() {
+ // this test has mixed content (text-type and not text type).
+ // and, it has a multi-text-type at the end.
+ Element root = new Element("root");
+ root.addContent(new Comment("Boo"));
+ root.addContent(new Text(" "));
+ root.addContent(new EntityRef("aer"));
+ FormatSetup fs = new FormatSetup() {
+ @Override
+ public void setup(Format fmt) {
+ fmt.setExpandEmptyElements(true);
+ }
+ };
+ checkOutput(root, fs,
+ "<root><!--Boo--> &aer;</root>",
+ "<root><!--Boo-->&aer;</root>",
+ "<root>\n <!--Boo-->\n &aer;\n</root>",
+ "<root>\n <!--Boo-->\n &aer;\n</root>");
+ }
+
+ @Test
+ public void testOutputElementMixedMultiText() {
+ // this test has mixed content (text-type and not text type).
+ // and, it has a multi-text-type at the end.
+ Element root = new Element("root");
+ root.addContent(new Comment("Boo"));
+ root.addContent(new Text(" "));
+ root.addContent(new Text("txt"));
+ FormatSetup fs = new FormatSetup() {
+ @Override
+ public void setup(Format fmt) {
+ fmt.setExpandEmptyElements(true);
+ }
+ };
+ checkOutput(root, fs,
+ "<root><!--Boo--> txt</root>",
+ "<root><!--Boo-->txt</root>",
+ "<root>\n <!--Boo-->\n txt\n</root>",
+ "<root>\n <!--Boo-->\n txt\n</root>");
+ }
+
+ @Test
+ public void testOutputElementMixedMultiZeroText() {
+ // this test has mixed content (text-type and not text type).
+ // and, it has a multi-text-type at the end.
+ Element root = new Element("root");
+ root.addContent(new Comment("Boo"));
+ root.addContent(new Text(""));
+ root.addContent(new Text(" "));
+ root.addContent(new Text(""));
+ root.addContent(new Text("txt"));
+ root.addContent(new Text(""));
+ FormatSetup fs = new FormatSetup() {
+ @Override
+ public void setup(Format fmt) {
+ fmt.setExpandEmptyElements(true);
+ fmt.setLineSeparator("\n");
+ }
+ };
+ checkOutput(root, fs,
+ "<root><!--Boo--> txt</root>",
+ "<root><!--Boo-->txt</root>",
+ "<root>\n <!--Boo-->\n txt\n</root>",
+ "<root>\n <!--Boo-->\n txt\n</root>");
+ }
+
+ @Test
+ public void testOutputElementMultiEntityLeftRight() {
+ Element root = new Element("root");
+ root.addContent(new EntityRef("erl"));
+ root.addContent(new Text(" "));
+ root.addContent(new Text(" "));
+ root.addContent(new EntityRef("err"));
+ checkOutput(root,
+ "<root>&erl; &err;</root>",
+ "<root>&erl; &err;</root>",
+ "<root>&erl; &err;</root>",
+ "<root>&erl; &err;</root>");
+ }
+
+ @Test
+ public void testOutputElementMultiTrimLeftRight() {
+ Element root = new Element("root");
+ root.addContent(new Text(" tl "));
+ root.addContent(new Text(" mid "));
+ root.addContent(new Text(" tr "));
+ checkOutput(root,
+ "<root> tl mid tr </root>",
+ "<root>tl mid tr</root>",
+ "<root>tl mid tr</root>",
+ "<root> tl mid tr </root>");
+ }
+
+ @Test
+ public void testOutputElementMultiCDATALeftRight() {
+ Element root = new Element("root");
+ root.addContent(new CDATA(" tl "));
+ root.addContent(new Text(" mid "));
+ root.addContent(new CDATA(" tr "));
+ checkOutput(root,
+ "<root><![CDATA[ tl ]]> mid <![CDATA[ tr ]]></root>",
+ "<root><![CDATA[tl]]> mid <![CDATA[tr]]></root>",
+ "<root><![CDATA[tl ]]> mid <![CDATA[ tr]]></root>",
+ "<root><![CDATA[ tl ]]> mid <![CDATA[ tr ]]></root>");
+ }
+
+ @Test
+ public void testTrimFullWhite() throws XMLStreamException {
+ // See issue #31.
+ // https://github.com/hunterhacker/jdom/issues/31
+ // This tests should pass when issue 31 is resolved.
+ Element root = new Element("root");
+ root.addContent(new Text(" "));
+ root.addContent(new Text("x"));
+ root.addContent(new Text(" "));
+ Format mf = Format.getRawFormat();
+ mf.setTextMode(TextMode.TRIM_FULL_WHITE);
+ StAXStreamOutputter xout = new StAXStreamOutputter(mf);
+ StringWriter sw = new StringWriter();
+ XMLStreamWriter xsw = soutfactory.createXMLStreamWriter(sw);
+ xout.output(root, xsw);
+ assertEquals("<root> x </root>", sw.toString());
+ }
+
+ @Test
+ public void testOutputElementNamespaces() {
+ String txt = "<ns:root xmlns:ns=\"myns\" xmlns:ans=\"attributens\" xmlns:two=\"two\" ans:att=\"val\"/>";
+ Element emt = new Element("root", Namespace.getNamespace("ns", "myns"));
+ Namespace ans = Namespace.getNamespace("ans", "attributens");
+ emt.setAttribute(new Attribute("att", "val", ans));
+ emt.addNamespaceDeclaration(Namespace.getNamespace("two", "two"));
+ checkOutput(emt,
+ txt, txt, txt, txt);
+ }
+
+ @Test
+ public void testOutputDocTypeSimple() {
+ checkOutput(new DocType("root"), "<!DOCTYPE root>", "<!DOCTYPE root>", "<!DOCTYPE root>", "<!DOCTYPE root>");
+ }
+
+ @Test
+ public void testOutputDocTypeInternalSubset() {
+ String dec = "<!DOCTYPE root [\ninternal]>";
+ DocType dt = new DocType("root");
+ dt.setInternalSubset("internal");
+ checkOutput(dt, dec, dec, dec, dec);
+ }
+
+ @Test
+ public void testOutputDocTypeSystem() {
+ String dec = "<!DOCTYPE root SYSTEM \"systemID\">";
+ checkOutput(new DocType("root", "systemID"), dec, dec, dec, dec);
+ }
+
+ @Test
+ public void testOutputDocTypePublic() {
+ String dec = "<!DOCTYPE root PUBLIC \"publicID\">";
+ checkOutput(new DocType("root", "publicID", null), dec, dec, dec, dec);
+ }
+
+ @Test
+ public void testOutputDocTypePublicSystem() {
+ String dec = "<!DOCTYPE root PUBLIC \"publicID\" \"systemID\">";
+ checkOutput(new DocType("root", "publicID", "systemID"), dec, dec, dec, dec);
+ }
+
+ @Test
+ public void testOutputDocumentSimple() {
+ Document doc = new Document();
+ doc.addContent(new Element("root"));
+ String xmldec = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
+ String rtdec = "<root/>";
+ checkOutput(doc,
+ xmldec + "\n" + rtdec + "\n",
+ xmldec + "\n" + rtdec + "\n",
+ xmldec + "\n" + rtdec + "\n",
+ xmldec + "\n" + rtdec + "\n");
+ }
+
+ @Test
+ public void testOutputDocumentOmitEncoding() {
+ Document doc = new Document();
+ doc.addContent(new Element("root"));
+ String xmldec = "<?xml version=\"1.0\"?>";
+ FormatSetup setup = new FormatSetup() {
+ @Override
+ public void setup(Format fmt) {
+ fmt.setOmitEncoding(true);
+ }
+ };
+ String rtdec = "<root/>";
+ checkOutput(doc, setup,
+ xmldec + "\n" + rtdec + "\n",
+ xmldec + "\n" + rtdec + "\n",
+ xmldec + "\n" + rtdec + "\n",
+ xmldec + "\n" + rtdec + "\n");
+ }
+
+ @Test
+ @Ignore
+ // TODO
+ public void testOutputDocumentOmitDeclaration() {
+ Document doc = new Document();
+ doc.addContent(new Element("root"));
+ FormatSetup setup = new FormatSetup() {
+ @Override
+ public void setup(Format fmt) {
+ fmt.setOmitDeclaration(true);
+ }
+ };
+ String rtdec = "<root/>";
+ checkOutput(doc, setup,
+ rtdec + "\n",
+ rtdec + "\n",
+ rtdec + "\n",
+ rtdec + "\n");
+ }
+
+ @Test
+ public void testOutputDocumentFull() {
+ DocType dt = new DocType("root");
+ Comment comment = new Comment("comment");
+ ProcessingInstruction pi = new ProcessingInstruction("jdomtest", "");
+ Element root = new Element("root");
+ Document doc = new Document();
+ doc.addContent(dt);
+ doc.addContent(comment);
+ doc.addContent(pi);
+ doc.addContent(root);
+ String xmldec = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
+ String dtdec = "<!DOCTYPE root>";
+ String commentdec = "<!--comment-->";
+ String pidec = "<?jdomtest?>";
+ String rtdec = "<root/>";
+ String lf = "\n";
+ checkOutput(doc,
+ xmldec + lf + dtdec + lf + commentdec + pidec + rtdec + lf,
+ xmldec + lf + dtdec + lf + commentdec + pidec + rtdec + lf,
+ xmldec + lf + dtdec + lf + lf + commentdec + lf + pidec + lf + rtdec + lf,
+ xmldec + lf + dtdec + lf + lf + commentdec + lf + pidec + lf + rtdec + lf);
+ }
+
+ @Test
+ public void testDeepNesting() {
+ // need to get beyond 16 levels of XML.
+ DocType dt = new DocType("root");
+ Element root = new Element("root");
+ Document doc = new Document();
+ doc.addContent(dt);
+ doc.addContent(root);
+ String xmldec = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
+ String dtdec = "<!DOCTYPE root>";
+ String lf = "\n";
+
+ String base = xmldec + lf + dtdec + lf;
+ StringBuilder raw = new StringBuilder(base);
+ StringBuilder pretty = new StringBuilder(base);
+ raw.append("<root>");
+ pretty.append(lf);
+ pretty.append("<root>");
+ pretty.append(lf);
+ final int depth = 40;
+ int cnt = depth;
+ Parent parent = root;
+ StringBuilder indent = new StringBuilder();
+ while (--cnt > 0) {
+ Element emt = new Element("emt");
+ parent.getContent().add(emt);
+ parent = emt;
+ raw.append("<emt>");
+ indent.append(" ");
+ pretty.append(indent.toString());
+ pretty.append("<emt>");
+ pretty.append(lf);
+ }
+
+ parent.getContent().add(new Element("bottom"));
+ raw.append("<bottom/>");
+ pretty.append(indent.toString());
+ pretty.append(" <bottom/>");
+ pretty.append(lf);
+
+ cnt = depth;
+ while (--cnt > 0) {
+ raw.append("</emt>");
+ pretty.append(indent.toString());
+ pretty.append("</emt>");
+ indent.setLength(indent.length() - 2);
+ pretty.append(lf);
+ }
+ raw.append("</root>");
+ raw.append(lf);
+ pretty.append("</root>");
+ pretty.append(lf);
+
+ checkOutput(doc, raw.toString(), raw.toString(), pretty.toString(), pretty.toString());
+ }
+
+ @Test
+ public void testOutputElementContent() {
+ Element root = new Element("root");
+ root.addContent(new Element("child"));
+ checkOutput(root, "outputElementContent", Element.class, null, "<child/>", "<child/>", "<child/>\n", "<child/>\n");
+ }
+
+ @Test
+ public void testOutputList() {
+ List<Object> c = new ArrayList<Object>();
+ c.add(new Element("root"));
+ checkOutput(c, "output", List.class, null, "<root/>", "<root/>", "<root/>\n", "<root/>\n");
+ }
+
+ @Test
+ public void testClone() {
+ StAXStreamOutputter xo = new StAXStreamOutputter();
+ assertTrue(xo != xo.clone());
+ }
+
+ @Test
+ public void testToString() {
+ Format fmt = Format.getCompactFormat();
+ fmt.setLineSeparator("\n\t ");
+ StAXStreamOutputter out = new StAXStreamOutputter(fmt);
+ assertNotNull(out.toString());
+ }
+
+ private interface FormatSetup {
+ public void setup(Format fmt);
+ }
+
+ private void checkOutput(Object content, String raw, String compact, String pretty, String trimfw) {
+ Class<?> clazz = content.getClass();
+ checkOutput(content, "output", clazz, null, raw, compact, pretty, trimfw);
+ }
+ private void checkOutput(Object content, FormatSetup setup, String raw, String compact, String pretty, String trimfw) {
+ Class<?> clazz = content.getClass();
+ checkOutput(content, "output", clazz, setup, raw, compact, pretty, trimfw);
+ }
+
+ /**
+ * The following method will run the output data through each of the three base
+ * formatters, raw, compact, and pretty. It will also run each of those
+ * formatters as the outputString(content), output(content, OutputStream)
+ * and output(content, Writer).
+ *
+ * The expectation is that the results of the three output forms (String,
+ * OutputStream, and Writer) will be identical, and that it will match
+ * the expected value for the appropriate formatter.
+ *
+ * @param content The content to output
+ * @param methodprefix What the methods are called
+ * @param clazz The class used as the parameter for the methods.
+ * @param setup A callback mechanism to modify the formatters
+ * @param raw What we expect the content to look like with the RAW format
+ * @param compact What we expect the content to look like with the COMPACT format
+ * @param pretty What we expect the content to look like with the PRETTY format
+ * @param trimfw What we expect the content to look like with the TRIM_FULL_WHITE format
+ */
+ private void checkOutput(Object content, String methodprefix, Class<?> clazz,
+ FormatSetup setup, String raw, String compact, String pretty, String trimfw) {
+ Method mstream = getMethod(methodprefix, clazz, XMLStreamWriter.class);
+
+ String[] descn = new String[] {"Raw", "Compact", "Pretty", "TrimFullWhite"};
+ Format ftrimfw = Format.getPrettyFormat();
+ ftrimfw.setTextMode(TextMode.TRIM_FULL_WHITE);
+ Format[] formats = new Format[] {
+ getFormat(setup, Format.getRawFormat()),
+ getFormat(setup, Format.getCompactFormat()),
+ getFormat(setup, Format.getPrettyFormat()),
+ getFormat(setup, ftrimfw)};
+ String[] result = new String[] {raw, compact, pretty, trimfw};
+
+ for (int i = 0; i < 4; i++) {
+ StAXStreamOutputter out = new StAXStreamOutputter(formats[i]);
+ CharArrayWriter caw = new CharArrayWriter(result[i].length() + 2);
+ try {
+ if (mstream != null) {
+ XMLStreamWriter xsw = soutfactory.createXMLStreamWriter(caw);
+ mstream.invoke(out, content, xsw);
+ xsw.close();
+ String rstream = caw.toString();
+ assertEquals("output OutputStream Format " + descn[i], result[i], rstream);
+ }
+
+ } catch (Exception e) {
+ //e.printStackTrace();
+ AssertionError ae = new AssertionError("Failed to process " + descn[i] + " on content " + clazz + ": " + e.getMessage());
+ ae.initCause(e);
+ throw ae;
+ }
+ }
+ }
+
+ private Format getFormat(FormatSetup setup, Format input) {
+ input.setLineSeparator("\n");
+ if (setup == null) {
+ return input;
+ }
+ setup.setup(input);
+ return input;
+ }
+
+ private Method getMethod(String name, Class<?>...classes) {
+ try {
+ return StAXStreamOutputter.class.getMethod(name, classes);
+ } catch (Exception e) {
+ // ignore.
+ System.out.println("Can't find " + name + ": " + e.getMessage());
+ }
+ return null;
+ }
+
+
+
+
+
+
+ /*
+ * The following are borrowed from the TestSAXOutputter
+ * The effect is that we compare the StAX string output with the re-parsed
+ * value of the input.
+ */
+
+ private void roundTripDocument(Document doc) {
+ StAXStreamOutputter xout = new StAXStreamOutputter(Format.getRawFormat());
+ // create a String representation of the input.
+ if (doc.hasRootElement()) {
+ normalizeAttributes(doc.getRootElement());
+ }
+
+ try {
+ StringWriter sw = new StringWriter();
+ XMLStreamWriter xsw = soutfactory.createXMLStreamWriter(sw);
+ xout.output(doc, xsw);
+ xsw.close();
+ String expect = sw.toString();
+
+ // convert the input to a SAX Stream
+
+ StAXStreamBuilder sbuilder = new StAXStreamBuilder();
+
+ char[] chars = expect.toCharArray();
+ CharArrayReader car = new CharArrayReader(chars);
+ XMLStreamReader xsr = sinfactory.createXMLStreamReader(car);
+
+ Document backagain = sbuilder.build(xsr);
+ xsr.close();
+
+ // get a String representation of the round-trip.
+ if (backagain.hasRootElement()) {
+ normalizeAttributes(backagain.getRootElement());
+ }
+ StringWriter swb = new StringWriter();
+ xsw = soutfactory.createXMLStreamWriter(swb);
+ xout.output(backagain, xsw);
+ String actual = swb.toString();
+
+ assertEquals(expect, actual);
+ } catch (Exception e) {
+ failException("Failed to round-trip the document with exception: "
+ + e.getMessage(), e);
+ }
+ }
+
+ private void roundTripElement(Element emt) {
+
+ try {
+ StAXStreamOutputter xout = new StAXStreamOutputter(Format.getRawFormat());
+
+ StringWriter sw = new StringWriter();
+ XMLStreamWriter xsw = soutfactory.createXMLStreamWriter(sw);
+ xout.output(emt, xsw);
+ xsw.close();
+ String expect = sw.toString();
+
+ StAXStreamBuilder sbuilder = new StAXStreamBuilder();
+
+ XMLStreamReader xsr = sinfactory.createXMLStreamReader(new StringReader(expect));
+ assertTrue(xsr.getEventType() == XMLStreamConstants.START_DOCUMENT);
+ assertTrue(xsr.hasNext());
+ xsr.next();
+
+ Element backagain = (Element)sbuilder.fragment(xsr);
+
+ // convert the input to a SAX Stream
+
+ sw.getBuffer().setLength(0);
+ xsw = soutfactory.createXMLStreamWriter(sw);
+ xout.output(backagain, xsw);
+ xsw.close();
+
+ String actual = sw.toString();
+ assertEquals(expect, actual);
+ } catch (Exception e) {
+ failException("Failed to round-trip the document with exception: "
+ + e.getMessage(), e);
+ }
+ }
+
+ private void roundTripFragment(List<Content> content) {
+ try {
+ StAXStreamOutputter xout = new StAXStreamOutputter(Format.getRawFormat());
+
+ StringWriter sw = new StringWriter();
+ XMLStreamWriter xsw = soutfactory.createXMLStreamWriter(sw);
+ xout.output(content, xsw);
+ xsw.close();
+ String expect = sw.toString();
+
+ StAXStreamBuilder sbuilder = new StAXStreamBuilder();
+
+ XMLStreamReader xsr = sinfactory.createXMLStreamReader(new StringReader(expect));
+// assertTrue(xsr.getEventType() == XMLStreamConstants.START_DOCUMENT);
+// assertTrue(xsr.hasNext());
+// xsr.next();
+
+ List<Content> backagain = sbuilder.buildFragments(xsr, new DefaultStAXFilter());
+
+ // convert the input to a SAX Stream
+
+ sw.getBuffer().setLength(0);
+ xsw = soutfactory.createXMLStreamWriter(sw);
+ xout.output(backagain, xsw);
+ xsw.close();
+
+ String actual = sw.toString();
+ assertEquals(expect, actual);
+ } catch (Exception e) {
+ failException("Failed to round-trip the document with exception: "
+ + e.getMessage(), e);
+ }
+
+ }
+
+ private void roundTripFragment(Content content) {
+ try {
+ StAXStreamOutputter xout = new StAXStreamOutputter(Format.getRawFormat());
+
+ StringWriter sw = new StringWriter();
+ XMLStreamWriter xsw = soutfactory.createXMLStreamWriter(sw);
+ switch(content.getCType()) {
+ case CDATA :
+ xout.output((CDATA)content, xsw);
+ break;
+ case Text:
+ xout.output((Text)content, xsw);
+ break;
+ case Comment:
+ xout.output((Comment)content, xsw);
+ break;
+ case DocType:
+ xout.output((DocType)content, xsw);
+ break;
+ case Element:
+ xout.output((Element)content, xsw);
+ break;
+ case EntityRef:
+ xout.output((EntityRef)content, xsw);
+ break;
+ case ProcessingInstruction:
+ xout.output((ProcessingInstruction)content, xsw);
+ break;
+ default:
+ throw new IllegalStateException(content.getCType().toString());
+ }
+ xsw.close();
+ String expect = sw.toString();
+
+ StAXStreamBuilder sbuilder = new StAXStreamBuilder();
+
+ Content backagain = sbuilder.fragment(
+ sinfactory.createXMLStreamReader(new StringReader(expect)));
+
+ // convert the input to a SAX Stream
+
+ sw.getBuffer().setLength(0);
+ xsw = soutfactory.createXMLStreamWriter(sw);
+ switch(content.getCType()) {
+ case CDATA :
+ xout.output((CDATA)backagain, xsw);
+ break;
+ case Text:
+ xout.output((Text)backagain, xsw);
+ break;
+ case Comment:
+ xout.output((Comment)backagain, xsw);
+ break;
+ case DocType:
+ xout.output((DocType)backagain, xsw);
+ break;
+ case Element:
+ xout.output((Element)backagain, xsw);
+ break;
+ case EntityRef:
+ xout.output((EntityRef)backagain, xsw);
+ break;
+ case ProcessingInstruction:
+ xout.output((ProcessingInstruction)backagain, xsw);
+ break;
+ default:
+ throw new IllegalStateException(backagain.getCType().toString());
+ }
+ xsw.close();
+
+ String actual = sw.toString();
+ assertEquals(expect, actual);
+ } catch (Exception e) {
+ failException("Failed to round-trip the document with exception: "
+ + e.getMessage(), e);
+ }
+ }
+
+ @Test
+ public void testRTOutputDocumentSimple() {
+ Document doc = new Document(new Element("root"));
+ roundTripDocument(doc);
+ }
+
+ @Test
+ @Ignore
+ // TODO
+ public void testRTOutputDocumentFull() {
+ Document doc = new Document();
+ DocType dt = new DocType("root");
+ dt.setInternalSubset(" ");
+ doc.addContent(dt);
+ doc.addContent(new Comment("This is a document"));
+ doc.addContent(new ProcessingInstruction("jdomtest", ""));
+ Element e = new Element("root");
+ e.addContent(new EntityRef("ref"));
+ doc.addContent(e);
+ roundTripDocument(doc);
+ }
+
+ @Test
+ public void testOutputDocumentRootAttNS() {
+ Document doc = new Document();
+ Element e = new Element("root");
+ e.setAttribute(new Attribute("att", "val", Namespace.getNamespace("ans", "mynamespace")));
+ doc.addContent(e);
+ roundTripDocument(doc);
+ }
+
+ @Test
+ public void testOutputDocumentFullNoLexical() throws JDOMException {
+ Document doc = new Document();
+ doc.addContent(new ProcessingInstruction("jdomtest", ""));
+ Element e = new Element("root");
+ doc.addContent(e);
+ e.addContent(new Text("text"));
+ e.addContent(new EntityRef("ref"));
+
+ // the Lexical handler is what helps track comments,
+ // and identifies CDATA sections.
+ // as a result the output of CDATA structures appears as plain text.
+ // and comments are dropped....
+ e.addContent(new Text("cdata"));
+ String expect = new XMLOutputter().outputString(doc);
+ e.removeContent(2);
+ e.addContent(new CDATA("cdata"));
+ e.addContent(new Comment("This is a document"));
+
+ SAXHandler handler = new SAXHandler();
+ SAXOutputter saxout = new SAXOutputter(handler, handler, handler, handler);
+ saxout.output(doc);
+
+ Document act = handler.getDocument();
+ String actual = new XMLOutputter().outputString(act);
+
+ assertEquals(expect, actual);
+
+ }
+
+ @Test
+ public void testOutputDocumentNoErrorHandler() {
+ DefaultHandler2 handler = new DefaultHandler2() {
+ @Override
+ public void error(SAXParseException arg0) throws SAXException {
+ throw new SAXException ("foo!");
+ }
+ };
+
+ SAXOutputter saxout = new SAXOutputter(handler);
+
+ try {
+ saxout.outputFragment(new DocType("rootemt"));
+ fail("SHould have exception!");
+ } catch (JDOMException e) {
+ assertTrue(e.getMessage().indexOf("rootemt") >= 0);
+ }
+
+ saxout.setErrorHandler(handler);
+
+ try {
+ saxout.outputFragment(new DocType("rootemt"));
+ fail("SHould have exception!");
+ } catch (JDOMException e) {
+ assertTrue(e.getMessage().endsWith("foo!"));
+ }
+
+ }
+
+ @Test
+ public void testOutputDocumentAttributes() {
+ Element emt = new Element("root");
+ emt.setAttribute("att", "val");
+ Document doc = new Document(emt);
+ roundTripDocument(doc);
+ }
+
+ @Test
+ public void testOutputDocumentNamespaces() {
+ Element emt = new Element("root", Namespace.getNamespace("ns", "myns"));
+ Namespace ans = Namespace.getNamespace("ans", "attributens");
+ emt.addNamespaceDeclaration(ans);
+ emt.addNamespaceDeclaration(Namespace.getNamespace("two", "two"));
+ emt.setAttribute(new Attribute("att", "val", ans));
+ emt.addContent(new Element("child", Namespace.getNamespace("", "childuri")));
+ Document doc = new Document(emt);
+ roundTripDocument(doc);
+ }
+
+ @Test
+ public void testRTOutputList() {
+ List<Content> list = new ArrayList<Content>();
+ list.add(new ProcessingInstruction("jdomtest", ""));
+ list.add(new Comment("comment"));
+ list.add(new Element("root"));
+ roundTripFragment(list);
+ }
+
+ @Test
+ public void testOutputElementAttributes() {
+ Element emt = new Element("root");
+ emt.setAttribute("att", "val");
+ emt.setAttribute(new Attribute("attx", "valx", AttributeType.UNDECLARED));
+ roundTripElement(emt);
+ }
+
+ @Test
+ public void testRTOutputElementNamespaces() {
+ Element emt = new Element("root", Namespace.getNamespace("ns", "myns"));
+ Namespace ans = Namespace.getNamespace("ans", "attributens");
+ emt.addNamespaceDeclaration(ans);
+ emt.addNamespaceDeclaration(Namespace.getNamespace("two", "two"));
+ emt.setAttribute(new Attribute("att", "val", ans));
+ emt.addContent(new Element("child", Namespace.getNamespace("", "childns")));
+ roundTripElement(emt);
+ }
+
+ @Test
+ @Ignore
+ // TODO
+ public void testOutputFragmentList() {
+ List<Content> list = new ArrayList<Content>();
+ list.add(new ProcessingInstruction("jdomtest", ""));
+ list.add(new Comment("comment"));
+ list.add(new CDATA("foo"));
+ list.add(new Element("root"));
+ list.add(new Text("bar"));
+ roundTripFragment(list);
+ }
+
+ @Test
+ @Ignore
+ // TODO
+ public void testOutputFragmentContent() {
+ roundTripFragment(new ProcessingInstruction("jdomtest", ""));
+ roundTripFragment(new Comment("comment"));
+ roundTripFragment(new CDATA("foo"));
+ roundTripFragment(new Element("root"));
+ roundTripFragment(new Text("bar"));
+ }
+
+ @Test
+ public void testOutputNullContent() throws JDOMException {
+ DefaultHandler2 handler = new DefaultHandler2() {
+ @Override
+ public void startDocument() throws SAXException {
+ throw new SAXException("SHould not be reaching this, ever");
+ }
+ };
+ SAXOutputter saxout = new SAXOutputter(handler, handler, handler, handler, handler);
+
+ Document doc = null;
+ Element emt = null;
+ List<Content> list = null;
+ List<Content> empty = new ArrayList<Content>();
+ saxout.output(doc);
+ saxout.output(emt);
+ saxout.output(list);
+ saxout.output(empty);
+ saxout.outputFragment(emt);
+ saxout.outputFragment(list);
+ saxout.outputFragment(empty);
+ }
+
+
+}
diff --git a/test/src/java/org/jdom2/test/cases/output/TestXMLOutputProcessor.java b/test/src/java/org/jdom2/test/cases/output/TestXMLOutputProcessor.java
index 33becb707..f44176480 100644
--- a/test/src/java/org/jdom2/test/cases/output/TestXMLOutputProcessor.java
+++ b/test/src/java/org/jdom2/test/cases/output/TestXMLOutputProcessor.java
@@ -8,6 +8,8 @@
import org.jdom2.IllegalDataException;
import org.jdom2.output.AbstractXMLOutputProcessor;
import org.jdom2.output.Format;
+import org.jdom2.output.FormatStack;
+
import org.junit.Test;
/**
|
db57f0af3a110ed418bb0177cbc46ed4c7672c82
|
camel
|
Removed the printStackTrace line in the- CxfWsdlFirstTest--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@665997 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/camel
|
diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstTest.java
index cd21176baabe0..0503dcbe21d31 100644
--- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstTest.java
+++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstTest.java
@@ -94,7 +94,6 @@ public void testInvokingServiceFromCXFClient() throws Exception {
fail("We expect to get the UnknowPersonFault here");
} catch (UnknownPersonFault fault) {
// We expect to get fault here
- fault.printStackTrace();
}
}
|
cb0d7d4735665fa8ca1b59555a06354859c0045a
|
elasticsearch
|
inital support for zen discovery module- (multicast discovery implemented)--
|
a
|
https://github.com/elastic/elasticsearch
|
diff --git a/.idea/dictionaries/kimchy.xml b/.idea/dictionaries/kimchy.xml
index d77ade9283014..4e8f214db02c1 100644
--- a/.idea/dictionaries/kimchy.xml
+++ b/.idea/dictionaries/kimchy.xml
@@ -1,20 +1,24 @@
<component name="ProjectDictionaryState">
<dictionary name="kimchy">
<words>
+ <w>addr</w>
<w>args</w>
<w>asciifolding</w>
<w>attr</w>
<w>banon</w>
+ <w>bindhost</w>
<w>birthdate</w>
<w>bool</w>
<w>booleans</w>
<w>camelcase</w>
+ <w>canonicalhost</w>
<w>checksum</w>
<w>closeable</w>
<w>commitable</w>
<w>committable</w>
<w>configurator</w>
<w>coord</w>
+ <w>datagram</w>
<w>desc</w>
<w>deserialize</w>
<w>elasticsearch</w>
@@ -26,6 +30,7 @@
<w>indices</w>
<w>inet</w>
<w>infos</w>
+ <w>intf</w>
<w>iter</w>
<w>jgroups</w>
<w>joda</w>
@@ -33,12 +38,14 @@
<w>kimchy</w>
<w>lifecycle</w>
<w>linefeeds</w>
+ <w>loopback</w>
<w>lucene</w>
<w>memcached</w>
<w>metadata</w>
<w>millis</w>
<w>mmap</w>
<w>multi</w>
+ <w>multicast</w>
<w>multiline</w>
<w>nanos</w>
<w>newcount</w>
@@ -49,6 +56,7 @@
<w>pluggable</w>
<w>plugins</w>
<w>porterstem</w>
+ <w>publishhost</w>
<w>rebalance</w>
<w>sbuf</w>
<w>searchable</w>
diff --git a/.idea/projectCodeStyle.xml b/.idea/projectCodeStyle.xml
index f98da4cdac39c..4164e9dc0e18f 100644
--- a/.idea/projectCodeStyle.xml
+++ b/.idea/projectCodeStyle.xml
@@ -61,6 +61,15 @@
<option name="LABEL_INDENT_SIZE" value="0" />
<option name="LABEL_INDENT_ABSOLUTE" value="false" />
</ADDITIONAL_INDENT_OPTIONS>
+ <ADDITIONAL_INDENT_OPTIONS fileType="php">
+ <option name="INDENT_SIZE" value="4" />
+ <option name="CONTINUATION_INDENT_SIZE" value="8" />
+ <option name="TAB_SIZE" value="4" />
+ <option name="USE_TAB_CHARACTER" value="false" />
+ <option name="SMART_TABS" value="false" />
+ <option name="LABEL_INDENT_SIZE" value="0" />
+ <option name="LABEL_INDENT_ABSOLUTE" value="false" />
+ </ADDITIONAL_INDENT_OPTIONS>
<ADDITIONAL_INDENT_OPTIONS fileType="scala">
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="8" />
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/ClusterService.java b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/ClusterService.java
index 6d9242b352e7b..9a064c49674bc 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/ClusterService.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/ClusterService.java
@@ -23,7 +23,7 @@
import org.elasticsearch.util.component.LifecycleComponent;
/**
- * @author kimchy (Shay Banon)
+ * @author kimchy (shay.banon)
*/
public interface ClusterService extends LifecycleComponent<ClusterService> {
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/metadata/MetaDataService.java b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/metadata/MetaDataService.java
index 3ba9549e356b5..6afb6ba527e6f 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/metadata/MetaDataService.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/metadata/MetaDataService.java
@@ -319,7 +319,11 @@ public synchronized void updateMapping(final String index, final String type, fi
}
// build the updated mapping source
final String updatedMappingSource = existingMapper.buildSource();
- logger.info("Index [" + index + "]: Update mapping [" + type + "] (dynamic) with source [" + updatedMappingSource + "]");
+ if (logger.isDebugEnabled()) {
+ logger.debug("Index [" + index + "]: Update mapping [" + type + "] (dynamic) with source [" + updatedMappingSource + "]");
+ } else if (logger.isInfoEnabled()) {
+ logger.info("Index [" + index + "]: Update mapping [" + type + "] (dynamic)");
+ }
// publish the new mapping
clusterService.submitStateUpdateTask("update-mapping [" + index + "][" + type + "]", new ClusterStateUpdateTask() {
@Override public ClusterState execute(ClusterState currentState) {
@@ -391,7 +395,11 @@ public synchronized PutMappingResult putMapping(final String[] indices, String m
mapping = new Tuple<String, String>(newMapper.type(), newMapper.buildSource());
}
mappings.put(index, mapping);
- logger.info("Index [" + index + "]: Put mapping [" + mapping.v1() + "] with source [" + mapping.v2() + "]");
+ if (logger.isDebugEnabled()) {
+ logger.debug("Index [" + index + "]: Put mapping [" + mapping.v1() + "] with source [" + mapping.v2() + "]");
+ } else if (logger.isInfoEnabled()) {
+ logger.info("Index [" + index + "]: Put mapping [" + mapping.v1() + "]");
+ }
}
final CountDownLatch latch = new CountDownLatch(clusterService.state().nodes().size() * indices.length);
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/jgroups/JgroupsDiscovery.java b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/jgroups/JgroupsDiscovery.java
index a449340ade6e5..c8b18942a5846 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/jgroups/JgroupsDiscovery.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/jgroups/JgroupsDiscovery.java
@@ -31,7 +31,7 @@
import org.elasticsearch.env.Environment;
import org.elasticsearch.transport.TransportService;
import org.elasticsearch.util.component.AbstractLifecycleComponent;
-import org.elasticsearch.util.io.HostResolver;
+import org.elasticsearch.util.io.NetworkUtils;
import org.elasticsearch.util.io.stream.BytesStreamInput;
import org.elasticsearch.util.io.stream.BytesStreamOutput;
import org.elasticsearch.util.settings.Settings;
@@ -109,8 +109,8 @@ public class JgroupsDiscovery extends AbstractLifecycleComponent<Discovery> impl
if (System.getProperty("jgroups.bind_addr") == null) {
// automatically set the bind address based on ElasticSearch default bindings...
try {
- InetAddress bindAddress = HostResolver.resolveBindHostAddress(null, settings, HostResolver.LOCAL_IP);
- if ((bindAddress instanceof Inet4Address && HostResolver.isIPv4()) || (bindAddress instanceof Inet6Address && !HostResolver.isIPv4())) {
+ InetAddress bindAddress = NetworkUtils.resolveBindHostAddress(null, settings, NetworkUtils.LOCAL);
+ if ((bindAddress instanceof Inet4Address && NetworkUtils.isIPv4()) || (bindAddress instanceof Inet6Address && !NetworkUtils.isIPv4())) {
sysPropsSet.put("jgroups.bind_addr", bindAddress.getHostAddress());
System.setProperty("jgroups.bind_addr", bindAddress.getHostAddress());
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/local/LocalDiscoveryModule.java b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/local/LocalDiscoveryModule.java
index 93a9e88ad2004..14cab3dc2d9cd 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/local/LocalDiscoveryModule.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/local/LocalDiscoveryModule.java
@@ -23,7 +23,7 @@
import org.elasticsearch.discovery.Discovery;
/**
- * @author kimchy (Shay Banon)
+ * @author kimchy (shay.banon)
*/
public class LocalDiscoveryModule extends AbstractModule {
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/DiscoveryNodesProvider.java b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/DiscoveryNodesProvider.java
new file mode 100644
index 0000000000000..eb3f2b0a2c5bc
--- /dev/null
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/DiscoveryNodesProvider.java
@@ -0,0 +1,30 @@
+/*
+ * Licensed to Elastic Search and Shay Banon under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. Elastic Search 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.elasticsearch.discovery.zen;
+
+import org.elasticsearch.cluster.node.DiscoveryNodes;
+
+/**
+ * @author kimchy (shay.banon)
+ */
+public interface DiscoveryNodesProvider {
+
+ DiscoveryNodes nodes();
+}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/ZenDiscovery.java b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/ZenDiscovery.java
new file mode 100644
index 0000000000000..7045c0d2d5832
--- /dev/null
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/ZenDiscovery.java
@@ -0,0 +1,439 @@
+/*
+ * Licensed to Elastic Search and Shay Banon under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. Elastic Search 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.elasticsearch.discovery.zen;
+
+import com.google.inject.Inject;
+import org.elasticsearch.ElasticSearchException;
+import org.elasticsearch.ElasticSearchIllegalStateException;
+import org.elasticsearch.cluster.*;
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
+import org.elasticsearch.discovery.Discovery;
+import org.elasticsearch.discovery.InitialStateDiscoveryListener;
+import org.elasticsearch.discovery.zen.elect.ElectMasterService;
+import org.elasticsearch.discovery.zen.fd.MasterFaultDetection;
+import org.elasticsearch.discovery.zen.fd.NodesFaultDetection;
+import org.elasticsearch.discovery.zen.membership.MembershipAction;
+import org.elasticsearch.discovery.zen.ping.ZenPing;
+import org.elasticsearch.discovery.zen.ping.ZenPingService;
+import org.elasticsearch.discovery.zen.publish.PublishClusterStateAction;
+import org.elasticsearch.threadpool.ThreadPool;
+import org.elasticsearch.transport.TransportService;
+import org.elasticsearch.util.TimeValue;
+import org.elasticsearch.util.UUID;
+import org.elasticsearch.util.component.AbstractLifecycleComponent;
+import org.elasticsearch.util.settings.Settings;
+
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static com.google.common.collect.Lists.*;
+import static org.elasticsearch.cluster.ClusterState.*;
+import static org.elasticsearch.cluster.node.DiscoveryNodes.*;
+import static org.elasticsearch.util.TimeValue.*;
+
+/**
+ * @author kimchy (shay.banon)
+ */
+public class ZenDiscovery extends AbstractLifecycleComponent<Discovery> implements Discovery, DiscoveryNodesProvider {
+
+ private final TransportService transportService;
+
+ private final ClusterService clusterService;
+
+ private final ClusterName clusterName;
+
+ private final ZenPingService pingService;
+
+ private final MasterFaultDetection masterFD;
+
+ private final NodesFaultDetection nodesFD;
+
+ private final PublishClusterStateAction publishClusterState;
+
+ private final MembershipAction membership;
+
+
+ private final TimeValue initialPingTimeout;
+
+ private final ElectMasterService electMaster;
+
+
+ private DiscoveryNode localNode;
+
+ private final CopyOnWriteArrayList<InitialStateDiscoveryListener> initialStateListeners = new CopyOnWriteArrayList<InitialStateDiscoveryListener>();
+
+ private volatile boolean master = false;
+
+ private volatile boolean firstMaster = false;
+
+ private volatile DiscoveryNodes latestDiscoNodes;
+
+ private final AtomicBoolean initialStateSent = new AtomicBoolean();
+
+ @Inject public ZenDiscovery(Settings settings, ClusterName clusterName, ThreadPool threadPool,
+ TransportService transportService, ClusterService clusterService,
+ ZenPingService pingService) {
+ super(settings);
+ this.clusterName = clusterName;
+ this.clusterService = clusterService;
+ this.transportService = transportService;
+ this.pingService = pingService;
+
+ this.initialPingTimeout = componentSettings.getAsTime("initial_ping_timeout", timeValueSeconds(3));
+
+ this.electMaster = new ElectMasterService(settings);
+
+ this.masterFD = new MasterFaultDetection(settings, threadPool, transportService, this);
+ this.masterFD.addListener(new MasterNodeFailureListener());
+
+ this.nodesFD = new NodesFaultDetection(settings, threadPool, transportService);
+ this.nodesFD.addListener(new NodeFailureListener());
+
+ this.publishClusterState = new PublishClusterStateAction(settings, transportService, this, new NewClusterStateListener());
+ this.pingService.setNodesProvider(this);
+ this.membership = new MembershipAction(settings, transportService, new MembershipListener());
+ }
+
+ @Override protected void doStart() throws ElasticSearchException {
+ localNode = new DiscoveryNode(settings.get("name"), settings.getAsBoolean("node.data", !settings.getAsBoolean("node.client", false)), UUID.randomUUID().toString(), transportService.boundAddress().publishAddress());
+ pingService.start();
+
+ boolean retry = true;
+ while (retry) {
+ retry = false;
+ DiscoveryNode masterNode = pingTillMasterResolved();
+ if (localNode.equals(masterNode)) {
+ // we are the master (first)
+ this.firstMaster = true;
+ this.master = true;
+ nodesFD.start(); // start the nodes FD
+ clusterService.submitStateUpdateTask("zen-disco-initial_connect(master)", new ProcessedClusterStateUpdateTask() {
+ @Override public ClusterState execute(ClusterState currentState) {
+ DiscoveryNodes.Builder builder = new DiscoveryNodes.Builder()
+ .localNodeId(localNode.id())
+ .masterNodeId(localNode.id())
+ // put our local node
+ .put(localNode);
+ // update the fact that we are the master...
+ latestDiscoNodes = builder.build();
+ return newClusterStateBuilder().state(currentState).nodes(builder).build();
+ }
+
+ @Override public void clusterStateProcessed(ClusterState clusterState) {
+ sendInitialStateEventIfNeeded();
+ }
+ });
+ } else {
+ this.firstMaster = false;
+ this.master = false;
+ try {
+ // first, make sure we can connect to the master
+ transportService.connectToNode(masterNode);
+ } catch (Exception e) {
+ logger.warn("Failed to connect to master [{}], retrying...", e, masterNode);
+ retry = true;
+ continue;
+ }
+ // send join request
+ try {
+ membership.sendJoinRequestBlocking(masterNode, localNode, initialPingTimeout);
+ } catch (Exception e) {
+ logger.warn("Failed to send join request to master [{}], retrying...", e, masterNode);
+ // failed to send the join request, retry
+ retry = true;
+ continue;
+ }
+ // cool, we found a master, start an FD on it
+ masterFD.start(masterNode);
+ }
+ }
+ }
+
+ @Override protected void doStop() throws ElasticSearchException {
+ pingService.stop();
+ if (masterFD.masterNode() != null) {
+ masterFD.stop();
+ }
+ nodesFD.stop();
+ initialStateSent.set(false);
+ if (!master) {
+ try {
+ membership.sendLeaveRequestBlocking(latestDiscoNodes.masterNode(), localNode, TimeValue.timeValueSeconds(1));
+ } catch (Exception e) {
+ logger.debug("Failed to send leave request to master [{}]", e, latestDiscoNodes.masterNode());
+ }
+ } else {
+ DiscoveryNode[] possibleMasters = electMaster.nextPossibleMasters(latestDiscoNodes.nodes().values(), 3);
+ for (DiscoveryNode possibleMaster : possibleMasters) {
+ if (localNode.equals(possibleMaster)) {
+ continue;
+ }
+ try {
+ membership.sendLeaveRequest(latestDiscoNodes.masterNode(), possibleMaster);
+ } catch (Exception e) {
+ logger.debug("Failed to send leave request from master [{}] to possible master [{}]", e, latestDiscoNodes.masterNode(), possibleMaster);
+ }
+ }
+ }
+ master = false;
+ }
+
+ @Override protected void doClose() throws ElasticSearchException {
+ masterFD.close();
+ nodesFD.close();
+ publishClusterState.close();
+ membership.close();
+ pingService.close();
+ }
+
+ @Override public void addListener(InitialStateDiscoveryListener listener) {
+ this.initialStateListeners.add(listener);
+ }
+
+ @Override public void removeListener(InitialStateDiscoveryListener listener) {
+ this.initialStateListeners.remove(listener);
+ }
+
+ @Override public String nodeDescription() {
+ return clusterName.value() + "/" + localNode.id();
+ }
+
+ @Override public boolean firstMaster() {
+ return firstMaster;
+ }
+
+ @Override public DiscoveryNodes nodes() {
+ DiscoveryNodes latestNodes = this.latestDiscoNodes;
+ if (latestNodes != null) {
+ return latestNodes;
+ }
+ // have not decided yet, just send the local node
+ return newNodesBuilder().put(localNode).localNodeId(localNode.id()).build();
+ }
+
+ @Override public void publish(ClusterState clusterState) {
+ if (!master) {
+ throw new ElasticSearchIllegalStateException("Shouldn't publish state when not master");
+ }
+ latestDiscoNodes = clusterState.nodes();
+ nodesFD.updateNodes(clusterState.nodes());
+ publishClusterState.publish(clusterState);
+ }
+
+ private void handleNodeFailure(final DiscoveryNode node) {
+ if (!master) {
+ // nothing to do here...
+ return;
+ }
+ clusterService.submitStateUpdateTask("zen-disco-node_failed(" + node + ")", new ProcessedClusterStateUpdateTask() {
+ @Override public ClusterState execute(ClusterState currentState) {
+ DiscoveryNodes.Builder builder = new DiscoveryNodes.Builder()
+ .putAll(currentState.nodes())
+ .remove(node.id());
+ latestDiscoNodes = builder.build();
+ return newClusterStateBuilder().state(currentState).nodes(latestDiscoNodes).build();
+ }
+
+ @Override public void clusterStateProcessed(ClusterState clusterState) {
+ sendInitialStateEventIfNeeded();
+ }
+ });
+ }
+
+ private void handleMasterGone(final DiscoveryNode masterNode, String reason) {
+ if (master) {
+ // we might get this on both a master telling us shutting down, and then the disconnect failure
+ return;
+ }
+
+ logger.info("Master [{}] left, reason [{}]", masterNode, reason);
+ List<DiscoveryNode> nodes = newArrayList(latestDiscoNodes.nodes().values());
+ nodes.remove(masterNode); // remove the master node from the list, it has failed
+ // sort then
+ DiscoveryNode electedMaster = electMaster.electMaster(nodes);
+ if (localNode.equals(electedMaster)) {
+ this.master = true;
+ masterFD.stop();
+ nodesFD.start();
+ clusterService.submitStateUpdateTask("zen-disco-elected_as_master(old master [" + masterNode + "])", new ProcessedClusterStateUpdateTask() {
+ @Override public ClusterState execute(ClusterState currentState) {
+ DiscoveryNodes.Builder builder = new DiscoveryNodes.Builder()
+ .putAll(currentState.nodes())
+ // make sure the old master node, which has failed, is not part of the nodes we publish
+ .remove(masterNode.id())
+ .masterNodeId(localNode.id());
+ // update the fact that we are the master...
+ latestDiscoNodes = builder.build();
+ return newClusterStateBuilder().state(currentState).nodes(latestDiscoNodes).build();
+ }
+
+ @Override public void clusterStateProcessed(ClusterState clusterState) {
+ sendInitialStateEventIfNeeded();
+ }
+ });
+ } else {
+ nodesFD.stop();
+ if (electedMaster != null) {
+ // we are not the master, start FD against the possible master
+ masterFD.restart(electedMaster);
+ } else {
+ masterFD.stop();
+ }
+ }
+ }
+
+ void handleNewClusterState(final ClusterState clusterState) {
+ if (master) {
+ logger.warn("Master should not receive new cluster state from [{}]", clusterState.nodes().masterNode());
+ } else {
+ latestDiscoNodes = clusterState.nodes();
+
+ // check to see that we monitor the correct master of the cluster
+ if (masterFD.masterNode() != null && masterFD.masterNode().equals(latestDiscoNodes.masterNode())) {
+ masterFD.restart(latestDiscoNodes.masterNode());
+ }
+
+ if (clusterState.nodes().localNode() == null) {
+ logger.warn("Received a cluster state from [{}] and not part of the cluster, should not happen", clusterState.nodes().masterNode());
+ } else {
+ clusterService.submitStateUpdateTask("zen-disco-receive(from [" + clusterState.nodes().masterNode() + "])", new ProcessedClusterStateUpdateTask() {
+ @Override public ClusterState execute(ClusterState currentState) {
+ return clusterState;
+ }
+
+ @Override public void clusterStateProcessed(ClusterState clusterState) {
+ sendInitialStateEventIfNeeded();
+ }
+ });
+ }
+ }
+ }
+
+ private void handleLeaveRequest(final DiscoveryNode node) {
+ if (master) {
+ clusterService.submitStateUpdateTask("zen-disco-node_failed(" + node + ")", new ClusterStateUpdateTask() {
+ @Override public ClusterState execute(ClusterState currentState) {
+ DiscoveryNodes.Builder builder = new DiscoveryNodes.Builder()
+ .putAll(currentState.nodes())
+ .remove(node.id());
+ latestDiscoNodes = builder.build();
+ return newClusterStateBuilder().state(currentState).nodes(latestDiscoNodes).build();
+ }
+ });
+ } else {
+ handleMasterGone(node, "shut_down");
+ }
+ }
+
+ private void handleJoinRequest(final DiscoveryNode node) {
+ if (!master) {
+ throw new ElasticSearchIllegalStateException("Node [" + localNode + "] not master for join request from [" + node + "]");
+ }
+ if (!transportService.addressSupported(node.address().getClass())) {
+ // TODO, what should we do now? Maybe inform that node that its crap?
+ logger.warn("Received a wrong address type from [{}], ignoring...", node);
+ } else {
+ clusterService.submitStateUpdateTask("zen-disco-receive(from node[" + node + "])", new ClusterStateUpdateTask() {
+ @Override public ClusterState execute(ClusterState currentState) {
+ if (currentState.nodes().nodeExists(node.id())) {
+ // no change, the node already exists in the cluster
+ logger.warn("Received an existing node [{}]", node);
+ return currentState;
+ }
+ return newClusterStateBuilder().state(currentState).nodes(currentState.nodes().newNode(node)).build();
+ }
+ });
+ }
+ }
+
+ private DiscoveryNode pingTillMasterResolved() {
+ while (true) {
+ ZenPing.PingResponse[] pingResponses = pingService.pingAndWait(initialPingTimeout);
+ List<DiscoveryNode> pingMasters = newArrayList();
+ for (ZenPing.PingResponse pingResponse : pingResponses) {
+ if (pingResponse.master() != null) {
+ pingMasters.add(pingResponse.master());
+ }
+ }
+ if (pingMasters.isEmpty()) {
+ // lets tie break between discovered nodes
+ List<DiscoveryNode> possibleMasterNodes = newArrayList();
+ possibleMasterNodes.add(localNode);
+ for (ZenPing.PingResponse pingResponse : pingResponses) {
+ possibleMasterNodes.add(pingResponse.target());
+ }
+ DiscoveryNode electedMaster = electMaster.electMaster(possibleMasterNodes);
+ if (localNode.equals(electedMaster)) {
+ return localNode;
+ }
+ } else {
+ DiscoveryNode electedMaster = electMaster.electMaster(pingMasters);
+ if (electedMaster != null) {
+ return electedMaster;
+ }
+ }
+ }
+ }
+
+ private void sendInitialStateEventIfNeeded() {
+ if (initialStateSent.compareAndSet(false, true)) {
+ for (InitialStateDiscoveryListener listener : initialStateListeners) {
+ listener.initialStateProcessed();
+ }
+ }
+ }
+
+ private class NewClusterStateListener implements PublishClusterStateAction.NewClusterStateListener {
+ @Override public void onNewClusterState(ClusterState clusterState) {
+ handleNewClusterState(clusterState);
+ }
+ }
+
+ private class MembershipListener implements MembershipAction.MembershipListener {
+ @Override public void onJoin(DiscoveryNode node) {
+ handleJoinRequest(node);
+ }
+
+ @Override public void onLeave(DiscoveryNode node) {
+ handleLeaveRequest(node);
+ }
+ }
+
+ private class NodeFailureListener implements NodesFaultDetection.Listener {
+
+ @Override public void onNodeFailure(DiscoveryNode node) {
+ handleNodeFailure(node);
+ }
+ }
+
+ private class MasterNodeFailureListener implements MasterFaultDetection.Listener {
+
+ @Override public void onMasterFailure(DiscoveryNode masterNode) {
+ handleMasterGone(masterNode, "failure");
+ }
+
+ @Override public void onDisconnectedFromMaster() {
+ // got disconnected from the master, send a join request
+ membership.sendJoinRequest(latestDiscoNodes.masterNode(), localNode);
+ }
+ }
+}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/ZenDiscoveryModule.java b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/ZenDiscoveryModule.java
new file mode 100644
index 0000000000000..80289d55dc925
--- /dev/null
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/ZenDiscoveryModule.java
@@ -0,0 +1,35 @@
+/*
+ * Licensed to Elastic Search and Shay Banon under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. Elastic Search 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.elasticsearch.discovery.zen;
+
+import com.google.inject.AbstractModule;
+import org.elasticsearch.discovery.Discovery;
+import org.elasticsearch.discovery.zen.ping.ZenPingService;
+
+/**
+ * @author kimchy (shay.banon)
+ */
+public class ZenDiscoveryModule extends AbstractModule {
+
+ @Override protected void configure() {
+ bind(ZenPingService.class).asEagerSingleton();
+ bind(Discovery.class).to(ZenDiscovery.class).asEagerSingleton();
+ }
+}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/elect/ElectMasterService.java b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/elect/ElectMasterService.java
new file mode 100644
index 0000000000000..aa18dce53e2ff
--- /dev/null
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/elect/ElectMasterService.java
@@ -0,0 +1,90 @@
+/*
+ * Licensed to Elastic Search and Shay Banon under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. Elastic Search 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.elasticsearch.discovery.zen.elect;
+
+import com.google.common.collect.Lists;
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.util.component.AbstractComponent;
+import org.elasticsearch.util.settings.Settings;
+
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+import static com.google.common.collect.Lists.*;
+
+/**
+ * @author kimchy (shay.banon)
+ */
+public class ElectMasterService extends AbstractComponent {
+
+ private final NodeComparator nodeComparator = new NodeComparator();
+
+ public ElectMasterService(Settings settings) {
+ super(settings);
+ }
+
+ /**
+ * Returns a list of the next possible masters.
+ */
+ public DiscoveryNode[] nextPossibleMasters(Iterable<DiscoveryNode> nodes, int numberOfPossibleMasters) {
+ List<DiscoveryNode> sortedNodes = sortedNodes(nodes);
+ if (sortedNodes == null) {
+ return new DiscoveryNode[0];
+ }
+ List<DiscoveryNode> nextPossibleMasters = newArrayListWithExpectedSize(numberOfPossibleMasters);
+ int counter = 0;
+ for (DiscoveryNode nextPossibleMaster : sortedNodes) {
+ if (++counter >= numberOfPossibleMasters) {
+ break;
+ }
+ nextPossibleMasters.add(nextPossibleMaster);
+ }
+ return nextPossibleMasters.toArray(new DiscoveryNode[nextPossibleMasters.size()]);
+ }
+
+ /**
+ * Elects a new master out of the possible nodes, returning it. Returns <tt>null</tt>
+ * if no master has been elected.
+ */
+ public DiscoveryNode electMaster(Iterable<DiscoveryNode> nodes) {
+ List<DiscoveryNode> sortedNodes = sortedNodes(nodes);
+ if (sortedNodes == null) {
+ return null;
+ }
+ return sortedNodes.get(0);
+ }
+
+ private List<DiscoveryNode> sortedNodes(Iterable<DiscoveryNode> nodes) {
+ List<DiscoveryNode> possibleNodes = Lists.newArrayList(nodes);
+ if (possibleNodes.isEmpty()) {
+ return null;
+ }
+ Collections.sort(possibleNodes, nodeComparator);
+ return possibleNodes;
+ }
+
+ private static class NodeComparator implements Comparator<DiscoveryNode> {
+
+ @Override public int compare(DiscoveryNode o1, DiscoveryNode o2) {
+ return o1.id().compareTo(o2.id());
+ }
+ }
+}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/fd/MasterFaultDetection.java b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/fd/MasterFaultDetection.java
new file mode 100644
index 0000000000000..673a73f160383
--- /dev/null
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/fd/MasterFaultDetection.java
@@ -0,0 +1,276 @@
+/*
+ * Licensed to Elastic Search and Shay Banon under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. Elastic Search 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.elasticsearch.discovery.zen.fd;
+
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
+import org.elasticsearch.discovery.zen.DiscoveryNodesProvider;
+import org.elasticsearch.threadpool.ThreadPool;
+import org.elasticsearch.transport.*;
+import org.elasticsearch.util.TimeValue;
+import org.elasticsearch.util.component.AbstractComponent;
+import org.elasticsearch.util.io.stream.StreamInput;
+import org.elasticsearch.util.io.stream.StreamOutput;
+import org.elasticsearch.util.io.stream.Streamable;
+import org.elasticsearch.util.settings.Settings;
+
+import java.io.IOException;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.elasticsearch.cluster.node.DiscoveryNode.*;
+import static org.elasticsearch.util.TimeValue.*;
+
+/**
+ * @author kimchy (shay.banon)
+ */
+public class MasterFaultDetection extends AbstractComponent {
+
+ public static interface Listener {
+
+ void onMasterFailure(DiscoveryNode masterNode);
+
+ void onDisconnectedFromMaster();
+ }
+
+ private final ThreadPool threadPool;
+
+ private final TransportService transportService;
+
+ private final DiscoveryNodesProvider nodesProvider;
+
+ private final CopyOnWriteArrayList<Listener> listeners = new CopyOnWriteArrayList<Listener>();
+
+
+ private final boolean connectOnNetworkDisconnect;
+
+ private final TimeValue pingInterval;
+
+ private final TimeValue pingRetryTimeout;
+
+ private final int pingRetryCount;
+
+ private final FDConnectionListener connectionListener;
+
+ private volatile DiscoveryNode masterNode;
+
+ private volatile int retryCount;
+
+ private final AtomicBoolean notifiedMasterFailure = new AtomicBoolean();
+
+ public MasterFaultDetection(Settings settings, ThreadPool threadPool, TransportService transportService, DiscoveryNodesProvider nodesProvider) {
+ super(settings);
+ this.threadPool = threadPool;
+ this.transportService = transportService;
+ this.nodesProvider = nodesProvider;
+
+ this.connectOnNetworkDisconnect = componentSettings.getAsBoolean("connect_on_network_disconnect", false);
+ this.pingInterval = componentSettings.getAsTime("ping_interval", timeValueSeconds(1));
+ this.pingRetryTimeout = componentSettings.getAsTime("ping_timeout", timeValueSeconds(6));
+ this.pingRetryCount = componentSettings.getAsInt("ping_retries", 5);
+
+ this.connectionListener = new FDConnectionListener();
+ transportService.addConnectionListener(connectionListener);
+
+ transportService.registerHandler(MasterPingRequestHandler.ACTION, new MasterPingRequestHandler());
+ }
+
+ public DiscoveryNode masterNode() {
+ return this.masterNode;
+ }
+
+ public void addListener(Listener listener) {
+ listeners.add(listener);
+ }
+
+ public void removeListener(Listener listener) {
+ listeners.remove(listener);
+ }
+
+ public void restart(DiscoveryNode masterNode) {
+ stop();
+ start(masterNode);
+ }
+
+ public void start(DiscoveryNode masterNode) {
+ this.masterNode = masterNode;
+ this.retryCount = 0;
+ this.notifiedMasterFailure.set(false);
+
+ // try and connect to make sure we are connected
+ try {
+ transportService.connectToNode(masterNode);
+ } catch (Exception e) {
+ notifyMasterFailure(masterNode);
+ }
+
+ // start the ping process
+ threadPool.schedule(new SendPingRequest(), pingInterval);
+ }
+
+ public void stop() {
+ // also will stop the next ping schedule
+ this.retryCount = 0;
+ this.masterNode = null;
+ }
+
+ public void close() {
+ stop();
+ this.listeners.clear();
+ transportService.removeConnectionListener(connectionListener);
+ transportService.removeHandler(MasterPingRequestHandler.ACTION);
+ }
+
+ private void handleTransportDisconnect(DiscoveryNode node) {
+ if (!node.equals(this.masterNode)) {
+ return;
+ }
+ if (connectOnNetworkDisconnect) {
+ try {
+ transportService.connectToNode(node);
+ } catch (Exception e) {
+ logger.trace("Master [{}] failed on disconnect (with verified connect)", masterNode);
+ notifyMasterFailure(masterNode);
+ }
+ } else {
+ logger.trace("Master [{}] failed on disconnect", masterNode);
+ notifyMasterFailure(masterNode);
+ }
+ }
+
+ private void notifyDisconnectedFromMaster() {
+ for (Listener listener : listeners) {
+ listener.onDisconnectedFromMaster();
+ }
+ // we don't stop on disconnection from master, we keep pinging it
+ }
+
+ private void notifyMasterFailure(DiscoveryNode masterNode) {
+ if (notifiedMasterFailure.compareAndSet(false, true)) {
+ for (Listener listener : listeners) {
+ listener.onMasterFailure(masterNode);
+ }
+ stop();
+ }
+ }
+
+ private class FDConnectionListener implements TransportConnectionListener {
+ @Override public void onNodeConnected(DiscoveryNode node) {
+ }
+
+ @Override public void onNodeDisconnected(DiscoveryNode node) {
+ handleTransportDisconnect(node);
+ }
+ }
+
+ private class SendPingRequest implements Runnable {
+ @Override public void run() {
+ if (masterNode != null) {
+ final DiscoveryNode sentToNode = masterNode;
+ transportService.sendRequest(masterNode, MasterPingRequestHandler.ACTION, new MasterPingRequest(nodesProvider.nodes().localNode()), pingRetryTimeout,
+ new BaseTransportResponseHandler<MasterPingResponseResponse>() {
+ @Override public MasterPingResponseResponse newInstance() {
+ return new MasterPingResponseResponse();
+ }
+
+ @Override public void handleResponse(MasterPingResponseResponse response) {
+ // check if the master node did not get switched on us...
+ if (sentToNode.equals(MasterFaultDetection.this.masterNode())) {
+ if (!response.connectedToMaster) {
+ logger.trace("Master [{}] does not have us registered with it...", masterNode);
+ notifyDisconnectedFromMaster();
+ } else {
+ threadPool.schedule(SendPingRequest.this, pingInterval);
+ }
+ }
+ }
+
+ @Override public void handleException(RemoteTransportException exp) {
+ // check if the master node did not get switched on us...
+ if (sentToNode.equals(MasterFaultDetection.this.masterNode())) {
+ int retryCount = ++MasterFaultDetection.this.retryCount;
+ logger.trace("Master [{}] failed to ping, retry [{}] out of [{}]", exp, masterNode, retryCount, pingRetryCount);
+ if (retryCount >= pingRetryCount) {
+ logger.trace("Master [{}] failed on ping", masterNode);
+ // not good, failure
+ notifyMasterFailure(sentToNode);
+ }
+ }
+ }
+ });
+ }
+ }
+ }
+
+ private class MasterPingRequestHandler extends BaseTransportRequestHandler<MasterPingRequest> {
+
+ public static final String ACTION = "discovery/zen/fd/masterPing";
+
+ @Override public MasterPingRequest newInstance() {
+ return new MasterPingRequest();
+ }
+
+ @Override public void messageReceived(MasterPingRequest request, TransportChannel channel) throws Exception {
+ DiscoveryNodes nodes = nodesProvider.nodes();
+ channel.sendResponse(new MasterPingResponseResponse(nodes.nodeExists(request.node.id())));
+ }
+ }
+
+
+ private class MasterPingRequest implements Streamable {
+
+ private DiscoveryNode node;
+
+ private MasterPingRequest() {
+ }
+
+ private MasterPingRequest(DiscoveryNode node) {
+ this.node = node;
+ }
+
+ @Override public void readFrom(StreamInput in) throws IOException {
+ node = readNode(in);
+ }
+
+ @Override public void writeTo(StreamOutput out) throws IOException {
+ node.writeTo(out);
+ }
+ }
+
+ private class MasterPingResponseResponse implements Streamable {
+
+ private boolean connectedToMaster;
+
+ private MasterPingResponseResponse() {
+ }
+
+ private MasterPingResponseResponse(boolean connectedToMaster) {
+ this.connectedToMaster = connectedToMaster;
+ }
+
+ @Override public void readFrom(StreamInput in) throws IOException {
+ connectedToMaster = in.readBoolean();
+ }
+
+ @Override public void writeTo(StreamOutput out) throws IOException {
+ out.writeBoolean(connectedToMaster);
+ }
+ }
+}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/fd/NodesFaultDetection.java b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/fd/NodesFaultDetection.java
new file mode 100644
index 0000000000000..42ea842c0b762
--- /dev/null
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/fd/NodesFaultDetection.java
@@ -0,0 +1,269 @@
+/*
+ * Licensed to Elastic Search and Shay Banon under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. Elastic Search 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.elasticsearch.discovery.zen.fd;
+
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
+import org.elasticsearch.threadpool.ThreadPool;
+import org.elasticsearch.transport.*;
+import org.elasticsearch.util.TimeValue;
+import org.elasticsearch.util.component.AbstractComponent;
+import org.elasticsearch.util.io.stream.StreamInput;
+import org.elasticsearch.util.io.stream.StreamOutput;
+import org.elasticsearch.util.io.stream.Streamable;
+import org.elasticsearch.util.settings.Settings;
+
+import java.io.IOException;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import static org.elasticsearch.cluster.node.DiscoveryNodes.*;
+import static org.elasticsearch.util.TimeValue.*;
+import static org.elasticsearch.util.concurrent.ConcurrentMaps.*;
+
+/**
+ * @author kimchy (shay.banon)
+ */
+public class NodesFaultDetection extends AbstractComponent {
+
+ public static interface Listener {
+
+ void onNodeFailure(DiscoveryNode node);
+ }
+
+ private final ThreadPool threadPool;
+
+ private final TransportService transportService;
+
+
+ private final boolean connectOnNetworkDisconnect;
+
+ private final TimeValue pingInterval;
+
+ private final TimeValue pingRetryTimeout;
+
+ private final int pingRetryCount;
+
+
+ private final CopyOnWriteArrayList<Listener> listeners = new CopyOnWriteArrayList<Listener>();
+
+ private final ConcurrentMap<DiscoveryNode, NodeFD> nodesFD = newConcurrentMap();
+
+ private final FDConnectionListener connectionListener;
+
+ private volatile DiscoveryNodes latestNodes = EMPTY_NODES;
+
+ private volatile boolean running = false;
+
+ public NodesFaultDetection(Settings settings, ThreadPool threadPool, TransportService transportService) {
+ super(settings);
+ this.threadPool = threadPool;
+ this.transportService = transportService;
+
+ this.connectOnNetworkDisconnect = componentSettings.getAsBoolean("connect_on_network_disconnect", false);
+ this.pingInterval = componentSettings.getAsTime("ping_interval", timeValueSeconds(1));
+ this.pingRetryTimeout = componentSettings.getAsTime("ping_timeout", timeValueSeconds(6));
+ this.pingRetryCount = componentSettings.getAsInt("ping_retries", 5);
+
+ transportService.registerHandler(PingRequestHandler.ACTION, new PingRequestHandler());
+
+ this.connectionListener = new FDConnectionListener();
+ transportService.addConnectionListener(connectionListener);
+ }
+
+ public void addListener(Listener listener) {
+ listeners.add(listener);
+ }
+
+ public void removeListener(Listener listener) {
+ listeners.remove(listener);
+ }
+
+ public void updateNodes(DiscoveryNodes nodes) {
+ DiscoveryNodes prevNodes = latestNodes;
+ this.latestNodes = nodes;
+ if (!running) {
+ return;
+ }
+ DiscoveryNodes.Delta delta = nodes.delta(prevNodes);
+ for (DiscoveryNode newNode : delta.addedNodes()) {
+ if (!nodesFD.containsKey(newNode)) {
+ nodesFD.put(newNode, new NodeFD());
+ threadPool.schedule(new SendPingRequest(newNode), pingInterval);
+ }
+ }
+ for (DiscoveryNode removedNode : delta.removedNodes()) {
+ nodesFD.remove(removedNode);
+ }
+ }
+
+ public NodesFaultDetection start() {
+ if (running) {
+ return this;
+ }
+ running = true;
+ return this;
+ }
+
+ public NodesFaultDetection stop() {
+ if (!running) {
+ return this;
+ }
+ running = false;
+ return this;
+ }
+
+ public void close() {
+ stop();
+ transportService.removeHandler(PingRequestHandler.ACTION);
+ transportService.removeConnectionListener(connectionListener);
+ }
+
+ private void handleTransportDisconnect(DiscoveryNode node) {
+ if (!latestNodes.nodeExists(node.id())) {
+ return;
+ }
+ NodeFD nodeFD = nodesFD.remove(node);
+ if (nodeFD == null) {
+ return;
+ }
+ if (!running) {
+ return;
+ }
+ if (connectOnNetworkDisconnect) {
+ try {
+ transportService.connectToNode(node);
+ } catch (Exception e) {
+ logger.trace("Node [{}] failed on disconnect (with verified connect)", node);
+ notifyNodeFailure(node);
+ }
+ } else {
+ logger.trace("Node [{}] failed on disconnect", node);
+ notifyNodeFailure(node);
+ }
+ }
+
+ private void notifyNodeFailure(DiscoveryNode node) {
+ for (Listener listener : listeners) {
+ listener.onNodeFailure(node);
+ }
+ }
+
+ private class SendPingRequest implements Runnable {
+
+ private final DiscoveryNode node;
+
+ private SendPingRequest(DiscoveryNode node) {
+ this.node = node;
+ }
+
+ @Override public void run() {
+ if (!running) {
+ return;
+ }
+ transportService.sendRequest(node, PingRequestHandler.ACTION, new PingRequest(), pingRetryTimeout,
+ new BaseTransportResponseHandler<PingResponse>() {
+ @Override public PingResponse newInstance() {
+ return new PingResponse();
+ }
+
+ @Override public void handleResponse(PingResponse response) {
+ if (running) {
+ NodeFD nodeFD = nodesFD.get(node);
+ if (nodeFD != null) {
+ nodeFD.retryCount = 0;
+ threadPool.schedule(SendPingRequest.this, pingInterval);
+ }
+ }
+ }
+
+ @Override public void handleException(RemoteTransportException exp) {
+ // check if the master node did not get switched on us...
+ if (running) {
+ NodeFD nodeFD = nodesFD.get(node);
+ if (nodeFD != null) {
+ int retryCount = ++nodeFD.retryCount;
+ logger.trace("Node [{}] failed to ping, retry [{}] out of [{}]", exp, node, retryCount, pingRetryCount);
+ if (retryCount >= pingRetryCount) {
+ logger.trace("Node [{}] failed on ping", node);
+ // not good, failure
+ if (nodesFD.remove(node) != null) {
+ notifyNodeFailure(node);
+ }
+ }
+ }
+ }
+ }
+ });
+ }
+ }
+
+ static class NodeFD {
+ volatile int retryCount;
+ }
+
+ private class FDConnectionListener implements TransportConnectionListener {
+ @Override public void onNodeConnected(DiscoveryNode node) {
+ }
+
+ @Override public void onNodeDisconnected(DiscoveryNode node) {
+ handleTransportDisconnect(node);
+ }
+ }
+
+
+ private class PingRequestHandler extends BaseTransportRequestHandler<PingRequest> {
+
+ public static final String ACTION = "discovery/zen/fd/ping";
+
+ @Override public PingRequest newInstance() {
+ return new PingRequest();
+ }
+
+ @Override public void messageReceived(PingRequest request, TransportChannel channel) throws Exception {
+ channel.sendResponse(new PingResponse());
+ }
+ }
+
+
+ private class PingRequest implements Streamable {
+
+ private PingRequest() {
+ }
+
+ @Override public void readFrom(StreamInput in) throws IOException {
+ }
+
+ @Override public void writeTo(StreamOutput out) throws IOException {
+ }
+ }
+
+ private class PingResponse implements Streamable {
+
+ private PingResponse() {
+ }
+
+ @Override public void readFrom(StreamInput in) throws IOException {
+ }
+
+ @Override public void writeTo(StreamOutput out) throws IOException {
+ }
+ }
+}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/membership/MembershipAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/membership/MembershipAction.java
new file mode 100644
index 0000000000000..f2bfd29e4aed0
--- /dev/null
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/membership/MembershipAction.java
@@ -0,0 +1,152 @@
+/*
+ * Licensed to Elastic Search and Shay Banon under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. Elastic Search 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.elasticsearch.discovery.zen.membership;
+
+import org.elasticsearch.ElasticSearchException;
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.transport.BaseTransportRequestHandler;
+import org.elasticsearch.transport.TransportChannel;
+import org.elasticsearch.transport.TransportService;
+import org.elasticsearch.transport.VoidTransportResponseHandler;
+import org.elasticsearch.util.TimeValue;
+import org.elasticsearch.util.component.AbstractComponent;
+import org.elasticsearch.util.io.stream.StreamInput;
+import org.elasticsearch.util.io.stream.StreamOutput;
+import org.elasticsearch.util.io.stream.Streamable;
+import org.elasticsearch.util.io.stream.VoidStreamable;
+import org.elasticsearch.util.settings.Settings;
+
+import java.io.IOException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+/**
+ * @author kimchy (shay.banon)
+ */
+public class MembershipAction extends AbstractComponent {
+
+ public static interface MembershipListener {
+ void onJoin(DiscoveryNode node);
+
+ void onLeave(DiscoveryNode node);
+ }
+
+ private final TransportService transportService;
+
+ private final MembershipListener listener;
+
+ public MembershipAction(Settings settings, TransportService transportService, MembershipListener listener) {
+ super(settings);
+ this.transportService = transportService;
+ this.listener = listener;
+
+ transportService.registerHandler(JoinRequestRequestHandler.ACTION, new JoinRequestRequestHandler());
+ transportService.registerHandler(LeaveRequestRequestHandler.ACTION, new LeaveRequestRequestHandler());
+ }
+
+ public void close() {
+ transportService.removeHandler(JoinRequestRequestHandler.ACTION);
+ transportService.removeHandler(LeaveRequestRequestHandler.ACTION);
+ }
+
+ public void sendLeaveRequest(DiscoveryNode masterNode, DiscoveryNode node) {
+ transportService.sendRequest(node, LeaveRequestRequestHandler.ACTION, new LeaveRequest(masterNode), VoidTransportResponseHandler.INSTANCE_NOSPAWN);
+ }
+
+ public void sendLeaveRequestBlocking(DiscoveryNode masterNode, DiscoveryNode node, TimeValue timeout) throws ElasticSearchException, TimeoutException {
+ transportService.submitRequest(masterNode, LeaveRequestRequestHandler.ACTION, new LeaveRequest(node), VoidTransportResponseHandler.INSTANCE_NOSPAWN).txGet(timeout.millis(), TimeUnit.MILLISECONDS);
+ }
+
+ public void sendJoinRequest(DiscoveryNode masterNode, DiscoveryNode node) {
+ transportService.sendRequest(masterNode, JoinRequestRequestHandler.ACTION, new JoinRequest(node), VoidTransportResponseHandler.INSTANCE_NOSPAWN);
+ }
+
+ public void sendJoinRequestBlocking(DiscoveryNode masterNode, DiscoveryNode node, TimeValue timeout) throws ElasticSearchException, TimeoutException {
+ transportService.submitRequest(masterNode, JoinRequestRequestHandler.ACTION, new JoinRequest(node), VoidTransportResponseHandler.INSTANCE_NOSPAWN).txGet(timeout.millis(), TimeUnit.MILLISECONDS);
+ }
+
+ private static class JoinRequest implements Streamable {
+
+ private DiscoveryNode node;
+
+ private JoinRequest() {
+ }
+
+ private JoinRequest(DiscoveryNode node) {
+ this.node = node;
+ }
+
+ @Override public void readFrom(StreamInput in) throws IOException {
+ node = DiscoveryNode.readNode(in);
+ }
+
+ @Override public void writeTo(StreamOutput out) throws IOException {
+ node.writeTo(out);
+ }
+ }
+
+ private class JoinRequestRequestHandler extends BaseTransportRequestHandler<JoinRequest> {
+
+ static final String ACTION = "discovery/zen/join";
+
+ @Override public JoinRequest newInstance() {
+ return new JoinRequest();
+ }
+
+ @Override public void messageReceived(JoinRequest request, TransportChannel channel) throws Exception {
+ listener.onJoin(request.node);
+ channel.sendResponse(VoidStreamable.INSTANCE);
+ }
+ }
+
+ private static class LeaveRequest implements Streamable {
+
+ private DiscoveryNode node;
+
+ private LeaveRequest() {
+ }
+
+ private LeaveRequest(DiscoveryNode node) {
+ this.node = node;
+ }
+
+ @Override public void readFrom(StreamInput in) throws IOException {
+ node = DiscoveryNode.readNode(in);
+ }
+
+ @Override public void writeTo(StreamOutput out) throws IOException {
+ node.writeTo(out);
+ }
+ }
+
+ private class LeaveRequestRequestHandler extends BaseTransportRequestHandler<LeaveRequest> {
+
+ static final String ACTION = "discovery/zen/leave";
+
+ @Override public LeaveRequest newInstance() {
+ return new LeaveRequest();
+ }
+
+ @Override public void messageReceived(LeaveRequest request, TransportChannel channel) throws Exception {
+ listener.onLeave(request.node);
+ channel.sendResponse(VoidStreamable.INSTANCE);
+ }
+ }
+}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/ping/ZenPing.java b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/ping/ZenPing.java
new file mode 100644
index 0000000000000..06475a76dcfcf
--- /dev/null
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/ping/ZenPing.java
@@ -0,0 +1,92 @@
+/*
+ * Licensed to Elastic Search and Shay Banon under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. Elastic Search 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.elasticsearch.discovery.zen.ping;
+
+import org.elasticsearch.ElasticSearchException;
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.discovery.zen.DiscoveryNodesProvider;
+import org.elasticsearch.util.TimeValue;
+import org.elasticsearch.util.component.LifecycleComponent;
+import org.elasticsearch.util.io.stream.StreamInput;
+import org.elasticsearch.util.io.stream.StreamOutput;
+import org.elasticsearch.util.io.stream.Streamable;
+
+import java.io.IOException;
+
+import static org.elasticsearch.cluster.node.DiscoveryNode.*;
+
+/**
+ * @author kimchy (shay.banon)
+ */
+public interface ZenPing extends LifecycleComponent<ZenPing> {
+
+ void setNodesProvider(DiscoveryNodesProvider nodesProvider);
+
+ void ping(PingListener listener, TimeValue timeout) throws ElasticSearchException;
+
+ public interface PingListener {
+
+ void onPing(PingResponse[] pings);
+ }
+
+ public class PingResponse implements Streamable {
+
+ private DiscoveryNode target;
+
+ private DiscoveryNode master;
+
+ public PingResponse() {
+ }
+
+ public PingResponse(DiscoveryNode target, DiscoveryNode master) {
+ this.target = target;
+ this.master = master;
+ }
+
+ public DiscoveryNode target() {
+ return target;
+ }
+
+ public DiscoveryNode master() {
+ return master;
+ }
+
+ @Override public void readFrom(StreamInput in) throws IOException {
+ target = readNode(in);
+ if (in.readBoolean()) {
+ master = readNode(in);
+ }
+ }
+
+ @Override public void writeTo(StreamOutput out) throws IOException {
+ target.writeTo(out);
+ if (master == null) {
+ out.writeBoolean(false);
+ } else {
+ out.writeBoolean(true);
+ master.writeTo(out);
+ }
+ }
+
+ @Override public String toString() {
+ return "ping_response target [" + target + "], master [" + master + "]";
+ }
+ }
+}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/ping/ZenPingException.java b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/ping/ZenPingException.java
new file mode 100644
index 0000000000000..6d598e1ffcbab
--- /dev/null
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/ping/ZenPingException.java
@@ -0,0 +1,36 @@
+/*
+ * Licensed to Elastic Search and Shay Banon under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. Elastic Search 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.elasticsearch.discovery.zen.ping;
+
+import org.elasticsearch.discovery.DiscoveryException;
+
+/**
+ * @author kimchy (shay.banon)
+ */
+public class ZenPingException extends DiscoveryException {
+
+ public ZenPingException(String message) {
+ super(message);
+ }
+
+ public ZenPingException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/ping/ZenPingService.java b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/ping/ZenPingService.java
new file mode 100644
index 0000000000000..d9938e5429220
--- /dev/null
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/ping/ZenPingService.java
@@ -0,0 +1,151 @@
+/*
+ * Licensed to Elastic Search and Shay Banon under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. Elastic Search 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.elasticsearch.discovery.zen.ping;
+
+import com.google.common.collect.ImmutableList;
+import com.google.inject.Inject;
+import org.elasticsearch.ElasticSearchException;
+import org.elasticsearch.ElasticSearchIllegalStateException;
+import org.elasticsearch.cluster.ClusterName;
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.discovery.zen.DiscoveryNodesProvider;
+import org.elasticsearch.discovery.zen.ping.multicast.MulticastZenPing;
+import org.elasticsearch.threadpool.ThreadPool;
+import org.elasticsearch.transport.TransportService;
+import org.elasticsearch.util.TimeValue;
+import org.elasticsearch.util.component.AbstractLifecycleComponent;
+import org.elasticsearch.util.settings.Settings;
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+/**
+ * @author kimchy (shay.banon)
+ */
+public class ZenPingService extends AbstractLifecycleComponent<ZenPing> implements ZenPing {
+
+ private volatile ImmutableList<? extends ZenPing> zenPings = ImmutableList.of();
+
+ @Inject public ZenPingService(Settings settings, ThreadPool threadPool, TransportService transportService, ClusterName clusterName) {
+ super(settings);
+
+ this.zenPings = ImmutableList.of(new MulticastZenPing(settings, threadPool, transportService, clusterName));
+ }
+
+ public ImmutableList<? extends ZenPing> zenPings() {
+ return this.zenPings;
+ }
+
+ public void zenPings(ImmutableList<? extends ZenPing> pings) {
+ this.zenPings = pings;
+ if (lifecycle.started()) {
+ for (ZenPing zenPing : zenPings) {
+ zenPing.start();
+ }
+ } else if (lifecycle.stopped()) {
+ for (ZenPing zenPing : zenPings) {
+ zenPing.stop();
+ }
+ }
+ }
+
+ @Override public void setNodesProvider(DiscoveryNodesProvider nodesProvider) {
+ if (lifecycle.started()) {
+ throw new ElasticSearchIllegalStateException("Can't set nodes provider when started");
+ }
+ for (ZenPing zenPing : zenPings) {
+ zenPing.setNodesProvider(nodesProvider);
+ }
+ }
+
+ @Override protected void doStart() throws ElasticSearchException {
+ for (ZenPing zenPing : zenPings) {
+ zenPing.start();
+ }
+ }
+
+ @Override protected void doStop() throws ElasticSearchException {
+ for (ZenPing zenPing : zenPings) {
+ zenPing.stop();
+ }
+ }
+
+ @Override protected void doClose() throws ElasticSearchException {
+ for (ZenPing zenPing : zenPings) {
+ zenPing.close();
+ }
+ }
+
+ public PingResponse[] pingAndWait(TimeValue timeout) {
+ final AtomicReference<PingResponse[]> response = new AtomicReference<PingResponse[]>();
+ final CountDownLatch latch = new CountDownLatch(1);
+ ping(new PingListener() {
+ @Override public void onPing(PingResponse[] pings) {
+ response.set(pings);
+ latch.countDown();
+ }
+ }, timeout);
+ try {
+ latch.await();
+ return response.get();
+ } catch (InterruptedException e) {
+ return null;
+ }
+ }
+
+ @Override public void ping(PingListener listener, TimeValue timeout) throws ElasticSearchException {
+ ImmutableList<? extends ZenPing> zenPings = this.zenPings;
+ CompoundPingListener compoundPingListener = new CompoundPingListener(listener, zenPings);
+ for (ZenPing zenPing : zenPings) {
+ zenPing.ping(compoundPingListener, timeout);
+ }
+ }
+
+ private static class CompoundPingListener implements PingListener {
+
+ private final PingListener listener;
+
+ private final ImmutableList<? extends ZenPing> zenPings;
+
+ private final AtomicInteger counter;
+
+ private ConcurrentMap<DiscoveryNode, PingResponse> responses = new ConcurrentHashMap<DiscoveryNode, PingResponse>();
+
+ private CompoundPingListener(PingListener listener, ImmutableList<? extends ZenPing> zenPings) {
+ this.listener = listener;
+ this.zenPings = zenPings;
+ this.counter = new AtomicInteger(zenPings.size());
+ }
+
+ @Override public void onPing(PingResponse[] pings) {
+ if (pings != null) {
+ for (PingResponse pingResponse : pings) {
+ responses.put(pingResponse.target(), pingResponse);
+ }
+ }
+ if (counter.decrementAndGet() == 0) {
+ listener.onPing(responses.values().toArray(new PingResponse[responses.size()]));
+ }
+ }
+ }
+}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/ping/multicast/MulticastZenPing.java b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/ping/multicast/MulticastZenPing.java
new file mode 100644
index 0000000000000..538a204cddea9
--- /dev/null
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/ping/multicast/MulticastZenPing.java
@@ -0,0 +1,359 @@
+/*
+ * Licensed to Elastic Search and Shay Banon under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. Elastic Search 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.elasticsearch.discovery.zen.ping.multicast;
+
+import org.elasticsearch.ElasticSearchException;
+import org.elasticsearch.ElasticSearchIllegalStateException;
+import org.elasticsearch.cluster.ClusterName;
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
+import org.elasticsearch.discovery.DiscoveryException;
+import org.elasticsearch.discovery.zen.DiscoveryNodesProvider;
+import org.elasticsearch.discovery.zen.ping.ZenPing;
+import org.elasticsearch.discovery.zen.ping.ZenPingException;
+import org.elasticsearch.threadpool.ThreadPool;
+import org.elasticsearch.transport.*;
+import org.elasticsearch.util.TimeValue;
+import org.elasticsearch.util.component.AbstractLifecycleComponent;
+import org.elasticsearch.util.io.stream.*;
+import org.elasticsearch.util.settings.ImmutableSettings;
+import org.elasticsearch.util.settings.Settings;
+
+import java.io.IOException;
+import java.net.*;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.elasticsearch.cluster.node.DiscoveryNode.*;
+import static org.elasticsearch.util.concurrent.ConcurrentMaps.*;
+import static org.elasticsearch.util.concurrent.DynamicExecutors.*;
+import static org.elasticsearch.util.io.NetworkUtils.*;
+
+/**
+ * @author kimchy (shay.banon)
+ */
+public class MulticastZenPing extends AbstractLifecycleComponent<ZenPing> implements ZenPing {
+
+ private final String address;
+
+ private final int port;
+
+ private final String group;
+
+ private final int bufferSize;
+
+ private final int ttl;
+
+ private final ThreadPool threadPool;
+
+ private final TransportService transportService;
+
+ private final ClusterName clusterName;
+
+
+ private volatile DiscoveryNodesProvider nodesProvider;
+
+ private volatile Receiver receiver;
+
+ private volatile Thread receiverThread;
+
+ private MulticastSocket multicastSocket;
+
+ private DatagramPacket datagramPacketSend;
+
+ private DatagramPacket datagramPacketReceive;
+
+ private final AtomicInteger pingIdGenerator = new AtomicInteger();
+
+ private final Map<Integer, ConcurrentMap<DiscoveryNode, PingResponse>> receivedResponses = newConcurrentMap();
+
+ private final Object sendMutex = new Object();
+
+ private final Object receiveMutex = new Object();
+
+ public MulticastZenPing(ThreadPool threadPool, TransportService transportService, ClusterName clusterName) {
+ this(ImmutableSettings.Builder.EMPTY_SETTINGS, threadPool, transportService, clusterName);
+ }
+
+ public MulticastZenPing(Settings settings, ThreadPool threadPool, TransportService transportService, ClusterName clusterName) {
+ super(settings);
+ this.threadPool = threadPool;
+ this.transportService = transportService;
+ this.clusterName = clusterName;
+
+ this.address = componentSettings.get("address");
+ this.port = componentSettings.getAsInt("port", 54328);
+ this.group = componentSettings.get("group", "224.2.2.4");
+ this.bufferSize = componentSettings.getAsInt("buffer_size", 2048);
+ this.ttl = componentSettings.getAsInt("ttl", 3);
+
+ this.transportService.registerHandler(PingResponseRequestHandler.ACTION, new PingResponseRequestHandler());
+ }
+
+ @Override public void setNodesProvider(DiscoveryNodesProvider nodesProvider) {
+ if (lifecycle.started()) {
+ throw new ElasticSearchIllegalStateException("Can't set nodes provider when started");
+ }
+ this.nodesProvider = nodesProvider;
+ }
+
+ @Override protected void doStart() throws ElasticSearchException {
+ try {
+ this.datagramPacketReceive = new DatagramPacket(new byte[bufferSize], bufferSize);
+ this.datagramPacketSend = new DatagramPacket(new byte[bufferSize], bufferSize, InetAddress.getByName(group), port);
+ } catch (Exception e) {
+ throw new DiscoveryException("Failed to set datagram packets", e);
+ }
+
+ try {
+ MulticastSocket multicastSocket = new MulticastSocket(null);
+ multicastSocket.setReuseAddress(true);
+ // bind to receive interface
+ multicastSocket.bind(new InetSocketAddress(port));
+ multicastSocket.setTimeToLive(ttl);
+ // set the send interface
+ InetAddress multicastInterface = resolvePublishHostAddress(address, settings);
+ multicastSocket.setInterface(multicastInterface);
+ multicastSocket.setReceiveBufferSize(bufferSize);
+ multicastSocket.setSendBufferSize(bufferSize);
+ multicastSocket.joinGroup(InetAddress.getByName(group));
+ multicastSocket.setSoTimeout(60000);
+
+ this.multicastSocket = multicastSocket;
+ } catch (Exception e) {
+ throw new DiscoveryException("Failed to setup multicast socket", e);
+ }
+
+ this.receiver = new Receiver();
+ this.receiverThread = daemonThreadFactory(settings, "discovery#multicast#received").newThread(receiver);
+ this.receiverThread.start();
+ }
+
+ @Override protected void doStop() throws ElasticSearchException {
+ receiver.stop();
+ receiverThread.interrupt();
+ multicastSocket.close();
+ }
+
+ @Override protected void doClose() throws ElasticSearchException {
+ }
+
+ public PingResponse[] pingAndWait(TimeValue timeout) {
+ final AtomicReference<PingResponse[]> response = new AtomicReference<PingResponse[]>();
+ final CountDownLatch latch = new CountDownLatch(1);
+ ping(new PingListener() {
+ @Override public void onPing(PingResponse[] pings) {
+ response.set(pings);
+ latch.countDown();
+ }
+ }, timeout);
+ try {
+ latch.await();
+ return response.get();
+ } catch (InterruptedException e) {
+ return null;
+ }
+ }
+
+ @Override public void ping(final PingListener listener, final TimeValue timeout) {
+ final int id = pingIdGenerator.incrementAndGet();
+ receivedResponses.put(id, new ConcurrentHashMap<DiscoveryNode, PingResponse>());
+ sendPingRequest(id);
+ // try and send another ping request halfway through (just in case someone woke up during it...)
+ // this can be a good trade-off to nailing the initial lookup or un-delivered messages
+ threadPool.schedule(new Runnable() {
+ @Override public void run() {
+ try {
+ sendPingRequest(id);
+ } catch (Exception e) {
+ logger.debug("[{}] Failed to send second ping request", e, id);
+ }
+ }
+ }, timeout.millis() / 2, TimeUnit.MILLISECONDS);
+ threadPool.schedule(new Runnable() {
+ @Override public void run() {
+ ConcurrentMap<DiscoveryNode, PingResponse> responses = receivedResponses.remove(id);
+ listener.onPing(responses.values().toArray(new PingResponse[responses.size()]));
+ }
+ }, timeout.millis(), TimeUnit.MILLISECONDS);
+ }
+
+ private void sendPingRequest(int id) {
+ synchronized (sendMutex) {
+ try {
+ HandlesStreamOutput out = BytesStreamOutput.Cached.cachedHandles();
+ out.writeInt(id);
+ clusterName.writeTo(out);
+ nodesProvider.nodes().localNode().writeTo(out);
+ datagramPacketSend.setData(((BytesStreamOutput) out.wrappedOut()).copiedByteArray());
+ } catch (IOException e) {
+ receivedResponses.remove(id);
+ throw new ZenPingException("Failed to serialize ping request", e);
+ }
+ try {
+ multicastSocket.send(datagramPacketSend);
+ if (logger.isTraceEnabled()) {
+ logger.trace("[{}] Sending ping request", id);
+ }
+ } catch (IOException e) {
+ receivedResponses.remove(id);
+ throw new ZenPingException("Failed to send ping request over multicast", e);
+ }
+ }
+ }
+
+ private class PingResponseRequestHandler extends BaseTransportRequestHandler<WrappedPingResponse> {
+
+ static final String ACTION = "discovery/zen/multicast";
+
+ @Override public WrappedPingResponse newInstance() {
+ return new WrappedPingResponse();
+ }
+
+ @Override public void messageReceived(WrappedPingResponse request, TransportChannel channel) throws Exception {
+ if (logger.isTraceEnabled()) {
+ logger.trace("[{}] Received {}", request.id, request.pingResponse);
+ }
+ ConcurrentMap<DiscoveryNode, PingResponse> responses = receivedResponses.get(request.id);
+ if (responses == null) {
+ logger.warn("Received ping response with no matching id [{}]", request.id);
+ } else {
+ responses.put(request.pingResponse.target(), request.pingResponse);
+ }
+ channel.sendResponse(VoidStreamable.INSTANCE);
+ }
+ }
+
+ class WrappedPingResponse implements Streamable {
+
+ int id;
+
+ PingResponse pingResponse;
+
+ WrappedPingResponse() {
+ }
+
+ WrappedPingResponse(int id, PingResponse pingResponse) {
+ this.id = id;
+ this.pingResponse = pingResponse;
+ }
+
+ @Override public void readFrom(StreamInput in) throws IOException {
+ id = in.readInt();
+ pingResponse = new PingResponse();
+ pingResponse.readFrom(in);
+ }
+
+ @Override public void writeTo(StreamOutput out) throws IOException {
+ out.writeInt(id);
+ pingResponse.writeTo(out);
+ }
+ }
+
+
+ private class Receiver implements Runnable {
+
+ private volatile boolean running = true;
+
+ public void stop() {
+ running = false;
+ }
+
+ @Override public void run() {
+ while (running) {
+ try {
+ int id;
+ DiscoveryNode requestingNodeX;
+ ClusterName clusterName;
+ synchronized (receiveMutex) {
+ try {
+ multicastSocket.receive(datagramPacketReceive);
+ } catch (SocketTimeoutException ignore) {
+ continue;
+ } catch (Exception e) {
+ if (running) {
+ logger.warn("Failed to receive packet", e);
+ }
+ continue;
+ }
+ try {
+ StreamInput input = HandlesStreamInput.Cached.cached(new BytesStreamInput(datagramPacketReceive.getData(), datagramPacketReceive.getOffset(), datagramPacketReceive.getLength()));
+ id = input.readInt();
+ clusterName = ClusterName.readClusterName(input);
+ requestingNodeX = readNode(input);
+ } catch (Exception e) {
+ logger.warn("Failed to read requesting node from {}", e, datagramPacketReceive.getSocketAddress());
+ continue;
+ }
+ }
+ DiscoveryNodes discoveryNodes = nodesProvider.nodes();
+ final DiscoveryNode requestingNode = requestingNodeX;
+ if (requestingNode.id().equals(discoveryNodes.localNodeId())) {
+ // that's me, ignore
+ continue;
+ }
+ if (!clusterName.equals(MulticastZenPing.this.clusterName)) {
+ // not our cluster, ignore it...
+ continue;
+ }
+ final WrappedPingResponse wrappedPingResponse = new WrappedPingResponse();
+ wrappedPingResponse.id = id;
+ wrappedPingResponse.pingResponse = new PingResponse(discoveryNodes.localNode(), discoveryNodes.masterNode());
+
+ if (logger.isTraceEnabled()) {
+ logger.trace("[{}] Received ping_request from [{}], sending {}", id, requestingNode, wrappedPingResponse.pingResponse);
+ }
+
+ if (!transportService.nodeConnected(requestingNode)) {
+ // do the connect and send on a thread pool
+ threadPool.execute(new Runnable() {
+ @Override public void run() {
+ // connect to the node if possible
+ try {
+ transportService.connectToNode(requestingNode);
+ } catch (Exception e) {
+ logger.warn("Failed to connect to requesting node {}", e, requestingNode);
+ }
+ transportService.sendRequest(requestingNode, PingResponseRequestHandler.ACTION, wrappedPingResponse, new VoidTransportResponseHandler(false) {
+ @Override public void handleException(RemoteTransportException exp) {
+ logger.warn("Failed to receive confirmation on sent ping response to [{}]", exp, requestingNode);
+ }
+ });
+ }
+ });
+ } else {
+ transportService.sendRequest(requestingNode, PingResponseRequestHandler.ACTION, wrappedPingResponse, new VoidTransportResponseHandler(false) {
+ @Override public void handleException(RemoteTransportException exp) {
+ logger.warn("Failed to receive confirmation on sent ping response to [{}]", exp, requestingNode);
+ }
+ });
+ }
+ } catch (Exception e) {
+ logger.warn("Unexpected exception in multicast receiver", e);
+ }
+ }
+ }
+ }
+}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/publish/PublishClusterStateAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/publish/PublishClusterStateAction.java
new file mode 100644
index 0000000000000..1a5f783511bc6
--- /dev/null
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/publish/PublishClusterStateAction.java
@@ -0,0 +1,111 @@
+/*
+ * Licensed to Elastic Search and Shay Banon under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. Elastic Search 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.elasticsearch.discovery.zen.publish;
+
+import org.elasticsearch.cluster.ClusterState;
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.discovery.zen.DiscoveryNodesProvider;
+import org.elasticsearch.transport.*;
+import org.elasticsearch.util.component.AbstractComponent;
+import org.elasticsearch.util.io.stream.StreamInput;
+import org.elasticsearch.util.io.stream.StreamOutput;
+import org.elasticsearch.util.io.stream.Streamable;
+import org.elasticsearch.util.io.stream.VoidStreamable;
+import org.elasticsearch.util.settings.Settings;
+
+import java.io.IOException;
+
+/**
+ * @author kimchy (shay.banon)
+ */
+public class PublishClusterStateAction extends AbstractComponent {
+
+ public static interface NewClusterStateListener {
+ void onNewClusterState(ClusterState clusterState);
+ }
+
+ private final TransportService transportService;
+
+ private final DiscoveryNodesProvider nodesProvider;
+
+ private final NewClusterStateListener listener;
+
+ public PublishClusterStateAction(Settings settings, TransportService transportService, DiscoveryNodesProvider nodesProvider,
+ NewClusterStateListener listener) {
+ super(settings);
+ this.transportService = transportService;
+ this.nodesProvider = nodesProvider;
+ this.listener = listener;
+ transportService.registerHandler(PublishClusterStateRequestHandler.ACTION, new PublishClusterStateRequestHandler());
+ }
+
+ public void close() {
+ transportService.removeHandler(PublishClusterStateRequestHandler.ACTION);
+ }
+
+ public void publish(ClusterState clusterState) {
+ DiscoveryNode localNode = nodesProvider.nodes().localNode();
+ for (final DiscoveryNode node : clusterState.nodes()) {
+ if (node.equals(localNode)) {
+ // no need to send to our self
+ continue;
+ }
+ transportService.sendRequest(node, PublishClusterStateRequestHandler.ACTION, new PublishClusterStateRequest(clusterState), new VoidTransportResponseHandler(false) {
+ @Override public void handleException(RemoteTransportException exp) {
+ logger.warn("Failed to send cluster state to [{}], should be detected as failed soon...", exp, node);
+ }
+ });
+ }
+ }
+
+ private class PublishClusterStateRequest implements Streamable {
+
+ private ClusterState clusterState;
+
+ private PublishClusterStateRequest() {
+ }
+
+ private PublishClusterStateRequest(ClusterState clusterState) {
+ this.clusterState = clusterState;
+ }
+
+ @Override public void readFrom(StreamInput in) throws IOException {
+ clusterState = ClusterState.Builder.readFrom(in, settings, nodesProvider.nodes().localNode());
+ }
+
+ @Override public void writeTo(StreamOutput out) throws IOException {
+ ClusterState.Builder.writeTo(clusterState, out);
+ }
+ }
+
+ private class PublishClusterStateRequestHandler extends BaseTransportRequestHandler<PublishClusterStateRequest> {
+
+ static final String ACTION = "discovery/zen/publish";
+
+ @Override public PublishClusterStateRequest newInstance() {
+ return new PublishClusterStateRequest();
+ }
+
+ @Override public void messageReceived(PublishClusterStateRequest request, TransportChannel channel) throws Exception {
+ listener.onNewClusterState(request.clusterState);
+ channel.sendResponse(VoidStreamable.INSTANCE);
+ }
+ }
+}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/http/netty/NettyHttpServerTransport.java b/modules/elasticsearch/src/main/java/org/elasticsearch/http/netty/NettyHttpServerTransport.java
index 606b33eec2d11..a88ac9ffc8a01 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/http/netty/NettyHttpServerTransport.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/http/netty/NettyHttpServerTransport.java
@@ -27,6 +27,7 @@
import org.elasticsearch.util.SizeUnit;
import org.elasticsearch.util.SizeValue;
import org.elasticsearch.util.component.AbstractLifecycleComponent;
+import org.elasticsearch.util.io.NetworkUtils;
import org.elasticsearch.util.settings.Settings;
import org.elasticsearch.util.transport.BoundTransportAddress;
import org.elasticsearch.util.transport.InetSocketTransportAddress;
@@ -49,7 +50,7 @@
import java.util.concurrent.atomic.AtomicReference;
import static org.elasticsearch.util.concurrent.DynamicExecutors.*;
-import static org.elasticsearch.util.io.HostResolver.*;
+import static org.elasticsearch.util.io.NetworkUtils.*;
/**
* @author kimchy (shay.banon)
@@ -103,7 +104,7 @@ public class NettyHttpServerTransport extends AbstractLifecycleComponent<HttpSer
this.publishHost = componentSettings.get("publish_host");
this.tcpNoDelay = componentSettings.getAsBoolean("tcp_no_delay", true);
this.tcpKeepAlive = componentSettings.getAsBoolean("tcp_keep_alive", null);
- this.reuseAddress = componentSettings.getAsBoolean("reuse_address", null);
+ this.reuseAddress = componentSettings.getAsBoolean("reuse_address", NetworkUtils.defaultReuseAddress());
this.tcpSendBufferSize = componentSettings.getAsSize("tcp_send_buffer_size", null);
this.tcpReceiveBufferSize = componentSettings.getAsSize("tcp_receive_buffer_size", null);
@@ -189,17 +190,7 @@ public void httpServerAdapter(HttpServerAdapter httpServerAdapter) {
InetSocketAddress boundAddress = (InetSocketAddress) serverChannel.getLocalAddress();
InetSocketAddress publishAddress;
try {
- InetAddress publishAddressX = resolvePublishHostAddress(publishHost, settings);
- if (publishAddressX == null) {
- // if its 0.0.0.0, we can't publish that.., default to the local ip address
- if (boundAddress.getAddress().isAnyLocalAddress()) {
- publishAddress = new InetSocketAddress(resolvePublishHostAddress(publishHost, settings, LOCAL_IP), boundAddress.getPort());
- } else {
- publishAddress = boundAddress;
- }
- } else {
- publishAddress = new InetSocketAddress(publishAddressX, boundAddress.getPort());
- }
+ publishAddress = new InetSocketAddress(resolvePublishHostAddress(publishHost, settings), boundAddress.getPort());
} catch (Exception e) {
throw new BindTransportException("Failed to resolve publish address", e);
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/query/json/JsonFilterBuilder.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/query/json/JsonFilterBuilder.java
index 7a87faccaacb5..ed0a1a1ebd9ed 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/query/json/JsonFilterBuilder.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/query/json/JsonFilterBuilder.java
@@ -22,7 +22,7 @@
import org.elasticsearch.util.json.ToJson;
/**
- * @author kimchy (Shay Banon)
+ * @author kimchy (shay.banon)
*/
public interface JsonFilterBuilder extends ToJson {
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/jmx/JmxService.java b/modules/elasticsearch/src/main/java/org/elasticsearch/jmx/JmxService.java
index de5423b6014b6..9a87e5e35a820 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/jmx/JmxService.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/jmx/JmxService.java
@@ -19,7 +19,7 @@
package org.elasticsearch.jmx;
-import org.elasticsearch.util.io.HostResolver;
+import org.elasticsearch.util.io.NetworkUtils;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.settings.Settings;
import org.elasticsearch.util.transport.PortsRange;
@@ -36,8 +36,6 @@
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicReference;
-import static org.elasticsearch.util.io.HostResolver.*;
-
/**
* @author kimchy (Shay Banon)
*/
@@ -116,7 +114,7 @@ public void connectAndRegister(String nodeDescription) {
connectorServer.start();
// create the publish url
- String publishHost = HostResolver.resolvePublishHostAddress(settings.get("jmx.publishHost"), settings, LOCAL_IP).getHostAddress();
+ String publishHost = NetworkUtils.resolvePublishHostAddress(settings.get("jmx.publishHost"), settings).getHostAddress();
publishUrl = settings.get("jmx.publishUrl", JMXRMI_PUBLISH_URI_PATTERN).replace("{jmx.port}", Integer.toString(portNumber)).replace("{jmx.host}", publishHost);
} catch (Exception e) {
lastException.set(e);
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/node/internal/InternalNode.java b/modules/elasticsearch/src/main/java/org/elasticsearch/node/internal/InternalNode.java
index 271b9b9f9c832..929e16e112ea7 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/node/internal/InternalNode.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/node/internal/InternalNode.java
@@ -46,6 +46,7 @@
import org.elasticsearch.jmx.JmxService;
import org.elasticsearch.monitor.MonitorModule;
import org.elasticsearch.monitor.MonitorService;
+import org.elasticsearch.monitor.jvm.JvmConfig;
import org.elasticsearch.node.Node;
import org.elasticsearch.plugins.PluginsModule;
import org.elasticsearch.plugins.PluginsService;
@@ -101,7 +102,7 @@ public InternalNode(Settings pSettings, boolean loadConfigSettings) throws Elast
Tuple<Settings, Environment> tuple = InternalSettingsPerparer.prepareSettings(pSettings, loadConfigSettings);
ESLogger logger = Loggers.getLogger(Node.class, tuple.v1().get("name"));
- logger.info("{{}}: Initializing ...", Version.full());
+ logger.info("{{}}[{}]: Initializing ...", Version.full(), JvmConfig.jvmConfig().pid());
this.pluginsService = new PluginsService(tuple.v1(), tuple.v2());
this.settings = pluginsService.updatedSettings();
@@ -135,7 +136,7 @@ public InternalNode(Settings pSettings, boolean loadConfigSettings) throws Elast
client = injector.getInstance(Client.class);
- logger.info("{{}}: Initialized", Version.full());
+ logger.info("{{}}[{}]: Initialized", Version.full(), JvmConfig.jvmConfig().pid());
}
@Override public Settings settings() {
@@ -152,7 +153,7 @@ public Node start() {
}
ESLogger logger = Loggers.getLogger(Node.class, settings.get("name"));
- logger.info("{{}}: Starting ...", Version.full());
+ logger.info("{{}}[{}]: Starting ...", Version.full(), JvmConfig.jvmConfig().pid());
for (Class<? extends LifecycleComponent> plugin : pluginsService.services()) {
injector.getInstance(plugin).start();
@@ -175,7 +176,7 @@ public Node start() {
}
injector.getInstance(JmxService.class).connectAndRegister(discoService.nodeDescription());
- logger.info("{{}}: Started", Version.full());
+ logger.info("{{}}[{}]: Started", Version.full(), JvmConfig.jvmConfig().pid());
return this;
}
@@ -185,7 +186,7 @@ public Node start() {
return this;
}
ESLogger logger = Loggers.getLogger(Node.class, settings.get("name"));
- logger.info("{{}}: Stopping ...", Version.full());
+ logger.info("{{}}[{}]: Stopping ...", Version.full(), JvmConfig.jvmConfig().pid());
if (settings.getAsBoolean("http.enabled", true)) {
injector.getInstance(HttpServer.class).stop();
@@ -215,7 +216,7 @@ public Node start() {
Injectors.close(injector);
- logger.info("{{}}: Stopped", Version.full());
+ logger.info("{{}}[{}]: Stopped", Version.full(), JvmConfig.jvmConfig().pid());
return this;
}
@@ -229,7 +230,7 @@ public void close() {
}
ESLogger logger = Loggers.getLogger(Node.class, settings.get("name"));
- logger.info("{{}}: Closing ...", Version.full());
+ logger.info("{{}}[{}]: Closing ...", Version.full(), JvmConfig.jvmConfig().pid());
if (settings.getAsBoolean("http.enabled", true)) {
injector.getInstance(HttpServer.class).close();
@@ -264,7 +265,7 @@ public void close() {
ThreadLocals.clearReferencesThreadLocals();
- logger.info("{{}}: Closed", Version.full());
+ logger.info("{{}}[{}]: Closed", Version.full(), JvmConfig.jvmConfig().pid());
}
public Injector injector() {
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/threadpool/ThreadPool.java b/modules/elasticsearch/src/main/java/org/elasticsearch/threadpool/ThreadPool.java
index d48d445a32ee6..32da99a2c039d 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/threadpool/ThreadPool.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/threadpool/ThreadPool.java
@@ -39,5 +39,7 @@ public interface ThreadPool extends ScheduledExecutorService {
Future<?> submit(Runnable task, FutureListener<?> listener);
- public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, TimeValue interval);
+ public ScheduledFuture<?> schedule(Runnable command, TimeValue delay);
+
+ ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, TimeValue interval);
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/threadpool/support/AbstractThreadPool.java b/modules/elasticsearch/src/main/java/org/elasticsearch/threadpool/support/AbstractThreadPool.java
index d0818480c741b..1fb55ae6fbc30 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/threadpool/support/AbstractThreadPool.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/threadpool/support/AbstractThreadPool.java
@@ -120,6 +120,10 @@ protected AbstractThreadPool(Settings settings) {
return executorService.submit(new FutureRunnable(task, null, listener));
}
+ @Override public ScheduledFuture<?> schedule(Runnable command, TimeValue delay) {
+ return schedule(command, delay.millis(), TimeUnit.MILLISECONDS);
+ }
+
@Override public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, TimeValue interval) {
return scheduleWithFixedDelay(command, interval.millis(), interval.millis(), TimeUnit.MILLISECONDS);
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/timer/TimerService.java b/modules/elasticsearch/src/main/java/org/elasticsearch/timer/TimerService.java
index 942c5ebb37bec..ac123fffd349c 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/timer/TimerService.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/timer/TimerService.java
@@ -23,6 +23,7 @@
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.util.TimeValue;
import org.elasticsearch.util.component.AbstractComponent;
+import org.elasticsearch.util.settings.ImmutableSettings;
import org.elasticsearch.util.settings.Settings;
import org.elasticsearch.util.timer.HashedWheelTimer;
import org.elasticsearch.util.timer.Timeout;
@@ -50,6 +51,12 @@ public class TimerService extends AbstractComponent {
private final TimeValue tickDuration;
+ private final int ticksPerWheel;
+
+ public TimerService(ThreadPool threadPool) {
+ this(ImmutableSettings.Builder.EMPTY_SETTINGS, threadPool);
+ }
+
@Inject public TimerService(Settings settings, ThreadPool threadPool) {
super(settings);
this.threadPool = threadPool;
@@ -58,8 +65,9 @@ public class TimerService extends AbstractComponent {
this.timeEstimatorFuture = threadPool.scheduleWithFixedDelay(timeEstimator, 50, 50, TimeUnit.MILLISECONDS);
this.tickDuration = componentSettings.getAsTime("tick_duration", timeValueMillis(100));
+ this.ticksPerWheel = componentSettings.getAsInt("ticks_per_wheel", 1024);
- this.timer = new HashedWheelTimer(logger, daemonThreadFactory(settings, "timer"), tickDuration.millis(), TimeUnit.MILLISECONDS);
+ this.timer = new HashedWheelTimer(logger, daemonThreadFactory(settings, "timer"), tickDuration.millis(), TimeUnit.MILLISECONDS, ticksPerWheel);
}
public void close() {
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/ConnectTransportException.java b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/ConnectTransportException.java
index 6b0abb69ec676..ed1a9db654629 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/ConnectTransportException.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/ConnectTransportException.java
@@ -22,7 +22,7 @@
import org.elasticsearch.cluster.node.DiscoveryNode;
/**
- * @author kimchy (Shay Banon)
+ * @author kimchy (shay.banon)
*/
public class ConnectTransportException extends TransportException {
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/NodeDisconnectedTransportException.java b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/NodeDisconnectedTransportException.java
new file mode 100644
index 0000000000000..c40e8a0a87d96
--- /dev/null
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/NodeDisconnectedTransportException.java
@@ -0,0 +1,36 @@
+/*
+ * Licensed to Elastic Search and Shay Banon under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. Elastic Search 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.elasticsearch.transport;
+
+import org.elasticsearch.cluster.node.DiscoveryNode;
+
+/**
+ * @author kimchy (shay.banon)
+ */
+public class NodeDisconnectedTransportException extends RemoteTransportException {
+
+ public NodeDisconnectedTransportException(DiscoveryNode node, String action) {
+ super(node.name(), node.address(), action, null);
+ }
+
+// @Override public Throwable fillInStackTrace() {
+// return fillStack();
+// }
+}
\ No newline at end of file
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/ReceiveTimeoutTransportException.java b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/ReceiveTimeoutTransportException.java
new file mode 100644
index 0000000000000..7737aa6ca8002
--- /dev/null
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/ReceiveTimeoutTransportException.java
@@ -0,0 +1,36 @@
+/*
+ * Licensed to Elastic Search and Shay Banon under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. Elastic Search 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.elasticsearch.transport;
+
+import org.elasticsearch.cluster.node.DiscoveryNode;
+
+/**
+ * @author kimchy (shay.banon)
+ */
+public class ReceiveTimeoutTransportException extends RemoteTransportException {
+
+ public ReceiveTimeoutTransportException(DiscoveryNode node, String action) {
+ super(node.name(), node.address(), action, null);
+ }
+
+// @Override public Throwable fillInStackTrace() {
+// return fillStack();
+// }
+}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/TransportResponseHandler.java b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/TransportResponseHandler.java
index cb5c6d2e3f398..6bb95e7d7c710 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/TransportResponseHandler.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/TransportResponseHandler.java
@@ -28,9 +28,9 @@ public interface TransportResponseHandler<T extends Streamable> {
/**
* creates a new instance of the return type from the remote call.
- * called by the infra before deserializing the response.
+ * called by the infra before de-serializing the response.
*
- * @return a new reponse copy.
+ * @return a new response copy.
*/
T newInstance();
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/TransportService.java b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/TransportService.java
index cc517d0c8dfce..0339c6502bfdc 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/TransportService.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/TransportService.java
@@ -23,13 +23,18 @@
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.threadpool.ThreadPool;
+import org.elasticsearch.timer.TimerService;
+import org.elasticsearch.util.TimeValue;
import org.elasticsearch.util.component.AbstractLifecycleComponent;
import org.elasticsearch.util.concurrent.highscalelib.NonBlockingHashMapLong;
import org.elasticsearch.util.io.stream.Streamable;
import org.elasticsearch.util.settings.Settings;
+import org.elasticsearch.util.timer.Timeout;
+import org.elasticsearch.util.timer.TimerTask;
import org.elasticsearch.util.transport.BoundTransportAddress;
import org.elasticsearch.util.transport.TransportAddress;
+import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;
@@ -46,9 +51,11 @@ public class TransportService extends AbstractLifecycleComponent<TransportServic
private final ThreadPool threadPool;
+ private final TimerService timerService;
+
final ConcurrentMap<String, TransportRequestHandler> serverHandlers = newConcurrentMap();
- final NonBlockingHashMapLong<TransportResponseHandler> clientHandlers = new NonBlockingHashMapLong<TransportResponseHandler>();
+ final NonBlockingHashMapLong<RequestHolder> clientHandlers = new NonBlockingHashMapLong<RequestHolder>();
final AtomicLong requestIds = new AtomicLong();
@@ -56,39 +63,20 @@ public class TransportService extends AbstractLifecycleComponent<TransportServic
private boolean throwConnectException = false;
- public TransportService(Transport transport, ThreadPool threadPool) {
- this(EMPTY_SETTINGS, transport, threadPool);
+ public TransportService(Transport transport, ThreadPool threadPool, TimerService timerService) {
+ this(EMPTY_SETTINGS, transport, threadPool, timerService);
}
- @Inject public TransportService(Settings settings, Transport transport, ThreadPool threadPool) {
+ @Inject public TransportService(Settings settings, Transport transport, ThreadPool threadPool, TimerService timerService) {
super(settings);
this.transport = transport;
this.threadPool = threadPool;
+ this.timerService = timerService;
}
@Override protected void doStart() throws ElasticSearchException {
// register us as an adapter for the transport service
- transport.transportServiceAdapter(new TransportServiceAdapter() {
- @Override public TransportRequestHandler handler(String action) {
- return serverHandlers.get(action);
- }
-
- @Override public TransportResponseHandler remove(long requestId) {
- return clientHandlers.remove(requestId);
- }
-
- @Override public void raiseNodeConnected(DiscoveryNode node) {
- for (TransportConnectionListener connectionListener : connectionListeners) {
- connectionListener.onNodeConnected(node);
- }
- }
-
- @Override public void raiseNodeDisconnected(DiscoveryNode node) {
- for (TransportConnectionListener connectionListener : connectionListeners) {
- connectionListener.onNodeDisconnected(node);
- }
- }
- });
+ transport.transportServiceAdapter(new Adapter());
transport.start();
if (transport.boundAddress() != null && logger.isInfoEnabled()) {
logger.info("{}", transport.boundAddress());
@@ -144,16 +132,30 @@ public void throwConnectException(boolean throwConnectException) {
public <T extends Streamable> TransportFuture<T> submitRequest(DiscoveryNode node, String action, Streamable message,
TransportResponseHandler<T> handler) throws TransportException {
+ return submitRequest(node, action, message, null, handler);
+ }
+
+ public <T extends Streamable> TransportFuture<T> submitRequest(DiscoveryNode node, String action, Streamable message,
+ TimeValue timeout, TransportResponseHandler<T> handler) throws TransportException {
PlainTransportFuture<T> futureHandler = new PlainTransportFuture<T>(handler);
- sendRequest(node, action, message, futureHandler);
+ sendRequest(node, action, message, timeout, futureHandler);
return futureHandler;
}
public <T extends Streamable> void sendRequest(final DiscoveryNode node, final String action, final Streamable message,
final TransportResponseHandler<T> handler) throws TransportException {
+ sendRequest(node, action, message, null, handler);
+ }
+
+ public <T extends Streamable> void sendRequest(final DiscoveryNode node, final String action, final Streamable message,
+ final TimeValue timeout, final TransportResponseHandler<T> handler) throws TransportException {
final long requestId = newRequestId();
try {
- clientHandlers.put(requestId, handler);
+ Timeout timeoutX = null;
+ if (timeout != null) {
+ timeoutX = timerService.newTimeout(new TimeoutTimerTask(requestId), timeout);
+ }
+ clientHandlers.put(requestId, new RequestHolder<T>(handler, node, action, timeoutX));
transport.sendRequest(node, requestId, action, message, handler);
} catch (final Exception e) {
// usually happen either because we failed to connect to the node
@@ -183,10 +185,105 @@ public void registerHandler(ActionTransportRequestHandler handler) {
}
public void registerHandler(String action, TransportRequestHandler handler) {
- serverHandlers.put(action, handler);
+ TransportRequestHandler handlerReplaced = serverHandlers.put(action, handler);
+ if (handlerReplaced != null) {
+ logger.warn("Registered two transport handlers for action {}, handlers: {}, {}", action, handler, handlerReplaced);
+ }
}
public void removeHandler(String action) {
serverHandlers.remove(action);
}
+
+ class Adapter implements TransportServiceAdapter {
+ @Override public TransportRequestHandler handler(String action) {
+ return serverHandlers.get(action);
+ }
+
+ @Override public TransportResponseHandler remove(long requestId) {
+ RequestHolder holder = clientHandlers.remove(requestId);
+ if (holder == null) {
+ return null;
+ }
+ if (holder.timeout() != null) {
+ holder.timeout().cancel();
+ }
+ return holder.handler();
+ }
+
+ @Override public void raiseNodeConnected(DiscoveryNode node) {
+ for (TransportConnectionListener connectionListener : connectionListeners) {
+ connectionListener.onNodeConnected(node);
+ }
+ }
+
+ @Override public void raiseNodeDisconnected(DiscoveryNode node) {
+ for (TransportConnectionListener connectionListener : connectionListeners) {
+ connectionListener.onNodeDisconnected(node);
+ }
+ // node got disconnected, raise disconnection on possible ongoing handlers
+ for (Map.Entry<Long, RequestHolder> entry : clientHandlers.entrySet()) {
+ RequestHolder holder = entry.getValue();
+ if (holder.node().equals(node)) {
+ holder = clientHandlers.remove(entry.getKey());
+ if (holder != null) {
+ holder.handler().handleException(new NodeDisconnectedTransportException(node, holder.action()));
+ }
+ }
+ }
+ }
+ }
+
+ class TimeoutTimerTask implements TimerTask {
+
+ private final long requestId;
+
+ TimeoutTimerTask(long requestId) {
+ this.requestId = requestId;
+ }
+
+ @Override public void run(Timeout timeout) throws Exception {
+ if (timeout.isCancelled()) {
+ return;
+ }
+ RequestHolder holder = clientHandlers.remove(requestId);
+ if (holder != null) {
+ holder.handler().handleException(new ReceiveTimeoutTransportException(holder.node(), holder.action()));
+ }
+ }
+ }
+
+ static class RequestHolder<T extends Streamable> {
+
+ private final TransportResponseHandler<T> handler;
+
+ private final DiscoveryNode node;
+
+ private final String action;
+
+ private final Timeout timeout;
+
+ RequestHolder(TransportResponseHandler<T> handler, DiscoveryNode node, String action, Timeout timeout) {
+ this.handler = handler;
+ this.node = node;
+ this.action = action;
+ this.timeout = timeout;
+ }
+
+ public TransportResponseHandler<T> handler() {
+ return handler;
+ }
+
+ public DiscoveryNode node() {
+ return this.node;
+ }
+
+ public String action() {
+ return this.action;
+ }
+
+ public Timeout timeout() {
+ return timeout;
+ }
+ }
}
\ No newline at end of file
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/local/LocalTransport.java b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/local/LocalTransport.java
index a00ff6974fc65..7ab21d47c757c 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/local/LocalTransport.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/local/LocalTransport.java
@@ -193,13 +193,22 @@ void messageReceived(byte[] data, String action, LocalTransport sourceTransport,
private void handleRequest(StreamInput stream, long requestId, LocalTransport sourceTransport) throws Exception {
final String action = stream.readUTF();
final LocalTransportChannel transportChannel = new LocalTransportChannel(this, sourceTransport, action, requestId);
- final TransportRequestHandler handler = transportServiceAdapter.handler(action);
- if (handler == null) {
- throw new ActionNotFoundTransportException("Action [" + action + "] not found");
+ try {
+ final TransportRequestHandler handler = transportServiceAdapter.handler(action);
+ if (handler == null) {
+ throw new ActionNotFoundTransportException("Action [" + action + "] not found");
+ }
+ final Streamable streamable = handler.newInstance();
+ streamable.readFrom(stream);
+ handler.messageReceived(streamable, transportChannel);
+ } catch (Exception e) {
+ try {
+ transportChannel.sendResponse(e);
+ } catch (IOException e1) {
+ logger.warn("Failed to send error message back to client for action [" + action + "]", e);
+ logger.warn("Actual Exception", e1);
+ }
}
- final Streamable streamable = handler.newInstance();
- streamable.readFrom(stream);
- handler.messageReceived(streamable, transportChannel);
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/netty/NettyTransport.java b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/netty/NettyTransport.java
index 942b25122584c..4741106f840ce 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/netty/NettyTransport.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/netty/NettyTransport.java
@@ -19,7 +19,6 @@
package org.elasticsearch.transport.netty;
-import com.google.common.collect.Lists;
import com.google.inject.Inject;
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.ElasticSearchIllegalStateException;
@@ -29,6 +28,7 @@
import org.elasticsearch.util.SizeValue;
import org.elasticsearch.util.TimeValue;
import org.elasticsearch.util.component.AbstractLifecycleComponent;
+import org.elasticsearch.util.io.NetworkUtils;
import org.elasticsearch.util.io.stream.BytesStreamOutput;
import org.elasticsearch.util.io.stream.HandlesStreamOutput;
import org.elasticsearch.util.io.stream.Streamable;
@@ -51,7 +51,6 @@
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
-import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
@@ -61,11 +60,12 @@
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
+import static com.google.common.collect.Lists.*;
import static org.elasticsearch.transport.Transport.Helper.*;
import static org.elasticsearch.util.TimeValue.*;
import static org.elasticsearch.util.concurrent.ConcurrentMaps.*;
import static org.elasticsearch.util.concurrent.DynamicExecutors.*;
-import static org.elasticsearch.util.io.HostResolver.*;
+import static org.elasticsearch.util.io.NetworkUtils.*;
import static org.elasticsearch.util.settings.ImmutableSettings.Builder.*;
import static org.elasticsearch.util.transport.NetworkExceptionHelper.*;
@@ -94,8 +94,6 @@ public class NettyTransport extends AbstractLifecycleComponent<Transport> implem
final int connectionsPerNode;
- final int connectRetries;
-
final Boolean tcpNoDelay;
final Boolean tcpKeepAlive;
@@ -138,10 +136,9 @@ public NettyTransport(ThreadPool threadPool) {
this.connectionsPerNode = componentSettings.getAsInt("connections_per_node", 5);
this.publishHost = componentSettings.get("publish_host");
this.connectTimeout = componentSettings.getAsTime("connect_timeout", timeValueSeconds(1));
- this.connectRetries = componentSettings.getAsInt("connect_retries", 2);
this.tcpNoDelay = componentSettings.getAsBoolean("tcp_no_delay", true);
this.tcpKeepAlive = componentSettings.getAsBoolean("tcp_keep_alive", null);
- this.reuseAddress = componentSettings.getAsBoolean("reuse_address", null);
+ this.reuseAddress = componentSettings.getAsBoolean("reuse_address", NetworkUtils.defaultReuseAddress());
this.tcpSendBufferSize = componentSettings.getAsSize("tcp_send_buffer_size", null);
this.tcpReceiveBufferSize = componentSettings.getAsSize("tcp_receive_buffer_size", null);
}
@@ -260,17 +257,7 @@ ThreadPool threadPool() {
InetSocketAddress boundAddress = (InetSocketAddress) serverChannel.getLocalAddress();
InetSocketAddress publishAddress;
try {
- InetAddress publishAddressX = resolvePublishHostAddress(publishHost, settings);
- if (publishAddressX == null) {
- // if its 0.0.0.0, we can't publish that.., default to the local ip address
- if (boundAddress.getAddress().isAnyLocalAddress()) {
- publishAddress = new InetSocketAddress(resolvePublishHostAddress(publishHost, settings, LOCAL_IP), boundAddress.getPort());
- } else {
- publishAddress = boundAddress;
- }
- } else {
- publishAddress = new InetSocketAddress(publishAddressX, boundAddress.getPort());
- }
+ publishAddress = new InetSocketAddress(resolvePublishHostAddress(publishHost, settings), boundAddress.getPort());
} catch (Exception e) {
throw new BindTransportException("Failed to resolve publish address", e);
}
@@ -412,59 +399,35 @@ TransportAddress wrapAddress(SocketAddress socketAddress) {
if (nodeConnections != null) {
return;
}
- // build connection(s) to the node
- ArrayList<Channel> channels = new ArrayList<Channel>();
- Throwable lastConnectException = null;
+ List<ChannelFuture> connectFutures = newArrayList();
for (int connectionIndex = 0; connectionIndex < connectionsPerNode; connectionIndex++) {
- for (int i = 1; i <= connectRetries; i++) {
- if (!lifecycle.started()) {
- for (Channel channel1 : channels) {
- channel1.close().awaitUninterruptibly();
- }
- throw new ConnectTransportException(node, "Can't connect when the transport is stopped");
- }
- InetSocketAddress address = ((InetSocketTransportAddress) node.address()).address();
- ChannelFuture channelFuture = clientBootstrap.connect(address);
- channelFuture.awaitUninterruptibly((long) (connectTimeout.millis() * 1.25));
- if (!channelFuture.isSuccess()) {
- // we failed to connect, check if we need to bail or retry
- if (i == connectRetries && connectionIndex == 0) {
- lastConnectException = channelFuture.getCause();
- if (connectionIndex == 0) {
- throw new ConnectTransportException(node, "connectTimeout[" + connectTimeout + "], connectRetries[" + connectRetries + "]", lastConnectException);
- } else {
- // break out of the retry loop, try another connection
- break;
- }
- } else {
- logger.trace("Retry #[" + i + "], connect to [" + node + "]");
- try {
- channelFuture.getChannel().close();
- } catch (Exception e) {
- // ignore
- }
- continue;
- }
- }
- // we got a connection, add it to our connections
- Channel channel = channelFuture.getChannel();
- if (!lifecycle.started()) {
- channel.close();
- for (Channel channel1 : channels) {
- channel1.close().awaitUninterruptibly();
- }
- throw new ConnectTransportException(node, "Can't connect when the transport is stopped");
+ InetSocketAddress address = ((InetSocketTransportAddress) node.address()).address();
+ connectFutures.add(clientBootstrap.connect(address));
+
+ }
+ List<Channel> channels = newArrayList();
+ Throwable lastConnectException = null;
+ for (ChannelFuture connectFuture : connectFutures) {
+ if (!lifecycle.started()) {
+ for (Channel channel : channels) {
+ channel.close().awaitUninterruptibly();
}
+ throw new ConnectTransportException(node, "Can't connect when the transport is stopped");
+ }
+ connectFuture.awaitUninterruptibly((long) (connectTimeout.millis() * 1.25));
+ if (!connectFuture.isSuccess()) {
+ lastConnectException = connectFuture.getCause();
+ } else {
+ Channel channel = connectFuture.getChannel();
channel.getCloseFuture().addListener(new ChannelCloseListener(node.id()));
channels.add(channel);
- break;
}
}
if (channels.isEmpty()) {
if (lastConnectException != null) {
- throw new ConnectTransportException(node, "connectTimeout[" + connectTimeout + "], connectRetries[" + connectRetries + "]", lastConnectException);
+ throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", lastConnectException);
}
- throw new ConnectTransportException(node, "connectTimeout[" + connectTimeout + "], connectRetries[" + connectRetries + "], reason unknown");
+ throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "], reason unknown");
}
if (logger.isDebugEnabled()) {
logger.debug("Connected to node[{}], number_of_connections[{}]", node, channels.size());
@@ -516,7 +479,7 @@ private Channel channel() {
}
private void channelClosed(Channel closedChannel) {
- List<Channel> updated = Lists.newArrayList();
+ List<Channel> updated = newArrayList();
for (Channel channel : channels) {
if (!channel.getId().equals(closedChannel.getId())) {
updated.add(channel);
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/netty/NettyTransportManagement.java b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/netty/NettyTransportManagement.java
index edf27c3f3d060..e60510d00207c 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/netty/NettyTransportManagement.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/netty/NettyTransportManagement.java
@@ -65,11 +65,6 @@ public String getConnectTimeout() {
return transport.connectTimeout.toString();
}
- @ManagedAttribute(description = "Connect retries")
- public int getConnectRetries() {
- return transport.connectRetries;
- }
-
@ManagedAttribute(description = "TcpNoDelay")
public Boolean getTcpNoDelay() {
return transport.tcpNoDelay;
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/util/io/HostResolver.java b/modules/elasticsearch/src/main/java/org/elasticsearch/util/io/HostResolver.java
deleted file mode 100644
index 0a536ac4fb44b..0000000000000
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/util/io/HostResolver.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * Licensed to Elastic Search and Shay Banon under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. Elastic Search 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.elasticsearch.util.io;
-
-import org.elasticsearch.util.settings.Settings;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.NetworkInterface;
-import java.net.SocketException;
-import java.net.UnknownHostException;
-import java.util.Enumeration;
-
-/**
- * @author kimchy (Shay Banon)
- */
-public abstract class HostResolver {
-
- public static final String GLOBAL_NETWORK_BINDHOST_SETTING = "network.bind_host";
- public static final String GLOBAL_NETWORK_PUBLISHHOST_SETTING = "network.publish_host";
-
- public static final String LOCAL_IP = "#local:ip#";
- public static final String LOCAL_HOST = "#local:host#";
- public static final String LOCAL_CANONICALHOST = "#local:canonicalhost#";
-
- public static boolean isIPv4() {
- return System.getProperty("java.net.preferIPv4Stack") != null && System.getProperty("java.net.preferIPv4Stack").equals("true");
- }
-
- public static InetAddress resolveBindHostAddress(String bindHost, Settings settings) throws IOException {
- return resolveBindHostAddress(bindHost, settings, null);
- }
-
- public static InetAddress resolveBindHostAddress(String bindHost, Settings settings, String defaultValue2) throws IOException {
- return resolveInetAddress(bindHost, settings.get(GLOBAL_NETWORK_BINDHOST_SETTING), defaultValue2);
- }
-
- public static InetAddress resolvePublishHostAddress(String publishHost, Settings settings) throws IOException {
- return resolvePublishHostAddress(publishHost, settings, null);
- }
-
- public static InetAddress resolvePublishHostAddress(String publishHost, Settings settings, String defaultValue2) throws IOException {
- return resolveInetAddress(publishHost, settings.get(GLOBAL_NETWORK_PUBLISHHOST_SETTING), defaultValue2);
- }
-
- public static InetAddress resolveInetAddress(String host, String defaultValue1, String defaultValue2) throws UnknownHostException, IOException {
- String resolvedHost = resolveHost(host, defaultValue1, defaultValue2);
- if (resolvedHost == null) {
- return null;
- }
- return InetAddress.getByName(resolvedHost);
- }
-
- public static String resolveHost(String host, String defaultValue1, String defaultValue2) throws UnknownHostException, IOException {
- if (host == null) {
- host = defaultValue1;
- }
- if (host == null) {
- host = defaultValue2;
- }
- if (host == null) {
- return null;
- }
- if (host.startsWith("#") && host.endsWith("#")) {
- host = host.substring(1, host.length() - 1);
- if (host.equals("local:ip")) {
- return InetAddress.getLocalHost().getHostAddress();
- } else if (host.equalsIgnoreCase("local:host")) {
- return InetAddress.getLocalHost().getHostName();
- } else if (host.equalsIgnoreCase("local:canonicalhost")) {
- return InetAddress.getLocalHost().getCanonicalHostName();
- } else {
- String name = host.substring(0, host.indexOf(':'));
- String type = host.substring(host.indexOf(':') + 1);
- Enumeration<NetworkInterface> niEnum;
- try {
- niEnum = NetworkInterface.getNetworkInterfaces();
- } catch (SocketException e) {
- throw new IOException("Failed to get network interfaces", e);
- }
- while (niEnum.hasMoreElements()) {
- NetworkInterface ni = niEnum.nextElement();
- if (name.equals(ni.getName()) || name.equals(ni.getDisplayName())) {
- Enumeration<InetAddress> inetEnum = ni.getInetAddresses();
- while (inetEnum.hasMoreElements()) {
- InetAddress addr = inetEnum.nextElement();
- if (addr.getHostAddress().equals("127.0.0.1")) {
- // ignore local host
- continue;
- }
- if (addr.getHostAddress().indexOf(".") == -1) {
- // ignore address like 0:0:0:0:0:0:0:1
- continue;
- }
- if ("host".equalsIgnoreCase(type)) {
- return addr.getHostName();
- } else if ("canonicalhost".equalsIgnoreCase(type)) {
- return addr.getCanonicalHostName();
- } else {
- return addr.getHostAddress();
- }
- }
- }
- }
- }
- throw new IOException("Failed to find network interface for [" + host + "]");
- }
- InetAddress inetAddress = java.net.InetAddress.getByName(host);
- String hostAddress = inetAddress.getHostAddress();
- String hostName = inetAddress.getHostName();
- String canonicalHostName = inetAddress.getCanonicalHostName();
- if (host.equalsIgnoreCase(hostAddress)) {
- return hostAddress;
- } else if (host.equalsIgnoreCase(canonicalHostName)) {
- return canonicalHostName;
- } else {
- return hostName; //resolve property into actual lower/upper case
- }
- }
-
- private HostResolver() {
-
- }
-}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/util/io/NetworkUtils.java b/modules/elasticsearch/src/main/java/org/elasticsearch/util/io/NetworkUtils.java
new file mode 100644
index 0000000000000..a21be4c5cdb7c
--- /dev/null
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/util/io/NetworkUtils.java
@@ -0,0 +1,286 @@
+/*
+ * Licensed to Elastic Search and Shay Banon under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. Elastic Search 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.elasticsearch.util.io;
+
+import org.elasticsearch.util.OsUtils;
+import org.elasticsearch.util.logging.ESLogger;
+import org.elasticsearch.util.logging.Loggers;
+import org.elasticsearch.util.settings.Settings;
+
+import java.io.IOException;
+import java.net.*;
+import java.util.*;
+
+/**
+ * @author kimchy (shay.banon)
+ */
+public abstract class NetworkUtils {
+
+ private final static ESLogger logger = Loggers.getLogger(NetworkUtils.class);
+
+ public static enum StackType {
+ IPv4, IPv6, Unknown
+ }
+
+ public static final String IPv4_SETTING = "java.net.preferIPv4Stack";
+ public static final String IPv6_SETTING = "java.net.preferIPv6Addresses";
+
+ public static final String NON_LOOPBACK_ADDRESS = "non_loopback_address";
+ public static final String LOCAL = "#local#";
+
+ public static final String GLOBAL_NETWORK_BINDHOST_SETTING = "network.bind_host";
+ public static final String GLOBAL_NETWORK_PUBLISHHOST_SETTING = "network.publish_host";
+
+ private final static InetAddress localAddress;
+
+ static {
+ InetAddress localAddressX = null;
+ try {
+ localAddressX = InetAddress.getLocalHost();
+ } catch (UnknownHostException e) {
+ logger.warn("Failed to find local host", e);
+ }
+ localAddress = localAddressX;
+ }
+
+ public static Boolean defaultReuseAddress() {
+ return OsUtils.WINDOWS ? null : true;
+ }
+
+ public static boolean isIPv4() {
+ return System.getProperty("java.net.preferIPv4Stack") != null && System.getProperty("java.net.preferIPv4Stack").equals("true");
+ }
+
+ public static InetAddress resolveBindHostAddress(String bindHost, Settings settings) throws IOException {
+ return resolveBindHostAddress(bindHost, settings, null);
+ }
+
+ public static InetAddress resolveBindHostAddress(String bindHost, Settings settings, String defaultValue2) throws IOException {
+ return resolveInetAddress(bindHost, settings.get(GLOBAL_NETWORK_BINDHOST_SETTING), defaultValue2);
+ }
+
+ public static InetAddress resolvePublishHostAddress(String publishHost, Settings settings) throws IOException {
+ InetAddress address = resolvePublishHostAddress(publishHost, settings, null);
+ // verify that its not a local address
+ if (address == null || address.isAnyLocalAddress()) {
+ address = localAddress;
+ }
+ return address;
+ }
+
+ public static InetAddress resolvePublishHostAddress(String publishHost, Settings settings, String defaultValue2) throws IOException {
+ return resolveInetAddress(publishHost, settings.get(GLOBAL_NETWORK_PUBLISHHOST_SETTING), defaultValue2);
+ }
+
+ public static InetAddress resolveInetAddress(String host, String defaultValue1, String defaultValue2) throws UnknownHostException, IOException {
+ if (host == null) {
+ host = defaultValue1;
+ }
+ if (host == null) {
+ host = defaultValue2;
+ }
+ if (host == null) {
+ return null;
+ }
+ if (host.startsWith("#") && host.endsWith("#")) {
+ host = host.substring(1, host.length() - 1);
+ if (host.equals("local")) {
+ return localAddress;
+ } else {
+ Collection<NetworkInterface> allInterfs = getAllAvailableInterfaces();
+ for (NetworkInterface ni : allInterfs) {
+ if (!ni.isUp() || ni.isLoopback()) {
+ continue;
+ }
+ if (host.equals(ni.getName()) || host.equals(ni.getDisplayName())) {
+ return getFirstNonLoopbackAddress(ni, getIpStackType());
+ }
+ }
+ }
+ throw new IOException("Failed to find network interface for [" + host + "]");
+ }
+ return InetAddress.getByName(host);
+ }
+
+ public static InetAddress getIPv4Localhost() throws UnknownHostException {
+ return getLocalhost(StackType.IPv4);
+ }
+
+ public static InetAddress getIPv6Localhost() throws UnknownHostException {
+ return getLocalhost(StackType.IPv6);
+ }
+
+ public static InetAddress getLocalhost(StackType ip_version) throws UnknownHostException {
+ if (ip_version == StackType.IPv4)
+ return InetAddress.getByName("127.0.0.1");
+ else
+ return InetAddress.getByName("::1");
+ }
+
+
+ /**
+ * Returns the first non-loopback address on any interface on the current host.
+ *
+ * @param ip_version Constraint on IP version of address to be returned, 4 or 6
+ */
+ public static InetAddress getFirstNonLoopbackAddress(StackType ip_version) throws SocketException {
+ InetAddress address = null;
+
+ Enumeration intfs = NetworkInterface.getNetworkInterfaces();
+ while (intfs.hasMoreElements()) {
+ NetworkInterface intf = (NetworkInterface) intfs.nextElement();
+ if (!intf.isUp() || intf.isLoopback())
+ continue;
+ address = getFirstNonLoopbackAddress(intf, ip_version);
+ if (address != null) {
+ return address;
+ }
+ }
+ return null;
+ }
+
+
+ /**
+ * Returns the first non-loopback address on the given interface on the current host.
+ *
+ * @param intf the interface to be checked
+ * @param ipVersion Constraint on IP version of address to be returned, 4 or 6
+ */
+ public static InetAddress getFirstNonLoopbackAddress(NetworkInterface intf, StackType ipVersion) throws SocketException {
+ if (intf == null)
+ throw new IllegalArgumentException("Network interface pointer is null");
+
+ for (Enumeration addresses = intf.getInetAddresses(); addresses.hasMoreElements();) {
+ InetAddress address = (InetAddress) addresses.nextElement();
+ if (!address.isLoopbackAddress()) {
+ if ((address instanceof Inet4Address && ipVersion == StackType.IPv4) ||
+ (address instanceof Inet6Address && ipVersion == StackType.IPv6))
+ return address;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * A function to check if an interface supports an IP version (i.e has addresses
+ * defined for that IP version).
+ *
+ * @param intf
+ * @return
+ */
+ public static boolean interfaceHasIPAddresses(NetworkInterface intf, StackType ipVersion) throws SocketException, UnknownHostException {
+ boolean supportsVersion = false;
+ if (intf != null) {
+ // get all the InetAddresses defined on the interface
+ Enumeration addresses = intf.getInetAddresses();
+ while (addresses != null && addresses.hasMoreElements()) {
+ // get the next InetAddress for the current interface
+ InetAddress address = (InetAddress) addresses.nextElement();
+
+ // check if we find an address of correct version
+ if ((address instanceof Inet4Address && (ipVersion == StackType.IPv4)) ||
+ (address instanceof Inet6Address && (ipVersion == StackType.IPv6))) {
+ supportsVersion = true;
+ break;
+ }
+ }
+ } else {
+ throw new UnknownHostException("network interface " + intf + " not found");
+ }
+ return supportsVersion;
+ }
+
+ /**
+ * Tries to determine the type of IP stack from the available interfaces and their addresses and from the
+ * system properties (java.net.preferIPv4Stack and java.net.preferIPv6Addresses)
+ *
+ * @return StackType.IPv4 for an IPv4 only stack, StackYTypeIPv6 for an IPv6 only stack, and StackType.Unknown
+ * if the type cannot be detected
+ */
+ public static StackType getIpStackType() {
+ boolean isIPv4StackAvailable = isStackAvailable(true);
+ boolean isIPv6StackAvailable = isStackAvailable(false);
+
+ // if only IPv4 stack available
+ if (isIPv4StackAvailable && !isIPv6StackAvailable) {
+ return StackType.IPv4;
+ }
+ // if only IPv6 stack available
+ else if (isIPv6StackAvailable && !isIPv4StackAvailable) {
+ return StackType.IPv6;
+ }
+ // if dual stack
+ else if (isIPv4StackAvailable && isIPv6StackAvailable) {
+ // get the System property which records user preference for a stack on a dual stack machine
+ if (Boolean.getBoolean(IPv4_SETTING)) // has preference over java.net.preferIPv6Addresses
+ return StackType.IPv4;
+ if (Boolean.getBoolean(IPv6_SETTING))
+ return StackType.IPv6;
+ return StackType.IPv6;
+ }
+ return StackType.Unknown;
+ }
+
+
+ public static boolean isStackAvailable(boolean ipv4) {
+ Collection<InetAddress> allAddrs = getAllAvailableAddresses();
+ for (InetAddress addr : allAddrs)
+ if (ipv4 && addr instanceof Inet4Address || (!ipv4 && addr instanceof Inet6Address))
+ return true;
+ return false;
+ }
+
+
+ public static List<NetworkInterface> getAllAvailableInterfaces() throws SocketException {
+ List<NetworkInterface> allInterfaces = new ArrayList<NetworkInterface>(10);
+ NetworkInterface intf;
+ for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
+ intf = (NetworkInterface) en.nextElement();
+ allInterfaces.add(intf);
+ }
+ return allInterfaces;
+ }
+
+ public static Collection<InetAddress> getAllAvailableAddresses() {
+ Set<InetAddress> retval = new HashSet<InetAddress>();
+ Enumeration en;
+
+ try {
+ en = NetworkInterface.getNetworkInterfaces();
+ if (en == null)
+ return retval;
+ while (en.hasMoreElements()) {
+ NetworkInterface intf = (NetworkInterface) en.nextElement();
+ Enumeration<InetAddress> addrs = intf.getInetAddresses();
+ while (addrs.hasMoreElements())
+ retval.add(addrs.nextElement());
+ }
+ } catch (SocketException e) {
+ logger.warn("Failed to derive all available interfaces", e);
+ }
+
+ return retval;
+ }
+
+
+ private NetworkUtils() {
+
+ }
+}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/util/io/stream/BytesStreamInput.java b/modules/elasticsearch/src/main/java/org/elasticsearch/util/io/stream/BytesStreamInput.java
index e040b157ab04d..2946c02135568 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/util/io/stream/BytesStreamInput.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/util/io/stream/BytesStreamInput.java
@@ -36,9 +36,13 @@ public class BytesStreamInput extends StreamInput {
protected int count;
public BytesStreamInput(byte buf[]) {
+ this(buf, 0, buf.length);
+ }
+
+ public BytesStreamInput(byte buf[], int position, int count) {
this.buf = buf;
- this.pos = 0;
- this.count = buf.length;
+ this.pos = position;
+ this.count = count;
}
@Override public byte readByte() throws IOException {
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/util/timer/TimerTask.java b/modules/elasticsearch/src/main/java/org/elasticsearch/util/timer/TimerTask.java
index 7eeb8f092488c..0fa41d86cd99d 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/util/timer/TimerTask.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/util/timer/TimerTask.java
@@ -23,7 +23,7 @@
* A task which is executed after the delay specified with
* {@link Timer#newTimeout(TimerTask, long, java.util.concurrent.TimeUnit)}.
*
- * @author kimchy (Shay Banon)
+ * @author kimchy (shay.banon)
*/
public interface TimerTask {
diff --git a/modules/elasticsearch/src/test/java/org/elasticsearch/discovery/zen/ping/multicast/MulticastZenPingTests.java b/modules/elasticsearch/src/test/java/org/elasticsearch/discovery/zen/ping/multicast/MulticastZenPingTests.java
new file mode 100644
index 0000000000000..19c39af0b6fc1
--- /dev/null
+++ b/modules/elasticsearch/src/test/java/org/elasticsearch/discovery/zen/ping/multicast/MulticastZenPingTests.java
@@ -0,0 +1,82 @@
+/*
+ * Licensed to Elastic Search and Shay Banon under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. Elastic Search 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.elasticsearch.discovery.zen.ping.multicast;
+
+import org.elasticsearch.cluster.ClusterName;
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
+import org.elasticsearch.discovery.zen.DiscoveryNodesProvider;
+import org.elasticsearch.discovery.zen.ping.ZenPing;
+import org.elasticsearch.threadpool.ThreadPool;
+import org.elasticsearch.threadpool.cached.CachedThreadPool;
+import org.elasticsearch.timer.TimerService;
+import org.elasticsearch.transport.TransportService;
+import org.elasticsearch.transport.local.LocalTransport;
+import org.elasticsearch.util.TimeValue;
+import org.testng.annotations.Test;
+
+import static org.hamcrest.MatcherAssert.*;
+import static org.hamcrest.Matchers.*;
+
+/**
+ * @author kimchy (shay.banon)
+ */
+@Test
+public class MulticastZenPingTests {
+
+ @Test public void testSimplePings() {
+ ThreadPool threadPool = new CachedThreadPool();
+ TimerService timerService = new TimerService(threadPool);
+ ClusterName clusterName = new ClusterName("test");
+ final TransportService transportServiceA = new TransportService(new LocalTransport(threadPool), threadPool, timerService).start();
+ final DiscoveryNode nodeA = new DiscoveryNode("A", transportServiceA.boundAddress().publishAddress());
+
+ final TransportService transportServiceB = new TransportService(new LocalTransport(threadPool), threadPool, timerService).start();
+ final DiscoveryNode nodeB = new DiscoveryNode("B", transportServiceA.boundAddress().publishAddress());
+
+ MulticastZenPing zenPingA = (MulticastZenPing) new MulticastZenPing(threadPool, transportServiceA, clusterName);
+ zenPingA.setNodesProvider(new DiscoveryNodesProvider() {
+ @Override public DiscoveryNodes nodes() {
+ return DiscoveryNodes.newNodesBuilder().put(nodeA).localNodeId("A").build();
+ }
+ });
+ zenPingA.start();
+
+ MulticastZenPing zenPingB = (MulticastZenPing) new MulticastZenPing(threadPool, transportServiceB, clusterName);
+ zenPingB.setNodesProvider(new DiscoveryNodesProvider() {
+ @Override public DiscoveryNodes nodes() {
+ return DiscoveryNodes.newNodesBuilder().put(nodeB).localNodeId("B").build();
+ }
+ });
+ zenPingB.start();
+
+ try {
+ ZenPing.PingResponse[] pingResponses = zenPingA.pingAndWait(TimeValue.timeValueSeconds(1));
+ assertThat(pingResponses.length, equalTo(1));
+ assertThat(pingResponses[0].target().id(), equalTo("B"));
+ } finally {
+ zenPingA.close();
+ zenPingB.close();
+ transportServiceA.close();
+ transportServiceB.close();
+ threadPool.shutdown();
+ }
+ }
+}
diff --git a/modules/elasticsearch/src/test/java/org/elasticsearch/transport/AbstractSimpleTransportTests.java b/modules/elasticsearch/src/test/java/org/elasticsearch/transport/AbstractSimpleTransportTests.java
index 19165542bc572..134da4a976180 100644
--- a/modules/elasticsearch/src/test/java/org/elasticsearch/transport/AbstractSimpleTransportTests.java
+++ b/modules/elasticsearch/src/test/java/org/elasticsearch/transport/AbstractSimpleTransportTests.java
@@ -21,7 +21,9 @@
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.threadpool.ThreadPool;
-import org.elasticsearch.threadpool.scaling.ScalingThreadPool;
+import org.elasticsearch.threadpool.cached.CachedThreadPool;
+import org.elasticsearch.timer.TimerService;
+import org.elasticsearch.util.TimeValue;
import org.elasticsearch.util.io.stream.StreamInput;
import org.elasticsearch.util.io.stream.StreamOutput;
import org.elasticsearch.util.io.stream.Streamable;
@@ -42,6 +44,7 @@
public abstract class AbstractSimpleTransportTests {
protected ThreadPool threadPool;
+ protected TimerService timerService;
protected TransportService serviceA;
protected TransportService serviceB;
@@ -49,7 +52,8 @@ public abstract class AbstractSimpleTransportTests {
protected DiscoveryNode serviceBNode;
@BeforeMethod public void setUp() {
- threadPool = new ScalingThreadPool();
+ threadPool = new CachedThreadPool();
+ timerService = new TimerService(threadPool);
build();
serviceA.connectToNode(serviceBNode);
serviceB.connectToNode(serviceANode);
@@ -106,6 +110,8 @@ public abstract class AbstractSimpleTransportTests {
assertThat(e.getMessage(), false, equalTo(true));
}
+ serviceA.removeHandler("sayHello");
+
System.out.println("after ...");
}
@@ -144,6 +150,8 @@ public abstract class AbstractSimpleTransportTests {
assertThat("bad message !!!", equalTo(e.getCause().getMessage()));
}
+ serviceA.removeHandler("sayHelloException");
+
System.out.println("after ...");
}
@@ -162,7 +170,53 @@ public void testDisconnectListener() throws Exception {
};
serviceA.addConnectionListener(disconnectListener);
serviceB.close();
- assertThat(latch.await(1, TimeUnit.SECONDS), equalTo(true));
+ assertThat(latch.await(5, TimeUnit.SECONDS), equalTo(true));
+ }
+
+ @Test public void testTimeoutSendException() throws Exception {
+ serviceA.registerHandler("sayHelloTimeout", new BaseTransportRequestHandler<StringMessage>() {
+ @Override public StringMessage newInstance() {
+ return new StringMessage();
+ }
+
+ @Override public void messageReceived(StringMessage request, TransportChannel channel) {
+ System.out.println("got message: " + request.message);
+ assertThat("moshe", equalTo(request.message));
+ // don't send back a response
+// try {
+// channel.sendResponse(new StringMessage("hello " + request.message));
+// } catch (IOException e) {
+// e.printStackTrace();
+// assertThat(e.getMessage(), false, equalTo(true));
+// }
+ }
+ });
+
+ TransportFuture<StringMessage> res = serviceB.submitRequest(serviceANode, "sayHelloTimeout",
+ new StringMessage("moshe"), TimeValue.timeValueMillis(100), new BaseTransportResponseHandler<StringMessage>() {
+ @Override public StringMessage newInstance() {
+ return new StringMessage();
+ }
+
+ @Override public void handleResponse(StringMessage response) {
+ assertThat("got response instead of exception", false, equalTo(true));
+ }
+
+ @Override public void handleException(RemoteTransportException exp) {
+ assertThat(exp, instanceOf(ReceiveTimeoutTransportException.class));
+ }
+ });
+
+ try {
+ StringMessage message = res.txGet();
+ assertThat("exception should be thrown", false, equalTo(true));
+ } catch (Exception e) {
+ assertThat(e, instanceOf(ReceiveTimeoutTransportException.class));
+ }
+
+ serviceA.removeHandler("sayHelloTimeout");
+
+ System.out.println("after ...");
}
private class StringMessage implements Streamable {
diff --git a/modules/elasticsearch/src/test/java/org/elasticsearch/transport/local/SimpleLocalTransportTests.java b/modules/elasticsearch/src/test/java/org/elasticsearch/transport/local/SimpleLocalTransportTests.java
index 569619f78f51e..d349901a12595 100644
--- a/modules/elasticsearch/src/test/java/org/elasticsearch/transport/local/SimpleLocalTransportTests.java
+++ b/modules/elasticsearch/src/test/java/org/elasticsearch/transport/local/SimpleLocalTransportTests.java
@@ -28,10 +28,10 @@
public class SimpleLocalTransportTests extends AbstractSimpleTransportTests {
@Override protected void build() {
- serviceA = new TransportService(new LocalTransport(threadPool), threadPool).start();
+ serviceA = new TransportService(new LocalTransport(threadPool), threadPool, timerService).start();
serviceANode = new DiscoveryNode("A", serviceA.boundAddress().publishAddress());
- serviceB = new TransportService(new LocalTransport(threadPool), threadPool).start();
+ serviceB = new TransportService(new LocalTransport(threadPool), threadPool, timerService).start();
serviceBNode = new DiscoveryNode("B", serviceB.boundAddress().publishAddress());
}
}
\ No newline at end of file
diff --git a/modules/elasticsearch/src/test/java/org/elasticsearch/transport/netty/SimpleNettyTransportTests.java b/modules/elasticsearch/src/test/java/org/elasticsearch/transport/netty/SimpleNettyTransportTests.java
index 0c3c4ea65317d..abee21b23890a 100644
--- a/modules/elasticsearch/src/test/java/org/elasticsearch/transport/netty/SimpleNettyTransportTests.java
+++ b/modules/elasticsearch/src/test/java/org/elasticsearch/transport/netty/SimpleNettyTransportTests.java
@@ -30,11 +30,10 @@
public class SimpleNettyTransportTests extends AbstractSimpleTransportTests {
@Override protected void build() {
- serviceA = new TransportService(settingsBuilder().put("name", "A").build(), new NettyTransport(settingsBuilder().put("name", "A").build(), threadPool), threadPool).start();
+ serviceA = new TransportService(settingsBuilder().put("name", "A").build(), new NettyTransport(settingsBuilder().put("name", "A").build(), threadPool), threadPool, timerService).start();
serviceANode = new DiscoveryNode("A", serviceA.boundAddress().publishAddress());
- serviceB = new TransportService(settingsBuilder().put("name", "B").build(), new NettyTransport(settingsBuilder().put("name", "B").build(), threadPool), threadPool).start();
+ serviceB = new TransportService(settingsBuilder().put("name", "B").build(), new NettyTransport(settingsBuilder().put("name", "B").build(), threadPool), threadPool, timerService).start();
serviceBNode = new DiscoveryNode("B", serviceB.boundAddress().publishAddress());
}
-
}
\ No newline at end of file
diff --git a/modules/elasticsearch/src/test/java/org/elasticsearch/transport/netty/benchmark/BenchmarkNettyClient.java b/modules/elasticsearch/src/test/java/org/elasticsearch/transport/netty/benchmark/BenchmarkNettyClient.java
index c877e16e0ba4e..d55e0a7bb6389 100644
--- a/modules/elasticsearch/src/test/java/org/elasticsearch/transport/netty/benchmark/BenchmarkNettyClient.java
+++ b/modules/elasticsearch/src/test/java/org/elasticsearch/transport/netty/benchmark/BenchmarkNettyClient.java
@@ -22,6 +22,7 @@
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.threadpool.cached.CachedThreadPool;
+import org.elasticsearch.timer.TimerService;
import org.elasticsearch.transport.BaseTransportResponseHandler;
import org.elasticsearch.transport.RemoteTransportException;
import org.elasticsearch.transport.TransportService;
@@ -56,8 +57,9 @@ public static void main(String[] args) {
.put("transport.netty.connectionsPerNode", 5)
.build();
- final ThreadPool threadPool = new CachedThreadPool();
- final TransportService transportService = new TransportService(new NettyTransport(settings, threadPool), threadPool).start();
+ final ThreadPool threadPool = new CachedThreadPool(settings);
+ final TimerService timerService = new TimerService(settings, threadPool);
+ final TransportService transportService = new TransportService(new NettyTransport(settings, threadPool), threadPool, timerService).start();
final DiscoveryNode node = new DiscoveryNode("server", new InetSocketTransportAddress("localhost", 9999));
diff --git a/modules/elasticsearch/src/test/java/org/elasticsearch/transport/netty/benchmark/BenchmarkNettyServer.java b/modules/elasticsearch/src/test/java/org/elasticsearch/transport/netty/benchmark/BenchmarkNettyServer.java
index e2e494d42f0d8..8faea99342c5a 100644
--- a/modules/elasticsearch/src/test/java/org/elasticsearch/transport/netty/benchmark/BenchmarkNettyServer.java
+++ b/modules/elasticsearch/src/test/java/org/elasticsearch/transport/netty/benchmark/BenchmarkNettyServer.java
@@ -21,6 +21,7 @@
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.threadpool.cached.CachedThreadPool;
+import org.elasticsearch.timer.TimerService;
import org.elasticsearch.transport.BaseTransportRequestHandler;
import org.elasticsearch.transport.TransportChannel;
import org.elasticsearch.transport.TransportService;
@@ -40,8 +41,9 @@ public static void main(String[] args) {
.put("transport.netty.port", 9999)
.build();
- final ThreadPool threadPool = new CachedThreadPool();
- final TransportService transportService = new TransportService(new NettyTransport(settings, threadPool), threadPool).start();
+ final ThreadPool threadPool = new CachedThreadPool(settings);
+ final TimerService timerService = new TimerService(settings, threadPool);
+ final TransportService transportService = new TransportService(new NettyTransport(settings, threadPool), threadPool, timerService).start();
transportService.registerHandler("benchmark", new BaseTransportRequestHandler<BenchmarkMessage>() {
@Override public BenchmarkMessage newInstance() {
diff --git a/plugins/memcached/src/main/java/org/elasticsearch/memcached/netty/NettyMemcachedServerTransport.java b/plugins/memcached/src/main/java/org/elasticsearch/memcached/netty/NettyMemcachedServerTransport.java
index 29c97fe2a8d32..65473eeba375f 100644
--- a/plugins/memcached/src/main/java/org/elasticsearch/memcached/netty/NettyMemcachedServerTransport.java
+++ b/plugins/memcached/src/main/java/org/elasticsearch/memcached/netty/NettyMemcachedServerTransport.java
@@ -28,6 +28,7 @@
import org.elasticsearch.transport.netty.NettyInternalESLoggerFactory;
import org.elasticsearch.util.SizeValue;
import org.elasticsearch.util.component.AbstractLifecycleComponent;
+import org.elasticsearch.util.io.NetworkUtils;
import org.elasticsearch.util.settings.Settings;
import org.elasticsearch.util.transport.BoundTransportAddress;
import org.elasticsearch.util.transport.InetSocketTransportAddress;
@@ -48,7 +49,7 @@
import java.util.concurrent.atomic.AtomicReference;
import static org.elasticsearch.util.concurrent.DynamicExecutors.*;
-import static org.elasticsearch.util.io.HostResolver.*;
+import static org.elasticsearch.util.io.NetworkUtils.*;
/**
* @author kimchy (shay.banon)
@@ -101,7 +102,7 @@ public class NettyMemcachedServerTransport extends AbstractLifecycleComponent<Me
this.publishHost = componentSettings.get("publish_host");
this.tcpNoDelay = componentSettings.getAsBoolean("tcp_no_delay", true);
this.tcpKeepAlive = componentSettings.getAsBoolean("tcp_keep_alive", null);
- this.reuseAddress = componentSettings.getAsBoolean("reuse_address", null);
+ this.reuseAddress = componentSettings.getAsBoolean("reuse_address", NetworkUtils.defaultReuseAddress());
this.tcpSendBufferSize = componentSettings.getAsSize("tcp_send_buffer_size", null);
this.tcpReceiveBufferSize = componentSettings.getAsSize("tcp_receive_buffer_size", null);
}
@@ -176,17 +177,7 @@ public class NettyMemcachedServerTransport extends AbstractLifecycleComponent<Me
InetSocketAddress boundAddress = (InetSocketAddress) serverChannel.getLocalAddress();
InetSocketAddress publishAddress;
try {
- InetAddress publishAddressX = resolvePublishHostAddress(publishHost, settings);
- if (publishAddressX == null) {
- // if its 0.0.0.0, we can't publish that.., default to the local ip address
- if (boundAddress.getAddress().isAnyLocalAddress()) {
- publishAddress = new InetSocketAddress(resolvePublishHostAddress(publishHost, settings, LOCAL_IP), boundAddress.getPort());
- } else {
- publishAddress = boundAddress;
- }
- } else {
- publishAddress = new InetSocketAddress(publishAddressX, boundAddress.getPort());
- }
+ publishAddress = new InetSocketAddress(resolvePublishHostAddress(publishHost, settings), boundAddress.getPort());
} catch (Exception e) {
throw new BindTransportException("Failed to resolve publish address", e);
}
|
3384d37a5254d5b232d2912ad67988ff505fb263
|
tapiji
|
Fix error while restoring UI state if memento files are not present.
If the Eclipse IDE is started the first time with internationalization support, the TapiJI managed memento files are not present within the workspace. This changeset prevents an exception during startup if the state file is not found.
(cherry picked from commit 9a915cc7ecb994b9aef66a7648592ed36e27b89b)
Conflicts:
org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java
org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java
org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java
org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java
|
a
|
https://github.com/tapiji/tapiji
|
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java
index 0700ff51..8248c03e 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java
@@ -1,13 +1,11 @@
/*******************************************************************************
- * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow.
- * 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
+ * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. 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:
- * Martin Reiterer - initial API and implementation
- * Alexej Strelzow - moved object management to RBManager, Babel integration
+ * Contributors: Martin Reiterer - initial API and implementation Alexej
+ * Strelzow - moved object management to RBManager, Babel integration
******************************************************************************/
package org.eclipse.babel.tapiji.tools.core.ui;
@@ -129,10 +127,14 @@ public void onDelete(String resourceBundleId,
public static ResourceBundleManager getManager(IProject project) {
// check if persistant state has been loaded
if (!state_loaded) {
- stateLoader = getStateLoader();
- stateLoader.loadState();
- state_loaded = true;
- excludedResources = stateLoader.getExcludedResources();
+ IStateLoader stateLoader = getStateLoader();
+ if (stateLoader != null) {
+ stateLoader.loadState();
+ state_loaded = true;
+ excludedResources = stateLoader.getExcludedResources();
+ } else {
+ Logger.logError("State-Loader uninitialized! Unable to restore project state.");
+ }
}
// set host-project
@@ -362,7 +364,7 @@ public static Set<IProject> getAllSupportedProjects() {
}
} catch (CoreException e) {
// TODO Auto-generated catch block
- e.printStackTrace();
+ Logger.logError(e);
}
}
return projs;
@@ -583,7 +585,12 @@ public static boolean isResourceExcluded(IResource res) {
IResource resource = res;
if (!state_loaded) {
- stateLoader.loadState();
+ IStateLoader stateLoader = getStateLoader();
+ if (stateLoader != null) {
+ stateLoader.loadState();
+ } else {
+ Logger.logError("State-Loader uninitialized! Unable to restore state.");
+ }
}
boolean isExcluded = false;
@@ -621,7 +628,7 @@ public IFile getRandomFile(String bundleName) {
IMessagesBundle bundle = messagesBundles.iterator().next();
return FileUtils.getFile(bundle);
} catch (Exception e) {
- e.printStackTrace();
+ Logger.logError(e);
}
return null;
}
@@ -793,26 +800,34 @@ public Set<Locale> getProjectProvidedLocales() {
return locales;
}
- private static IStateLoader getStateLoader() {
+ public static IStateLoader getStateLoader() {
+ if (stateLoader == null) {
- IExtensionPoint extp = Platform.getExtensionRegistry()
- .getExtensionPoint(
- "org.eclipse.babel.tapiji.tools.core" + ".stateLoader");
- IConfigurationElement[] elements = extp.getConfigurationElements();
+ IExtensionPoint extp = Platform.getExtensionRegistry()
+ .getExtensionPoint(
+ "org.eclipse.babel.tapiji.tools.core"
+ + ".stateLoader");
+ IConfigurationElement[] elements = extp.getConfigurationElements();
- if (elements.length != 0) {
- try {
- return (IStateLoader) elements[0]
- .createExecutableExtension("class");
- } catch (CoreException e) {
- e.printStackTrace();
+ if (elements.length != 0) {
+ try {
+ stateLoader = (IStateLoader) elements[0]
+ .createExecutableExtension("class");
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
}
}
- return null;
+
+ return stateLoader;
+
}
public static void saveManagerState() {
- stateLoader.saveState();
+ IStateLoader stateLoader = getStateLoader();
+ if (stateLoader != null) {
+ stateLoader.saveState();
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java
index 56974777..d40dbd60 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java
@@ -1,12 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2012 Martin Reiterer.
- * 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
+ * Copyright (c) 2012 Martin Reiterer. 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:
- * Martin Reiterer - initial API and implementation
+ * Contributors: Martin Reiterer - initial API and implementation
******************************************************************************/
package org.eclipse.babel.tapiji.tools.core.ui.decorators;
@@ -34,10 +32,6 @@ public class ExcludedResource implements ILabelDecorator,
IResourceExclusionListener {
private static final String ENTRY_SUFFIX = "[no i18n]";
- private static final Image OVERLAY_IMAGE_ON = ImageUtils
- .getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_ON);
- private static final Image OVERLAY_IMAGE_OFF = ImageUtils
- .getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF);
private final List<ILabelProviderListener> label_provider_listener = new ArrayList<ILabelProviderListener>();
public boolean decorate(Object element) {
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java
index a5353e0d..b0482588 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java
@@ -10,6 +10,7 @@
******************************************************************************/
package org.eclipse.babel.tapiji.tools.core.ui.memento;
+import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.HashSet;
@@ -48,15 +49,17 @@ public class ResourceBundleManagerStateLoader implements IStateLoader {
*/
@Override
public void loadState() {
-
- excludedResources = new HashSet<IResourceDescriptor>();
- FileReader reader = null;
- try {
- reader = new FileReader(FileUtils.getRBManagerStateFile());
- loadManagerState(XMLMemento.createReadRoot(reader));
- } catch (Exception e) {
- Logger.logError(e);
- }
+
+ excludedResources = new HashSet<IResourceDescriptor>();
+ FileReader reader = null;
+ try {
+ reader = new FileReader(FileUtils.getRBManagerStateFile());
+ loadManagerState(XMLMemento.createReadRoot(reader));
+ } catch (FileNotFoundException e) {
+ Logger.logInfo("Unable to restore internationalization state. Reason: internationalization.xml not found!");
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
}
private void loadManagerState(XMLMemento memento) {
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java
index 7f21d7bc..dcbabae0 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java
@@ -1,12 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2012 Martin Reiterer.
- * 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
+ * Copyright (c) 2012 Martin Reiterer. 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:
- * Martin Reiterer - initial API and implementation
+ * Contributors: Martin Reiterer - initial API and implementation
******************************************************************************/
package org.eclipse.babel.tapiji.tools.core;
@@ -16,7 +14,15 @@
public class Logger {
public static void logInfo(String message) {
- log(IStatus.INFO, IStatus.OK, message, null);
+ log(IStatus.INFO, IStatus.INFO, message, null);
+ }
+
+ public static void logWarning(String message) {
+ log(IStatus.WARNING, IStatus.WARNING, message, null);
+ }
+
+ public static void logError(String message) {
+ log(IStatus.ERROR, IStatus.ERROR, message, null);
}
public static void logError(Throwable exception) {
@@ -24,7 +30,7 @@ public static void logError(Throwable exception) {
}
public static void logError(String message, Throwable exception) {
- log(IStatus.ERROR, IStatus.OK, message, exception);
+ log(IStatus.ERROR, IStatus.ERROR, message, exception);
}
public static void log(int severity, int code, String message,
|
6950c38a0436ec937797f01fba8d7d95e6d6225f
|
elasticsearch
|
Tests: Improve test coverage.--Close -7428-
|
p
|
https://github.com/elastic/elasticsearch
|
diff --git a/rest-api-spec/test/cat.indices/10_basic.yml b/rest-api-spec/test/cat.indices/10_basic.yml
new file mode 100644
index 0000000000000..b3025a25ace5e
--- /dev/null
+++ b/rest-api-spec/test/cat.indices/10_basic.yml
@@ -0,0 +1,26 @@
+---
+"Test cat indices output":
+
+ - do:
+ cat.indices: {}
+
+ - match:
+ $body: |
+ /^$/
+
+ - do:
+ indices.create:
+ index: index1
+ body:
+ settings:
+ number_of_shards: "1"
+ number_of_replicas: "0"
+ - do:
+ cluster.health:
+ wait_for_status: yellow
+ - do:
+ cat.indices: {}
+
+ - match:
+ $body: |
+ /^(green \s+ index1 \s+ 1 \s+ 0 \s+ 0 \s+ 0 \s+ (\d+|\d+[.]\d+)(kb|b) \s+ (\d+|\d+[.]\d+)(kb|b))$/
diff --git a/src/main/java/org/elasticsearch/common/Booleans.java b/src/main/java/org/elasticsearch/common/Booleans.java
index 830e10ea823a3..dc0816cf4d42c 100644
--- a/src/main/java/org/elasticsearch/common/Booleans.java
+++ b/src/main/java/org/elasticsearch/common/Booleans.java
@@ -24,6 +24,11 @@
*/
public class Booleans {
+ /**
+ * Returns <code>true</code> iff the sequence is neither of the following:
+ * <tt>false</tt>, <tt>0</tt>, <tt>off</tt>, <tt>no</tt>,
+ * otherwise <code>false</code>
+ */
public static boolean parseBoolean(char[] text, int offset, int length, boolean defaultValue) {
if (text == null || length == 0) {
return defaultValue;
@@ -73,27 +78,40 @@ public static boolean isBoolean(char[] text, int offset, int length) {
return false;
}
-
- public static boolean parseBoolean(String value, boolean defaultValue) {
- if (value == null) {
+ public static Boolean parseBoolean(String value, Boolean defaultValue) {
+ if (value == null) { // only for the null case we do that here!
return defaultValue;
}
- return !(value.equals("false") || value.equals("0") || value.equals("off") || value.equals("no"));
+ return parseBoolean(value, false);
}
-
- public static Boolean parseBoolean(String value, Boolean defaultValue) {
+ /**
+ * Returns <code>true</code> iff the value is neither of the following:
+ * <tt>false</tt>, <tt>0</tt>, <tt>off</tt>, <tt>no</tt>
+ * otherwise <code>false</code>
+ */
+ public static boolean parseBoolean(String value, boolean defaultValue) {
if (value == null) {
return defaultValue;
}
return !(value.equals("false") || value.equals("0") || value.equals("off") || value.equals("no"));
}
+ /**
+ * Returns <code>true</code> iff the value is either of the following:
+ * <tt>false</tt>, <tt>0</tt>, <tt>off</tt>, <tt>no</tt>
+ * otherwise <code>false</code>
+ */
public static boolean isExplicitFalse(String value) {
- return (value.equals("false") || value.equals("0") || value.equals("off") || value.equals("no"));
+ return value != null && (value.equals("false") || value.equals("0") || value.equals("off") || value.equals("no"));
}
+ /**
+ * Returns <code>true</code> iff the value is either of the following:
+ * <tt>true</tt>, <tt>1</tt>, <tt>on</tt>, <tt>yes</tt>
+ * otherwise <code>false</code>
+ */
public static boolean isExplicitTrue(String value) {
- return (value.equals("true") || value.equals("1") || value.equals("on") || value.equals("yes"));
+ return value != null && (value.equals("true") || value.equals("1") || value.equals("on") || value.equals("yes"));
}
}
diff --git a/src/main/java/org/elasticsearch/common/Preconditions.java b/src/main/java/org/elasticsearch/common/Preconditions.java
index bc6aef92b779a..045d24d761701 100644
--- a/src/main/java/org/elasticsearch/common/Preconditions.java
+++ b/src/main/java/org/elasticsearch/common/Preconditions.java
@@ -23,7 +23,6 @@
import org.elasticsearch.ElasticsearchIllegalStateException;
import org.elasticsearch.ElasticsearchNullPointerException;
-import java.util.Collection;
import java.util.NoSuchElementException;
/**
@@ -246,204 +245,6 @@ public static <T> T checkNotNull(T reference, String errorMessageTemplate,
return reference;
}
- /**
- * Ensures that an {@code Iterable} object passed as a parameter to the
- * calling method is not null and contains no null elements.
- *
- * @param iterable the iterable to check the contents of
- * @return the non-null {@code iterable} reference just validated
- * @throws org.elasticsearch.ElasticsearchNullPointerException
- * if {@code iterable} is null or contains at
- * least one null element
- */
- public static <T extends Iterable<?>> T checkContentsNotNull(T iterable) {
- if (containsOrIsNull(iterable)) {
- throw new ElasticsearchNullPointerException();
- }
- return iterable;
- }
-
- /**
- * Ensures that an {@code Iterable} object passed as a parameter to the
- * calling method is not null and contains no null elements.
- *
- * @param iterable the iterable to check the contents of
- * @param errorMessage the exception message to use if the check fails; will
- * be converted to a string using {@link String#valueOf(Object)}
- * @return the non-null {@code iterable} reference just validated
- * @throws org.elasticsearch.ElasticsearchNullPointerException
- * if {@code iterable} is null or contains at
- * least one null element
- */
- public static <T extends Iterable<?>> T checkContentsNotNull(
- T iterable, Object errorMessage) {
- if (containsOrIsNull(iterable)) {
- throw new ElasticsearchNullPointerException(String.valueOf(errorMessage));
- }
- return iterable;
- }
-
- /**
- * Ensures that an {@code Iterable} object passed as a parameter to the
- * calling method is not null and contains no null elements.
- *
- * @param iterable the iterable to check the contents of
- * @param errorMessageTemplate a template for the exception message should the
- * check fail. The message is formed by replacing each {@code %s}
- * placeholder in the template with an argument. These are matched by
- * position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
- * Unmatched arguments will be appended to the formatted message in square
- * braces. Unmatched placeholders will be left as-is.
- * @param errorMessageArgs the arguments to be substituted into the message
- * template. Arguments are converted to strings using
- * {@link String#valueOf(Object)}.
- * @return the non-null {@code iterable} reference just validated
- * @throws org.elasticsearch.ElasticsearchNullPointerException
- * if {@code iterable} is null or contains at
- * least one null element
- */
- public static <T extends Iterable<?>> T checkContentsNotNull(T iterable,
- String errorMessageTemplate, Object... errorMessageArgs) {
- if (containsOrIsNull(iterable)) {
- throw new ElasticsearchNullPointerException(
- format(errorMessageTemplate, errorMessageArgs));
- }
- return iterable;
- }
-
- private static boolean containsOrIsNull(Iterable<?> iterable) {
- if (iterable == null) {
- return true;
- }
-
- if (iterable instanceof Collection) {
- Collection<?> collection = (Collection<?>) iterable;
- try {
- return collection.contains(null);
- } catch (ElasticsearchNullPointerException e) {
- // A NPE implies that the collection doesn't contain null.
- return false;
- }
- } else {
- for (Object element : iterable) {
- if (element == null) {
- return true;
- }
- }
- return false;
- }
- }
-
- /**
- * Ensures that {@code index} specifies a valid <i>element</i> in an array,
- * list or string of size {@code size}. An element index may range from zero,
- * inclusive, to {@code size}, exclusive.
- *
- * @param index a user-supplied index identifying an element of an array, list
- * or string
- * @param size the size of that array, list or string
- * @throws IndexOutOfBoundsException if {@code index} is negative or is not
- * less than {@code size}
- * @throws org.elasticsearch.ElasticsearchIllegalArgumentException
- * if {@code size} is negative
- */
- public static void checkElementIndex(int index, int size) {
- checkElementIndex(index, size, "index");
- }
-
- /**
- * Ensures that {@code index} specifies a valid <i>element</i> in an array,
- * list or string of size {@code size}. An element index may range from zero,
- * inclusive, to {@code size}, exclusive.
- *
- * @param index a user-supplied index identifying an element of an array, list
- * or string
- * @param size the size of that array, list or string
- * @param desc the text to use to describe this index in an error message
- * @throws IndexOutOfBoundsException if {@code index} is negative or is not
- * less than {@code size}
- * @throws org.elasticsearch.ElasticsearchIllegalArgumentException
- * if {@code size} is negative
- */
- public static void checkElementIndex(int index, int size, String desc) {
- checkArgument(size >= 0, "negative size: %s", size);
- if (index < 0) {
- throw new IndexOutOfBoundsException(
- format("%s (%s) must not be negative", desc, index));
- }
- if (index >= size) {
- throw new IndexOutOfBoundsException(
- format("%s (%s) must be less than size (%s)", desc, index, size));
- }
- }
-
- /**
- * Ensures that {@code index} specifies a valid <i>position</i> in an array,
- * list or string of size {@code size}. A position index may range from zero
- * to {@code size}, inclusive.
- *
- * @param index a user-supplied index identifying a position in an array, list
- * or string
- * @param size the size of that array, list or string
- * @throws IndexOutOfBoundsException if {@code index} is negative or is
- * greater than {@code size}
- * @throws org.elasticsearch.ElasticsearchIllegalArgumentException
- * if {@code size} is negative
- */
- public static void checkPositionIndex(int index, int size) {
- checkPositionIndex(index, size, "index");
- }
-
- /**
- * Ensures that {@code index} specifies a valid <i>position</i> in an array,
- * list or string of size {@code size}. A position index may range from zero
- * to {@code size}, inclusive.
- *
- * @param index a user-supplied index identifying a position in an array, list
- * or string
- * @param size the size of that array, list or string
- * @param desc the text to use to describe this index in an error message
- * @throws IndexOutOfBoundsException if {@code index} is negative or is
- * greater than {@code size}
- * @throws org.elasticsearch.ElasticsearchIllegalArgumentException
- * if {@code size} is negative
- */
- public static void checkPositionIndex(int index, int size, String desc) {
- checkArgument(size >= 0, "negative size: %s", size);
- if (index < 0) {
- throw new IndexOutOfBoundsException(format(
- "%s (%s) must not be negative", desc, index));
- }
- if (index > size) {
- throw new IndexOutOfBoundsException(format(
- "%s (%s) must not be greater than size (%s)", desc, index, size));
- }
- }
-
- /**
- * Ensures that {@code start} and {@code end} specify a valid <i>positions</i>
- * in an array, list or string of size {@code size}, and are in order. A
- * position index may range from zero to {@code size}, inclusive.
- *
- * @param start a user-supplied index identifying a starting position in an
- * array, list or string
- * @param end a user-supplied index identifying a ending position in an array,
- * list or string
- * @param size the size of that array, list or string
- * @throws IndexOutOfBoundsException if either index is negative or is
- * greater than {@code size}, or if {@code end} is less than {@code start}
- * @throws org.elasticsearch.ElasticsearchIllegalArgumentException
- * if {@code size} is negative
- */
- public static void checkPositionIndexes(int start, int end, int size) {
- checkPositionIndex(start, size, "start index");
- checkPositionIndex(end, size, "end index");
- if (end < start) {
- throw new IndexOutOfBoundsException(format(
- "end index (%s) must not be less than start index (%s)", end, start));
- }
- }
-
/**
* Substitutes each {@code %s} in {@code template} with an argument. These
* are matched by position - the first {@code %s} gets {@code args[0]}, etc.
diff --git a/src/main/java/org/elasticsearch/common/Strings.java b/src/main/java/org/elasticsearch/common/Strings.java
index adbc19fd81581..debfaf5c2e077 100644
--- a/src/main/java/org/elasticsearch/common/Strings.java
+++ b/src/main/java/org/elasticsearch/common/Strings.java
@@ -49,20 +49,6 @@ public class Strings {
private static final String CURRENT_PATH = ".";
- private static final char EXTENSION_SEPARATOR = '.';
-
- public static void tabify(int tabs, String from, StringBuilder to) throws Exception {
- try (BufferedReader reader = new BufferedReader(new FastStringReader(from))) {
- String line;
- while ((line = reader.readLine()) != null) {
- for (int i = 0; i < tabs; i++) {
- to.append('\t');
- }
- to.append(line).append('\n');
- }
- }
- }
-
public static void spaceify(int spaces, String from, StringBuilder to) throws Exception {
try (BufferedReader reader = new BufferedReader(new FastStringReader(from))) {
String line;
@@ -137,55 +123,6 @@ public static List<String> splitSmart(String s, String separator, boolean decode
}
- public static List<String> splitWS(String s, boolean decode) {
- ArrayList<String> lst = new ArrayList<>(2);
- StringBuilder sb = new StringBuilder();
- int pos = 0, end = s.length();
- while (pos < end) {
- char ch = s.charAt(pos++);
- if (Character.isWhitespace(ch)) {
- if (sb.length() > 0) {
- lst.add(sb.toString());
- sb = new StringBuilder();
- }
- continue;
- }
-
- if (ch == '\\') {
- if (!decode) sb.append(ch);
- if (pos >= end) break; // ERROR, or let it go?
- ch = s.charAt(pos++);
- if (decode) {
- switch (ch) {
- case 'n':
- ch = '\n';
- break;
- case 't':
- ch = '\t';
- break;
- case 'r':
- ch = '\r';
- break;
- case 'b':
- ch = '\b';
- break;
- case 'f':
- ch = '\f';
- break;
- }
- }
- }
-
- sb.append(ch);
- }
-
- if (sb.length() > 0) {
- lst.add(sb.toString());
- }
-
- return lst;
- }
-
//---------------------------------------------------------------------
// General convenience methods for working with Strings
//---------------------------------------------------------------------
@@ -316,63 +253,6 @@ public static boolean containsWhitespace(CharSequence str) {
return false;
}
- /**
- * Check whether the given String contains any whitespace characters.
- *
- * @param str the String to check (may be <code>null</code>)
- * @return <code>true</code> if the String is not empty and
- * contains at least 1 whitespace character
- * @see #containsWhitespace(CharSequence)
- */
- public static boolean containsWhitespace(String str) {
- return containsWhitespace((CharSequence) str);
- }
-
- /**
- * Trim leading and trailing whitespace from the given String.
- *
- * @param str the String to check
- * @return the trimmed String
- * @see java.lang.Character#isWhitespace
- */
- public static String trimWhitespace(String str) {
- if (!hasLength(str)) {
- return str;
- }
- StringBuilder sb = new StringBuilder(str);
- while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {
- sb.deleteCharAt(0);
- }
- while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {
- sb.deleteCharAt(sb.length() - 1);
- }
- return sb.toString();
- }
-
- /**
- * Trim <i>all</i> whitespace from the given String:
- * leading, trailing, and inbetween characters.
- *
- * @param str the String to check
- * @return the trimmed String
- * @see java.lang.Character#isWhitespace
- */
- public static String trimAllWhitespace(String str) {
- if (!hasLength(str)) {
- return str;
- }
- StringBuilder sb = new StringBuilder(str);
- int index = 0;
- while (sb.length() > index) {
- if (Character.isWhitespace(sb.charAt(index))) {
- sb.deleteCharAt(index);
- } else {
- index++;
- }
- }
- return sb.toString();
- }
-
/**
* Trim leading whitespace from the given String.
*
@@ -391,24 +271,6 @@ public static String trimLeadingWhitespace(String str) {
return sb.toString();
}
- /**
- * Trim trailing whitespace from the given String.
- *
- * @param str the String to check
- * @return the trimmed String
- * @see java.lang.Character#isWhitespace
- */
- public static String trimTrailingWhitespace(String str) {
- if (!hasLength(str)) {
- return str;
- }
- StringBuilder sb = new StringBuilder(str);
- while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {
- sb.deleteCharAt(sb.length() - 1);
- }
- return sb.toString();
- }
-
/**
* Trim all occurences of the supplied leading character from the given String.
*
@@ -427,72 +289,6 @@ public static String trimLeadingCharacter(String str, char leadingCharacter) {
return sb.toString();
}
- /**
- * Trim all occurences of the supplied trailing character from the given String.
- *
- * @param str the String to check
- * @param trailingCharacter the trailing character to be trimmed
- * @return the trimmed String
- */
- public static String trimTrailingCharacter(String str, char trailingCharacter) {
- if (!hasLength(str)) {
- return str;
- }
- StringBuilder sb = new StringBuilder(str);
- while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {
- sb.deleteCharAt(sb.length() - 1);
- }
- return sb.toString();
- }
-
-
- /**
- * Test if the given String starts with the specified prefix,
- * ignoring upper/lower case.
- *
- * @param str the String to check
- * @param prefix the prefix to look for
- * @see java.lang.String#startsWith
- */
- public static boolean startsWithIgnoreCase(String str, String prefix) {
- if (str == null || prefix == null) {
- return false;
- }
- if (str.startsWith(prefix)) {
- return true;
- }
- if (str.length() < prefix.length()) {
- return false;
- }
- String lcStr = str.substring(0, prefix.length()).toLowerCase(Locale.ROOT);
- String lcPrefix = prefix.toLowerCase(Locale.ROOT);
- return lcStr.equals(lcPrefix);
- }
-
- /**
- * Test if the given String ends with the specified suffix,
- * ignoring upper/lower case.
- *
- * @param str the String to check
- * @param suffix the suffix to look for
- * @see java.lang.String#endsWith
- */
- public static boolean endsWithIgnoreCase(String str, String suffix) {
- if (str == null || suffix == null) {
- return false;
- }
- if (str.endsWith(suffix)) {
- return true;
- }
- if (str.length() < suffix.length()) {
- return false;
- }
-
- String lcStr = str.substring(str.length() - suffix.length()).toLowerCase(Locale.ROOT);
- String lcSuffix = suffix.toLowerCase(Locale.ROOT);
- return lcStr.equals(lcSuffix);
- }
-
/**
* Test whether the given string matches the given substring
* at the given index.
@@ -609,28 +405,6 @@ public static String quote(String str) {
return (str != null ? "'" + str + "'" : null);
}
- /**
- * Turn the given Object into a String with single quotes
- * if it is a String; keeping the Object as-is else.
- *
- * @param obj the input Object (e.g. "myString")
- * @return the quoted String (e.g. "'myString'"),
- * or the input object as-is if not a String
- */
- public static Object quoteIfString(Object obj) {
- return (obj instanceof String ? quote((String) obj) : obj);
- }
-
- /**
- * Unqualify a string qualified by a '.' dot character. For example,
- * "this.name.is.qualified", returns "qualified".
- *
- * @param qualifiedName the qualified name
- */
- public static String unqualify(String qualifiedName) {
- return unqualify(qualifiedName, '.');
- }
-
/**
* Unqualify a string qualified by a separator character. For example,
* "this:name:is:qualified" returns "qualified" if using a ':' separator.
@@ -654,18 +428,6 @@ public static String capitalize(String str) {
return changeFirstCharacterCase(str, true);
}
- /**
- * Uncapitalize a <code>String</code>, changing the first letter to
- * lower case as per {@link Character#toLowerCase(char)}.
- * No other letters are changed.
- *
- * @param str the String to uncapitalize, may be <code>null</code>
- * @return the uncapitalized String, <code>null</code> if null
- */
- public static String uncapitalize(String str) {
- return changeFirstCharacterCase(str, false);
- }
-
private static String changeFirstCharacterCase(String str, boolean capitalize) {
if (str == null || str.length() == 0) {
return str;
@@ -702,74 +464,6 @@ public static boolean validFileNameExcludingAstrix(String fileName) {
return true;
}
- /**
- * Extract the filename from the given path,
- * e.g. "mypath/myfile.txt" -> "myfile.txt".
- *
- * @param path the file path (may be <code>null</code>)
- * @return the extracted filename, or <code>null</code> if none
- */
- public static String getFilename(String path) {
- if (path == null) {
- return null;
- }
- int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);
- return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);
- }
-
- /**
- * Extract the filename extension from the given path,
- * e.g. "mypath/myfile.txt" -> "txt".
- *
- * @param path the file path (may be <code>null</code>)
- * @return the extracted filename extension, or <code>null</code> if none
- */
- public static String getFilenameExtension(String path) {
- if (path == null) {
- return null;
- }
- int sepIndex = path.lastIndexOf(EXTENSION_SEPARATOR);
- return (sepIndex != -1 ? path.substring(sepIndex + 1) : null);
- }
-
- /**
- * Strip the filename extension from the given path,
- * e.g. "mypath/myfile.txt" -> "mypath/myfile".
- *
- * @param path the file path (may be <code>null</code>)
- * @return the path with stripped filename extension,
- * or <code>null</code> if none
- */
- public static String stripFilenameExtension(String path) {
- if (path == null) {
- return null;
- }
- int sepIndex = path.lastIndexOf(EXTENSION_SEPARATOR);
- return (sepIndex != -1 ? path.substring(0, sepIndex) : path);
- }
-
- /**
- * Apply the given relative path to the given path,
- * assuming standard Java folder separation (i.e. "/" separators);
- *
- * @param path the path to start from (usually a full file path)
- * @param relativePath the relative path to apply
- * (relative to the full file path above)
- * @return the full file path that results from applying the relative path
- */
- public static String applyRelativePath(String path, String relativePath) {
- int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);
- if (separatorIndex != -1) {
- String newPath = path.substring(0, separatorIndex);
- if (!relativePath.startsWith(FOLDER_SEPARATOR)) {
- newPath += FOLDER_SEPARATOR;
- }
- return newPath + relativePath;
- } else {
- return relativePath;
- }
- }
-
/**
* Normalize the path by suppressing sequences like "path/.." and
* inner simple dots.
@@ -830,142 +524,6 @@ public static String cleanPath(String path) {
return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);
}
- /**
- * Compare two paths after normalization of them.
- *
- * @param path1 first path for comparison
- * @param path2 second path for comparison
- * @return whether the two paths are equivalent after normalization
- */
- public static boolean pathEquals(String path1, String path2) {
- return cleanPath(path1).equals(cleanPath(path2));
- }
-
- /**
- * Parse the given <code>localeString</code> into a {@link Locale}.
- * <p>This is the inverse operation of {@link Locale#toString Locale's toString}.
- *
- * @param localeString the locale string, following <code>Locale's</code>
- * <code>toString()</code> format ("en", "en_UK", etc);
- * also accepts spaces as separators, as an alternative to underscores
- * @return a corresponding <code>Locale</code> instance
- */
- public static Locale parseLocaleString(String localeString) {
- String[] parts = tokenizeToStringArray(localeString, "_ ", false, false);
- String language = (parts.length != 0 ? parts[0] : "");
- String country = (parts.length > 1 ? parts[1] : "");
- String variant = "";
- if (parts.length >= 2) {
- // There is definitely a variant, and it is everything after the country
- // code sans the separator between the country code and the variant.
- int endIndexOfCountryCode = localeString.indexOf(country) + country.length();
- // Strip off any leading '_' and whitespace, what's left is the variant.
- variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));
- if (variant.startsWith("_")) {
- variant = trimLeadingCharacter(variant, '_');
- }
- }
- return (language.length() > 0 ? new Locale(language, country, variant) : null);
- }
-
- /**
- * Determine the RFC 3066 compliant language tag,
- * as used for the HTTP "Accept-Language" header.
- *
- * @param locale the Locale to transform to a language tag
- * @return the RFC 3066 compliant language tag as String
- */
- public static String toLanguageTag(Locale locale) {
- return locale.getLanguage() + (hasText(locale.getCountry()) ? "-" + locale.getCountry() : "");
- }
-
-
- //---------------------------------------------------------------------
- // Convenience methods for working with String arrays
- //---------------------------------------------------------------------
-
- /**
- * Append the given String to the given String array, returning a new array
- * consisting of the input array contents plus the given String.
- *
- * @param array the array to append to (can be <code>null</code>)
- * @param str the String to append
- * @return the new array (never <code>null</code>)
- */
- public static String[] addStringToArray(String[] array, String str) {
- if (isEmpty(array)) {
- return new String[]{str};
- }
- String[] newArr = new String[array.length + 1];
- System.arraycopy(array, 0, newArr, 0, array.length);
- newArr[array.length] = str;
- return newArr;
- }
-
- /**
- * Concatenate the given String arrays into one,
- * with overlapping array elements included twice.
- * <p>The order of elements in the original arrays is preserved.
- *
- * @param array1 the first array (can be <code>null</code>)
- * @param array2 the second array (can be <code>null</code>)
- * @return the new array (<code>null</code> if both given arrays were <code>null</code>)
- */
- public static String[] concatenateStringArrays(String[] array1, String[] array2) {
- if (isEmpty(array1)) {
- return array2;
- }
- if (isEmpty(array2)) {
- return array1;
- }
- String[] newArr = new String[array1.length + array2.length];
- System.arraycopy(array1, 0, newArr, 0, array1.length);
- System.arraycopy(array2, 0, newArr, array1.length, array2.length);
- return newArr;
- }
-
- /**
- * Merge the given String arrays into one, with overlapping
- * array elements only included once.
- * <p>The order of elements in the original arrays is preserved
- * (with the exception of overlapping elements, which are only
- * included on their first occurence).
- *
- * @param array1 the first array (can be <code>null</code>)
- * @param array2 the second array (can be <code>null</code>)
- * @return the new array (<code>null</code> if both given arrays were <code>null</code>)
- */
- public static String[] mergeStringArrays(String[] array1, String[] array2) {
- if (isEmpty(array1)) {
- return array2;
- }
- if (isEmpty(array2)) {
- return array1;
- }
- List<String> result = new ArrayList<>();
- result.addAll(Arrays.asList(array1));
- for (String str : array2) {
- if (!result.contains(str)) {
- result.add(str);
- }
- }
- return toStringArray(result);
- }
-
- /**
- * Turn given source String array into sorted array.
- *
- * @param array the source array
- * @return the sorted array (never <code>null</code>)
- */
- public static String[] sortStringArray(String[] array) {
- if (isEmpty(array)) {
- return new String[0];
- }
- Arrays.sort(array);
- return array;
- }
-
/**
* Copy the given Collection into a String array.
* The Collection must contain String elements only.
@@ -981,57 +539,6 @@ public static String[] toStringArray(Collection<String> collection) {
return collection.toArray(new String[collection.size()]);
}
- /**
- * Copy the given Enumeration into a String array.
- * The Enumeration must contain String elements only.
- *
- * @param enumeration the Enumeration to copy
- * @return the String array (<code>null</code> if the passed-in
- * Enumeration was <code>null</code>)
- */
- public static String[] toStringArray(Enumeration<String> enumeration) {
- if (enumeration == null) {
- return null;
- }
- List<String> list = Collections.list(enumeration);
- return list.toArray(new String[list.size()]);
- }
-
- /**
- * Trim the elements of the given String array,
- * calling <code>String.trim()</code> on each of them.
- *
- * @param array the original String array
- * @return the resulting array (of the same size) with trimmed elements
- */
- public static String[] trimArrayElements(String[] array) {
- if (isEmpty(array)) {
- return new String[0];
- }
- String[] result = new String[array.length];
- for (int i = 0; i < array.length; i++) {
- String element = array[i];
- result[i] = (element != null ? element.trim() : null);
- }
- return result;
- }
-
- /**
- * Remove duplicate Strings from the given array.
- * Also sorts the array, as it uses a TreeSet.
- *
- * @param array the String array
- * @return an array without duplicates, in natural sort order
- */
- public static String[] removeDuplicateStrings(String[] array) {
- if (isEmpty(array)) {
- return array;
- }
- Set<String> set = new TreeSet<>();
- set.addAll(Arrays.asList(array));
- return toStringArray(set);
- }
-
public static Set<String> splitStringByCommaToSet(final String s) {
return splitStringToSet(s, ',');
}
@@ -1128,22 +635,6 @@ public static String[] split(String toSplit, String delimiter) {
return new String[]{beforeDelimiter, afterDelimiter};
}
- /**
- * Take an array Strings and split each element based on the given delimiter.
- * A <code>Properties</code> instance is then generated, with the left of the
- * delimiter providing the key, and the right of the delimiter providing the value.
- * <p>Will trim both the key and value before adding them to the
- * <code>Properties</code> instance.
- *
- * @param array the array to process
- * @param delimiter to split each element using (typically the equals symbol)
- * @return a <code>Properties</code> instance representing the array contents,
- * or <code>null</code> if the array to process was null or empty
- */
- public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {
- return splitArrayElementsIntoProperties(array, delimiter, null);
- }
-
/**
* Take an array Strings and split each element based on the given delimiter.
* A <code>Properties</code> instance is then generated, with the left of the
@@ -1603,5 +1094,4 @@ public static boolean isAllOrWildcard(String[] data) {
return CollectionUtils.isEmpty(data) ||
data.length == 1 && ("_all".equals(data[0]) || "*".equals(data[0]));
}
-
-}
+}
\ No newline at end of file
diff --git a/src/main/java/org/elasticsearch/common/geo/GeoHashUtils.java b/src/main/java/org/elasticsearch/common/geo/GeoHashUtils.java
index a3b98ccbfc629..15aca20e23af8 100644
--- a/src/main/java/org/elasticsearch/common/geo/GeoHashUtils.java
+++ b/src/main/java/org/elasticsearch/common/geo/GeoHashUtils.java
@@ -21,7 +21,6 @@
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Iterator;
/**
@@ -120,23 +119,6 @@ private static final char encode(int x, int y) {
public static Collection<? extends CharSequence> neighbors(String geohash) {
return addNeighbors(geohash, geohash.length(), new ArrayList<CharSequence>(8));
}
-
- /**
- * Create an {@link Iterable} which allows to iterate over the cells that
- * contain a given geohash
- *
- * @param geohash Geohash of a cell
- *
- * @return {@link Iterable} of path
- */
- public static Iterable<String> path(final String geohash) {
- return new Iterable<String>() {
- @Override
- public Iterator<String> iterator() {
- return new GeohashPathIterator(geohash);
- }
- };
- }
/**
* Calculate the geohash of a neighbor of a geohash
@@ -331,19 +313,6 @@ public static GeoPoint decode(String geohash, GeoPoint ret) {
return ret.reset((interval[0] + interval[1]) / 2D, (interval[2] + interval[3]) / 2D);
}
- /**
- * Decodes the given geohash into a geohash cell defined by the points nothWest and southEast
- *
- * @param geohash Geohash to deocde
- * @param northWest the point north/west of the cell
- * @param southEast the point south/east of the cell
- */
- public static void decodeCell(String geohash, GeoPoint northWest, GeoPoint southEast) {
- double[] interval = decodeCell(geohash);
- northWest.reset(interval[1], interval[2]);
- southEast.reset(interval[0], interval[3]);
- }
-
private static double[] decodeCell(String geohash) {
double[] interval = {-90.0, 90.0, -180.0, 180.0};
boolean isEven = true;
diff --git a/src/main/java/org/elasticsearch/common/geo/GeoPoint.java b/src/main/java/org/elasticsearch/common/geo/GeoPoint.java
index 8278c9ca7347c..0e1d6961de52e 100644
--- a/src/main/java/org/elasticsearch/common/geo/GeoPoint.java
+++ b/src/main/java/org/elasticsearch/common/geo/GeoPoint.java
@@ -78,11 +78,6 @@ public GeoPoint resetFromGeoHash(String hash) {
return this;
}
- void latlon(double lat, double lon) {
- this.lat = lat;
- this.lon = lon;
- }
-
public final double lat() {
return this.lat;
}
diff --git a/src/main/java/org/elasticsearch/common/geo/GeoUtils.java b/src/main/java/org/elasticsearch/common/geo/GeoUtils.java
index c1b9cca01d380..c4bc51d7bfb82 100644
--- a/src/main/java/org/elasticsearch/common/geo/GeoUtils.java
+++ b/src/main/java/org/elasticsearch/common/geo/GeoUtils.java
@@ -421,4 +421,7 @@ public static GeoPoint parseGeoPoint(XContentParser parser, GeoPoint point) thro
throw new ElasticsearchParseException("geo_point expected");
}
}
+
+ private GeoUtils() {
+ }
}
diff --git a/src/main/java/org/elasticsearch/common/geo/GeohashPathIterator.java b/src/main/java/org/elasticsearch/common/geo/GeohashPathIterator.java
deleted file mode 100644
index 6e6821ee81b96..0000000000000
--- a/src/main/java/org/elasticsearch/common/geo/GeohashPathIterator.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Licensed to Elasticsearch under one or more contributor
- * license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright
- * ownership. Elasticsearch 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.elasticsearch.common.geo;
-
-import java.util.Iterator;
-
-/**
- * This class iterates over the cells of a given geohash. Assume geohashes
- * form a tree, this iterator traverses this tree form a leaf (actual gehash)
- * to the root (geohash of length 1).
- */
-public final class GeohashPathIterator implements Iterator<String> {
-
- private final String geohash;
- private int currentLength;
-
- /**
- * Create a new {@link GeohashPathIterator} for a given geohash
- * @param geohash The geohash to traverse
- */
- public GeohashPathIterator(String geohash) {
- this.geohash = geohash;
- this.currentLength = geohash.length();
- }
-
- @Override
- public boolean hasNext() {
- return currentLength > 0;
- }
-
- @Override
- public String next() {
- String result = geohash.substring(0, currentLength);
- currentLength--;
- return result;
- }
-
- @Override
- public void remove() {
- throw new UnsupportedOperationException("unable to remove a geohash from this path");
- }
-}
\ No newline at end of file
diff --git a/src/main/java/org/elasticsearch/common/geo/SpatialStrategy.java b/src/main/java/org/elasticsearch/common/geo/SpatialStrategy.java
index 02ee8a774e114..a83f29156a1f3 100644
--- a/src/main/java/org/elasticsearch/common/geo/SpatialStrategy.java
+++ b/src/main/java/org/elasticsearch/common/geo/SpatialStrategy.java
@@ -18,12 +18,6 @@
*/
package org.elasticsearch.common.geo;
-import org.apache.lucene.spatial.prefix.PrefixTreeStrategy;
-import org.apache.lucene.spatial.prefix.RecursivePrefixTreeStrategy;
-import org.apache.lucene.spatial.prefix.TermQueryPrefixTreeStrategy;
-import org.apache.lucene.spatial.prefix.tree.SpatialPrefixTree;
-
-import java.lang.String;
/**
*
@@ -42,11 +36,4 @@ private SpatialStrategy(String strategyName) {
public String getStrategyName() {
return strategyName;
}
-
- public PrefixTreeStrategy create(SpatialPrefixTree grid, String fieldName) {
- if (this == TERM) {
- return new TermQueryPrefixTreeStrategy(grid, fieldName);
- }
- return new RecursivePrefixTreeStrategy(grid, fieldName);
- }
}
diff --git a/src/main/java/org/elasticsearch/index/fielddata/IndexFieldDataCache.java b/src/main/java/org/elasticsearch/index/fielddata/IndexFieldDataCache.java
index 6921840f5dd13..9e1fceff5251f 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/IndexFieldDataCache.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/IndexFieldDataCache.java
@@ -29,7 +29,6 @@
import org.apache.lucene.util.Accountable;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.lucene.SegmentReaderUtils;
-import org.elasticsearch.index.fielddata.ordinals.GlobalOrdinalsIndexFieldData;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.service.IndexService;
import org.elasticsearch.index.shard.ShardId;
@@ -143,7 +142,7 @@ public void onRemoval(RemovalNotification<Key, Accountable> notification) {
public <FD extends AtomicFieldData, IFD extends IndexFieldData<FD>> FD load(final AtomicReaderContext context, final IFD indexFieldData) throws Exception {
final Key key = new Key(context.reader().getCoreCacheKey());
//noinspection unchecked
- Accountable fd = cache.get(key, new Callable<FD>() {
+ final Accountable accountable = cache.get(key, new Callable<FD>() {
@Override
public FD call() throws Exception {
SegmentReaderUtils.registerCoreListener(context.reader(), FieldBased.this);
@@ -157,7 +156,6 @@ public FD call() throws Exception {
}
}
final FD fieldData = indexFieldData.loadDirect(context);
- key.sizeInBytes = fieldData.ramBytesUsed();
for (Listener listener : key.listeners) {
try {
listener.onLoad(fieldNames, fieldDataType, fieldData);
@@ -166,20 +164,20 @@ public FD call() throws Exception {
logger.error("Failed to call listener on atomic field data loading", e);
}
}
+ key.sizeInBytes = fieldData.ramBytesUsed();
return fieldData;
}
});
- return (FD) fd;
+ return (FD) accountable;
}
public <FD extends AtomicFieldData, IFD extends IndexFieldData.Global<FD>> IFD load(final IndexReader indexReader, final IFD indexFieldData) throws Exception {
final Key key = new Key(indexReader.getCoreCacheKey());
//noinspection unchecked
- Accountable ifd = cache.get(key, new Callable<Accountable>() {
+ final Accountable accountable = cache.get(key, new Callable<Accountable>() {
@Override
- public GlobalOrdinalsIndexFieldData call() throws Exception {
+ public Accountable call() throws Exception {
indexReader.addReaderClosedListener(FieldBased.this);
-
key.listeners.add(indicesFieldDataCacheListener);
final ShardId shardId = ShardUtils.extractShardId(indexReader);
if (shardId != null) {
@@ -188,8 +186,7 @@ public GlobalOrdinalsIndexFieldData call() throws Exception {
key.listeners.add(shard.fieldData());
}
}
- GlobalOrdinalsIndexFieldData ifd = (GlobalOrdinalsIndexFieldData) indexFieldData.localGlobalDirect(indexReader);
- key.sizeInBytes = ifd.ramBytesUsed();
+ final Accountable ifd = (Accountable) indexFieldData.localGlobalDirect(indexReader);
for (Listener listener : key.listeners) {
try {
listener.onLoad(fieldNames, fieldDataType, ifd);
@@ -198,11 +195,11 @@ public GlobalOrdinalsIndexFieldData call() throws Exception {
logger.error("Failed to call listener on global ordinals loading", e);
}
}
-
+ key.sizeInBytes = ifd.ramBytesUsed();
return ifd;
}
});
- return (IFD) ifd;
+ return (IFD) accountable;
}
@Override
diff --git a/src/main/java/org/elasticsearch/index/fielddata/IndexFieldDataService.java b/src/main/java/org/elasticsearch/index/fielddata/IndexFieldDataService.java
index 3d289dcdb707f..077088b2c5a07 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/IndexFieldDataService.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/IndexFieldDataService.java
@@ -53,6 +53,11 @@
*/
public class IndexFieldDataService extends AbstractIndexComponent {
+ public static final String FIELDDATA_CACHE_KEY = "index.fielddata.cache";
+ public static final String FIELDDATA_CACHE_VALUE_SOFT = "soft";
+ public static final String FIELDDATA_CACHE_VALUE_NODE = "node";
+ public static final String FIELDDATA_CACHE_VALUE_RESIDENT = "resident";
+
private static final String DISABLED_FORMAT = "disabled";
private static final String DOC_VALUES_FORMAT = "doc_values";
private static final String ARRAY_FORMAT = "array";
@@ -273,12 +278,12 @@ public <IFD extends IndexFieldData<?>> IFD getForField(FieldMapper<?> mapper) {
if (cache == null) {
// we default to node level cache, which in turn defaults to be unbounded
// this means changing the node level settings is simple, just set the bounds there
- String cacheType = type.getSettings().get("cache", indexSettings.get("index.fielddata.cache", "node"));
- if ("resident".equals(cacheType)) {
+ String cacheType = type.getSettings().get("cache", indexSettings.get(FIELDDATA_CACHE_KEY, FIELDDATA_CACHE_VALUE_NODE));
+ if (FIELDDATA_CACHE_VALUE_RESIDENT.equals(cacheType)) {
cache = new IndexFieldDataCache.Resident(logger, indexService, fieldNames, type, indicesFieldDataCacheListener);
- } else if ("soft".equals(cacheType)) {
+ } else if (FIELDDATA_CACHE_VALUE_SOFT.equals(cacheType)) {
cache = new IndexFieldDataCache.Soft(logger, indexService, fieldNames, type, indicesFieldDataCacheListener);
- } else if ("node".equals(cacheType)) {
+ } else if (FIELDDATA_CACHE_VALUE_NODE.equals(cacheType)) {
cache = indicesFieldDataCache.buildIndexFieldDataCache(indexService, index, fieldNames, type);
} else if ("none".equals(cacheType)){
cache = new IndexFieldDataCache.None();
diff --git a/src/main/java/org/elasticsearch/index/gateway/local/LocalIndexShardGateway.java b/src/main/java/org/elasticsearch/index/gateway/local/LocalIndexShardGateway.java
index 4a9e99fec16f8..2dd45562bd8d3 100644
--- a/src/main/java/org/elasticsearch/index/gateway/local/LocalIndexShardGateway.java
+++ b/src/main/java/org/elasticsearch/index/gateway/local/LocalIndexShardGateway.java
@@ -127,7 +127,7 @@ public void recover(boolean indexShouldExists, RecoveryState recoveryState) thro
} catch (Throwable e1) {
files += " (failure=" + ExceptionsHelper.detailedMessage(e1) + ")";
}
- if (indexShouldExists && indexShard.store().indexStore().persistent()) {
+ if (indexShouldExists && indexShard.indexService().store().persistent()) {
throw new IndexShardGatewayRecoveryException(shardId(), "shard allocated for local recovery (post api), should exist, but doesn't, current files: " + files, e);
}
}
diff --git a/src/main/java/org/elasticsearch/index/query/TermsFilterParser.java b/src/main/java/org/elasticsearch/index/query/TermsFilterParser.java
index 421d699c3153f..af2a7d6bff356 100644
--- a/src/main/java/org/elasticsearch/index/query/TermsFilterParser.java
+++ b/src/main/java/org/elasticsearch/index/query/TermsFilterParser.java
@@ -52,6 +52,16 @@ public class TermsFilterParser implements FilterParser {
public static final String NAME = "terms";
private IndicesTermsFilterCache termsFilterCache;
+ public static final String EXECUTION_KEY = "execution";
+ public static final String EXECUTION_VALUE_PLAIN = "plain";
+ public static final String EXECUTION_VALUE_FIELDDATA = "fielddata";
+ public static final String EXECUTION_VALUE_BOOL = "bool";
+ public static final String EXECUTION_VALUE_BOOL_NOCACHE = "bool_nocache";
+ public static final String EXECUTION_VALUE_AND = "and";
+ public static final String EXECUTION_VALUE_AND_NOCACHE = "and_nocache";
+ public static final String EXECUTION_VALUE_OR = "or";
+ public static final String EXECUTION_VALUE_OR_NOCACHE = "or_nocache";
+
@Inject
public TermsFilterParser() {
}
@@ -84,7 +94,7 @@ public Filter parse(QueryParseContext parseContext) throws IOException, QueryPar
CacheKeyFilter.Key cacheKey = null;
XContentParser.Token token;
- String execution = "plain";
+ String execution = EXECUTION_VALUE_PLAIN;
List<Object> terms = Lists.newArrayList();
String fieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
@@ -133,7 +143,7 @@ public Filter parse(QueryParseContext parseContext) throws IOException, QueryPar
throw new QueryParsingException(parseContext.index(), "[terms] filter lookup element requires specifying the path");
}
} else if (token.isValue()) {
- if ("execution".equals(currentFieldName)) {
+ if (EXECUTION_KEY.equals(currentFieldName)) {
execution = parser.text();
} else if ("_name".equals(currentFieldName)) {
filterName = parser.text();
@@ -193,7 +203,7 @@ public Filter parse(QueryParseContext parseContext) throws IOException, QueryPar
try {
Filter filter;
- if ("plain".equals(execution)) {
+ if (EXECUTION_VALUE_PLAIN.equals(execution)) {
if (fieldMapper != null) {
filter = fieldMapper.termsFilter(terms, parseContext);
} else {
@@ -207,7 +217,7 @@ public Filter parse(QueryParseContext parseContext) throws IOException, QueryPar
if (cache == null || cache) {
filter = parseContext.cacheFilter(filter, cacheKey);
}
- } else if ("fielddata".equals(execution)) {
+ } else if (EXECUTION_VALUE_FIELDDATA.equals(execution)) {
// if there are no mappings, then nothing has been indexing yet against this shard, so we can return
// no match (but not cached!), since the FieldDataTermsFilter relies on a mapping...
if (fieldMapper == null) {
@@ -218,7 +228,7 @@ public Filter parse(QueryParseContext parseContext) throws IOException, QueryPar
if (cache != null && cache) {
filter = parseContext.cacheFilter(filter, cacheKey);
}
- } else if ("bool".equals(execution)) {
+ } else if (EXECUTION_VALUE_BOOL.equals(execution)) {
XBooleanFilter boolFiler = new XBooleanFilter();
if (fieldMapper != null) {
for (Object term : terms) {
@@ -234,7 +244,7 @@ public Filter parse(QueryParseContext parseContext) throws IOException, QueryPar
if (cache != null && cache) {
filter = parseContext.cacheFilter(filter, cacheKey);
}
- } else if ("bool_nocache".equals(execution)) {
+ } else if (EXECUTION_VALUE_BOOL_NOCACHE.equals(execution)) {
XBooleanFilter boolFiler = new XBooleanFilter();
if (fieldMapper != null) {
for (Object term : terms) {
@@ -250,7 +260,7 @@ public Filter parse(QueryParseContext parseContext) throws IOException, QueryPar
if (cache == null || cache) {
filter = parseContext.cacheFilter(filter, cacheKey);
}
- } else if ("and".equals(execution)) {
+ } else if (EXECUTION_VALUE_AND.equals(execution)) {
List<Filter> filters = Lists.newArrayList();
if (fieldMapper != null) {
for (Object term : terms) {
@@ -266,7 +276,7 @@ public Filter parse(QueryParseContext parseContext) throws IOException, QueryPar
if (cache != null && cache) {
filter = parseContext.cacheFilter(filter, cacheKey);
}
- } else if ("and_nocache".equals(execution)) {
+ } else if (EXECUTION_VALUE_AND_NOCACHE.equals(execution)) {
List<Filter> filters = Lists.newArrayList();
if (fieldMapper != null) {
for (Object term : terms) {
@@ -282,7 +292,7 @@ public Filter parse(QueryParseContext parseContext) throws IOException, QueryPar
if (cache == null || cache) {
filter = parseContext.cacheFilter(filter, cacheKey);
}
- } else if ("or".equals(execution)) {
+ } else if (EXECUTION_VALUE_OR.equals(execution)) {
List<Filter> filters = Lists.newArrayList();
if (fieldMapper != null) {
for (Object term : terms) {
@@ -298,7 +308,7 @@ public Filter parse(QueryParseContext parseContext) throws IOException, QueryPar
if (cache != null && cache) {
filter = parseContext.cacheFilter(filter, cacheKey);
}
- } else if ("or_nocache".equals(execution)) {
+ } else if (EXECUTION_VALUE_OR_NOCACHE.equals(execution)) {
List<Filter> filters = Lists.newArrayList();
if (fieldMapper != null) {
for (Object term : terms) {
diff --git a/src/main/java/org/elasticsearch/index/store/IndexStore.java b/src/main/java/org/elasticsearch/index/store/IndexStore.java
index 743a25607bfc4..6f51f1ad0d2f8 100644
--- a/src/main/java/org/elasticsearch/index/store/IndexStore.java
+++ b/src/main/java/org/elasticsearch/index/store/IndexStore.java
@@ -20,7 +20,6 @@
package org.elasticsearch.index.store;
import org.apache.lucene.store.StoreRateLimiting;
-import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.index.CloseableIndexComponent;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.indices.store.IndicesStore;
@@ -50,16 +49,6 @@ public interface IndexStore extends CloseableIndexComponent {
*/
Class<? extends DirectoryService> shardDirectory();
- /**
- * Returns the backing store total space. Return <tt>-1</tt> if not available.
- */
- ByteSizeValue backingStoreTotalSpace();
-
- /**
- * Returns the backing store free space. Return <tt>-1</tt> if not available.
- */
- ByteSizeValue backingStoreFreeSpace();
-
/**
* Returns <tt>true</tt> if this shard is allocated on this node. Allocated means
* that it has storage files that can be deleted using {@link #deleteUnallocated(org.elasticsearch.index.shard.ShardId)}.
diff --git a/src/main/java/org/elasticsearch/index/store/Store.java b/src/main/java/org/elasticsearch/index/store/Store.java
index 969a6c11d5fd5..9fac24e0fc093 100644
--- a/src/main/java/org/elasticsearch/index/store/Store.java
+++ b/src/main/java/org/elasticsearch/index/store/Store.java
@@ -83,7 +83,6 @@ public class Store extends AbstractIndexShardComponent implements CloseableIndex
private final AtomicBoolean isClosed = new AtomicBoolean(false);
private final AtomicInteger refCount = new AtomicInteger(1);
- private final IndexStore indexStore;
private final CodecService codecService;
private final DirectoryService directoryService;
private final StoreDirectory directory;
@@ -91,9 +90,8 @@ public class Store extends AbstractIndexShardComponent implements CloseableIndex
private final DistributorDirectory distributorDirectory;
@Inject
- public Store(ShardId shardId, @IndexSettings Settings indexSettings, IndexStore indexStore, CodecService codecService, DirectoryService directoryService, Distributor distributor) throws IOException {
+ public Store(ShardId shardId, @IndexSettings Settings indexSettings, CodecService codecService, DirectoryService directoryService, Distributor distributor) throws IOException {
super(shardId, indexSettings);
- this.indexStore = indexStore;
this.codecService = codecService;
this.directoryService = directoryService;
this.sync = componentSettings.getAsBoolean("sync", true);
@@ -101,10 +99,6 @@ public Store(ShardId shardId, @IndexSettings Settings indexSettings, IndexStore
this.directory = new StoreDirectory(distributorDirectory);
}
- public IndexStore indexStore() {
- ensureOpen();
- return this.indexStore;
- }
public Directory directory() {
ensureOpen();
@@ -132,7 +126,7 @@ private static SegmentInfos readSegmentsInfo(IndexCommit commit, Directory direc
}
}
- private final void ensureOpen() {
+ final void ensureOpen() { // for testing
if (this.refCount.get() <= 0) {
throw new AlreadyClosedException("Store is already closed");
}
diff --git a/src/main/java/org/elasticsearch/index/store/fs/FsIndexStore.java b/src/main/java/org/elasticsearch/index/store/fs/FsIndexStore.java
index d4ab729397cac..ad552b862292f 100644
--- a/src/main/java/org/elasticsearch/index/store/fs/FsIndexStore.java
+++ b/src/main/java/org/elasticsearch/index/store/fs/FsIndexStore.java
@@ -22,7 +22,6 @@
import org.elasticsearch.ElasticsearchIllegalStateException;
import org.elasticsearch.common.io.FileSystemUtils;
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.service.IndexService;
@@ -58,30 +57,6 @@ public boolean persistent() {
return true;
}
- @Override
- public ByteSizeValue backingStoreTotalSpace() {
- if (locations == null) {
- return new ByteSizeValue(0);
- }
- long totalSpace = 0;
- for (File location : locations) {
- totalSpace += location.getTotalSpace();
- }
- return new ByteSizeValue(totalSpace);
- }
-
- @Override
- public ByteSizeValue backingStoreFreeSpace() {
- if (locations == null) {
- return new ByteSizeValue(0);
- }
- long usableSpace = 0;
- for (File location : locations) {
- usableSpace += location.getUsableSpace();
- }
- return new ByteSizeValue(usableSpace);
- }
-
@Override
public boolean canDeleteUnallocated(ShardId shardId) {
if (locations == null) {
diff --git a/src/main/java/org/elasticsearch/index/store/ram/RamIndexStore.java b/src/main/java/org/elasticsearch/index/store/ram/RamIndexStore.java
index 96bb5da5ed07f..c39242f9f777c 100644
--- a/src/main/java/org/elasticsearch/index/store/ram/RamIndexStore.java
+++ b/src/main/java/org/elasticsearch/index/store/ram/RamIndexStore.java
@@ -21,15 +21,12 @@
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.service.IndexService;
import org.elasticsearch.index.settings.IndexSettings;
import org.elasticsearch.index.store.DirectoryService;
import org.elasticsearch.index.store.support.AbstractIndexStore;
import org.elasticsearch.indices.store.IndicesStore;
-import org.elasticsearch.monitor.jvm.JvmInfo;
-import org.elasticsearch.monitor.jvm.JvmStats;
/**
*
@@ -50,14 +47,4 @@ public boolean persistent() {
public Class<? extends DirectoryService> shardDirectory() {
return RamDirectoryService.class;
}
-
- @Override
- public ByteSizeValue backingStoreTotalSpace() {
- return JvmInfo.jvmInfo().getMem().heapMax();
- }
-
- @Override
- public ByteSizeValue backingStoreFreeSpace() {
- return JvmStats.jvmStats().getMem().heapUsed();
- }
}
diff --git a/src/main/java/org/elasticsearch/indices/fielddata/cache/IndicesFieldDataCache.java b/src/main/java/org/elasticsearch/indices/fielddata/cache/IndicesFieldDataCache.java
index 9764c1056ec9f..dd54b817e9e5e 100644
--- a/src/main/java/org/elasticsearch/indices/fielddata/cache/IndicesFieldDataCache.java
+++ b/src/main/java/org/elasticsearch/indices/fielddata/cache/IndicesFieldDataCache.java
@@ -32,7 +32,10 @@
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.Index;
-import org.elasticsearch.index.fielddata.*;
+import org.elasticsearch.index.fielddata.AtomicFieldData;
+import org.elasticsearch.index.fielddata.FieldDataType;
+import org.elasticsearch.index.fielddata.IndexFieldData;
+import org.elasticsearch.index.fielddata.IndexFieldDataCache;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.service.IndexService;
import org.elasticsearch.index.shard.ShardId;
@@ -110,10 +113,7 @@ public void onRemoval(RemovalNotification<Key, Accountable> notification) {
IndexFieldCache indexCache = key.indexCache;
long sizeInBytes = key.sizeInBytes;
final Accountable value = notification.getValue();
- assert sizeInBytes >= 0 || value != null : "Expected size [" + sizeInBytes + "] to be positive or value [" + value + "] to be non-null";
- if (sizeInBytes == -1 && value != null) {
- sizeInBytes = value.ramBytesUsed();
- }
+ assert value == null || sizeInBytes > 0 && sizeInBytes == value.ramBytesUsed() : "Expected size [" + sizeInBytes + "] to be positive or value [" + value + "] to be non-null";
for (IndexFieldDataCache.Listener listener : key.listeners) {
try {
listener.onUnload(indexCache.fieldNames, indexCache.fieldDataType, notification.wasEvicted(), sizeInBytes);
@@ -198,7 +198,6 @@ public AtomicFieldData call() throws Exception {
public <FD extends AtomicFieldData, IFD extends IndexFieldData.Global<FD>> IFD load(final IndexReader indexReader, final IFD indexFieldData) throws Exception {
final Key key = new Key(this, indexReader.getCoreCacheKey());
-
//noinspection unchecked
final Accountable accountable = cache.get(key, new Callable<Accountable>() {
@Override
@@ -221,6 +220,7 @@ public Accountable call() throws Exception {
logger.error("Failed to call listener on global ordinals loading", e);
}
}
+ key.sizeInBytes = ifd.ramBytesUsed();
return ifd;
}
});
diff --git a/src/main/java/org/elasticsearch/script/ScriptService.java b/src/main/java/org/elasticsearch/script/ScriptService.java
index 4674498dac7e3..3f6a2ee1fabc0 100644
--- a/src/main/java/org/elasticsearch/script/ScriptService.java
+++ b/src/main/java/org/elasticsearch/script/ScriptService.java
@@ -24,7 +24,6 @@
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.ElasticsearchIllegalArgumentException;
-
import org.elasticsearch.ElasticsearchIllegalStateException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.delete.DeleteRequest;
@@ -53,8 +52,6 @@
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.VersionType;
-import org.elasticsearch.index.fielddata.IndexFieldDataService;
-import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.query.TemplateQueryParser;
import org.elasticsearch.search.lookup.SearchLookup;
import org.elasticsearch.watcher.FileChangesListener;
@@ -78,6 +75,8 @@ public class ScriptService extends AbstractComponent {
public static final String DEFAULT_SCRIPTING_LANGUAGE_SETTING = "script.default_lang";
public static final String DISABLE_DYNAMIC_SCRIPTING_SETTING = "script.disable_dynamic";
+ public static final String SCRIPT_CACHE_SIZE_SETTING = "script.cache.max_size";
+ public static final String SCRIPT_CACHE_EXPIRE_SETTING = "script.cache.expire";
public static final String DISABLE_DYNAMIC_SCRIPTING_DEFAULT = "sandbox";
public static final String SCRIPT_INDEX = ".scripts";
@@ -219,8 +218,8 @@ public ScriptService(Settings settings, Environment env, Set<ScriptEngineService
ResourceWatcherService resourceWatcherService) {
super(settings);
- int cacheMaxSize = componentSettings.getAsInt("cache.max_size", 500);
- TimeValue cacheExpire = componentSettings.getAsTime("cache.expire", null);
+ int cacheMaxSize = settings.getAsInt(SCRIPT_CACHE_SIZE_SETTING, 500);
+ TimeValue cacheExpire = settings.getAsTime(SCRIPT_CACHE_EXPIRE_SETTING, null);
logger.debug("using script cache with max_size [{}], expire [{}]", cacheMaxSize, cacheExpire);
this.defaultLang = settings.get(DEFAULT_SCRIPTING_LANGUAGE_SETTING, "groovy");
@@ -347,9 +346,6 @@ public CompiledScript compile(String lang, String script, ScriptType scriptType
throw new ScriptException("dynamic scripting for [" + lang + "] disabled");
}
- if (cacheKey == null) {
- cacheKey = new CacheKey(lang, script);
- }
// not the end of the world if we compile it twice...
compiled = getCompiledScript(lang, script);
//Since the cache key is the script content itself we don't need to
@@ -509,18 +505,6 @@ public SearchScript search(SearchLookup lookup, String lang, String script, Scri
return search(compile(lang, script, scriptType), lookup, vars);
}
- public SearchScript search(MapperService mapperService, IndexFieldDataService fieldDataService, String lang, String script, ScriptType scriptType, @Nullable Map<String, Object> vars) {
- return search(compile(lang, script), new SearchLookup(mapperService, fieldDataService, null), vars);
- }
-
- public Object execute(CompiledScript compiledScript, Map vars) {
- return scriptEngines.get(compiledScript.lang()).execute(compiledScript.compiled(), vars);
- }
-
- public void clear() {
- cache.invalidateAll();
- }
-
private boolean dynamicScriptEnabled(String lang) {
ScriptEngineService service = scriptEngines.get(lang);
if (service == null) {
diff --git a/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/InternalOrder.java b/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/InternalOrder.java
index 485c51c65f60d..8413ac05edb95 100644
--- a/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/InternalOrder.java
+++ b/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/InternalOrder.java
@@ -152,7 +152,7 @@ protected Comparator<Terms.Bucket> comparator(Aggregator termsAggregator) {
// attached to the order will still be used in the reduce phase of the Aggregation.
OrderPath path = path();
- final Aggregator aggregator = path.resolveAggregator(termsAggregator, false);
+ final Aggregator aggregator = path.resolveAggregator(termsAggregator);
final String key = path.tokens[path.tokens.length - 1].key;
if (aggregator instanceof SingleBucketAggregator) {
diff --git a/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/TermsAggregator.java b/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/TermsAggregator.java
index 93afda694d874..e669a46e6bd97 100644
--- a/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/TermsAggregator.java
+++ b/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/TermsAggregator.java
@@ -139,7 +139,7 @@ public TermsAggregator(String name, BucketAggregationMode bucketAggregationMode,
// Don't defer any child agg if we are dependent on it for pruning results
if (order instanceof Aggregation){
OrderPath path = ((Aggregation) order).path();
- aggUsedForSorting = path.resolveTopmostAggregator(this, false);
+ aggUsedForSorting = path.resolveTopmostAggregator(this);
}
}
diff --git a/src/main/java/org/elasticsearch/search/aggregations/support/OrderPath.java b/src/main/java/org/elasticsearch/search/aggregations/support/OrderPath.java
index 29a2abfe8d7cb..94eedb36db4c3 100644
--- a/src/main/java/org/elasticsearch/search/aggregations/support/OrderPath.java
+++ b/src/main/java/org/elasticsearch/search/aggregations/support/OrderPath.java
@@ -236,13 +236,9 @@ public double resolveValue(HasAggregations root) {
* Resolves the aggregator pointed by this path using the given root as a point of reference.
*
* @param root The point of reference of this path
- * @param validate Indicates whether the path should be validated first over the given root aggregator
* @return The aggregator pointed by this path starting from the given aggregator as a point of reference
*/
- public Aggregator resolveAggregator(Aggregator root, boolean validate) {
- if (validate) {
- validate(root);
- }
+ public Aggregator resolveAggregator(Aggregator root) {
Aggregator aggregator = root;
for (int i = 0; i < tokens.length; i++) {
OrderPath.Token token = tokens[i];
@@ -258,14 +254,9 @@ public Aggregator resolveAggregator(Aggregator root, boolean validate) {
* Resolves the topmost aggregator pointed by this path using the given root as a point of reference.
*
* @param root The point of reference of this path
- * @param validate Indicates whether the path should be validated first over the given root aggregator
* @return The first child aggregator of the root pointed by this path
*/
- public Aggregator resolveTopmostAggregator(Aggregator root, boolean validate) {
- if (validate) {
- validate(root);
- }
-
+ public Aggregator resolveTopmostAggregator(Aggregator root) {
OrderPath.Token token = tokens[0];
Aggregator aggregator = root.subAggregator(token.name);
assert (aggregator instanceof SingleBucketAggregator )
diff --git a/src/test/java/org/elasticsearch/common/BooleansTests.java b/src/test/java/org/elasticsearch/common/BooleansTests.java
index 7440d8cba6d46..252baaba25770 100644
--- a/src/test/java/org/elasticsearch/common/BooleansTests.java
+++ b/src/test/java/org/elasticsearch/common/BooleansTests.java
@@ -23,12 +23,18 @@
import org.hamcrest.Matchers;
import org.junit.Test;
+import java.util.Locale;
+
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.nullValue;
+
public class BooleansTests extends ElasticsearchTestCase {
@Test
public void testIsBoolean() {
String[] booleans = new String[]{"true", "false", "on", "off", "yes", "no", "0", "1"};
String[] notBooleans = new String[]{"11", "00", "sdfsdfsf", "F", "T"};
+ assertThat(Booleans.isBoolean(null, 0, 1), is(false));
for (String b : booleans) {
String t = "prefix" + b + "suffix";
@@ -40,4 +46,33 @@ public void testIsBoolean() {
assertThat("recognized [" + nb + "] as boolean", Booleans.isBoolean(t.toCharArray(), "prefix".length(), nb.length()), Matchers.equalTo(false));
}
}
+ @Test
+ public void parseBoolean() {
+ assertThat(Booleans.parseBoolean(randomFrom("true", "on", "yes", "1"), randomBoolean()), is(true));
+ assertThat(Booleans.parseBoolean(randomFrom("false", "off", "no", "0"), randomBoolean()), is(false));
+ assertThat(Booleans.parseBoolean(randomFrom("true", "on", "yes").toUpperCase(Locale.ROOT), randomBoolean()), is(true));
+ assertThat(Booleans.parseBoolean(null, false), is(false));
+ assertThat(Booleans.parseBoolean(null, true), is(true));
+
+ assertThat(Booleans.parseBoolean(randomFrom("true", "on", "yes", "1"), randomFrom(null, Boolean.TRUE, Boolean.FALSE)), is(true));
+ assertThat(Booleans.parseBoolean(randomFrom("false", "off", "no", "0"), randomFrom(null, Boolean.TRUE, Boolean.FALSE)), is(false));
+ assertThat(Booleans.parseBoolean(randomFrom("true", "on", "yes").toUpperCase(Locale.ROOT),randomFrom(null, Boolean.TRUE, Boolean.FALSE)), is(true));
+ assertThat(Booleans.parseBoolean(null, Boolean.FALSE), is(false));
+ assertThat(Booleans.parseBoolean(null, Boolean.TRUE), is(true));
+ assertThat(Booleans.parseBoolean(null, null), nullValue());
+
+ char[] chars = randomFrom("true", "on", "yes", "1").toCharArray();
+ assertThat(Booleans.parseBoolean(chars, 0, chars.length, randomBoolean()), is(true));
+ chars = randomFrom("false", "off", "no", "0").toCharArray();
+ assertThat(Booleans.parseBoolean(chars,0, chars.length, randomBoolean()), is(false));
+ chars = randomFrom("true", "on", "yes").toUpperCase(Locale.ROOT).toCharArray();
+ assertThat(Booleans.parseBoolean(chars,0, chars.length, randomBoolean()), is(true));
+ }
+
+ public void testIsExplict() {
+ assertThat(Booleans.isExplicitFalse(randomFrom("true", "on", "yes", "1", "foo", null)), is(false));
+ assertThat(Booleans.isExplicitFalse(randomFrom("false", "off", "no", "0")), is(true));
+ assertThat(Booleans.isExplicitTrue(randomFrom("true", "on", "yes", "1")), is(true));
+ assertThat(Booleans.isExplicitTrue(randomFrom("false", "off", "no", "0", "foo", null)), is(false));
+ }
}
diff --git a/src/test/java/org/elasticsearch/common/geo/GeoJSONShapeParserTests.java b/src/test/java/org/elasticsearch/common/geo/GeoJSONShapeParserTests.java
index 1214ffcc38d33..211f7a54b6258 100644
--- a/src/test/java/org/elasticsearch/common/geo/GeoJSONShapeParserTests.java
+++ b/src/test/java/org/elasticsearch/common/geo/GeoJSONShapeParserTests.java
@@ -19,6 +19,8 @@
package org.elasticsearch.common.geo;
+import com.spatial4j.core.shape.Circle;
+import com.spatial4j.core.shape.Rectangle;
import com.spatial4j.core.shape.Shape;
import com.spatial4j.core.shape.ShapeCollection;
import com.spatial4j.core.shape.jts.JtsGeometry;
@@ -103,6 +105,30 @@ public void testParse_multiLineString() throws IOException {
assertGeometryEquals(jtsGeom(expected), multilinesGeoJson);
}
+ @Test
+ public void testParse_circle() throws IOException {
+ String multilinesGeoJson = XContentFactory.jsonBuilder().startObject().field("type", "circle")
+ .startArray("coordinates").value(100.0).value(0.0).endArray()
+ .field("radius", "100m")
+ .endObject().string();
+
+ Circle expected = SPATIAL_CONTEXT.makeCircle(100.0, 0.0, 360 * 100 / GeoUtils.EARTH_EQUATOR);
+ assertGeometryEquals(expected, multilinesGeoJson);
+ }
+
+ @Test
+ public void testParse_envelope() throws IOException {
+ String multilinesGeoJson = XContentFactory.jsonBuilder().startObject().field("type", "envelope")
+ .startArray("coordinates")
+ .startArray().value(-50).value(30).endArray()
+ .startArray().value(50).value(-30).endArray()
+ .endArray()
+ .endObject().string();
+
+ Rectangle expected = SPATIAL_CONTEXT.makeRectangle(-50, 50, -30, 30);
+ assertGeometryEquals(expected, multilinesGeoJson);
+ }
+
@Test
public void testParse_polygonNoHoles() throws IOException {
String polygonGeoJson = XContentFactory.jsonBuilder().startObject().field("type", "Polygon")
diff --git a/src/test/java/org/elasticsearch/common/geo/ShapeBuilderTests.java b/src/test/java/org/elasticsearch/common/geo/ShapeBuilderTests.java
index 060288178a947..4c6703d3ef3fe 100644
--- a/src/test/java/org/elasticsearch/common/geo/ShapeBuilderTests.java
+++ b/src/test/java/org/elasticsearch/common/geo/ShapeBuilderTests.java
@@ -69,6 +69,34 @@ public void testNewPolygon() {
assertEquals(exterior.getCoordinateN(2), new Coordinate(45, -30));
assertEquals(exterior.getCoordinateN(3), new Coordinate(-45, -30));
}
+
+ @Test
+ public void testNewPolygon_coordinate() {
+ Polygon polygon = ShapeBuilder.newPolygon()
+ .point(new Coordinate(-45, 30))
+ .point(new Coordinate(45, 30))
+ .point(new Coordinate(45, -30))
+ .point(new Coordinate(-45, -30))
+ .point(new Coordinate(-45, 30)).toPolygon();
+
+ LineString exterior = polygon.getExteriorRing();
+ assertEquals(exterior.getCoordinateN(0), new Coordinate(-45, 30));
+ assertEquals(exterior.getCoordinateN(1), new Coordinate(45, 30));
+ assertEquals(exterior.getCoordinateN(2), new Coordinate(45, -30));
+ assertEquals(exterior.getCoordinateN(3), new Coordinate(-45, -30));
+ }
+
+ @Test
+ public void testNewPolygon_coordinates() {
+ Polygon polygon = ShapeBuilder.newPolygon()
+ .points(new Coordinate(-45, 30), new Coordinate(45, 30), new Coordinate(45, -30), new Coordinate(-45, -30), new Coordinate(-45, 30)).toPolygon();
+
+ LineString exterior = polygon.getExteriorRing();
+ assertEquals(exterior.getCoordinateN(0), new Coordinate(-45, 30));
+ assertEquals(exterior.getCoordinateN(1), new Coordinate(45, 30));
+ assertEquals(exterior.getCoordinateN(2), new Coordinate(45, -30));
+ assertEquals(exterior.getCoordinateN(3), new Coordinate(-45, -30));
+ }
@Test
public void testLineStringBuilder() {
diff --git a/src/test/java/org/elasticsearch/index/TermsFilterIntegrationTests.java b/src/test/java/org/elasticsearch/index/TermsFilterIntegrationTests.java
new file mode 100644
index 0000000000000..25e96f7fedded
--- /dev/null
+++ b/src/test/java/org/elasticsearch/index/TermsFilterIntegrationTests.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to Elasticsearch under one or more contributor
+ * license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright
+ * ownership. Elasticsearch 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.elasticsearch.index;
+
+import org.elasticsearch.common.logging.ESLogger;
+import org.elasticsearch.common.logging.Loggers;
+import org.elasticsearch.index.query.FilterBuilders;
+import org.elasticsearch.index.query.QueryBuilders;
+import org.elasticsearch.test.ElasticsearchIntegrationTest;
+
+import java.util.Arrays;
+
+import static org.elasticsearch.index.query.TermsFilterParser.*;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
+
+public class TermsFilterIntegrationTests extends ElasticsearchIntegrationTest {
+
+ private final ESLogger logger = Loggers.getLogger(TermsFilterIntegrationTests.class);
+
+ public void testExecution() throws Exception {
+ assertAcked(prepareCreate("test").addMapping("type", "f", "type=string"));
+ ensureYellow();
+ indexRandom(true,
+ client().prepareIndex("test", "type").setSource("f", new String[] {"a", "b", "c"}),
+ client().prepareIndex("test", "type").setSource("f", "b"));
+
+ for (boolean cache : new boolean[] {false, true}) {
+ logger.info("cache=" + cache);
+ for (String execution : Arrays.asList(
+ EXECUTION_VALUE_PLAIN,
+ EXECUTION_VALUE_FIELDDATA,
+ EXECUTION_VALUE_BOOL,
+ EXECUTION_VALUE_BOOL_NOCACHE,
+ EXECUTION_VALUE_OR,
+ EXECUTION_VALUE_OR_NOCACHE)) {
+ logger.info("Execution=" + execution);
+ assertHitCount(client().prepareCount("test").setQuery(
+ QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(),
+ FilterBuilders.termsFilter("f", "a", "b").execution(execution).cache(cache))).get(), 2L);
+ }
+
+ for (String execution : Arrays.asList(
+ EXECUTION_VALUE_AND,
+ EXECUTION_VALUE_AND_NOCACHE)) {
+ logger.info("Execution=" + execution);
+ assertHitCount(client().prepareCount("test").setQuery(
+ QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(),
+ FilterBuilders.termsFilter("f", "a", "b").execution(execution).cache(cache))).get(), 1L);
+ }
+ }
+ }
+
+}
diff --git a/src/test/java/org/elasticsearch/index/engine/internal/InternalEngineTests.java b/src/test/java/org/elasticsearch/index/engine/internal/InternalEngineTests.java
index f92561c3e632b..612274ba3b3ea 100644
--- a/src/test/java/org/elasticsearch/index/engine/internal/InternalEngineTests.java
+++ b/src/test/java/org/elasticsearch/index/engine/internal/InternalEngineTests.java
@@ -170,12 +170,12 @@ private ParsedDocument testParsedDocument(String uid, String id, String type, St
protected Store createStore() throws IOException {
DirectoryService directoryService = new RamDirectoryService(shardId, EMPTY_SETTINGS);
- return new Store(shardId, EMPTY_SETTINGS, null, null, directoryService, new LeastUsedDistributor(directoryService));
+ return new Store(shardId, EMPTY_SETTINGS, null, directoryService, new LeastUsedDistributor(directoryService));
}
protected Store createStoreReplica() throws IOException {
DirectoryService directoryService = new RamDirectoryService(shardId, EMPTY_SETTINGS);
- return new Store(shardId, EMPTY_SETTINGS, null, null, directoryService, new LeastUsedDistributor(directoryService));
+ return new Store(shardId, EMPTY_SETTINGS, null, directoryService, new LeastUsedDistributor(directoryService));
}
protected Translog createTranslog() {
diff --git a/src/test/java/org/elasticsearch/index/fielddata/ScriptDocValuesTests.java b/src/test/java/org/elasticsearch/index/fielddata/ScriptDocValuesTests.java
new file mode 100644
index 0000000000000..a51af09f76edb
--- /dev/null
+++ b/src/test/java/org/elasticsearch/index/fielddata/ScriptDocValuesTests.java
@@ -0,0 +1,111 @@
+/*
+ * Licensed to Elasticsearch under one or more contributor
+ * license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright
+ * ownership. Elasticsearch 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.elasticsearch.index.fielddata;
+
+import org.elasticsearch.common.geo.GeoDistance;
+import org.elasticsearch.common.geo.GeoPoint;
+import org.elasticsearch.common.unit.DistanceUnit;
+import org.elasticsearch.test.ElasticsearchTestCase;
+
+import java.util.Arrays;
+
+public class ScriptDocValuesTests extends ElasticsearchTestCase {
+
+ private static MultiGeoPointValues wrap(final GeoPoint... points) {
+ return new MultiGeoPointValues() {
+ int docID = -1;
+
+ @Override
+ public GeoPoint valueAt(int i) {
+ if (docID != 0) {
+ fail();
+ }
+ return points[i];
+ }
+
+ @Override
+ public void setDocument(int docId) {
+ this.docID = docId;
+ }
+
+ @Override
+ public int count() {
+ if (docID != 0) {
+ return 0;
+ }
+ return points.length;
+ }
+ };
+ }
+
+ private static double randomLat() {
+ return randomDouble() * 180 - 90;
+ }
+
+ private static double randomLon() {
+ return randomDouble() * 360 - 180;
+ }
+
+ public void testGeoGetLatLon() {
+ final double lat1 = randomLat();
+ final double lat2 = randomLat();
+ final double lon1 = randomLon();
+ final double lon2 = randomLon();
+ final MultiGeoPointValues values = wrap(new GeoPoint(lat1, lon1), new GeoPoint(lat2, lon2));
+ final ScriptDocValues.GeoPoints script = new ScriptDocValues.GeoPoints(values);
+ script.setNextDocId(1);
+ assertEquals(true, script.isEmpty());
+ script.setNextDocId(0);
+ assertEquals(false, script.isEmpty());
+ assertEquals(new GeoPoint(lat1, lon1), script.getValue());
+ assertEquals(Arrays.asList(new GeoPoint(lat1, lon1), new GeoPoint(lat2, lon2)), script.getValues());
+ assertEquals(lat1, script.getLat(), 0);
+ assertEquals(lon1, script.getLon(), 0);
+ assertTrue(Arrays.equals(new double[] {lat1, lat2}, script.getLats()));
+ assertTrue(Arrays.equals(new double[] {lon1, lon2}, script.getLons()));
+ }
+
+ public void testGeoDistance() {
+ final double lat = randomLat();
+ final double lon = randomLon();
+ final MultiGeoPointValues values = wrap(new GeoPoint(lat, lon));
+ final ScriptDocValues.GeoPoints script = new ScriptDocValues.GeoPoints(values);
+ script.setNextDocId(0);
+
+ final ScriptDocValues.GeoPoints emptyScript = new ScriptDocValues.GeoPoints(wrap());
+ emptyScript.setNextDocId(0);
+
+ final double otherLat = randomLat();
+ final double otherLon = randomLon();
+
+ assertEquals(GeoDistance.ARC.calculate(lat, lon, otherLat, otherLon, DistanceUnit.KILOMETERS),
+ script.arcDistanceInKm(otherLat, otherLon), 0.01);
+ assertEquals(GeoDistance.ARC.calculate(lat, lon, otherLat, otherLon, DistanceUnit.KILOMETERS),
+ script.arcDistanceInKmWithDefault(otherLat, otherLon, 42), 0.01);
+ assertEquals(42, emptyScript.arcDistanceInKmWithDefault(otherLat, otherLon, 42), 0);
+
+ assertEquals(GeoDistance.PLANE.calculate(lat, lon, otherLat, otherLon, DistanceUnit.KILOMETERS),
+ script.distanceInKm(otherLat, otherLon), 0.01);
+ assertEquals(GeoDistance.PLANE.calculate(lat, lon, otherLat, otherLon, DistanceUnit.KILOMETERS),
+ script.distanceInKmWithDefault(otherLat, otherLon, 42), 0.01);
+ assertEquals(42, emptyScript.distanceInKmWithDefault(otherLat, otherLon, 42), 0);
+ }
+
+}
diff --git a/src/test/java/org/elasticsearch/index/mapper/FileBasedMappingsTests.java b/src/test/java/org/elasticsearch/index/mapper/FileBasedMappingsTests.java
new file mode 100644
index 0000000000000..2bc209daa0275
--- /dev/null
+++ b/src/test/java/org/elasticsearch/index/mapper/FileBasedMappingsTests.java
@@ -0,0 +1,109 @@
+/*
+ * Licensed to Elasticsearch under one or more contributor
+ * license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright
+ * ownership. Elasticsearch 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.elasticsearch.index.mapper;
+
+import com.google.common.io.Files;
+import org.elasticsearch.action.admin.indices.mapping.get.GetFieldMappingsResponse;
+import org.elasticsearch.action.admin.indices.mapping.get.GetFieldMappingsResponse.FieldMappingMetaData;
+import org.elasticsearch.cluster.ClusterName;
+import org.elasticsearch.common.io.FileSystemUtils;
+import org.elasticsearch.common.logging.ESLogger;
+import org.elasticsearch.common.logging.Loggers;
+import org.elasticsearch.common.settings.ImmutableSettings;
+import org.elasticsearch.common.settings.Settings;
+import org.elasticsearch.common.xcontent.XContentBuilder;
+import org.elasticsearch.common.xcontent.json.JsonXContent;
+import org.elasticsearch.node.Node;
+import org.elasticsearch.node.NodeBuilder;
+import org.elasticsearch.test.ElasticsearchTestCase;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.util.Arrays;
+
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
+
+public class FileBasedMappingsTests extends ElasticsearchTestCase {
+
+ private static final String NAME = FileBasedMappingsTests.class.getSimpleName();
+
+ private final ESLogger logger = Loggers.getLogger(FileBasedMappingsTests.class);
+
+ public void testFileBasedMappings() throws Exception {
+ File configDir = Files.createTempDir();
+ File mappingsDir = new File(configDir, "mappings");
+ File indexMappings = new File(new File(mappingsDir, "index"), "type.json");
+ File defaultMappings = new File(new File(mappingsDir, "_default"), "type.json");
+ try {
+ indexMappings.getParentFile().mkdirs();
+ defaultMappings.getParentFile().mkdirs();
+
+ try (XContentBuilder builder = new XContentBuilder(JsonXContent.jsonXContent, new FileOutputStream(indexMappings))) {
+ builder.startObject()
+ .startObject("type")
+ .startObject("properties")
+ .startObject("f")
+ .field("type", "string")
+ .endObject()
+ .endObject()
+ .endObject()
+ .endObject();
+ }
+
+ try (XContentBuilder builder = new XContentBuilder(JsonXContent.jsonXContent, new FileOutputStream(defaultMappings))) {
+ builder.startObject()
+ .startObject("type")
+ .startObject("properties")
+ .startObject("g")
+ .field("type", "string")
+ .endObject()
+ .endObject()
+ .endObject()
+ .endObject();
+ }
+
+ Settings settings = ImmutableSettings.builder()
+ .put(ClusterName.SETTING, NAME)
+ .put("node.name", NAME)
+ .put("path.conf", configDir.getAbsolutePath())
+ .put("http.enabled", false)
+ .put("index.store.type", "ram")
+ .put("gateway.type", "none")
+ .build();
+
+ try (Node node = NodeBuilder.nodeBuilder().local(true).data(true).settings(settings).build()) {
+ node.start();
+
+ assertAcked(node.client().admin().indices().prepareCreate("index").addMapping("type", "h", "type=string").get());
+ final GetFieldMappingsResponse response = node.client().admin().indices().prepareGetFieldMappings("index").setTypes("type").setFields("f", "g", "h").get();
+ System.out.println(response.mappings());
+ for (String field : Arrays.asList("f", "g", "h")) {
+ logger.info("Checking field " + field);
+ FieldMappingMetaData fMappings = response.fieldMappings("index", "type", field);
+ assertNotNull(fMappings);
+ assertEquals(field, fMappings.fullName());
+ }
+ }
+ } finally {
+ FileSystemUtils.deleteRecursively(configDir);
+ }
+ }
+
+}
diff --git a/src/test/java/org/elasticsearch/index/mapper/externalvalues/ExternalRootMapper.java b/src/test/java/org/elasticsearch/index/mapper/externalvalues/ExternalRootMapper.java
new file mode 100644
index 0000000000000..cb9596917c92c
--- /dev/null
+++ b/src/test/java/org/elasticsearch/index/mapper/externalvalues/ExternalRootMapper.java
@@ -0,0 +1,105 @@
+/*
+ * Licensed to Elasticsearch under one or more contributor
+ * license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright
+ * ownership. Elasticsearch 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.elasticsearch.index.mapper.externalvalues;
+
+import org.apache.lucene.document.Field.Store;
+import org.apache.lucene.document.StringField;
+import org.elasticsearch.common.xcontent.XContentBuilder;
+import org.elasticsearch.index.mapper.*;
+
+import java.io.IOException;
+import java.util.Map;
+
+public class ExternalRootMapper implements RootMapper {
+
+ static final String CONTENT_TYPE = "_external_root";
+ static final String FIELD_NAME = "_is_external";
+ static final String FIELD_VALUE = "true";
+
+ @Override
+ public String name() {
+ return CONTENT_TYPE;
+ }
+
+ @Override
+ public void parse(ParseContext context) throws IOException {
+ }
+
+ @Override
+ public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException {
+ if (!(mergeWith instanceof ExternalRootMapper)) {
+ mergeContext.addConflict("Trying to merge " + mergeWith + " with " + this);
+ }
+ }
+
+ @Override
+ public void traverse(FieldMapperListener fieldMapperListener) {
+ }
+
+ @Override
+ public void traverse(ObjectMapperListener objectMapperListener) {
+ }
+
+ @Override
+ public void close() {
+ }
+
+ @Override
+ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
+ return builder.startObject(CONTENT_TYPE).endObject();
+ }
+
+ @Override
+ public void preParse(ParseContext context) throws IOException {
+ }
+
+ @Override
+ public void postParse(ParseContext context) throws IOException {
+ context.doc().add(new StringField(FIELD_NAME, FIELD_VALUE, Store.YES));
+ }
+
+ @Override
+ public boolean includeInObject() {
+ return false;
+ }
+
+ public static class Builder extends Mapper.Builder<Builder, ExternalRootMapper> {
+
+ protected Builder() {
+ super(CONTENT_TYPE);
+ }
+
+ @Override
+ public ExternalRootMapper build(BuilderContext context) {
+ return new ExternalRootMapper();
+ }
+
+ }
+
+ public static class TypeParser implements Mapper.TypeParser {
+
+ @Override
+ public Mapper.Builder<?, ?> parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
+ return new Builder();
+ }
+
+ }
+
+}
diff --git a/src/test/java/org/elasticsearch/index/mapper/externalvalues/ExternalValuesMapperIntegrationTests.java b/src/test/java/org/elasticsearch/index/mapper/externalvalues/ExternalValuesMapperIntegrationTests.java
index 5d61f770909a5..d92c5a0fa6961 100644
--- a/src/test/java/org/elasticsearch/index/mapper/externalvalues/ExternalValuesMapperIntegrationTests.java
+++ b/src/test/java/org/elasticsearch/index/mapper/externalvalues/ExternalValuesMapperIntegrationTests.java
@@ -49,6 +49,8 @@ protected Settings nodeSettings(int nodeOrdinal) {
public void testExternalValues() throws Exception {
prepareCreate("test-idx").addMapping("type",
XContentFactory.jsonBuilder().startObject().startObject("type")
+ .startObject(ExternalRootMapper.CONTENT_TYPE)
+ .endObject()
.startObject("properties")
.startObject("field").field("type", RegisterExternalTypes.EXTERNAL).endObject()
.endObject()
diff --git a/src/test/java/org/elasticsearch/index/mapper/externalvalues/RegisterExternalTypes.java b/src/test/java/org/elasticsearch/index/mapper/externalvalues/RegisterExternalTypes.java
index 8a9ed9cac8e55..5cd8110a37166 100755
--- a/src/test/java/org/elasticsearch/index/mapper/externalvalues/RegisterExternalTypes.java
+++ b/src/test/java/org/elasticsearch/index/mapper/externalvalues/RegisterExternalTypes.java
@@ -35,6 +35,7 @@ public class RegisterExternalTypes extends AbstractIndexComponent {
public RegisterExternalTypes(Index index, @IndexSettings Settings indexSettings, MapperService mapperService) {
super(index, indexSettings);
+ mapperService.documentMapperParser().putRootTypeParser(ExternalRootMapper.CONTENT_TYPE, new ExternalRootMapper.TypeParser());
mapperService.documentMapperParser().putTypeParser(EXTERNAL, new ExternalMapper.TypeParser(EXTERNAL, "foo"));
mapperService.documentMapperParser().putTypeParser(EXTERNAL_BIS, new ExternalMapper.TypeParser(EXTERNAL_BIS, "bar"));
mapperService.documentMapperParser().putTypeParser(EXTERNAL_UPPER, new ExternalMapper.TypeParser(EXTERNAL_UPPER, "FOO BAR"));
diff --git a/src/test/java/org/elasticsearch/index/mapper/externalvalues/SimpleExternalMappingTests.java b/src/test/java/org/elasticsearch/index/mapper/externalvalues/SimpleExternalMappingTests.java
index 504bf4f4a368a..d9765dcb96b13 100644
--- a/src/test/java/org/elasticsearch/index/mapper/externalvalues/SimpleExternalMappingTests.java
+++ b/src/test/java/org/elasticsearch/index/mapper/externalvalues/SimpleExternalMappingTests.java
@@ -36,11 +36,15 @@ public class SimpleExternalMappingTests extends ElasticsearchSingleNodeLuceneTes
@Test
public void testExternalValues() throws Exception {
MapperService mapperService = createIndex("test").mapperService();
+ mapperService.documentMapperParser().putRootTypeParser(ExternalRootMapper.CONTENT_TYPE,
+ new ExternalRootMapper.TypeParser());
mapperService.documentMapperParser().putTypeParser(RegisterExternalTypes.EXTERNAL,
new ExternalMapper.TypeParser(RegisterExternalTypes.EXTERNAL, "foo"));
DocumentMapper documentMapper = mapperService.documentMapperParser().parse(
XContentFactory.jsonBuilder().startObject().startObject("type")
+ .startObject(ExternalRootMapper.CONTENT_TYPE)
+ .endObject()
.startObject("properties")
.startObject("field").field("type", "external").endObject()
.endObject()
@@ -64,6 +68,7 @@ public void testExternalValues() throws Exception {
assertThat(doc.rootDoc().getField("field.field"), notNullValue());
assertThat(doc.rootDoc().getField("field.field").stringValue(), is("foo"));
+ assertThat(doc.rootDoc().getField(ExternalRootMapper.FIELD_NAME).stringValue(), is(ExternalRootMapper.FIELD_VALUE));
}
diff --git a/src/test/java/org/elasticsearch/index/merge/policy/MergePolicySettingsTest.java b/src/test/java/org/elasticsearch/index/merge/policy/MergePolicySettingsTest.java
index e62aca50b1d5c..46d55f996887f 100644
--- a/src/test/java/org/elasticsearch/index/merge/policy/MergePolicySettingsTest.java
+++ b/src/test/java/org/elasticsearch/index/merge/policy/MergePolicySettingsTest.java
@@ -34,9 +34,7 @@
import java.io.IOException;
import static org.elasticsearch.common.settings.ImmutableSettings.Builder.EMPTY_SETTINGS;
-import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.is;
public class MergePolicySettingsTest extends ElasticsearchTestCase {
@@ -174,7 +172,7 @@ public Settings build(boolean value) {
protected Store createStore(Settings settings) throws IOException {
DirectoryService directoryService = new RamDirectoryService(shardId, EMPTY_SETTINGS);
- return new Store(shardId, settings, null, null, directoryService, new LeastUsedDistributor(directoryService));
+ return new Store(shardId, settings, null, directoryService, new LeastUsedDistributor(directoryService));
}
}
diff --git a/src/test/java/org/elasticsearch/index/store/StoreTest.java b/src/test/java/org/elasticsearch/index/store/StoreTest.java
index 2d31689c5b655..292dd0d9c621e 100644
--- a/src/test/java/org/elasticsearch/index/store/StoreTest.java
+++ b/src/test/java/org/elasticsearch/index/store/StoreTest.java
@@ -40,12 +40,65 @@
import java.nio.file.NoSuchFileException;
import java.util.*;
+import static com.carrotsearch.randomizedtesting.RandomizedTest.randomBoolean;
import static com.carrotsearch.randomizedtesting.RandomizedTest.randomInt;
import static com.carrotsearch.randomizedtesting.RandomizedTest.randomIntBetween;
import static org.hamcrest.Matchers.*;
public class StoreTest extends ElasticsearchLuceneTestCase {
+ @Test
+ public void testRefCount() throws IOException {
+ final ShardId shardId = new ShardId(new Index("index"), 1);
+ DirectoryService directoryService = new LuceneManagedDirectoryService(random());
+ Store store = new Store(shardId, ImmutableSettings.EMPTY, null, directoryService, randomDistributor(directoryService));
+ int incs = randomIntBetween(1, 100);
+ for (int i = 0; i < incs; i++) {
+ if (randomBoolean()) {
+ store.incRef();
+ } else {
+ assertTrue(store.tryIncRef());
+ }
+ store.ensureOpen();
+ }
+
+ for (int i = 0; i < incs; i++) {
+ store.decRef();
+ store.ensureOpen();
+ }
+
+ store.incRef();
+ store.close();
+ for (int i = 0; i < incs; i++) {
+ if (randomBoolean()) {
+ store.incRef();
+ } else {
+ assertTrue(store.tryIncRef());
+ }
+ store.ensureOpen();
+ }
+
+ for (int i = 0; i < incs; i++) {
+ store.decRef();
+ store.ensureOpen();
+ }
+
+ store.decRef();
+ assertFalse(store.tryIncRef());
+ try {
+ store.incRef();
+ fail(" expected exception");
+ } catch (AlreadyClosedException ex) {
+
+ }
+ try {
+ store.ensureOpen();
+ fail(" expected exception");
+ } catch (AlreadyClosedException ex) {
+
+ }
+ }
+
@Test
public void testVerifyingIndexOutput() throws IOException {
Directory dir = newDirectory();
@@ -106,7 +159,7 @@ public void testVerifyingIndexOutputWithBogusInput() throws IOException {
public void testWriteLegacyChecksums() throws IOException {
final ShardId shardId = new ShardId(new Index("index"), 1);
DirectoryService directoryService = new LuceneManagedDirectoryService(random());
- Store store = new Store(shardId, ImmutableSettings.EMPTY, null, null, directoryService, randomDistributor(directoryService));
+ Store store = new Store(shardId, ImmutableSettings.EMPTY, null, directoryService, randomDistributor(directoryService));
// set default codec - all segments need checksums
IndexWriter writer = new IndexWriter(store.directory(), newIndexWriterConfig(random(), TEST_VERSION_CURRENT, new MockAnalyzer(random())).setCodec(actualDefaultCodec()));
int docs = 1 + random().nextInt(100);
@@ -169,7 +222,7 @@ public void testWriteLegacyChecksums() throws IOException {
public void testNewChecksums() throws IOException {
final ShardId shardId = new ShardId(new Index("index"), 1);
DirectoryService directoryService = new LuceneManagedDirectoryService(random());
- Store store = new Store(shardId, ImmutableSettings.EMPTY, null, null, directoryService, randomDistributor(directoryService));
+ Store store = new Store(shardId, ImmutableSettings.EMPTY, null, directoryService, randomDistributor(directoryService));
// set default codec - all segments need checksums
IndexWriter writer = new IndexWriter(store.directory(), newIndexWriterConfig(random(), TEST_VERSION_CURRENT, new MockAnalyzer(random())).setCodec(actualDefaultCodec()));
int docs = 1 + random().nextInt(100);
@@ -224,7 +277,7 @@ public void testNewChecksums() throws IOException {
public void testMixedChecksums() throws IOException {
final ShardId shardId = new ShardId(new Index("index"), 1);
DirectoryService directoryService = new LuceneManagedDirectoryService(random());
- Store store = new Store(shardId, ImmutableSettings.EMPTY, null, null, directoryService, randomDistributor(directoryService));
+ Store store = new Store(shardId, ImmutableSettings.EMPTY, null, directoryService, randomDistributor(directoryService));
// this time random codec....
IndexWriter writer = new IndexWriter(store.directory(), newIndexWriterConfig(random(), TEST_VERSION_CURRENT, new MockAnalyzer(random())).setCodec(actualDefaultCodec()));
int docs = 1 + random().nextInt(100);
@@ -310,7 +363,7 @@ public void testMixedChecksums() throws IOException {
public void testRenameFile() throws IOException {
final ShardId shardId = new ShardId(new Index("index"), 1);
DirectoryService directoryService = new LuceneManagedDirectoryService(random(), false);
- Store store = new Store(shardId, ImmutableSettings.EMPTY, null, null, directoryService, randomDistributor(directoryService));
+ Store store = new Store(shardId, ImmutableSettings.EMPTY, null, directoryService, randomDistributor(directoryService));
{
IndexOutput output = store.directory().createOutput("foo.bar", IOContext.DEFAULT);
int iters = scaledRandomIntBetween(10, 100);
@@ -528,7 +581,7 @@ public void testRecoveryDiff() throws IOException, InterruptedException {
iwc.setMaxThreadStates(1);
final ShardId shardId = new ShardId(new Index("index"), 1);
DirectoryService directoryService = new LuceneManagedDirectoryService(random);
- Store store = new Store(shardId, ImmutableSettings.EMPTY, null, null, directoryService, randomDistributor(random, directoryService));
+ Store store = new Store(shardId, ImmutableSettings.EMPTY, null, directoryService, randomDistributor(random, directoryService));
IndexWriter writer = new IndexWriter(store.directory(), iwc);
final boolean lotsOfSegments = rarely(random);
for (Document d : docs) {
@@ -558,7 +611,7 @@ public void testRecoveryDiff() throws IOException, InterruptedException {
iwc.setMaxThreadStates(1);
final ShardId shardId = new ShardId(new Index("index"), 1);
DirectoryService directoryService = new LuceneManagedDirectoryService(random);
- store = new Store(shardId, ImmutableSettings.EMPTY, null, null, directoryService, randomDistributor(random, directoryService));
+ store = new Store(shardId, ImmutableSettings.EMPTY, null, directoryService, randomDistributor(random, directoryService));
IndexWriter writer = new IndexWriter(store.directory(), iwc);
final boolean lotsOfSegments = rarely(random);
for (Document d : docs) {
diff --git a/src/test/java/org/elasticsearch/script/IndexedScriptTests.java b/src/test/java/org/elasticsearch/script/IndexedScriptTests.java
index e879ccb035f11..3024b0ec6dc8f 100644
--- a/src/test/java/org/elasticsearch/script/IndexedScriptTests.java
+++ b/src/test/java/org/elasticsearch/script/IndexedScriptTests.java
@@ -22,6 +22,7 @@
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
+import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.test.ElasticsearchIntegrationTest;
import org.junit.Test;
@@ -40,7 +41,7 @@ public void testFieldIndexedScript() throws ExecutionException, InterruptedExce
List<IndexRequestBuilder> builders = new ArrayList();
builders.add(client().prepareIndex(ScriptService.SCRIPT_INDEX, "groovy", "script1").setSource("{" +
"\"script\":\"2\""+
- "}"));
+ "}").setTimeout(TimeValue.timeValueSeconds(randomIntBetween(2,10))));
builders.add(client().prepareIndex(ScriptService.SCRIPT_INDEX, "groovy", "script2").setSource("{" +
"\"script\":\"factor*2\""+
diff --git a/src/test/java/org/elasticsearch/search/geo/GeoPolygonTests.java b/src/test/java/org/elasticsearch/search/geo/GeoPolygonTests.java
new file mode 100644
index 0000000000000..d370041a24a13
--- /dev/null
+++ b/src/test/java/org/elasticsearch/search/geo/GeoPolygonTests.java
@@ -0,0 +1,104 @@
+/*
+ * Licensed to Elasticsearch under one or more contributor
+ * license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright
+ * ownership. Elasticsearch 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.elasticsearch.search.geo;
+
+import org.elasticsearch.action.search.SearchResponse;
+import org.elasticsearch.common.xcontent.XContentBuilder;
+import org.elasticsearch.common.xcontent.XContentFactory;
+import org.elasticsearch.search.SearchHit;
+import org.elasticsearch.test.ElasticsearchIntegrationTest;
+import org.junit.Test;
+
+import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
+import static org.elasticsearch.index.query.FilterBuilders.geoPolygonFilter;
+import static org.elasticsearch.index.query.QueryBuilders.filteredQuery;
+import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
+import static org.hamcrest.Matchers.anyOf;
+import static org.hamcrest.Matchers.equalTo;
+
[email protected]
+public class GeoPolygonTests extends ElasticsearchIntegrationTest {
+
+ @Override
+ protected void setupSuiteScopeCluster() throws Exception {
+ XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().startObject("type1")
+ .startObject("properties").startObject("location").field("type", "geo_point").field("lat_lon", true)
+ .startObject("fielddata").field("format", randomNumericFieldDataFormat()).endObject().endObject().endObject()
+ .endObject().endObject();
+ assertAcked(prepareCreate("test").addMapping("type1", xContentBuilder));
+ ensureGreen();
+
+ indexRandom(true, client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject()
+ .field("name", "New York")
+ .startObject("location").field("lat", 40.714).field("lon", -74.006).endObject()
+ .endObject()),
+ // to NY: 5.286 km
+ client().prepareIndex("test", "type1", "2").setSource(jsonBuilder().startObject()
+ .field("name", "Times Square")
+ .startObject("location").field("lat", 40.759).field("lon", -73.984).endObject()
+ .endObject()),
+ // to NY: 0.4621 km
+ client().prepareIndex("test", "type1", "3").setSource(jsonBuilder().startObject()
+ .field("name", "Tribeca")
+ .startObject("location").field("lat", 40.718).field("lon", -74.008).endObject()
+ .endObject()),
+ // to NY: 1.055 km
+ client().prepareIndex("test", "type1", "4").setSource(jsonBuilder().startObject()
+ .field("name", "Wall Street")
+ .startObject("location").field("lat", 40.705).field("lon", -74.009).endObject()
+ .endObject()),
+ // to NY: 1.258 km
+ client().prepareIndex("test", "type1", "5").setSource(jsonBuilder().startObject()
+ .field("name", "Soho")
+ .startObject("location").field("lat", 40.725).field("lon", -74).endObject()
+ .endObject()),
+ // to NY: 2.029 km
+ client().prepareIndex("test", "type1", "6").setSource(jsonBuilder().startObject()
+ .field("name", "Greenwich Village")
+ .startObject("location").field("lat", 40.731).field("lon", -73.996).endObject()
+ .endObject()),
+ // to NY: 8.572 km
+ client().prepareIndex("test", "type1", "7").setSource(jsonBuilder().startObject()
+ .field("name", "Brooklyn")
+ .startObject("location").field("lat", 40.65).field("lon", -73.95).endObject()
+ .endObject()));
+ ensureSearchable("test");
+ }
+
+ @Test
+ public void simplePolygonTest() throws Exception {
+
+ SearchResponse searchResponse = client().prepareSearch("test") // from NY
+ .setQuery(filteredQuery(matchAllQuery(), geoPolygonFilter("location")
+ .addPoint(40.7, -74.0)
+ .addPoint(40.7, -74.1)
+ .addPoint(40.8, -74.1)
+ .addPoint(40.8, -74.0)
+ .addPoint(40.7, -74.0)))
+ .execute().actionGet();
+ assertHitCount(searchResponse, 4);
+ assertThat(searchResponse.getHits().hits().length, equalTo(4));
+ for (SearchHit hit : searchResponse.getHits()) {
+ assertThat(hit.id(), anyOf(equalTo("1"), equalTo("3"), equalTo("4"), equalTo("5")));
+ }
+ }
+}
diff --git a/src/test/java/org/elasticsearch/search/query/SimpleQueryTests.java b/src/test/java/org/elasticsearch/search/query/SimpleQueryTests.java
index e53c36c50873f..ae6d8addb5ac2 100644
--- a/src/test/java/org/elasticsearch/search/query/SimpleQueryTests.java
+++ b/src/test/java/org/elasticsearch/search/query/SimpleQueryTests.java
@@ -2089,6 +2089,15 @@ public void testSimpleQueryString() throws ExecutionException, InterruptedExcept
assertFirstHit(searchResponse, hasId("5"));
assertSearchHits(searchResponse, "5", "6");
assertThat(searchResponse.getHits().getAt(0).getMatchedQueries()[0], equalTo("myquery"));
+
+ searchResponse = client().prepareSearch().setQuery(simpleQueryString("spaghetti").field("*body")).get();
+ assertHitCount(searchResponse, 2l);
+ assertSearchHits(searchResponse, "5", "6");
+
+ // Have to bypass the builder here because the builder always uses "fields" instead of "field"
+ searchResponse = client().prepareSearch().setQuery("{\"simple_query_string\": {\"query\": \"spaghetti\", \"field\": \"_all\"}}").get();
+ assertHitCount(searchResponse, 2l);
+ assertSearchHits(searchResponse, "5", "6");
}
@Test
@@ -2192,6 +2201,11 @@ public void testSimpleQueryStringFlags() throws ExecutionException, InterruptedE
assertHitCount(searchResponse, 3l);
assertSearchHits(searchResponse, "1", "2", "3");
+ // Sending a negative 'flags' value is the same as SimpleQueryStringFlag.ALL
+ searchResponse = client().prepareSearch().setQuery("{\"simple_query_string\": {\"query\": \"foo bar\", \"flags\": -1}}").get();
+ assertHitCount(searchResponse, 3l);
+ assertSearchHits(searchResponse, "1", "2", "3");
+
searchResponse = client().prepareSearch().setQuery(
simpleQueryString("foo | bar")
.defaultOperator(SimpleQueryStringBuilder.Operator.AND)
diff --git a/src/test/java/org/elasticsearch/test/ElasticsearchIntegrationTest.java b/src/test/java/org/elasticsearch/test/ElasticsearchIntegrationTest.java
index 88108512bfb68..7d1ed84e1b3f0 100644
--- a/src/test/java/org/elasticsearch/test/ElasticsearchIntegrationTest.java
+++ b/src/test/java/org/elasticsearch/test/ElasticsearchIntegrationTest.java
@@ -75,12 +75,11 @@
import org.elasticsearch.discovery.zen.elect.ElectMasterService;
import org.elasticsearch.index.codec.CodecService;
import org.elasticsearch.index.fielddata.FieldDataType;
+import org.elasticsearch.index.fielddata.IndexFieldDataService;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.mapper.FieldMapper.Loading;
-import org.elasticsearch.index.mapper.internal.FieldNamesFieldMapper;
-import org.elasticsearch.index.mapper.internal.IdFieldMapper;
-import org.elasticsearch.index.mapper.internal.TypeFieldMapper;
+import org.elasticsearch.index.mapper.internal.*;
import org.elasticsearch.index.merge.policy.*;
import org.elasticsearch.index.merge.scheduler.ConcurrentMergeSchedulerProvider;
import org.elasticsearch.index.merge.scheduler.MergeSchedulerModule;
@@ -95,6 +94,7 @@
import org.elasticsearch.indices.recovery.RecoverySettings;
import org.elasticsearch.indices.store.IndicesStore;
import org.elasticsearch.rest.RestStatus;
+import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.SearchService;
import org.elasticsearch.test.client.RandomizingClient;
import org.hamcrest.Matchers;
@@ -344,6 +344,29 @@ private void randomIndexTemplate() throws IOException {
.field("index", randomFrom("no", "not_analyzed"))
.endObject();
}
+ if (randomBoolean()) {
+ mappings.startObject(TimestampFieldMapper.NAME)
+ .field("enabled", randomBoolean())
+ .startObject("fielddata")
+ .field(FieldDataType.FORMAT_KEY, randomFrom("array", "doc_values"))
+ .endObject()
+ .endObject();
+ }
+ if (randomBoolean()) {
+ mappings.startObject(SizeFieldMapper.NAME)
+ .field("enabled", randomBoolean())
+ .endObject();
+ }
+ if (randomBoolean()) {
+ mappings.startObject(AllFieldMapper.NAME)
+ .field("auto_boost", true)
+ .endObject();
+ }
+ if (randomBoolean()) {
+ mappings.startObject(SourceFieldMapper.NAME)
+ .field("compress", randomBoolean())
+ .endObject();
+ }
if (compatibilityVersion().onOrAfter(Version.V_1_3_0)) {
mappings.startObject(FieldNamesFieldMapper.NAME)
.startObject("fielddata")
@@ -420,6 +443,7 @@ private static ImmutableSettings.Builder setRandomSettings(Random random, Immuta
setRandomMerge(random, builder);
setRandomTranslogSettings(random, builder);
setRandomNormsLoading(random, builder);
+ setRandomScriptingSettings(random, builder);
if (random.nextBoolean()) {
if (random.nextInt(10) == 0) { // do something crazy slow here
builder.put(IndicesStore.INDICES_STORE_THROTTLE_MAX_BYTES_PER_SEC, new ByteSizeValue(RandomInts.randomIntBetween(random, 1, 10), ByteSizeUnit.MB));
@@ -453,6 +477,23 @@ private static ImmutableSettings.Builder setRandomSettings(Random random, Immuta
builder.put(IndicesQueryCache.INDEX_CACHE_QUERY_ENABLED, random.nextBoolean());
}
+ if (random.nextBoolean()) {
+ builder.put(IndexFieldDataService.FIELDDATA_CACHE_KEY, randomFrom(
+ IndexFieldDataService.FIELDDATA_CACHE_VALUE_NODE,
+ IndexFieldDataService.FIELDDATA_CACHE_VALUE_RESIDENT,
+ IndexFieldDataService.FIELDDATA_CACHE_VALUE_SOFT));
+ }
+
+ return builder;
+ }
+
+ private static ImmutableSettings.Builder setRandomScriptingSettings(Random random, ImmutableSettings.Builder builder) {
+ if (random.nextBoolean()) {
+ builder.put(ScriptService.SCRIPT_CACHE_SIZE_SETTING, RandomInts.randomIntBetween(random, -100, 2000));
+ }
+ if (random.nextBoolean()) {
+ builder.put(ScriptService.SCRIPT_CACHE_EXPIRE_SETTING, TimeValue.timeValueMillis(RandomInts.randomIntBetween(random, 750, 10000000)));
+ }
return builder;
}
diff --git a/src/test/java/org/elasticsearch/test/hamcrest/ElasticsearchGeoAssertions.java b/src/test/java/org/elasticsearch/test/hamcrest/ElasticsearchGeoAssertions.java
index e4cb23b921fec..1c3c636beee9a 100644
--- a/src/test/java/org/elasticsearch/test/hamcrest/ElasticsearchGeoAssertions.java
+++ b/src/test/java/org/elasticsearch/test/hamcrest/ElasticsearchGeoAssertions.java
@@ -21,6 +21,8 @@
import com.spatial4j.core.shape.Shape;
import com.spatial4j.core.shape.ShapeCollection;
+import com.spatial4j.core.shape.impl.GeoCircle;
+import com.spatial4j.core.shape.impl.RectangleImpl;
import com.spatial4j.core.shape.jts.JtsGeometry;
import com.spatial4j.core.shape.jts.JtsPoint;
import com.vividsolutions.jts.geom.*;
@@ -197,6 +199,10 @@ public static void assertEquals(Shape s1, Shape s2) {
Assert.assertEquals(p1, p2);
} else if (s1 instanceof ShapeCollection && s2 instanceof ShapeCollection) {
assertEquals((ShapeCollection)s1, (ShapeCollection)s2);
+ } else if (s1 instanceof GeoCircle && s2 instanceof GeoCircle) {
+ Assert.assertEquals((GeoCircle)s1, (GeoCircle)s2);
+ } else if (s1 instanceof RectangleImpl && s2 instanceof RectangleImpl) {
+ Assert.assertEquals((RectangleImpl)s1, (RectangleImpl)s2);
} else {
//We want to know the type of the shape because we test shape equality in a special way...
//... in particular we test that one ring is equivalent to another ring even if the points are rotated or reversed.
diff --git a/src/test/java/org/elasticsearch/test/store/MockRamIndexStore.java b/src/test/java/org/elasticsearch/test/store/MockRamIndexStore.java
index 51aacad21804c..a8ce2ac036210 100644
--- a/src/test/java/org/elasticsearch/test/store/MockRamIndexStore.java
+++ b/src/test/java/org/elasticsearch/test/store/MockRamIndexStore.java
@@ -20,16 +20,12 @@
package org.elasticsearch.test.store;
import org.elasticsearch.common.inject.Inject;
-
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.service.IndexService;
import org.elasticsearch.index.store.DirectoryService;
import org.elasticsearch.index.store.support.AbstractIndexStore;
import org.elasticsearch.indices.store.IndicesStore;
-import org.elasticsearch.monitor.jvm.JvmInfo;
-import org.elasticsearch.monitor.jvm.JvmStats;
public class MockRamIndexStore extends AbstractIndexStore{
@@ -47,15 +43,4 @@ public boolean persistent() {
public Class<? extends DirectoryService> shardDirectory() {
return MockRamDirectoryService.class;
}
-
- @Override
- public ByteSizeValue backingStoreTotalSpace() {
- return JvmInfo.jvmInfo().getMem().heapMax();
- }
-
- @Override
- public ByteSizeValue backingStoreFreeSpace() {
- return JvmStats.jvmStats().getMem().heapUsed();
- }
-
}
|
c727419b47232670c44f5f7eb1d512cc20d780c9
|
arrayexpress$annotare2
|
Added some flexibility with scan protocol assignment; will assign to raw files, or (if none uploaded) to processed files
|
p
|
https://github.com/arrayexpress/annotare2
|
diff --git a/app/om/src/main/java/uk/ac/ebi/fg/annotare2/submission/model/ExperimentProfile.java b/app/om/src/main/java/uk/ac/ebi/fg/annotare2/submission/model/ExperimentProfile.java
index 076abe703..5848a858e 100644
--- a/app/om/src/main/java/uk/ac/ebi/fg/annotare2/submission/model/ExperimentProfile.java
+++ b/app/om/src/main/java/uk/ac/ebi/fg/annotare2/submission/model/ExperimentProfile.java
@@ -28,7 +28,6 @@
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.collect.Maps.newLinkedHashMap;
-import static com.google.common.collect.Sets.newHashSet;
import static com.google.common.collect.Sets.newLinkedHashSet;
import static java.util.Collections.unmodifiableCollection;
import static java.util.Collections.unmodifiableSet;
@@ -232,7 +231,7 @@ public Sample createSample() {
public Extract createExtract(Sample... samples) {
if (samples.length == 0) {
- throw new IllegalArgumentException("Can't create empty extract");
+ throw new IllegalArgumentException("Unable to create empty extract");
}
Extract extract = new Extract(nextId());
extractMap.put(extract.getId(), extract);
@@ -434,8 +433,16 @@ public Collection<Protocol> getProtocols() {
return list;
}
- public Collection<Protocol> getProtocolsByType(ProtocolSubjectType type) {
- return type.filter(getProtocols());
+ public Collection<Protocol> getProtocolsByType(ProtocolSubjectType... type) {
+ Set<ProtocolSubjectType> filter = new HashSet<ProtocolSubjectType>(Arrays.asList(type));
+ List<Protocol> list = newArrayList();
+ for (Integer id : protocolOrder) {
+ Protocol protocol = protocolMap.get(id);
+ if (filter.contains(protocol.getSubjectType())) {
+ list.add(protocol);
+ }
+ }
+ return list;
}
public Collection<Sample> getSamples() {
@@ -514,9 +521,6 @@ public Set<FileRef> getFileRefs(Protocol protocol) {
}
public Set<Protocol> getProtocols(Sample sample) {
- if (sample == null) {
- return getProtocols(ProtocolSubjectType.SAMPLE);
- }
Collection<Protocol> sampleProtocols = getProtocolsByType(ProtocolSubjectType.SAMPLE);
Set<Protocol> protocols = newLinkedHashSet();
for (Protocol p : sampleProtocols) {
@@ -529,9 +533,6 @@ public Set<Protocol> getProtocols(Sample sample) {
}
public Set<Protocol> getProtocols(Extract extract) {
- if (extract == null) {
- return getProtocols(ProtocolSubjectType.EXTRACT);
- }
Collection<Protocol> extractProtocols = getProtocolsByType(ProtocolSubjectType.EXTRACT);
Set<Protocol> protocols = newLinkedHashSet();
for (Protocol p : extractProtocols) {
@@ -544,9 +545,6 @@ public Set<Protocol> getProtocols(Extract extract) {
}
public Set<Protocol> getProtocols(LabeledExtract labeledExtract) {
- if (labeledExtract == null) {
- return getProtocols(ProtocolSubjectType.LABELED_EXTRACT);
- }
Collection<Protocol> labelExtractProtocols = getProtocolsByType(ProtocolSubjectType.LABELED_EXTRACT);
Set<Protocol> protocols = newLinkedHashSet();
for (Protocol p : labelExtractProtocols) {
@@ -557,17 +555,18 @@ public Set<Protocol> getProtocols(LabeledExtract labeledExtract) {
return protocols;
}
- public Set<Protocol> getProtocols(ProtocolSubjectType type) {
- Collection<Protocol> protocolsByType = getProtocolsByType(type);
- Set<Protocol> protocols = newHashSet();
- for (Protocol p : protocolsByType) {
- p.setAssigned(!protocol2Samples.containsKey(p));
+ public Set<Protocol> getProtocols(FileRef fileRef, ProtocolSubjectType subjectType) {
+ Collection<Protocol> fileProtocols = getProtocolsByType(subjectType);
+
+ Set<Protocol> protocols = newLinkedHashSet();
+ for (Protocol p : fileProtocols) {
+ Set<FileRef> fileRefs = protocol2FileRefs.get(p);
+ p.setAssigned(fileRefs.isEmpty() || fileRefs.contains(fileRef));
protocols.add(p);
}
return protocols;
}
-
public void assignProtocol2Samples(Protocol protocol, Collection<Sample> samples) {
Set<Sample> set = new HashSet<Sample>();
set.addAll(samples);
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/magetab/MageTabGenerator.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/magetab/MageTabGenerator.java
index 6eb279f5e..a9f708aa7 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/magetab/MageTabGenerator.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/magetab/MageTabGenerator.java
@@ -293,23 +293,35 @@ private Map<String, SDRFNode> generateLabeledExtractNodes(Map<Integer, SDRFNode>
}
private Map<String, SDRFNode> generateMicroarrayAssayNodes(Map<String, SDRFNode> labeledExtractLayer) {
+ // no labeled extracts supplied? no assays can be generated
if (labeledExtractLayer.isEmpty()) {
return emptyMap();
}
- FileColumn fileColumn = getFirstFileColumn();
- if (null == fileColumn) {
+ // no files uploaded? no assays can be generated
+ if (exp.getFileColumns().isEmpty()) {
return emptyMap();
}
+ Collection<FileColumn> fileColumns = exp.getFileColumns(FileType.RAW_FILE);
+ if (fileColumns.isEmpty()) {
+ fileColumns = exp.getFileColumns(FileType.PROCESSED_FILE);
+ }
+ if (fileColumns.isEmpty()) {
+ fileColumns =
+ }
+
+
Map<String, SDRFNode> layer = new LinkedHashMap<String, SDRFNode>();
int fakeId = -1;
for (String labeledExtractId : labeledExtractLayer.keySet()) {
LabeledExtract labeledExtract = exp.getLabeledExtract(labeledExtractId);
+
SDRFNode labeledExtractNode = labeledExtractLayer.get(labeledExtractId);
Collection<Protocol> protocols = exp.getProtocols(labeledExtract);
- FileRef file = (labeledExtract == null) ? null : fileColumn.getFileRef(labeledExtract.getId());
+ FileRef file = null;
+ //(labeledExtract == null) ? null : fileColumn.getFileRef(labeledExtract.getId());
if (null != file) {
layer.put(labeledExtract.getId(),
createAssayNode(labeledExtract,
@@ -325,12 +337,12 @@ private Map<String, SDRFNode> generateMicroarrayAssayNodes(Map<String, SDRFNode>
return layer;
}
- private FileColumn getFirstFileColumn() {
- Collection<FileColumn> columns = sortFileColumns(
- exp.getFileColumns()
- );
- return columns.isEmpty() ? null : columns.iterator().next();
- }
+ //private FileColumn getFirstFileColumn() {
+ // Collection<FileColumn> columns = sortFileColumns(
+ // exp.getFileColumns()
+ // );
+ // return columns.isEmpty() ? null : columns.iterator().next();
+ //}
private String removeExtension(String fileName) {
return (null != fileName ? fileName.replaceAll("^(.+)[.][^.]*$", "$1") : null);
|
bfbc5024840ee4f60d52377b1192d8650451cb13
|
Delta Spike
|
DELTASPIKE-277 add missing beans.xml
|
p
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/modules/jsf/api/src/main/resources/META-INF/beans.xml b/deltaspike/modules/jsf/api/src/main/resources/META-INF/beans.xml
new file mode 100644
index 000000000..407073011
--- /dev/null
+++ b/deltaspike/modules/jsf/api/src/main/resources/META-INF/beans.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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.
+-->
+<beans xmlns="http://java.sun.com/xml/ns/javaee"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
+</beans>
|
7487bb42329c5c1ea23e4196e22ebba99ca65433
|
bendisposto$prob
|
added drag and drop support between observer
|
a
|
https://github.com/hhu-stups/prob-rodinplugin
|
diff --git a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/action/BMotionObserverWizard.java b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/action/BMotionObserverWizard.java
index f3858835..154c8f27 100644
--- a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/action/BMotionObserverWizard.java
+++ b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/action/BMotionObserverWizard.java
@@ -8,6 +8,7 @@
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.wizard.IWizard;
+import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbenchPart;
@@ -15,6 +16,7 @@ public class BMotionObserverWizard extends BMotionAbstractWizard {
public BMotionObserverWizard(IWorkbenchPart workbenchPart, IWizard newWizard) {
super(workbenchPart, newWizard);
+ setShellStyle(SWT.CLOSE);
setDeleteToolTip("Delete Observer");
}
diff --git a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/action/ObserverAction.java b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/action/ObserverAction.java
index d0dcaa4f..60d41ba1 100644
--- a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/action/ObserverAction.java
+++ b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/action/ObserverAction.java
@@ -28,6 +28,7 @@ public class ObserverAction extends SelectionAction {
private String className;
private Observer clonedObserver;
private Observer newObserver;
+ private BControl actionControl;
public ObserverAction(IWorkbenchPart part) {
super(part);
@@ -44,11 +45,14 @@ protected boolean calculateEnabled() {
return true;
}
+ @Override
public void run() {
clonedObserver = null;
- if (getControl() != null) {
+ actionControl = getControl();
+
+ if (actionControl != null) {
newObserver = getControl().getObserver(getClassName());
@@ -115,7 +119,7 @@ public void run() {
} else if (status == WizardDialog.CANCEL) {
if (clonedObserver != null)
- getControl().addObserver(clonedObserver);
+ actionControl.addObserver(clonedObserver);
} else if (status == BMotionObserverWizard.DELETE) {
RemoveObserverAction action = new RemoveObserverAction(
@@ -137,7 +141,7 @@ public void run() {
public ObserverCommand createObserverCommandCommand() {
ObserverCommand command = new ObserverCommand();
command.setClassName(getClassName());
- command.setControl(getControl());
+ command.setControl(actionControl);
return command;
}
@@ -163,4 +167,5 @@ protected BControl getControl() {
return null;
}
+
}
diff --git a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverCSwitchCoordinates.java b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverCSwitchCoordinates.java
index 643e3f1f..28daf887 100644
--- a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverCSwitchCoordinates.java
+++ b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverCSwitchCoordinates.java
@@ -68,7 +68,7 @@ public void createControl(Composite parent) {
container.setLayout(new GridLayout(1, true));
tableViewer = WizardObserverUtil.createObserverWizardTableViewer(
- container, ToggleObjectCoordinates.class);
+ container, ToggleObjectCoordinates.class, getObserver());
TableViewerColumn column = new TableViewerColumn(tableViewer,
SWT.NONE);
diff --git a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverDragListener.java b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverDragListener.java
index 1f99dccd..45b1c1ad 100644
--- a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverDragListener.java
+++ b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverDragListener.java
@@ -26,7 +26,8 @@ public void dragFinished(DragSourceEvent event) {
public void dragSetData(DragSourceEvent event) {
IStructuredSelection selection = (IStructuredSelection) viewer
.getSelection();
- event.data = selection.getFirstElement();
+ Object[] lobjects = selection.toArray();
+ event.data = lobjects;
}
@Override
diff --git a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverDropListener.java b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverDropListener.java
index 25e1793e..b9d4c121 100644
--- a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverDropListener.java
+++ b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverDropListener.java
@@ -6,31 +6,77 @@
package de.bmotionstudio.gef.editor.observer.wizard;
import org.eclipse.core.databinding.observable.list.WritableList;
+import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerDropAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.TransferData;
+import org.eclipse.swt.widgets.Display;
+
+import de.bmotionstudio.gef.editor.observer.ObserverEvalObject;
public class WizardObserverDropListener extends ViewerDropAdapter {
- public WizardObserverDropListener(Viewer viewer) {
+ private String observerName;
+
+ public WizardObserverDropListener(Viewer viewer, String observerName) {
super(viewer);
+ this.observerName = observerName;
}
@Override
public void drop(DropTargetEvent event) {
- Object sourceSetAttributeObject = event.data;
+
+ Object[] sourceSetAttributeObjects = (Object[]) event.data;
Object targetSetAttributeObject = determineTarget(event);
+
Object input = getViewer().getInput();
if (input instanceof WritableList) {
+
WritableList list = (WritableList) input;
- int indexOf = list.indexOf(targetSetAttributeObject);
- if (indexOf != -1) {
- list.remove(sourceSetAttributeObject);
- list.add(indexOf, sourceSetAttributeObject);
+
+ for (Object sourceObject : sourceSetAttributeObjects) {
+
+ if (sourceObject instanceof ObserverEvalObject) {
+
+ ObserverEvalObject sourceEvalObject = (ObserverEvalObject) sourceObject;
+
+ if (sourceObject.getClass().equals(list.getElementType())) {
+
+ int indexOf = list.indexOf(targetSetAttributeObject);
+ if (indexOf == -1)
+ indexOf = 0;
+ ObserverEvalObject newElement = sourceEvalObject;
+ if (!list.remove(sourceEvalObject)) {
+ try {
+ newElement = sourceEvalObject.clone();
+ } catch (CloneNotSupportedException e) {
+ e.printStackTrace();
+ }
+ }
+
+ list.add(indexOf, newElement);
+
+ } else {
+
+ MessageDialog.openInformation(Display.getDefault()
+ .getActiveShell(),
+ "Drag and Drop is not supported",
+ "It is not possible to add an item of the type "
+ + sourceEvalObject.getClass()
+ + " to the observer \"" + observerName
+ + "\".");
+
+ }
+
+ }
+
}
+
}
+
super.drop(event);
+
}
@Override
diff --git a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverListenOperationByPredicate.java b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverListenOperationByPredicate.java
index a1c2b4b7..64041169 100644
--- a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverListenOperationByPredicate.java
+++ b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverListenOperationByPredicate.java
@@ -80,7 +80,7 @@ public void createControl(final Composite parent) {
setControl(container);
tableViewer = WizardObserverUtil.createObserverWizardTableViewer(
- container, PredicateOperation.class);
+ container, PredicateOperation.class, getObserver());
TableViewerColumn column = new TableViewerColumn(tableViewer,
SWT.NONE);
diff --git a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverSetAttribute.java b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverSetAttribute.java
index cdb7e2e2..72e9938d 100644
--- a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverSetAttribute.java
+++ b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverSetAttribute.java
@@ -86,7 +86,7 @@ public void createControl(Composite parent) {
container.setLayout(gl);
tableViewer = WizardObserverUtil.createObserverWizardTableViewer(
- container, SetAttributeObject.class);
+ container, SetAttributeObject.class, getObserver());
TableViewerColumn column = new TableViewerColumn(tableViewer,
SWT.NONE);
diff --git a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverSwitchCoordinates.java b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverSwitchCoordinates.java
index fe06205d..abbcfb6b 100644
--- a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverSwitchCoordinates.java
+++ b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverSwitchCoordinates.java
@@ -69,7 +69,7 @@ public void createControl(Composite parent) {
container.setLayout(new GridLayout(1, true));
tableViewer = WizardObserverUtil.createObserverWizardTableViewer(
- container, ToggleObjectCoordinates.class);
+ container, ToggleObjectCoordinates.class, getObserver());
TableViewerColumn column = new TableViewerColumn(tableViewer,
SWT.NONE);
diff --git a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverSwitchImage.java b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverSwitchImage.java
index 0e696b4a..5e9cba0d 100644
--- a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverSwitchImage.java
+++ b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/observer/wizard/WizardObserverSwitchImage.java
@@ -68,7 +68,7 @@ public void createControl(final Composite parent) {
container.setLayout(new GridLayout(1, true));
tableViewer = WizardObserverUtil.createObserverWizardTableViewer(
- container, ToggleObjectImage.class);
+ container, ToggleObjectImage.class, getObserver());
TableViewerColumn column = new TableViewerColumn(tableViewer,
SWT.NONE);
diff --git a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/util/WizardObserverUtil.java b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/util/WizardObserverUtil.java
index 7867f0b3..4059b971 100644
--- a/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/util/WizardObserverUtil.java
+++ b/de.bmotionstudio.gef.editor/src/de/bmotionstudio/gef/editor/util/WizardObserverUtil.java
@@ -19,6 +19,7 @@
import de.bmotionstudio.gef.editor.BMotionStudioSWTConstants;
import de.bmotionstudio.gef.editor.library.AttributeTransfer;
+import de.bmotionstudio.gef.editor.observer.Observer;
import de.bmotionstudio.gef.editor.observer.wizard.WizardObserverAddItemAction;
import de.bmotionstudio.gef.editor.observer.wizard.WizardObserverDeleteItemsAction;
import de.bmotionstudio.gef.editor.observer.wizard.WizardObserverDragListener;
@@ -34,7 +35,7 @@ public static boolean isEditElement(ColumnViewer viewer) {
}
public static TableViewer createObserverWizardTableViewer(Composite parent,
- Class<?> itemClass) {
+ Class<?> itemClass, Observer observer) {
final TableViewer tableViewer = new TableViewer(parent, SWT.BORDER
| SWT.FULL_SELECTION | SWT.MULTI);
@@ -46,8 +47,12 @@ public static TableViewer createObserverWizardTableViewer(Composite parent,
int operations = DND.DROP_COPY | DND.DROP_MOVE;
Transfer[] transferTypes = new Transfer[] { AttributeTransfer
.getInstance() };
- tableViewer.addDropSupport(operations, transferTypes,
- new WizardObserverDropListener(tableViewer));
+ tableViewer
+ .addDropSupport(
+ operations,
+ transferTypes,
+ new WizardObserverDropListener(tableViewer, observer
+ .getName()));
tableViewer.addDragSupport(operations, transferTypes,
new WizardObserverDragListener(tableViewer));
|
88a7e673b3ed7e07aa5cf31a1163697808a1f763
|
orientdb
|
Changed syntax for "create class" command. Now- wants the keyword "CLUSTER" and also accepts cluster names--
|
a
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OSchemaShared.java b/core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OSchemaShared.java
index 3e2f224a526..4ab42160331 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OSchemaShared.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OSchemaShared.java
@@ -194,7 +194,8 @@ public OClass createClass(final String iClassName, final OClass iSuperClass, fin
cmd.append(iSuperClass.getName());
}
- if (iClusterIds != null)
+ if (iClusterIds != null) {
+ cmd.append(" cluster ");
for (int i = 0; i < iClusterIds.length; ++i) {
if (i > 0)
cmd.append(',');
@@ -203,6 +204,7 @@ public OClass createClass(final String iClassName, final OClass iSuperClass, fin
cmd.append(iClusterIds[i]);
}
+ }
getDatabase().command(new OCommandSQL(cmd.toString())).execute();
getDatabase().reload();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateClass.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateClass.java
index 4c889c6224d..66655e98eac 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateClass.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateClass.java
@@ -36,6 +36,7 @@ public class OCommandExecutorSQLCreateClass extends OCommandExecutorSQLPermissio
public static final String KEYWORD_CREATE = "CREATE";
public static final String KEYWORD_CLASS = "CLASS";
public static final String KEYWORD_EXTENDS = "EXTENDS";
+ public static final String KEYWORD_CLUSTER = "CLUSTER";
private String className;
private OClass superClass;
@@ -68,46 +69,54 @@ public OCommandExecutorSQLCreateClass parse(final OCommandRequestText iRequest)
throw new OCommandSQLParsingException("Class " + className + " already exists", text, oldPos);
oldPos = pos;
- pos = OSQLHelper.nextWord(text, textUpperCase, oldPos, word, true);
- if (pos > -1) {
- if (word.toString().equals(KEYWORD_EXTENDS)) {
+
+ while ((pos = OSQLHelper.nextWord(text, textUpperCase, oldPos, word, true)) > -1) {
+ final String k = word.toString();
+ if (k.equals(KEYWORD_EXTENDS)) {
oldPos = pos;
pos = OSQLHelper.nextWord(text, textUpperCase, oldPos, word, false);
if (pos == -1)
throw new OCommandSQLParsingException("Syntax error after EXTENDS for class " + className
- + ". Expected the super-class name ", text, oldPos);
+ + ". Expected the super-class name", text, oldPos);
if (!database.getMetadata().getSchema().existsClass(word.toString()))
throw new OCommandSQLParsingException("Super-class " + word + " not exists", text, oldPos);
superClass = database.getMetadata().getSchema().getClass(word.toString());
-
+ } else if (k.equals(KEYWORD_CLUSTER)) {
oldPos = pos;
pos = OSQLHelper.nextWord(text, textUpperCase, oldPos, word, false);
- }
+ if (pos == -1)
+ throw new OCommandSQLParsingException("Syntax error after CLUSTER for class " + className
+ + ". Expected the cluster id or name", text, oldPos);
- if (pos > -1) {
final String[] clusterIdsAsStrings = word.toString().split(",");
if (clusterIdsAsStrings.length > 0) {
clusterIds = new int[clusterIdsAsStrings.length];
for (int i = 0; i < clusterIdsAsStrings.length; ++i) {
- clusterIds[i] = Integer.parseInt(clusterIdsAsStrings[i]);
+ if (Character.isDigit(clusterIdsAsStrings[i].charAt(0)))
+ // GET CLUSTER ID FROM NAME
+ clusterIds[i] = Integer.parseInt(clusterIdsAsStrings[i]);
+ else
+ // GET CLUSTER ID
+ clusterIds[i] = database.getStorage().getClusterIdByName(clusterIdsAsStrings[i]);
+
if (database.getStorage().getClusterById(clusterIds[i]) == null)
throw new OCommandSQLParsingException("Cluster with id " + clusterIds[i] + " doesn't exists", text, oldPos);
}
}
- } else {
- final int clusterId = database.getStorage().getClusterIdByName(className);
- if (clusterId > -1) {
- clusterIds = new int[] { clusterId };
- }
}
- } else {
+
+ oldPos = pos;
+ }
+
+ if (clusterIds == null) {
final int clusterId = database.getStorage().getClusterIdByName(className);
if (clusterId > -1) {
clusterIds = new int[] { clusterId };
}
}
+
return this;
}
|
a2ac32d1d9827f6edf7b72cf47fdbf9023e78ba9
|
intellij-community
|
optimization: cache org.junit.Test--
|
p
|
https://github.com/JetBrains/intellij-community
|
diff --git a/java/execution/impl/src/com/intellij/execution/junit/JUnitUtil.java b/java/execution/impl/src/com/intellij/execution/junit/JUnitUtil.java
index 61357de92a8ae..f884997e30386 100644
--- a/java/execution/impl/src/com/intellij/execution/junit/JUnitUtil.java
+++ b/java/execution/impl/src/com/intellij/execution/junit/JUnitUtil.java
@@ -24,6 +24,7 @@
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
+import com.intellij.openapi.util.Key;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.searches.ClassInheritorsSearch;
@@ -33,6 +34,7 @@
import com.intellij.util.containers.Convertor;
import junit.runner.BaseTestRunner;
import org.jetbrains.annotations.NonNls;
+import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.After;
import org.junit.AfterClass;
@@ -51,19 +53,22 @@ public class JUnitUtil {
@NonNls public static final String RUN_WITH = "org.junit.runner.RunWith";
@NonNls public static final String SUITE_METHOD_NAME = "suite";
- public static boolean isSuiteMethod(final PsiMethod psiMethod) {
- if (psiMethod == null) return false;
+ private static final Key<PsiType> TEST_INTERFACE_KEY = Key.create(TEST_INTERFACE);
+ public static boolean isSuiteMethod(@NotNull PsiMethod psiMethod, @NotNull Project project) {
if (!psiMethod.hasModifierProperty(PsiModifier.PUBLIC)) return false;
if (!psiMethod.hasModifierProperty(PsiModifier.STATIC)) return false;
if (psiMethod.isConstructor()) return false;
final PsiType returnType = psiMethod.getReturnType();
- if (returnType != null) {
- if (!returnType.equalsToText(TEST_INTERFACE) && !returnType.equalsToText(TESTSUITE_CLASS)) {
- final PsiType testType =
- JavaPsiFacade.getInstance(psiMethod.getProject()).getElementFactory().createTypeFromText(TEST_INTERFACE, null);
- if (!TypeConversionUtil.isAssignable(testType, returnType)) {
- return false;
- }
+ if (returnType == null || returnType instanceof PsiPrimitiveType) return false;
+ if (!returnType.equalsToText(TEST_INTERFACE) && !returnType.equalsToText(TESTSUITE_CLASS)) {
+ PsiType cachedTestInterfaceType = project.getUserData(TEST_INTERFACE_KEY);
+ if (cachedTestInterfaceType == null) {
+ final PsiType testType = JavaPsiFacade.getInstance(project).getElementFactory().createTypeFromText(TEST_INTERFACE, null);
+ project.putUserData(TEST_INTERFACE_KEY,testType);
+ cachedTestInterfaceType = testType;
+ }
+ if (!TypeConversionUtil.isAssignable(cachedTestInterfaceType, returnType)) {
+ return false;
}
}
return psiMethod.getParameterList().getParametersCount() == 0;
@@ -109,7 +114,7 @@ public static boolean isTestClass(final PsiClass psiClass) {
return isTestClass(psiClass, true, true);
}
- private static boolean isTestClass(final PsiClass psiClass, boolean checkAbstract, boolean checkForTestCaseInheritance) {
+ private static boolean isTestClass(@NotNull PsiClass psiClass, boolean checkAbstract, boolean checkForTestCaseInheritance) {
if (!PsiClassUtil.isRunnableClass(psiClass, true, checkAbstract)) return false;
if (checkForTestCaseInheritance && isTestCaseInheritor(psiClass)) return true;
final PsiModifierList modifierList = psiClass.getModifierList();
@@ -118,7 +123,7 @@ private static boolean isTestClass(final PsiClass psiClass, boolean checkAbstrac
for (final PsiMethod method : psiClass.getAllMethods()) {
ProgressManager.checkCanceled();
- if (isSuiteMethod(method)) return true;
+ if (isSuiteMethod(method, psiClass.getProject())) return true;
if (isTestAnnotated(method)) return true;
}
@@ -241,7 +246,7 @@ public boolean process(PsiClass psiClass) {
public static PsiMethod findFirstTestMethod(PsiClass clazz) {
PsiMethod testMethod = null;
for (PsiMethod method : clazz.getMethods()) {
- if (isTestMethod(MethodLocation.elementInClass(method, clazz)) || isSuiteMethod(method)) {
+ if (isTestMethod(MethodLocation.elementInClass(method, clazz)) || isSuiteMethod(method, clazz.getProject())) {
testMethod = method;
break;
}
diff --git a/plugins/junit/src/com/intellij/execution/ConfigurationUtil.java b/plugins/junit/src/com/intellij/execution/ConfigurationUtil.java
index 47a46f16712f1..71031a9fdb6f3 100644
--- a/plugins/junit/src/com/intellij/execution/ConfigurationUtil.java
+++ b/plugins/junit/src/com/intellij/execution/ConfigurationUtil.java
@@ -19,6 +19,7 @@
import com.intellij.execution.junit.JUnitUtil;
import com.intellij.execution.junit.TestClassFilter;
import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.*;
@@ -38,7 +39,8 @@ public class ConfigurationUtil {
public static boolean findAllTestClasses(final TestClassFilter testClassFilter, final Set<PsiClass> found) {
final PsiManager manager = testClassFilter.getPsiManager();
- GlobalSearchScope projectScopeWithoutLibraries = GlobalSearchScope.projectScope(manager.getProject());
+ final Project project = manager.getProject();
+ GlobalSearchScope projectScopeWithoutLibraries = GlobalSearchScope.projectScope(project);
final GlobalSearchScope scope = projectScopeWithoutLibraries.intersectWith(testClassFilter.getScope());
ClassInheritorsSearch.search(testClassFilter.getBase(), scope, true).forEach(new PsiElementProcessorAdapter<PsiClass>(new PsiElementProcessor<PsiClass>() {
public boolean execute(final PsiClass aClass) {
@@ -51,7 +53,7 @@ public boolean execute(final PsiClass aClass) {
final PsiMethod[] suiteMethods = ApplicationManager.getApplication().runReadAction(
new Computable<PsiMethod[]>() {
public PsiMethod[] compute() {
- return JavaPsiFacade.getInstance(manager.getProject()).getShortNamesCache().getMethodsByName(JUnitUtil.SUITE_METHOD_NAME, scope);
+ return JavaPsiFacade.getInstance(project).getShortNamesCache().getMethodsByName(JUnitUtil.SUITE_METHOD_NAME, scope);
}
}
);
@@ -67,7 +69,7 @@ public PsiClass compute() {
if (containingClass.getContainingClass() != null && !containingClass.hasModifierProperty(PsiModifier.STATIC)) continue;
if (ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
public Boolean compute() {
- return JUnitUtil.isSuiteMethod(method);
+ return JUnitUtil.isSuiteMethod(method, project);
}
}).booleanValue()) {
found.add(containingClass);
|
a725717261c347366e5bc36d95ade9b3ec0109a9
|
spring-framework
|
tests for custom conversion service / validator--
|
p
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java
index 68db7132d2f0..e4f2fda92d51 100644
--- a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java
+++ b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java
@@ -1,13 +1,19 @@
package org.springframework.web.servlet.config;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import java.util.Date;
import java.util.Locale;
+import javax.validation.Valid;
+import javax.validation.constraints.NotNull;
+
import org.junit.Before;
import org.junit.Test;
+import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.io.ClassPathResource;
@@ -17,6 +23,9 @@
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.stereotype.Controller;
+import org.springframework.validation.BindingResult;
+import org.springframework.validation.Errors;
+import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.support.GenericWebApplicationContext;
@@ -52,14 +61,93 @@ public void testDefaultConfig() throws Exception {
request.addParameter("date", "2009-10-31");
MockHttpServletResponse response = new MockHttpServletResponse();
adapter.handle(request, response, handler);
+ assertTrue(handler.recordedValidationError);
}
-
+
+ @Test(expected=ConversionNotSupportedException.class)
+ public void testCustomConversionService() throws Exception {
+ XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(container);
+ reader.loadBeanDefinitions(new ClassPathResource("mvc-config-custom-conversion-service.xml", getClass()));
+ assertEquals(3, container.getBeanDefinitionCount());
+ DefaultAnnotationHandlerMapping mapping = container.getBean(DefaultAnnotationHandlerMapping.class);
+ assertNotNull(mapping);
+ assertEquals(0, mapping.getOrder());
+ AnnotationMethodHandlerAdapter adapter = container.getBean(AnnotationMethodHandlerAdapter.class);
+ assertNotNull(adapter);
+
+ TestController handler = new TestController();
+
+ // default web binding initializer behavior test
+ MockHttpServletRequest request = new MockHttpServletRequest();
+ request.addParameter("date", "2009-10-31");
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ adapter.handle(request, response, handler);
+ }
+
+ @Test
+ public void testCustomValidator() throws Exception {
+ XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(container);
+ reader.loadBeanDefinitions(new ClassPathResource("mvc-config-custom-validator.xml", getClass()));
+ assertEquals(3, container.getBeanDefinitionCount());
+ DefaultAnnotationHandlerMapping mapping = container.getBean(DefaultAnnotationHandlerMapping.class);
+ assertNotNull(mapping);
+ assertEquals(0, mapping.getOrder());
+ AnnotationMethodHandlerAdapter adapter = container.getBean(AnnotationMethodHandlerAdapter.class);
+ assertNotNull(adapter);
+
+ TestController handler = new TestController();
+
+ // default web binding initializer behavior test
+ MockHttpServletRequest request = new MockHttpServletRequest();
+ request.addParameter("date", "2009-10-31");
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ adapter.handle(request, response, handler);
+
+ assertTrue(container.getBean(TestValidator.class).validatorInvoked);
+ assertFalse(handler.recordedValidationError);
+ }
+
@Controller
public static class TestController {
+ private boolean recordedValidationError;
+
@RequestMapping
- public void testBind(@RequestParam @DateTimeFormat(iso=ISO.DATE) Date date) {
-
+ public void testBind(@RequestParam @DateTimeFormat(iso=ISO.DATE) Date date, @Valid TestBean bean, BindingResult result) {
+ if (result.getErrorCount() == 1) {
+ this.recordedValidationError = true;
+ } else {
+ this.recordedValidationError = false;
+ }
}
}
+
+ public static class TestValidator implements Validator {
+
+ boolean validatorInvoked;
+
+ public boolean supports(Class<?> clazz) {
+ return true;
+ }
+
+ public void validate(Object target, Errors errors) {
+ this.validatorInvoked = true;
+ }
+
+ }
+
+ private static class TestBean {
+
+ @NotNull
+ private String field;
+
+ public String getField() {
+ return field;
+ }
+
+ public void setField(String field) {
+ this.field = field;
+ }
+
+ }
}
diff --git a/org.springframework.web.servlet/src/test/resources/org/springframework/web/servlet/config/mvc-config-custom-conversion-service.xml b/org.springframework.web.servlet/src/test/resources/org/springframework/web/servlet/config/mvc-config-custom-conversion-service.xml
new file mode 100644
index 000000000000..334c20d7f90d
--- /dev/null
+++ b/org.springframework.web.servlet/src/test/resources/org/springframework/web/servlet/config/mvc-config-custom-conversion-service.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+ xmlns:mvc="http://www.springframework.org/schema/mvc"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+ http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
+
+ <mvc:annotation-driven conversion-service="conversionService" />
+
+ <bean id="conversionService" class="org.springframework.core.convert.support.DefaultConversionService" />
+
+</beans>
diff --git a/org.springframework.web.servlet/src/test/resources/org/springframework/web/servlet/config/mvc-config-custom-validator.xml b/org.springframework.web.servlet/src/test/resources/org/springframework/web/servlet/config/mvc-config-custom-validator.xml
new file mode 100644
index 000000000000..31e46473e32c
--- /dev/null
+++ b/org.springframework.web.servlet/src/test/resources/org/springframework/web/servlet/config/mvc-config-custom-validator.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+ xmlns:mvc="http://www.springframework.org/schema/mvc"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+ http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
+
+ <mvc:annotation-driven validator="validator"/>
+
+ <bean id="validator" class="org.springframework.web.servlet.config.MvcNamespaceTests$TestValidator" />
+
+</beans>
|
2bb65e9200acf7460230e496cceefd4d598d510f
|
internetarchive$heritrix3
|
[HER-1546] Springify(5): Update checkpointing to work smoothly with spring-configured crawls
processor-related bean checkpoint support:
* Processor.java
implement Checkpointable and BeanNameAware; methods to support JSON state-saving
* DispositionChain.java
implement Checkpointable and during-checkpoint disposition-lockout for state stability
* **Extractor**.java
pull common reporting & checkpointing up to Extractor.java
* WriterPoolProcessor.java
implement Checkpointable; freeze and roll writer-pool during checkpoint
* PersistLogProcessor.java
roll log on checkpoint
* TextSeedModule.java, SeedModule.java
eliminate obsolete (and probably unnecessary) checkpoint support
* (others)
adapt to above changes
|
p
|
https://github.com/internetarchive/heritrix3
|
diff --git a/modules/src/main/java/org/archive/modules/extractor/AggressiveExtractorHTML.java b/modules/src/main/java/org/archive/modules/extractor/AggressiveExtractorHTML.java
index 6f8c1dd7d..91cbcfc4d 100644
--- a/modules/src/main/java/org/archive/modules/extractor/AggressiveExtractorHTML.java
+++ b/modules/src/main/java/org/archive/modules/extractor/AggressiveExtractorHTML.java
@@ -48,17 +48,4 @@ protected void processScript(CrawlURI curi, CharSequence sequence,
processGeneralTag(curi, sequence.subSequence(0,6),
sequence.subSequence(endOfOpenTag, sequence.length()));
}
-
- /* (non-Javadoc)
- * @see org.archive.crawler.framework.Processor#report()
- */
- public String report() {
- StringBuffer ret = new StringBuffer(256);
- ret.append(super.report());
- ret.append(" Function: Link extraction on HTML documents " +
- "(including embedded CSS)\n");
- ret.append(" ProcessorURIs handled: " + numberOfCURIsHandled + "\n");
- ret.append(" Links extracted: " + numberOfLinksExtracted + "\n");
- return ret.toString();
- }
}
diff --git a/modules/src/main/java/org/archive/modules/extractor/Extractor.java b/modules/src/main/java/org/archive/modules/extractor/Extractor.java
index 400eedc3f..7a7f4f1c8 100644
--- a/modules/src/main/java/org/archive/modules/extractor/Extractor.java
+++ b/modules/src/main/java/org/archive/modules/extractor/Extractor.java
@@ -20,6 +20,7 @@
package org.archive.modules.extractor;
+import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -28,6 +29,8 @@
import org.archive.modules.Processor;
import org.archive.net.UURI;
import org.archive.net.UURIFactory;
+import org.json.JSONException;
+import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
@@ -41,6 +44,7 @@
*/
public abstract class Extractor extends Processor {
+ protected AtomicLong numberOfLinksExtracted = new AtomicLong(0);
/** Logger. */
private static final Logger logger =
@@ -130,5 +134,30 @@ public void logUriError(URIException e, UURI uuri,
}
loggerModule.logUriError(e, uuri, l);
}
+
+ @Override
+ protected JSONObject toCheckpointJson() throws JSONException {
+ JSONObject json = super.toCheckpointJson();
+ json.put("numberOfLinksExtracted", numberOfLinksExtracted.get());
+ return json;
+ }
+
+ @Override
+ protected void fromCheckpointJson(JSONObject json) throws JSONException {
+ super.fromCheckpointJson(json);
+ numberOfLinksExtracted.set(json.getLong("numberOfLinksExtracted"));
+ }
+
+ @Override
+ protected boolean shouldProcess(CrawlURI uri) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+ public String report() {
+ StringBuffer ret = new StringBuffer();
+ ret.append(super.report());
+ ret.append(" " + numberOfLinksExtracted + " links from " + getURICount() +" CrawlURIs\n");
+ return ret.toString();
+ }
}
diff --git a/modules/src/main/java/org/archive/modules/extractor/ExtractorCSS.java b/modules/src/main/java/org/archive/modules/extractor/ExtractorCSS.java
index 2138a5fa6..7364153ab 100644
--- a/modules/src/main/java/org/archive/modules/extractor/ExtractorCSS.java
+++ b/modules/src/main/java/org/archive/modules/extractor/ExtractorCSS.java
@@ -75,7 +75,6 @@ public class ExtractorCSS extends ContentExtractor {
// (G1) optional ' or "
// (G2) URI
- private long numberOfLinksExtracted = 0;
/**
*/
@@ -103,8 +102,8 @@ public boolean innerExtract(CrawlURI curi) {
ReplayCharSequence cs = null;
try {
cs = curi.getRecorder().getReplayCharSequence();
- this.numberOfLinksExtracted +=
- processStyleCode(this, curi, cs);
+ numberOfLinksExtracted.addAndGet(
+ processStyleCode(this, curi, cs));
// Set flag to indicate that link extraction is completed.
return true;
} catch (IOException e) {
@@ -145,14 +144,4 @@ public static long processStyleCode(Extractor ext,
}
return foundLinks;
}
-
- public String report() {
- StringBuffer ret = new StringBuffer();
- ret.append(super.report());
- ret.append(" Function: Link extraction on Cascading Style Sheets (.css)\n");
- ret.append(" ExtractorURIs handled: " + getURICount() + "\n");
- ret.append(" Links extracted: " + numberOfLinksExtracted + "\n");
-
- return ret.toString();
- }
}
diff --git a/modules/src/main/java/org/archive/modules/extractor/ExtractorDOC.java b/modules/src/main/java/org/archive/modules/extractor/ExtractorDOC.java
index 32b3ee4b9..8ca08ce92 100644
--- a/modules/src/main/java/org/archive/modules/extractor/ExtractorDOC.java
+++ b/modules/src/main/java/org/archive/modules/extractor/ExtractorDOC.java
@@ -47,8 +47,6 @@ public class ExtractorDOC extends ContentExtractor {
private static Logger logger =
Logger.getLogger("org.archive.crawler.extractor.ExtractorDOC");
- private long numberOfCURIsHandled = 0;
- private long numberOfLinksExtracted = 0;
/**
* @param name
@@ -117,19 +115,6 @@ private void addLink(CrawlURI curi, String hyperlink) {
} catch (URIException e1) {
logUriError(e1, curi.getUURI(), hyperlink);
}
- numberOfLinksExtracted++;
- }
-
- /* (non-Javadoc)
- * @see org.archive.crawler.framework.Processor#report()
- */
- public String report() {
- StringBuffer ret = new StringBuffer();
- ret.append(super.report());
- ret.append(" Function: Link extraction on MS Word documents (.doc)\n");
- ret.append(" CrawlURIs handled: " + numberOfCURIsHandled + "\n");
- ret.append(" Links extracted: " + numberOfLinksExtracted + "\n");
-
- return ret.toString();
+ numberOfLinksExtracted.incrementAndGet();
}
}
diff --git a/modules/src/main/java/org/archive/modules/extractor/ExtractorHTML.java b/modules/src/main/java/org/archive/modules/extractor/ExtractorHTML.java
index f9abe9225..23b97f748 100644
--- a/modules/src/main/java/org/archive/modules/extractor/ExtractorHTML.java
+++ b/modules/src/main/java/org/archive/modules/extractor/ExtractorHTML.java
@@ -299,9 +299,6 @@ public CrawlMetadata getMetadata() {
public void setMetadata(CrawlMetadata provider) {
this.metadata = provider;
}
-
- protected long numberOfCURIsHandled = 0;
- protected long numberOfLinksExtracted = 0;
private Pattern relevantTagExtractor;
private Pattern eachAttributeExtractor;
@@ -448,8 +445,8 @@ protected void processGeneralTag(CrawlURI curi, CharSequence element,
} else if (attr.start(11) > -1) {
// STYLE inline attribute
// then, parse for URIs
- this.numberOfLinksExtracted += ExtractorCSS.processStyleCode(
- this, curi, value);
+ numberOfLinksExtracted.addAndGet(ExtractorCSS.processStyleCode(
+ this, curi, value));
} else if (attr.start(12) > -1) {
// METHOD
@@ -511,8 +508,8 @@ protected void processGeneralTag(CrawlURI curi, CharSequence element,
*/
protected void processScriptCode(CrawlURI curi, CharSequence cs) {
if (getExtractJavascript()) {
- this.numberOfLinksExtracted +=
- ExtractorJS.considerStrings(this, curi, cs, false);
+ numberOfLinksExtracted.addAndGet(
+ ExtractorJS.considerStrings(this, curi, cs, false));
}
}
@@ -537,7 +534,7 @@ protected void processLink(CrawlURI curi, final CharSequence value,
(value instanceof String)?
(String)value: value.toString(),
context, Hop.NAVLINK);
- this.numberOfLinksExtracted++;
+ numberOfLinksExtracted.incrementAndGet();
}
}
@@ -571,7 +568,7 @@ protected void processEmbed(CrawlURI curi, final CharSequence value,
(value instanceof String)?
(String)value: value.toString(),
context, hop);
- this.numberOfLinksExtracted++;
+ numberOfLinksExtracted.incrementAndGet();
}
@@ -599,7 +596,6 @@ protected boolean shouldExtract(CrawlURI uri) {
public boolean innerExtract(CrawlURI curi) {
- this.numberOfCURIsHandled++;
ReplayCharSequence cs = null;
try {
cs = curi.getRecorder().getReplayCharSequence();
@@ -808,26 +804,11 @@ protected void processStyle(CrawlURI curi, CharSequence sequence,
sequence.subSequence(0,endOfOpenTag));
// then, parse for URIs
- this.numberOfLinksExtracted += ExtractorCSS.processStyleCode(
+ numberOfLinksExtracted.addAndGet(ExtractorCSS.processStyleCode(
this,
curi,
- sequence.subSequence(endOfOpenTag,sequence.length()));
- }
-
-
-
- /* (non-Javadoc)
- * @see org.archive.crawler.framework.Processor#report()
- */
- public String report() {
- StringBuffer ret = new StringBuffer();
- ret.append(super.report());
- ret.append(" Function: Link extraction on HTML documents\n");
- ret.append(" CrawlURIs handled: " + this.numberOfCURIsHandled + "\n");
- ret.append(" Links extracted: " + this.numberOfLinksExtracted + "\n");
- return ret.toString();
- }
-
+ sequence.subSequence(endOfOpenTag,sequence.length())));
+ }
/**
* Create a suitable XPath-like context from an element name and optional
diff --git a/modules/src/main/java/org/archive/modules/extractor/ExtractorHTTP.java b/modules/src/main/java/org/archive/modules/extractor/ExtractorHTTP.java
index f1e8f4e7a..8f7d1ee2c 100644
--- a/modules/src/main/java/org/archive/modules/extractor/ExtractorHTTP.java
+++ b/modules/src/main/java/org/archive/modules/extractor/ExtractorHTTP.java
@@ -36,14 +36,9 @@ public class ExtractorHTTP extends Extractor {
private static final long serialVersionUID = 3L;
-// protected long numberOfCURIsHandled = 0;
- protected long numberOfLinksExtracted = 0;
-
public ExtractorHTTP() {
}
-
-
@Override
protected boolean shouldProcess(CrawlURI uri) {
if (uri.getFetchStatus() <= 0) {
@@ -72,20 +67,10 @@ protected void addHeaderLink(CrawlURI curi, Header loc) {
LinkContext lc = new HTMLLinkContext(loc.getName()+":");
Link link = new Link(curi.getUURI(), dest, lc, Hop.REFER);
curi.getOutLinks().add(link);
- numberOfLinksExtracted++;
+ numberOfLinksExtracted.incrementAndGet();
} catch (URIException e) {
logUriError(e, curi.getUURI(), loc.getValue());
}
}
-
- public String report() {
- StringBuffer ret = new StringBuffer();
- ret.append(super.report());
- ret.append(" Function: " +
- "Extracts URIs from HTTP response headers\n");
- ret.append(" CrawlURIs handled: " + this.getURICount());
- ret.append(" Links extracted: " + numberOfLinksExtracted + "\n");
- return ret.toString();
- }
}
diff --git a/modules/src/main/java/org/archive/modules/extractor/ExtractorImpliedURI.java b/modules/src/main/java/org/archive/modules/extractor/ExtractorImpliedURI.java
index 918d749d1..95763c551 100644
--- a/modules/src/main/java/org/archive/modules/extractor/ExtractorImpliedURI.java
+++ b/modules/src/main/java/org/archive/modules/extractor/ExtractorImpliedURI.java
@@ -20,7 +20,6 @@
import java.util.ArrayList;
import java.util.List;
-import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
@@ -101,10 +100,7 @@ public boolean getRemoveTriggerUris() {
public void setRemoveTriggerUris(boolean remove) {
kp.put("removeTriggerUris",remove);
}
-
- final AtomicLong linksExtracted = new AtomicLong();
-
-
+
/**
* Constructor.
*/
@@ -140,7 +136,7 @@ public void extract(CrawlURI curi) {
Hop hop = Hop.SPECULATIVE;
Link out = new Link(src, target, lc, hop);
curi.getOutLinks().add(out);
- linksExtracted.incrementAndGet();
+ numberOfLinksExtracted.incrementAndGet();
boolean removeTriggerURI = getRemoveTriggerUris();
// remove trigger URI from the outlinks if configured so.
@@ -149,7 +145,7 @@ public void extract(CrawlURI curi) {
LOGGER.log(Level.FINE, link.getDestination() +
" has been removed from " +
link.getSource() + " outlinks list.");
- linksExtracted.decrementAndGet();
+ numberOfLinksExtracted.decrementAndGet();
} else {
LOGGER.log(Level.FINE, "Failed to remove " +
link.getDestination() + " from " +
@@ -183,13 +179,4 @@ protected static String extractImplied(CharSequence uri, Pattern trigger, String
}
return null;
}
-
- public String report() {
- StringBuffer ret = new StringBuffer();
- ret.append(super.report());
- ret.append(" Function: Extracts links inside other URIs\n");
- ret.append(" CrawlURIs handled: " + getURICount() + "\n");
- ret.append(" Links extracted: " + linksExtracted.get() + "\n");
- return ret.toString();
- }
}
diff --git a/modules/src/main/java/org/archive/modules/extractor/ExtractorJS.java b/modules/src/main/java/org/archive/modules/extractor/ExtractorJS.java
index 97f3cf101..9f8b4903b 100644
--- a/modules/src/main/java/org/archive/modules/extractor/ExtractorJS.java
+++ b/modules/src/main/java/org/archive/modules/extractor/ExtractorJS.java
@@ -263,17 +263,4 @@ public static String speculativeFixup(String string, CrawlURI puri) {
return retVal;
}
-
- /* (non-Javadoc)
- * @see org.archive.crawler.framework.Processor#report()
- */
- public String report() {
- StringBuffer ret = new StringBuffer();
- ret.append(super.report());
- ret.append(" Function: Link extraction on JavaScript code\n");
- ret.append(" CrawlURIs handled: " + numberOfCURIsHandled + "\n");
- ret.append(" Links extracted: " + numberOfLinksExtracted + "\n");
-
- return ret.toString();
- }
}
diff --git a/modules/src/main/java/org/archive/modules/extractor/ExtractorPDF.java b/modules/src/main/java/org/archive/modules/extractor/ExtractorPDF.java
index 9a71227e4..4513c1801 100644
--- a/modules/src/main/java/org/archive/modules/extractor/ExtractorPDF.java
+++ b/modules/src/main/java/org/archive/modules/extractor/ExtractorPDF.java
@@ -21,7 +21,6 @@
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
-import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;
import org.apache.commons.httpclient.URIException;
@@ -57,8 +56,6 @@ public void setMaxSizeToParse(long threshold) {
kp.put("maxSizeToParse",threshold);
}
- final private AtomicLong numberOfLinksExtracted = new AtomicLong(0);
-
public ExtractorPDF() {
}
@@ -134,19 +131,4 @@ protected boolean innerExtract(CrawlURI curi){
// Set flag to indicate that link extraction is completed.
return true;
}
-
- /**
- * Provide a human-readable textual summary of this Processor's state.
- *
- * @see org.archive.crawler.framework.Processor#report()
- */
- public String report() {
- StringBuffer ret = new StringBuffer();
- ret.append(super.report());
- ret.append(" Function: Link extraction on PDF documents\n");
- ret.append(" CrawlURIs handled: " + getURICount() + "\n");
- ret.append(" Links extracted: " + numberOfLinksExtracted + "\n");
-
- return ret.toString();
- }
}
diff --git a/modules/src/main/java/org/archive/modules/extractor/ExtractorSWF.java b/modules/src/main/java/org/archive/modules/extractor/ExtractorSWF.java
index 7a09a4900..95da44a5b 100644
--- a/modules/src/main/java/org/archive/modules/extractor/ExtractorSWF.java
+++ b/modules/src/main/java/org/archive/modules/extractor/ExtractorSWF.java
@@ -20,7 +20,6 @@
import java.io.IOException;
import java.io.InputStream;
-import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;
import java.util.regex.Matcher;
@@ -53,8 +52,6 @@ public class ExtractorSWF extends ContentExtractor {
private static Logger logger =
Logger.getLogger(ExtractorSWF.class.getName());
- protected AtomicLong linksExtracted = new AtomicLong(0);
-
private static final int MAX_READ_SIZE = 1024 * 1024; // 1MB
static final String JSSTRING = "javascript:";
@@ -102,7 +99,7 @@ protected boolean innerExtract(CrawlURI curi) {
new ExtractorSWFReader(new ExtractorTagParser(customTags), documentStream);
reader.readFile();
- linksExtracted.addAndGet(curiAction.getLinkCount());
+ numberOfLinksExtracted.addAndGet(curiAction.getLinkCount());
logger.fine(curi + " has " + curiAction.getLinkCount() + " links.");
} catch (IOException e) {
curi.getNonFatalFailures().add(e);
@@ -118,18 +115,7 @@ protected boolean innerExtract(CrawlURI curi) {
// Set flag to indicate that link extraction is completed.
return true;
}
-
- public String report() {
- StringBuffer ret = new StringBuffer();
- ret.append(super.report());
- ret.append(" Function: Link extraction on Shockwave Flash " +
- "documents (.swf)\n");
-
- ret.append(" CrawlURIs handled: " + getURICount() + "\n");
- ret.append(" Links extracted: " + linksExtracted + "\n");
- return ret.toString();
- }
-
+
class ExtractorSWFReader extends SWFReader
{
public ExtractorSWFReader(SWFTags consumer, InputStream inputstream) {
diff --git a/modules/src/main/java/org/archive/modules/extractor/ExtractorURI.java b/modules/src/main/java/org/archive/modules/extractor/ExtractorURI.java
index 014667572..593cb17ca 100644
--- a/modules/src/main/java/org/archive/modules/extractor/ExtractorURI.java
+++ b/modules/src/main/java/org/archive/modules/extractor/ExtractorURI.java
@@ -20,7 +20,6 @@
import java.util.ArrayList;
import java.util.List;
-import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
@@ -55,9 +54,6 @@ public class ExtractorURI extends Extractor {
Logger.getLogger(ExtractorURI.class.getName());
static final String ABS_HTTP_URI_PATTERN = "^https?://[^\\s<>]*$";
-
-
- private AtomicLong linksExtracted = new AtomicLong(0);
/**
* Constructor
@@ -113,7 +109,7 @@ protected void extractLink(CrawlURI curi, Link wref) {
LinkContext lc = LinkContext.SPECULATIVE_MISC;
Hop hop = Hop.SPECULATIVE;
Link link = new Link(src, dest, lc, hop);
- linksExtracted.incrementAndGet();
+ numberOfLinksExtracted.incrementAndGet();
curi.getOutLinks().add(link);
} catch (URIException e) {
LOGGER.log(Level.FINE, "bad URI", e);
@@ -170,14 +166,4 @@ protected static List<String> extractQueryStringLinks(UURI source) {
}
return results;
}
-
- public String report() {
- StringBuffer ret = new StringBuffer();
- ret.append(super.report());
- ret.append(" Function: Extracts links inside other URIs\n");
- ret.append(" CrawlURIs handled: " + getURICount() + "\n");
- ret.append(" Links extracted: " + linksExtracted + "\n");
-
- return ret.toString();
- }
}
diff --git a/modules/src/main/java/org/archive/modules/extractor/ExtractorUniversal.java b/modules/src/main/java/org/archive/modules/extractor/ExtractorUniversal.java
index b97d5059e..9fceebb0c 100644
--- a/modules/src/main/java/org/archive/modules/extractor/ExtractorUniversal.java
+++ b/modules/src/main/java/org/archive/modules/extractor/ExtractorUniversal.java
@@ -20,7 +20,6 @@
import java.io.IOException;
import java.io.InputStream;
-import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -344,10 +343,6 @@ public void setMaxSizeToParse(long threshold) {
+ "|(zw(/.*)?)" // zw Zimbabwe
);
-
- protected AtomicLong linksExtracted = new AtomicLong(0);
-
-
/**
* Constructor.
*/
@@ -412,7 +407,7 @@ else if(isURLableChar(ch)){
}
// And add the URL to speculative embeds.
- linksExtracted.incrementAndGet();
+ numberOfLinksExtracted.incrementAndGet();
UURI src = curi.getUURI();
UURI dest = UURIFactory.getInstance(newURL);
LinkContext lc = LinkContext.SPECULATIVE_MISC;
@@ -529,18 +524,4 @@ private boolean isURLableChar(int ch) {
|| (ch>=97 && ch<=122)
|| (ch==126);
}
-
- /* (non-Javadoc)
- * @see org.archive.crawler.framework.Processor#report()
- */
- public String report() {
- StringBuffer ret = new StringBuffer();
- ret.append(super.report());
- ret.append(" Function: Link extraction on unknown file" +
- " types.\n");
- ret.append(" CrawlURIs handled: " + getURICount() + "\n");
- ret.append(" Links extracted: " + linksExtracted + "\n");
-
- return ret.toString();
- }
}
diff --git a/modules/src/main/java/org/archive/modules/extractor/ExtractorXML.java b/modules/src/main/java/org/archive/modules/extractor/ExtractorXML.java
index 03b24b443..0e422e0f7 100644
--- a/modules/src/main/java/org/archive/modules/extractor/ExtractorXML.java
+++ b/modules/src/main/java/org/archive/modules/extractor/ExtractorXML.java
@@ -19,7 +19,6 @@
package org.archive.modules.extractor;
import java.io.IOException;
-import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -52,8 +51,6 @@ public class ExtractorXML extends ContentExtractor {
"(?i)[\"\'>]\\s*(http:[^\\s\"\'<>]+)\\s*[\"\'<]");
// GROUPS:
// (G1) URI
-
- private AtomicLong linksExtracted = new AtomicLong(0);
/**
* @param name
@@ -86,7 +83,7 @@ protected boolean innerExtract(CrawlURI curi) {
ReplayCharSequence cs = null;
try {
cs = curi.getRecorder().getReplayCharSequence();
- this.linksExtracted.addAndGet(processXml(this, curi, cs));
+ numberOfLinksExtracted.addAndGet(processXml(this, curi, cs));
// Set flag to indicate that link extraction is completed.
return true;
} catch (IOException e) {
@@ -123,14 +120,4 @@ public static long processXml(Extractor ext,
}
return foundLinks;
}
-
- public String report() {
- StringBuffer ret = new StringBuffer();
- ret.append(super.report());
- ret.append(" Function: Link extraction on XML/RSS\n");
- ret.append(" CrawlURIs handled: " + getURICount() + "\n");
- ret.append(" Links extracted: " + linksExtracted + "\n");
-
- return ret.toString();
- }
}
diff --git a/modules/src/main/java/org/archive/modules/extractor/JerichoExtractorHTML.java b/modules/src/main/java/org/archive/modules/extractor/JerichoExtractorHTML.java
index 2c3062776..c001b137f 100644
--- a/modules/src/main/java/org/archive/modules/extractor/JerichoExtractorHTML.java
+++ b/modules/src/main/java/org/archive/modules/extractor/JerichoExtractorHTML.java
@@ -29,6 +29,7 @@
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
+import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -81,7 +82,7 @@ public class JerichoExtractorHTML extends ExtractorHTML {
final private static Logger logger =
Logger.getLogger(JerichoExtractorHTML.class.getName());
- protected long numberOfFormsProcessed = 0;
+ protected AtomicLong numberOfFormsProcessed = new AtomicLong(0);
/*
public JerichoExtractorHTML(String name) {
@@ -247,8 +248,8 @@ protected void processGeneralTag(CrawlURI curi, Element element,
((attrValue = attr.getValue()) != null)) {
// STYLE inline attribute
// then, parse for URIs
- this.numberOfLinksExtracted += ExtractorCSS.processStyleCode(
- this, curi, attrValue);
+ numberOfLinksExtracted.addAndGet(ExtractorCSS.processStyleCode(
+ this, curi, attrValue));
}
// handle codebase/resources
@@ -332,8 +333,8 @@ protected void processStyle(CrawlURI curi, Element element) {
processGeneralTag(curi, element, element.getAttributes());
// then, parse for URIs
- this.numberOfLinksExtracted += ExtractorCSS.processStyleCode(
- this, curi, element.getContent());
+ numberOfLinksExtracted.addAndGet(ExtractorCSS.processStyleCode(
+ this, curi, element.getContent()));
}
protected void processForm(CrawlURI curi, Element element) {
@@ -354,7 +355,7 @@ protected void processForm(CrawlURI curi, Element element) {
&& ! "GET".equalsIgnoreCase(method)) {
return;
}
- numberOfFormsProcessed++;
+ numberOfFormsProcessed.incrementAndGet();
// get all form fields
FormFields formFields = element.findFormFields();
@@ -448,10 +449,7 @@ void extract(CrawlURI curi, CharSequence cs) {
public String report() {
StringBuffer ret = new StringBuffer();
ret.append(super.report());
- ret.append(" Function: Link extraction on HTML documents\n");
- ret.append(" CrawlURIs handled: " + this.numberOfCURIsHandled + "\n");
- ret.append(" Forms processed: " + this.numberOfFormsProcessed + "\n");
- ret.append(" Links extracted: " + this.numberOfLinksExtracted + "\n");
+ ret.append(" " + this.numberOfFormsProcessed + " forms processed\n");
return ret.toString();
}
}
diff --git a/modules/src/main/java/org/archive/modules/extractor/TrapSuppressExtractor.java b/modules/src/main/java/org/archive/modules/extractor/TrapSuppressExtractor.java
index 7ae56431f..1b47423aa 100644
--- a/modules/src/main/java/org/archive/modules/extractor/TrapSuppressExtractor.java
+++ b/modules/src/main/java/org/archive/modules/extractor/TrapSuppressExtractor.java
@@ -70,19 +70,4 @@ protected boolean innerExtract(CrawlURI curi){
}
return false;
}
-
- /**
- * Provide a human-readable textual summary of this Processor's state.
- *
- * @see org.archive.crawler.framework.Processor#report()
- */
- public String report() {
- StringBuffer ret = new StringBuffer();
- ret.append(super.report());
- ret.append(" Function: Suppress extraction on likely traps\n");
- ret.append(" CrawlURIs handled: " + numberOfCURIsHandled + "\n");
- ret.append(" CrawlURIs suppressed: " + numberOfCURIsSuppressed + "\n");
-
- return ret.toString();
- }
}
diff --git a/modules/src/main/java/org/archive/modules/recrawl/PersistLogProcessor.java b/modules/src/main/java/org/archive/modules/recrawl/PersistLogProcessor.java
index 4f3007160..2dd32b3da 100644
--- a/modules/src/main/java/org/archive/modules/recrawl/PersistLogProcessor.java
+++ b/modules/src/main/java/org/archive/modules/recrawl/PersistLogProcessor.java
@@ -21,15 +21,15 @@
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
-import java.util.List;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.SerializationUtils;
import org.archive.checkpointing.Checkpointable;
-import org.archive.checkpointing.RecoverAction;
+import org.archive.crawler.framework.Checkpoint;
import org.archive.io.CrawlerJournal;
import org.archive.modules.CrawlURI;
import org.archive.spring.ConfigPath;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.Lifecycle;
@@ -96,12 +96,22 @@ protected void innerProcess(CrawlURI curi) {
new String(Base64.encodeBase64(
SerializationUtils.serialize((Serializable)curi.getPersistentDataMap()))));
}
+
+ public void startCheckpoint(Checkpoint checkpointInProgress) {}
- public void checkpoint(File dir, List<RecoverAction> actions) throws IOException {
+ public void doCheckpoint(Checkpoint checkpointInProgress) throws IOException {
// rotate log
- log.checkpoint(dir,null);
+ log.doCheckpoint(checkpointInProgress);
}
+
+ public void finishCheckpoint(Checkpoint checkpointInProgress) {}
+ Checkpoint recoveryCheckpoint;
+ @Autowired(required=false)
+ public void setRecoveryCheckpoint(Checkpoint checkpoint) {
+ this.recoveryCheckpoint = checkpoint;
+ }
+
@Override
protected boolean shouldProcess(CrawlURI uri) {
return shouldStore(uri);
diff --git a/modules/src/main/java/org/archive/modules/seeds/SeedModule.java b/modules/src/main/java/org/archive/modules/seeds/SeedModule.java
index 0412fac02..ba957aaf5 100644
--- a/modules/src/main/java/org/archive/modules/seeds/SeedModule.java
+++ b/modules/src/main/java/org/archive/modules/seeds/SeedModule.java
@@ -20,13 +20,10 @@
package org.archive.modules.seeds;
import java.io.File;
-import java.io.IOException;
import java.io.Serializable;
import java.util.HashSet;
-import java.util.List;
import java.util.Set;
-import org.archive.checkpointing.RecoverAction;
import org.archive.modules.CrawlURI;
import org.springframework.beans.factory.annotation.Autowired;
@@ -84,8 +81,6 @@ public SeedModule() {
public abstract void addSeed(final CrawlURI curi);
- public abstract void checkpoint(File dir, List<RecoverAction> actions) throws IOException;
-
public void addSeedListener(SeedListener sl) {
seedListeners.add(sl);
}
diff --git a/modules/src/main/java/org/archive/modules/seeds/TextSeedModule.java b/modules/src/main/java/org/archive/modules/seeds/TextSeedModule.java
index c4e0fa888..7f235c17e 100644
--- a/modules/src/main/java/org/archive/modules/seeds/TextSeedModule.java
+++ b/modules/src/main/java/org/archive/modules/seeds/TextSeedModule.java
@@ -25,17 +25,13 @@
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
-import java.io.Serializable;
import java.io.Writer;
import java.util.Iterator;
-import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.io.IOUtils;
-import org.archive.checkpointing.Checkpointable;
-import org.archive.checkpointing.RecoverAction;
import org.archive.io.ReadSource;
import org.archive.modules.CrawlURI;
import org.archive.modules.SchedulingConstants;
@@ -55,9 +51,7 @@
* @contributor gojomo
*/
public class TextSeedModule extends SeedModule
-implements ReadSource,
- Serializable,
- Checkpointable {
+implements ReadSource {
private static final long serialVersionUID = 3L;
private static final Logger logger =
@@ -191,6 +185,8 @@ public synchronized void addSeed(final CrawlURI curi) {
// TODO: do something else to log seed update
logger.warning("nowhere to log added seed: "+curi);
} else {
+ // TODO: determine if this modification to seeds file means
+ // TextSeedModule should (again) be Checkpointable
try {
Writer fw = ((WriteTarget)textSource).obtainWriter(true);
// Write to new (last) line the URL.
@@ -207,37 +203,6 @@ public synchronized void addSeed(final CrawlURI curi) {
}
publishAddedSeed(curi);
}
-
- @Override
- public void checkpoint(File dir, List<RecoverAction> actions)
- throws IOException {
- int id = System.identityHashCode(this);
- String backup = "seeds" + id + " .txt";
- backup.getBytes();
- //TODO:SPRINGY
-// FileUtils.copyFile(getSeedsFile().getFile(), new File(dir, backup));
-// actions.add(new SeedModuleRecoverAction(backup, getSeedsFile().getFile()));
- }
-
-// private static class SeedModuleRecoverAction implements RecoverAction {
-//
-// private static final long serialVersionUID = 1L;
-//
-// private File target;
-// private String backup;
-//
-// public SeedModuleRecoverAction(String backup, File target) {
-// this.target = target;
-// this.backup = backup;
-// }
-//
-// public void recoverFrom(File checkpointDir, CheckpointRecovery cr)
-// throws Exception {
-// target = new File(cr.translatePath(target.getAbsolutePath()));
-// FileUtils.copyFile(new File(checkpointDir, backup), target);
-// }
-//
-// }
public Reader obtainReader() {
return textSource.obtainReader();
diff --git a/modules/src/main/java/org/archive/modules/writer/WriterPoolProcessor.java b/modules/src/main/java/org/archive/modules/writer/WriterPoolProcessor.java
index eac6826d0..e62003214 100644
--- a/modules/src/main/java/org/archive/modules/writer/WriterPoolProcessor.java
+++ b/modules/src/main/java/org/archive/modules/writer/WriterPoolProcessor.java
@@ -24,8 +24,6 @@
import java.io.File;
import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
@@ -33,7 +31,8 @@
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
-import org.archive.checkpointing.RecoverAction;
+import org.archive.checkpointing.Checkpointable;
+import org.archive.crawler.framework.Checkpoint;
import org.archive.io.DefaultWriterPoolSettings;
import org.archive.io.WriterPool;
import org.archive.io.WriterPoolMember;
@@ -46,6 +45,8 @@
import org.archive.modules.net.CrawlHost;
import org.archive.modules.net.ServerCache;
import org.archive.spring.ConfigPath;
+import org.json.JSONException;
+import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.Lifecycle;
@@ -56,7 +57,7 @@
* @author stack
*/
public abstract class WriterPoolProcessor extends Processor
-implements Lifecycle {
+implements Lifecycle, Checkpointable {
private static final long serialVersionUID = 1L;
private static final Logger logger =
Logger.getLogger(WriterPoolProcessor.class.getName());
@@ -348,40 +349,32 @@ protected String getHostAddress(CrawlURI curi) {
return h.getIP().getHostAddress();
}
-
- public void checkpoint(File checkpointDir, List<RecoverAction> actions)
+ // TODO: add non-urgent checkpoint request, that waits for a good
+ // moment (when (W)ARCs are already rolling over)?
+ public void doCheckpoint(Checkpoint checkpointInProgress)
throws IOException {
- int serial = getSerialNo().get();
- if (this.pool.getNumActive() > 0) {
- // If we have open active Archive files, up the serial number
- // so after checkpoint, we start at one past current number and
- // so the number we serialize, is one past current serialNo.
- // All this serial number manipulation should be fine in here since
- // we're paused checkpointing (Revisit if this assumption changes).
- serial = getSerialNo().incrementAndGet();
- }
-
- // Close all ARCs on checkpoint.
- try {
- this.pool.close();
- } finally {
- // Reopen on checkpoint.
- this.serial = new AtomicInteger(serial);
- setupPool(this.serial);
- }
- }
-
- private void writeObject(ObjectOutputStream out) throws IOException {
- out.defaultWriteObject();
+ // close all ARCs on checkpoint
+ this.pool.close();
+
+ super.doCheckpoint(checkpointInProgress);
+
+ // reopen post checkpoint
+ setupPool(this.serial);
}
+ @Override
+ protected JSONObject toCheckpointJson() throws JSONException {
+ JSONObject json = super.toCheckpointJson();
+ json.put("serialNumber", getSerialNo().get());
+ return json;
+ }
- private void readObject(ObjectInputStream stream)
- throws IOException, ClassNotFoundException {
- stream.defaultReadObject();
- this.setupPool(serial);
+ @Override
+ protected void fromCheckpointJson(JSONObject json) throws JSONException {
+ super.fromCheckpointJson(json);
+ serial.set(json.getInt("serialNumber"));
}
-
+
protected WriterPool getPool() {
return pool;
}
|
2f40ce3e2a5e244315c16865967f58930f57cf7c
|
ReactiveX-RxJava
|
Added takeLast to Observable--
|
a
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-core/src/main/java/rx/Observable.java b/rxjava-core/src/main/java/rx/Observable.java
index 0df09cb3c7..d234a73ba2 100644
--- a/rxjava-core/src/main/java/rx/Observable.java
+++ b/rxjava-core/src/main/java/rx/Observable.java
@@ -1347,6 +1347,22 @@ public static <T> Observable<T> take(final Observable<T> items, final int num) {
return _create(OperationTake.take(items, num));
}
+ /**
+ * Returns an Observable that emits the last <code>count</code> items emitted by the source
+ * Observable.
+ *
+ * @param items
+ * the source Observable
+ * @param count
+ * the number of items from the end of the sequence emitted by the source
+ * Observable to emit
+ * @return an Observable that only emits the last <code>count</code> items emitted by the source
+ * Observable
+ */
+ public static <T> Observable<T> takeLast(final Observable<T> items, final int count) {
+ return _create(OperationTakeLast.takeLast(items, count));
+ }
+
/**
* Returns an Observable that emits a single item, a list composed of all the items emitted by
* the source Observable.
@@ -2235,6 +2251,20 @@ public Observable<T> take(final int num) {
return take(this, num);
}
+ /**
+ * Returns an Observable that emits the last <code>count</code> items emitted by the source
+ * Observable.
+ *
+ * @param count
+ * the number of items from the end of the sequence emitted by the source
+ * Observable to emit
+ * @return an Observable that only emits the last <code>count</code> items emitted by the source
+ * Observable
+ */
+ public Observable<T> takeLast(final int count) {
+ return takeLast(this, count);
+ }
+
/**
* Returns an Observable that emits a single item, a list composed of all the items emitted by
* the source Observable.
diff --git a/rxjava-core/src/main/java/rx/operators/OperationTakeLast.java b/rxjava-core/src/main/java/rx/operators/OperationTakeLast.java
index a3116dea58..57e336739e 100644
--- a/rxjava-core/src/main/java/rx/operators/OperationTakeLast.java
+++ b/rxjava-core/src/main/java/rx/operators/OperationTakeLast.java
@@ -23,13 +23,14 @@
import rx.util.functions.Func1;
import java.util.Iterator;
-import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingDeque;
-import java.util.concurrent.atomic.AtomicInteger;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
+/**
+ * Returns a specified number of contiguous elements from the end of an observable sequence.
+ */
public final class OperationTakeLast {
public static <T> Func1<Observer<T>, Subscription> takeLast(final Observable<T> items, final int count) {
|
6418b54f81a9e56242fb78fda4bf95e7b3d4c572
|
spring-framework
|
DataBinder tries ConversionService if- PropertyEditor could not produce required type--Issue: SPR-13042-
|
a
|
https://github.com/spring-projects/spring-framework
|
diff --git a/spring-beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java b/spring-beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java
index ff4cfa681afc..149d7ec3e670 100644
--- a/spring-beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java
+++ b/spring-beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java
@@ -159,29 +159,28 @@ public <T> T convertIfNecessary(
public <T> T convertIfNecessary(String propertyName, Object oldValue, Object newValue,
Class<T> requiredType, TypeDescriptor typeDescriptor) throws IllegalArgumentException {
- Object convertedValue = newValue;
-
// Custom editor for this type?
PropertyEditor editor = this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName);
- ConversionFailedException firstAttemptEx = null;
+ ConversionFailedException conversionAttemptEx = null;
// No custom editor but custom ConversionService specified?
ConversionService conversionService = this.propertyEditorRegistry.getConversionService();
- if (editor == null && conversionService != null && convertedValue != null && typeDescriptor != null) {
+ if (editor == null && conversionService != null && newValue != null && typeDescriptor != null) {
TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue);
- TypeDescriptor targetTypeDesc = typeDescriptor;
- if (conversionService.canConvert(sourceTypeDesc, targetTypeDesc)) {
+ if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) {
try {
- return (T) conversionService.convert(convertedValue, sourceTypeDesc, targetTypeDesc);
+ return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor);
}
catch (ConversionFailedException ex) {
// fallback to default conversion logic below
- firstAttemptEx = ex;
+ conversionAttemptEx = ex;
}
}
}
+ Object convertedValue = newValue;
+
// Value not of required type?
if (editor != null || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) {
if (requiredType != null && Collection.class.isAssignableFrom(requiredType) && convertedValue instanceof String) {
@@ -233,7 +232,7 @@ else if (convertedValue instanceof Map) {
return (T) convertedValue.toString();
}
else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) {
- if (firstAttemptEx == null && !requiredType.isInterface() && !requiredType.isEnum()) {
+ if (conversionAttemptEx == null && !requiredType.isInterface() && !requiredType.isEnum()) {
try {
Constructor<T> strCtor = requiredType.getConstructor(String.class);
return BeanUtils.instantiateClass(strCtor, convertedValue);
@@ -272,9 +271,19 @@ else if (convertedValue instanceof Number && Number.class.isAssignableFrom(requi
}
if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) {
- if (firstAttemptEx != null) {
- throw firstAttemptEx;
+ if (conversionAttemptEx != null) {
+ // Original exception from former ConversionService call above...
+ throw conversionAttemptEx;
}
+ else if (conversionService != null) {
+ // ConversionService not tried before, probably custom editor found
+ // but editor couldn't produce the required type...
+ TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue);
+ if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) {
+ return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor);
+ }
+ }
+
// Definitely doesn't match: throw IllegalArgumentException/IllegalStateException
StringBuilder msg = new StringBuilder();
msg.append("Cannot convert value of type [").append(ClassUtils.getDescriptiveType(newValue));
@@ -295,12 +304,12 @@ else if (convertedValue instanceof Number && Number.class.isAssignableFrom(requi
}
}
- if (firstAttemptEx != null) {
+ if (conversionAttemptEx != null) {
if (editor == null && !standardConversion && requiredType != null && !Object.class.equals(requiredType)) {
- throw firstAttemptEx;
+ throw conversionAttemptEx;
}
logger.debug("Original ConversionService attempt failed - ignored since " +
- "PropertyEditor based conversion eventually succeeded", firstAttemptEx);
+ "PropertyEditor based conversion eventually succeeded", conversionAttemptEx);
}
return (T) convertedValue;
diff --git a/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java b/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java
index 291f8582afec..aecc61995a77 100644
--- a/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java
+++ b/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java
@@ -43,12 +43,15 @@
import org.springframework.beans.NullValueInNestedPathException;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
+import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.context.support.StaticMessageSource;
+import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.format.Formatter;
import org.springframework.format.number.NumberStyleFormatter;
+import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.tests.sample.beans.BeanWithObjectProperty;
import org.springframework.tests.sample.beans.DerivedTestBean;
@@ -592,6 +595,19 @@ public String print(String object, Locale locale) {
assertEquals("test", binder.getBindingResult().getFieldValue("name"));
}
+ @Test
+ public void testConversionWithInappropriateStringEditor() {
+ DataBinder dataBinder = new DataBinder(null);
+ DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
+ dataBinder.setConversionService(conversionService);
+ dataBinder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
+
+ NameBean bean = new NameBean("Fred");
+ assertEquals("ConversionService should have invoked toString()", "Fred", dataBinder.convertIfNecessary(bean, String.class));
+ conversionService.addConverter(new NameBeanConverter());
+ assertEquals("Type converter should have been used", "[Fred]", dataBinder.convertIfNecessary(bean, String.class));
+ }
+
@Test
public void testBindingWithAllowedFields() throws Exception {
TestBean rod = new TestBean();
@@ -2087,4 +2103,30 @@ public Map<String, Object> getF() {
}
}
+
+ public static class NameBean {
+
+ private final String name;
+
+ public NameBean(String name) {
+ this.name = name;
+ }
+ public String getName() {
+ return name;
+ }
+ @Override
+ public String toString() {
+ return name;
+ }
+ }
+
+
+ public static class NameBeanConverter implements Converter<NameBean, String> {
+
+ @Override
+ public String convert(NameBean source) {
+ return "[" + source.getName() + "]";
+ }
+ }
+
}
|
215f988c8b38f13d6d0b8cba9985d670ba4cc2cb
|
tapiji
|
Clean up build.properties files
(cherry picked from commit 37533f23fb71c70eab08d9f1de091fcae1b0c400)
Conflicts:
org.eclipse.babel.editor.nls/build.properties
org.eclipse.babel.tapiji.tools.core/build.properties
|
p
|
https://github.com/tapiji/tapiji
|
diff --git a/org.eclipse.babel.core.pdeutils/build.properties b/org.eclipse.babel.core.pdeutils/build.properties
index b9667611..06134302 100644
--- a/org.eclipse.babel.core.pdeutils/build.properties
+++ b/org.eclipse.babel.core.pdeutils/build.properties
@@ -3,12 +3,10 @@ output.. = bin/
bin.includes = META-INF/,\
.,\
org.eclipse.babel.core.pdeutils.jar,\
- about.html,\
- epl-v10.html
+ about.html
source.org.eclipse.babel.core.pdeutils.jar = src/
jars.compile.order = org.eclipse.babel.core.pdeutils.jar,\
.
output.org.eclipse.babel.core.pdeutils.jar = bin/
source.org.eclipse.babel.core.pdeutils.jar = src/
-src.includes = epl-v10.html,\
- about.html
+src.includes = about.html
diff --git a/org.eclipse.babel.editor.nls/about.html b/org.eclipse.babel.editor.nls/about.html
new file mode 100644
index 00000000..c258ef55
--- /dev/null
+++ b/org.eclipse.babel.editor.nls/about.html
@@ -0,0 +1,28 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
+<title>About</title>
+</head>
+<body lang="EN-US">
+<h2>About This Content</h2>
+
+<p>June 5, 2006</p>
+<h3>License</h3>
+
+<p>The Eclipse Foundation makes available all content in this plug-in ("Content"). Unless otherwise
+indicated below, the Content is provided to you under the terms and conditions of the
+Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is available
+at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>.
+For purposes of the EPL, "Program" will mean the Content.</p>
+
+<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is
+being redistributed by another party ("Redistributor") and different terms and conditions may
+apply to your use of any object code in the Content. Check the Redistributor's license that was
+provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise
+indicated below, the terms and conditions of the EPL still apply to any source code in the Content
+and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p>
+
+</body>
+</html>
\ No newline at end of file
diff --git a/org.eclipse.babel.editor.nls/build.properties b/org.eclipse.babel.editor.nls/build.properties
index 812de0d6..5db3b7e1 100644
--- a/org.eclipse.babel.editor.nls/build.properties
+++ b/org.eclipse.babel.editor.nls/build.properties
@@ -1,5 +1,8 @@
-bin.includes = META-INF/,\
- nl/,\
- plugin_fr.properties
-src.includes = nl/,\
- plugin_fr.properties
+bin.includes = META-INF/,\
+ nl/,\
+ plugin_fr.properties,\
+ about.html
+src.includes = nl/,\
+ plugin_fr.properties,\
+ about.html
+
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/build.properties b/org.eclipse.babel.tapiji.tools.core.ui/build.properties
index 05b10a6c..507fa84c 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/build.properties
+++ b/org.eclipse.babel.tapiji.tools.core.ui/build.properties
@@ -3,8 +3,6 @@ output.. = bin/
bin.includes = META-INF/,\
plugin.xml,\
icons/,\
- about.html,\
- epl-v10.html
+ about.html
src.includes = icons/,\
- epl-v10.html,\
about.html
diff --git a/org.eclipse.babel.tapiji.tools.core/build.properties b/org.eclipse.babel.tapiji.tools.core/build.properties
index 62a5dd41..45aad752 100644
--- a/org.eclipse.babel.tapiji.tools.core/build.properties
+++ b/org.eclipse.babel.tapiji.tools.core/build.properties
@@ -4,9 +4,7 @@ bin.includes = plugin.xml,\
META-INF/,\
.,\
schema/,\
- about.html,\
- epl-v10.html
+ about.html
src.includes = schema/,\
- about.html,\
- epl-v10.html
+ about.html
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/build.properties b/org.eclipse.babel.tapiji.tools.java.ui/build.properties
index 23b68b71..44de5d7e 100644
--- a/org.eclipse.babel.tapiji.tools.java.ui/build.properties
+++ b/org.eclipse.babel.tapiji.tools.java.ui/build.properties
@@ -2,7 +2,5 @@ source.. = src/
output.. = bin/
bin.includes = META-INF/,\
plugin.xml,\
- epl-v10.html,\
- about.html
-src.includes = epl-v10.html,\
about.html
+src.includes = about.html
diff --git a/org.eclipse.babel.tapiji.tools.java/build.properties b/org.eclipse.babel.tapiji.tools.java/build.properties
index 302de5ff..3e7f0edc 100644
--- a/org.eclipse.babel.tapiji.tools.java/build.properties
+++ b/org.eclipse.babel.tapiji.tools.java/build.properties
@@ -1,7 +1,5 @@
source.. = src/
output.. = bin/
bin.includes = META-INF/,\
- epl-v10.html,\
- about.html
-src.includes = epl-v10.html,\
about.html
+src.includes = about.html
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/build.properties b/org.eclipse.babel.tapiji.tools.rbmanager/build.properties
index 8584b90f..49e3707d 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/build.properties
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/build.properties
@@ -3,9 +3,7 @@ output.. = bin/
bin.includes = META-INF/,\
.,\
icons/,\
- epl-v10.html,\
about.html,\
plugin.xml
src.includes = icons/,\
- epl-v10.html,\
about.html
|
dde07c616e4a0e866a0d7f0bc3f63979fc571d08
|
Mylyn Reviews
|
Merge branch 'master' of git://git.eclipse.org/gitroot/mylyn/org.eclipse.mylyn.reviews
|
p
|
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
|
diff --git a/framework/org.eclipse.mylyn.reviews.core/.settings/org.eclipse.core.resources.prefs b/framework/org.eclipse.mylyn.reviews.core/.settings/org.eclipse.core.resources.prefs
new file mode 100644
index 00000000..325dab47
--- /dev/null
+++ b/framework/org.eclipse.mylyn.reviews.core/.settings/org.eclipse.core.resources.prefs
@@ -0,0 +1,3 @@
+#Sat Feb 05 01:34:50 PST 2011
+eclipse.preferences.version=1
+encoding//model/reviews.ecorediag=UTF-8
diff --git a/framework/org.eclipse.mylyn.reviews.core/META-INF/MANIFEST.MF b/framework/org.eclipse.mylyn.reviews.core/META-INF/MANIFEST.MF
index ab99a50d..b2aef3a0 100644
--- a/framework/org.eclipse.mylyn.reviews.core/META-INF/MANIFEST.MF
+++ b/framework/org.eclipse.mylyn.reviews.core/META-INF/MANIFEST.MF
@@ -1,6 +1,6 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
-Bundle-Name: Mylyn Reviews
+Bundle-Name: Mylyn Reviews (Incubation)
Bundle-SymbolicName: org.eclipse.mylyn.reviews.core;singleton:=true
Bundle-Version: 0.7.0.qualifier
Require-Bundle: org.eclipse.core.runtime,
diff --git a/framework/org.eclipse.mylyn.reviews.core/model/.gitignore b/framework/org.eclipse.mylyn.reviews.core/model/.gitignore
new file mode 100644
index 00000000..befd229a
--- /dev/null
+++ b/framework/org.eclipse.mylyn.reviews.core/model/.gitignore
@@ -0,0 +1 @@
+/reviews.ecorediag
diff --git a/framework/org.eclipse.mylyn.reviews.core/model/reviews.ecore b/framework/org.eclipse.mylyn.reviews.core/model/reviews.ecore
index 4351a753..3d439fa8 100644
--- a/framework/org.eclipse.mylyn.reviews.core/model/reviews.ecore
+++ b/framework/org.eclipse.mylyn.reviews.core/model/reviews.ecore
@@ -12,6 +12,7 @@
containment="true"/>
<eStructuralFeatures xsi:type="ecore:EReference" name="state" lowerBound="1" eType="#//ReviewState"
containment="true"/>
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="id" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
</eClassifiers>
<eClassifiers xsi:type="ecore:EClass" name="Comment" eSuperTypes="#//ReviewComponent">
<eStructuralFeatures xsi:type="ecore:EReference" name="author" lowerBound="1"
@@ -83,6 +84,8 @@
<eStructuralFeatures xsi:type="ecore:EAttribute" name="id" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
<eStructuralFeatures xsi:type="ecore:EReference" name="items" upperBound="-1"
eType="#//ReviewItem" containment="true"/>
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="revision" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"
+ defaultValueLiteral=""/>
</eClassifiers>
<eClassifiers xsi:type="ecore:EClass" name="LineLocation" eSuperTypes="#//Location">
<eStructuralFeatures xsi:type="ecore:EReference" name="ranges" upperBound="-1"
diff --git a/framework/org.eclipse.mylyn.reviews.core/model/reviews.genmodel b/framework/org.eclipse.mylyn.reviews.core/model/reviews.genmodel
index 830597c8..23e73b0c 100644
--- a/framework/org.eclipse.mylyn.reviews.core/model/reviews.genmodel
+++ b/framework/org.eclipse.mylyn.reviews.core/model/reviews.genmodel
@@ -2,7 +2,7 @@
<genmodel:GenModel xmi:version="2.0"
xmlns:xmi="http://www.omg.org/XMI" xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore"
xmlns:genmodel="http://www.eclipse.org/emf/2002/GenModel" copyrightText="Copyright (c) 2011 Tasktop Technologies 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:
 Tasktop Technologies - initial API and implementation"
- modelDirectory="/org.eclipse.mylyn.gerrit.core/src" editDirectory="/org.eclipse.mylyn.reviews.edit/src"
+ modelDirectory="/org.eclipse.mylyn.reviews.core/src" editDirectory="/org.eclipse.mylyn.reviews.edit/src"
editorDirectory="/org.eclipse.mylyn.reviews.editor/src" modelPluginID="org.eclipse.mylyn.reviews.core"
modelName="Reviews" modelPluginClass="" nonNLSMarkers="true" rootExtendsInterface=""
rootImplementsInterface="" suppressEMFTypes="true" suppressEMFMetaData="true"
@@ -22,6 +22,7 @@
<genFeatures notify="false" createChild="false" propertySortChoices="true" ecoreFeature="ecore:EReference reviews.ecore#//Review/items"/>
<genFeatures property="None" children="true" createChild="true" ecoreFeature="ecore:EReference reviews.ecore#//Review/reviewTask"/>
<genFeatures property="None" children="true" createChild="true" ecoreFeature="ecore:EReference reviews.ecore#//Review/state"/>
+ <genFeatures createChild="false" ecoreFeature="ecore:EAttribute reviews.ecore#//Review/id"/>
</genClasses>
<genClasses ecoreClass="reviews.ecore#//Comment">
<genFeatures notify="false" createChild="false" propertySortChoices="true" ecoreFeature="ecore:EReference reviews.ecore#//Comment/author"/>
@@ -72,6 +73,7 @@
<genClasses ecoreClass="reviews.ecore#//ReviewItemSet">
<genFeatures createChild="false" ecoreFeature="ecore:EAttribute reviews.ecore#//ReviewItemSet/id"/>
<genFeatures property="None" children="true" createChild="true" ecoreFeature="ecore:EReference reviews.ecore#//ReviewItemSet/items"/>
+ <genFeatures createChild="false" ecoreFeature="ecore:EAttribute reviews.ecore#//ReviewItemSet/revision"/>
</genClasses>
<genClasses ecoreClass="reviews.ecore#//LineLocation">
<genFeatures property="None" children="true" createChild="true" ecoreFeature="ecore:EReference reviews.ecore#//LineLocation/ranges"/>
@@ -84,7 +86,6 @@
<genFeatures createChild="false" ecoreFeature="ecore:EAttribute reviews.ecore#//FileRevision/path"/>
<genFeatures createChild="false" ecoreFeature="ecore:EAttribute reviews.ecore#//FileRevision/revision"/>
<genFeatures createChild="false" ecoreFeature="ecore:EAttribute reviews.ecore#//FileRevision/content"/>
- <genFeatures notify="false" createChild="false" propertySortChoices="true" ecoreFeature="ecore:EReference reviews.ecore#//FileRevision/topics"/>
</genClasses>
</genPackages>
</genmodel:GenModel>
diff --git a/framework/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/IReview.java b/framework/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/IReview.java
index abb6c14f..b010f681 100644
--- a/framework/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/IReview.java
+++ b/framework/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/IReview.java
@@ -24,6 +24,7 @@
* <li>{@link org.eclipse.mylyn.reviews.core.model.IReview#getItems <em>Items</em>}</li>
* <li>{@link org.eclipse.mylyn.reviews.core.model.IReview#getReviewTask <em>Review Task</em>}</li>
* <li>{@link org.eclipse.mylyn.reviews.core.model.IReview#getState <em>State</em>}</li>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.IReview#getId <em>Id</em>}</li>
* </ul>
* </p>
*
@@ -106,4 +107,28 @@ public interface IReview extends IReviewComponent {
*/
void setState(IReviewState value);
+ /**
+ * Returns the value of the '<em><b>Id</b></em>' attribute.
+ * <!-- begin-user-doc -->
+ * <p>
+ * If the meaning of the '<em>Id</em>' attribute isn't clear,
+ * there really should be more of a description here...
+ * </p>
+ * <!-- end-user-doc -->
+ * @return the value of the '<em>Id</em>' attribute.
+ * @see #setId(String)
+ * @generated
+ */
+ String getId();
+
+ /**
+ * Sets the value of the '{@link org.eclipse.mylyn.reviews.core.model.IReview#getId <em>Id</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @param value the new value of the '<em>Id</em>' attribute.
+ * @see #getId()
+ * @generated
+ */
+ void setId(String value);
+
} // IReview
diff --git a/framework/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/IReviewItemSet.java b/framework/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/IReviewItemSet.java
index 9fef85c7..8d007541 100644
--- a/framework/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/IReviewItemSet.java
+++ b/framework/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/IReviewItemSet.java
@@ -22,6 +22,7 @@
* <ul>
* <li>{@link org.eclipse.mylyn.reviews.core.model.IReviewItemSet#getId <em>Id</em>}</li>
* <li>{@link org.eclipse.mylyn.reviews.core.model.IReviewItemSet#getItems <em>Items</em>}</li>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.IReviewItemSet#getRevision <em>Revision</em>}</li>
* </ul>
* </p>
*
@@ -66,4 +67,29 @@ public interface IReviewItemSet extends IReviewItem {
*/
List<IReviewItem> getItems();
+ /**
+ * Returns the value of the '<em><b>Revision</b></em>' attribute.
+ * The default value is <code>""</code>.
+ * <!-- begin-user-doc -->
+ * <p>
+ * If the meaning of the '<em>Revision</em>' attribute isn't clear,
+ * there really should be more of a description here...
+ * </p>
+ * <!-- end-user-doc -->
+ * @return the value of the '<em>Revision</em>' attribute.
+ * @see #setRevision(String)
+ * @generated
+ */
+ String getRevision();
+
+ /**
+ * Sets the value of the '{@link org.eclipse.mylyn.reviews.core.model.IReviewItemSet#getRevision <em>Revision</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @param value the new value of the '<em>Revision</em>' attribute.
+ * @see #getRevision()
+ * @generated
+ */
+ void setRevision(String value);
+
} // IReviewItemSet
diff --git a/framework/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/internal/core/model/Review.java b/framework/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/internal/core/model/Review.java
index 57fcaff6..efd6f15c 100644
--- a/framework/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/internal/core/model/Review.java
+++ b/framework/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/internal/core/model/Review.java
@@ -43,6 +43,7 @@
* <li>{@link org.eclipse.mylyn.reviews.internal.core.model.Review#getItems <em>Items</em>}</li>
* <li>{@link org.eclipse.mylyn.reviews.internal.core.model.Review#getReviewTask <em>Review Task</em>}</li>
* <li>{@link org.eclipse.mylyn.reviews.internal.core.model.Review#getState <em>State</em>}</li>
+ * <li>{@link org.eclipse.mylyn.reviews.internal.core.model.Review#getId <em>Id</em>}</li>
* </ul>
* </p>
*
@@ -89,6 +90,26 @@ public class Review extends ReviewComponent implements IReview {
*/
protected IReviewState state;
+ /**
+ * The default value of the '{@link #getId() <em>Id</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getId()
+ * @generated
+ * @ordered
+ */
+ protected static final String ID_EDEFAULT = null;
+
+ /**
+ * The cached value of the '{@link #getId() <em>Id</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getId()
+ * @generated
+ * @ordered
+ */
+ protected String id = ID_EDEFAULT;
+
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
@@ -231,6 +252,27 @@ public void setState(IReviewState newState) {
eNotify(new ENotificationImpl(this, Notification.SET, ReviewsPackage.REVIEW__STATE, newState, newState));
}
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public String getId() {
+ return id;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public void setId(String newId) {
+ String oldId = id;
+ id = newId;
+ if (eNotificationRequired())
+ eNotify(new ENotificationImpl(this, Notification.SET, ReviewsPackage.REVIEW__ID, oldId, id));
+ }
+
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
@@ -263,6 +305,8 @@ public Object eGet(int featureID, boolean resolve, boolean coreType) {
return getReviewTask();
case ReviewsPackage.REVIEW__STATE:
return getState();
+ case ReviewsPackage.REVIEW__ID:
+ return getId();
}
return super.eGet(featureID, resolve, coreType);
}
@@ -290,6 +334,9 @@ public void eSet(int featureID, Object newValue) {
case ReviewsPackage.REVIEW__STATE:
setState((IReviewState) newValue);
return;
+ case ReviewsPackage.REVIEW__ID:
+ setId((String) newValue);
+ return;
}
super.eSet(featureID, newValue);
}
@@ -314,6 +361,9 @@ public void eUnset(int featureID) {
case ReviewsPackage.REVIEW__STATE:
setState((IReviewState) null);
return;
+ case ReviewsPackage.REVIEW__ID:
+ setId(ID_EDEFAULT);
+ return;
}
super.eUnset(featureID);
}
@@ -334,8 +384,27 @@ public boolean eIsSet(int featureID) {
return reviewTask != null;
case ReviewsPackage.REVIEW__STATE:
return state != null;
+ case ReviewsPackage.REVIEW__ID:
+ return ID_EDEFAULT == null ? id != null : !ID_EDEFAULT.equals(id);
}
return super.eIsSet(featureID);
}
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public String toString() {
+ if (eIsProxy())
+ return super.toString();
+
+ StringBuffer result = new StringBuffer(super.toString());
+ result.append(" (id: "); //$NON-NLS-1$
+ result.append(id);
+ result.append(')');
+ return result.toString();
+ }
+
} //Review
diff --git a/framework/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/internal/core/model/ReviewItemSet.java b/framework/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/internal/core/model/ReviewItemSet.java
index 585db6a6..e9b133a1 100644
--- a/framework/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/internal/core/model/ReviewItemSet.java
+++ b/framework/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/internal/core/model/ReviewItemSet.java
@@ -35,6 +35,7 @@
* <ul>
* <li>{@link org.eclipse.mylyn.reviews.internal.core.model.ReviewItemSet#getId <em>Id</em>}</li>
* <li>{@link org.eclipse.mylyn.reviews.internal.core.model.ReviewItemSet#getItems <em>Items</em>}</li>
+ * <li>{@link org.eclipse.mylyn.reviews.internal.core.model.ReviewItemSet#getRevision <em>Revision</em>}</li>
* </ul>
* </p>
*
@@ -71,6 +72,26 @@ public class ReviewItemSet extends ReviewItem implements IReviewItemSet {
*/
protected EList<IReviewItem> items;
+ /**
+ * The default value of the '{@link #getRevision() <em>Revision</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getRevision()
+ * @generated
+ * @ordered
+ */
+ protected static final String REVISION_EDEFAULT = ""; //$NON-NLS-1$
+
+ /**
+ * The cached value of the '{@link #getRevision() <em>Revision</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getRevision()
+ * @generated
+ * @ordered
+ */
+ protected String revision = REVISION_EDEFAULT;
+
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
@@ -124,6 +145,28 @@ public List<IReviewItem> getItems() {
return items;
}
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public String getRevision() {
+ return revision;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public void setRevision(String newRevision) {
+ String oldRevision = revision;
+ revision = newRevision;
+ if (eNotificationRequired())
+ eNotify(new ENotificationImpl(this, Notification.SET, ReviewsPackage.REVIEW_ITEM_SET__REVISION,
+ oldRevision, revision));
+ }
+
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
@@ -150,6 +193,8 @@ public Object eGet(int featureID, boolean resolve, boolean coreType) {
return getId();
case ReviewsPackage.REVIEW_ITEM_SET__ITEMS:
return getItems();
+ case ReviewsPackage.REVIEW_ITEM_SET__REVISION:
+ return getRevision();
}
return super.eGet(featureID, resolve, coreType);
}
@@ -170,6 +215,9 @@ public void eSet(int featureID, Object newValue) {
getItems().clear();
getItems().addAll((Collection<? extends IReviewItem>) newValue);
return;
+ case ReviewsPackage.REVIEW_ITEM_SET__REVISION:
+ setRevision((String) newValue);
+ return;
}
super.eSet(featureID, newValue);
}
@@ -188,6 +236,9 @@ public void eUnset(int featureID) {
case ReviewsPackage.REVIEW_ITEM_SET__ITEMS:
getItems().clear();
return;
+ case ReviewsPackage.REVIEW_ITEM_SET__REVISION:
+ setRevision(REVISION_EDEFAULT);
+ return;
}
super.eUnset(featureID);
}
@@ -204,6 +255,8 @@ public boolean eIsSet(int featureID) {
return ID_EDEFAULT == null ? id != null : !ID_EDEFAULT.equals(id);
case ReviewsPackage.REVIEW_ITEM_SET__ITEMS:
return items != null && !items.isEmpty();
+ case ReviewsPackage.REVIEW_ITEM_SET__REVISION:
+ return REVISION_EDEFAULT == null ? revision != null : !REVISION_EDEFAULT.equals(revision);
}
return super.eIsSet(featureID);
}
@@ -221,6 +274,8 @@ public String toString() {
StringBuffer result = new StringBuffer(super.toString());
result.append(" (id: "); //$NON-NLS-1$
result.append(id);
+ result.append(", revision: "); //$NON-NLS-1$
+ result.append(revision);
result.append(')');
return result.toString();
}
diff --git a/framework/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/internal/core/model/ReviewsPackage.java b/framework/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/internal/core/model/ReviewsPackage.java
index ab2cf6c8..7e66115f 100644
--- a/framework/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/internal/core/model/ReviewsPackage.java
+++ b/framework/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/internal/core/model/ReviewsPackage.java
@@ -167,6 +167,15 @@ public class ReviewsPackage extends EPackageImpl {
*/
public static final int REVIEW__STATE = REVIEW_COMPONENT_FEATURE_COUNT + 3;
+ /**
+ * The feature id for the '<em><b>Id</b></em>' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ * @ordered
+ */
+ public static final int REVIEW__ID = REVIEW_COMPONENT_FEATURE_COUNT + 4;
+
/**
* The number of structural features of the '<em>Review</em>' class.
* <!-- begin-user-doc -->
@@ -174,7 +183,7 @@ public class ReviewsPackage extends EPackageImpl {
* @generated
* @ordered
*/
- public static final int REVIEW_FEATURE_COUNT = REVIEW_COMPONENT_FEATURE_COUNT + 4;
+ public static final int REVIEW_FEATURE_COUNT = REVIEW_COMPONENT_FEATURE_COUNT + 5;
/**
* The meta object id for the '{@link org.eclipse.mylyn.reviews.internal.core.model.Comment <em>Comment</em>}' class.
@@ -835,6 +844,15 @@ public class ReviewsPackage extends EPackageImpl {
*/
public static final int REVIEW_ITEM_SET__ITEMS = REVIEW_ITEM_FEATURE_COUNT + 1;
+ /**
+ * The feature id for the '<em><b>Revision</b></em>' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ * @ordered
+ */
+ public static final int REVIEW_ITEM_SET__REVISION = REVIEW_ITEM_FEATURE_COUNT + 2;
+
/**
* The number of structural features of the '<em>Review Item Set</em>' class.
* <!-- begin-user-doc -->
@@ -842,7 +860,7 @@ public class ReviewsPackage extends EPackageImpl {
* @generated
* @ordered
*/
- public static final int REVIEW_ITEM_SET_FEATURE_COUNT = REVIEW_ITEM_FEATURE_COUNT + 2;
+ public static final int REVIEW_ITEM_SET_FEATURE_COUNT = REVIEW_ITEM_FEATURE_COUNT + 3;
/**
* The meta object id for the '{@link org.eclipse.mylyn.reviews.internal.core.model.LineLocation <em>Line Location</em>}' class.
@@ -1238,6 +1256,19 @@ public EReference getReview_State() {
return (EReference) reviewEClass.getEStructuralFeatures().get(3);
}
+ /**
+ * Returns the meta object for the attribute '{@link org.eclipse.mylyn.reviews.core.model.IReview#getId <em>Id</em>}'.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return the meta object for the attribute '<em>Id</em>'.
+ * @see org.eclipse.mylyn.reviews.core.model.IReview#getId()
+ * @see #getReview()
+ * @generated
+ */
+ public EAttribute getReview_Id() {
+ return (EAttribute) reviewEClass.getEStructuralFeatures().get(4);
+ }
+
/**
* Returns the meta object for class '{@link org.eclipse.mylyn.reviews.core.model.IComment <em>Comment</em>}'.
* <!-- begin-user-doc -->
@@ -1759,6 +1790,19 @@ public EReference getReviewItemSet_Items() {
return (EReference) reviewItemSetEClass.getEStructuralFeatures().get(1);
}
+ /**
+ * Returns the meta object for the attribute '{@link org.eclipse.mylyn.reviews.core.model.IReviewItemSet#getRevision <em>Revision</em>}'.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @return the meta object for the attribute '<em>Revision</em>'.
+ * @see org.eclipse.mylyn.reviews.core.model.IReviewItemSet#getRevision()
+ * @see #getReviewItemSet()
+ * @generated
+ */
+ public EAttribute getReviewItemSet_Revision() {
+ return (EAttribute) reviewItemSetEClass.getEStructuralFeatures().get(2);
+ }
+
/**
* Returns the meta object for class '{@link org.eclipse.mylyn.reviews.core.model.ILineLocation <em>Line Location</em>}'.
* <!-- begin-user-doc -->
@@ -1909,6 +1953,7 @@ public void createPackageContents() {
createEReference(reviewEClass, REVIEW__ITEMS);
createEReference(reviewEClass, REVIEW__REVIEW_TASK);
createEReference(reviewEClass, REVIEW__STATE);
+ createEAttribute(reviewEClass, REVIEW__ID);
commentEClass = createEClass(COMMENT);
createEReference(commentEClass, COMMENT__AUTHOR);
@@ -1962,6 +2007,7 @@ public void createPackageContents() {
reviewItemSetEClass = createEClass(REVIEW_ITEM_SET);
createEAttribute(reviewItemSetEClass, REVIEW_ITEM_SET__ID);
createEReference(reviewItemSetEClass, REVIEW_ITEM_SET__ITEMS);
+ createEAttribute(reviewItemSetEClass, REVIEW_ITEM_SET__REVISION);
lineLocationEClass = createEClass(LINE_LOCATION);
createEReference(lineLocationEClass, LINE_LOCATION__RANGES);
@@ -2039,6 +2085,10 @@ public void initializePackageContents() {
this.getReviewState(),
null,
"state", null, 1, 1, IReview.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); //$NON-NLS-1$
+ initEAttribute(
+ getReview_Id(),
+ ecorePackage.getEString(),
+ "id", null, 0, 1, IReview.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); //$NON-NLS-1$
initEClass(commentEClass, IComment.class, "Comment", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); //$NON-NLS-1$
initEReference(
@@ -2203,6 +2253,10 @@ public void initializePackageContents() {
this.getReviewItem(),
null,
"items", null, 0, -1, IReviewItemSet.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); //$NON-NLS-1$
+ initEAttribute(
+ getReviewItemSet_Revision(),
+ ecorePackage.getEString(),
+ "revision", "", 0, 1, IReviewItemSet.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); //$NON-NLS-1$ //$NON-NLS-2$
initEClass(lineLocationEClass, ILineLocation.class,
"LineLocation", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); //$NON-NLS-1$
@@ -2315,6 +2369,14 @@ public interface Literals {
*/
public static final EReference REVIEW__STATE = eINSTANCE.getReview_State();
+ /**
+ * The meta object literal for the '<em><b>Id</b></em>' attribute feature.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public static final EAttribute REVIEW__ID = eINSTANCE.getReview_Id();
+
/**
* The meta object literal for the '{@link org.eclipse.mylyn.reviews.internal.core.model.Comment <em>Comment</em>}' class.
* <!-- begin-user-doc -->
@@ -2667,6 +2729,14 @@ public interface Literals {
*/
public static final EReference REVIEW_ITEM_SET__ITEMS = eINSTANCE.getReviewItemSet_Items();
+ /**
+ * The meta object literal for the '<em><b>Revision</b></em>' attribute feature.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public static final EAttribute REVIEW_ITEM_SET__REVISION = eINSTANCE.getReviewItemSet_Revision();
+
/**
* The meta object literal for the '{@link org.eclipse.mylyn.reviews.internal.core.model.LineLocation <em>Line Location</em>}' class.
* <!-- begin-user-doc -->
diff --git a/framework/org.eclipse.mylyn.reviews.ui/META-INF/MANIFEST.MF b/framework/org.eclipse.mylyn.reviews.ui/META-INF/MANIFEST.MF
index 748a0538..1cf3ad70 100644
--- a/framework/org.eclipse.mylyn.reviews.ui/META-INF/MANIFEST.MF
+++ b/framework/org.eclipse.mylyn.reviews.ui/META-INF/MANIFEST.MF
@@ -1,6 +1,6 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
-Bundle-Name: Mylyn Reviews
+Bundle-Name: Mylyn Reviews (Incubation)
Bundle-SymbolicName: org.eclipse.mylyn.reviews.ui;singleton:=true
Bundle-Version: 0.7.0.qualifier
Require-Bundle: org.eclipse.ui,
diff --git a/gerrit/org.eclipse.mylyn.gerrit.core/META-INF/MANIFEST.MF b/gerrit/org.eclipse.mylyn.gerrit.core/META-INF/MANIFEST.MF
index c0919606..f1f0d27e 100644
--- a/gerrit/org.eclipse.mylyn.gerrit.core/META-INF/MANIFEST.MF
+++ b/gerrit/org.eclipse.mylyn.gerrit.core/META-INF/MANIFEST.MF
@@ -1,6 +1,6 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
-Bundle-Name: Mylyn Gerrit Connector
+Bundle-Name: Mylyn Gerrit Connector (Incubation)
Bundle-SymbolicName: org.eclipse.mylyn.gerrit.core;singleton:=true
Bundle-Version: 0.7.0.qualifier
Bundle-Activator: org.eclipse.mylyn.internal.gerrit.core.GerritCorePlugin
diff --git a/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/client/GerritClient.java b/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/client/GerritClient.java
index 786bfe0e..b20ada78 100644
--- a/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/client/GerritClient.java
+++ b/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/client/GerritClient.java
@@ -11,6 +11,7 @@
*********************************************************************/
package org.eclipse.mylyn.internal.gerrit.core.client;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -24,6 +25,7 @@
import org.eclipse.mylyn.reviews.core.model.ILineLocation;
import org.eclipse.mylyn.reviews.core.model.ILineRange;
import org.eclipse.mylyn.reviews.core.model.IReview;
+import org.eclipse.mylyn.reviews.core.model.IReviewItem;
import org.eclipse.mylyn.reviews.core.model.IReviewItemSet;
import org.eclipse.mylyn.reviews.core.model.ITopic;
import org.eclipse.mylyn.reviews.core.model.IUser;
@@ -43,12 +45,14 @@
import com.google.gerrit.common.data.PatchScript;
import com.google.gerrit.common.data.PatchSetDetail;
import com.google.gerrit.common.data.SingleListChangeInfo;
+import com.google.gerrit.common.data.SystemInfoService;
import com.google.gerrit.prettify.common.SparseFileContent;
import com.google.gerrit.reviewdb.Account;
import com.google.gerrit.reviewdb.Account.Id;
import com.google.gerrit.reviewdb.AccountDiffPreference;
import com.google.gerrit.reviewdb.AccountDiffPreference.Whitespace;
import com.google.gerrit.reviewdb.Change;
+import com.google.gerrit.reviewdb.ContributorAgreement;
import com.google.gerrit.reviewdb.Patch;
import com.google.gerrit.reviewdb.PatchLineComment;
import com.google.gerrit.reviewdb.PatchSet;
@@ -122,19 +126,37 @@ public void execute(IProgressMonitor monitor) throws GerritException {
}
public GerritSystemInfo getInfo(IProgressMonitor monitor) throws GerritException {
- Account account = execute(monitor, new GerritOperation<Account>() {
- @Override
- public void execute(IProgressMonitor monitor) throws GerritException {
- getAccountService().myAccount(this);
- }
- });
- return new GerritSystemInfo(account);
+ List<ContributorAgreement> contributorAgreements = null;
+ Account account = null;
+ if (!isAnonymous()) {
+// contributorAgreements = execute(monitor, new GerritOperation<List<ContributorAgreement>>() {
+// @Override
+// public void execute(IProgressMonitor monitor) throws GerritException {
+// getSystemInfoService().contributorAgreements(this);
+// }
+// });
+ account = execute(monitor, new GerritOperation<Account>() {
+ @Override
+ public void execute(IProgressMonitor monitor) throws GerritException {
+ getAccountService().myAccount(this);
+ }
+ });
+ } else {
+ // XXX should run some more meaningful validation as anonymous, for now any call is good to validate the URL etc.
+ executeQuery(monitor, "status:open"); //$NON-NLS-1$
+ }
+ return new GerritSystemInfo(contributorAgreements, account);
+ }
+
+ private boolean isAnonymous() {
+ return client.isAnonymous();
}
public PatchScript getPatchScript(final Patch.Key key, final PatchSet.Id leftId, final PatchSet.Id rightId,
IProgressMonitor monitor) throws GerritException {
//final AccountDiffPreference diffPrefs = getDiffPreference(monitor);
- final AccountDiffPreference diffPrefs = new AccountDiffPreference(getAccount(monitor).getId());
+ //final AccountDiffPreference diffPrefs = new AccountDiffPreference(getAccount(monitor).getId());
+ final AccountDiffPreference diffPrefs = new AccountDiffPreference((Account.Id) null);
diffPrefs.setLineLength(Integer.MAX_VALUE);
diffPrefs.setTabSize(4);
diffPrefs.setContext(AccountDiffPreference.WHOLE_FILE_CONTEXT);
@@ -258,6 +280,10 @@ public void execute(IProgressMonitor monitor) throws GerritException {
return myAcount;
}
+ private SystemInfoService getSystemInfoService() {
+ return getService(SystemInfoService.class);
+ }
+
private AccountService getAccountService() {
return getService(AccountService.class);
}
@@ -302,43 +328,54 @@ protected synchronized <T extends RemoteJsonService> T getService(Class<T> clazz
public IReview getReview(String reviewId, IProgressMonitor monitor) throws GerritException {
IReview review = FACTORY.createReview();
- ChangeDetail detail = getChangeDetail(Integer.parseInt(reviewId), monitor);
+ review.setId(reviewId);
+ ChangeDetail detail = getChangeDetail(id(reviewId), monitor);
List<PatchSet> patchSets = detail.getPatchSets();
for (PatchSet patchSet : patchSets) {
IReviewItemSet itemSet = FACTORY.createReviewItemSet();
itemSet.setName(NLS.bind("Patch Set {0}", patchSet.getPatchSetId()));
- itemSet.setId(patchSet.getRevision().get());
+ itemSet.setId(patchSet.getPatchSetId() + "");
+ itemSet.setAddedBy(createUser(patchSet.getUploader(), detail.getAccounts()));
+ itemSet.setRevision(patchSet.getRevision().get());
+ itemSet.setReview(review);
+ // TODO store patchSet.getRefName()
review.getItems().add(itemSet);
- if (patchSet.getId().equals(detail.getCurrentPatchSetDetail().getPatchSet().getId())) {
- for (Patch patch : detail.getCurrentPatchSetDetail().getPatches()) {
- IFileItem item = FACTORY.createFileItem();
- PatchScript patchScript = getPatchScript(patch.getKey(), null, patchSet.getId(), monitor);
- if (patchScript != null) {
- CommentDetail commentDetail = patchScript.getCommentDetail();
-
- IFileRevision revisionA = FACTORY.createFileRevision();
- revisionA.setContent(patchScript.getA().asString());
- revisionA.setPath(patchScript.getA().getPath());
- revisionA.setRevision("Base");
- addComments(revisionA, commentDetail.getCommentsA(), commentDetail.getAccounts());
- item.setBase(revisionA);
-
- IFileRevision revisionB = FACTORY.createFileRevision();
- SparseFileContent target = patchScript.getB().apply(patchScript.getA(), patchScript.getEdits());
- revisionB.setContent(target.asString());
- revisionB.setPath(patchScript.getB().getPath());
- revisionB.setRevision(itemSet.getName());
- addComments(revisionB, commentDetail.getCommentsB(), commentDetail.getAccounts());
- item.setTarget(revisionB);
- }
- item.setName(patch.getFileName());
- itemSet.getItems().add(item);
- }
- }
}
return review;
}
+ public List<IReviewItem> getChangeSetDetails(IReviewItemSet itemSet, IProgressMonitor monitor)
+ throws GerritException {
+ List<IReviewItem> result = new ArrayList<IReviewItem>();
+ Change.Id changeId = new Change.Id(id(itemSet.getReview().getId()));
+ PatchSetDetail detail = getPatchSetDetail(changeId, id(itemSet.getId()), monitor);
+ for (Patch patch : detail.getPatches()) {
+ IFileItem item = FACTORY.createFileItem();
+ PatchScript patchScript = getPatchScript(patch.getKey(), null, detail.getPatchSet().getId(), monitor);
+ if (patchScript != null) {
+ CommentDetail commentDetail = patchScript.getCommentDetail();
+
+ IFileRevision revisionA = FACTORY.createFileRevision();
+ revisionA.setContent(patchScript.getA().asString());
+ revisionA.setPath(patchScript.getA().getPath());
+ revisionA.setRevision("Base");
+ addComments(revisionA, commentDetail.getCommentsA(), commentDetail.getAccounts());
+ item.setBase(revisionA);
+
+ IFileRevision revisionB = FACTORY.createFileRevision();
+ SparseFileContent target = patchScript.getB().apply(patchScript.getA(), patchScript.getEdits());
+ revisionB.setContent(target.asString());
+ revisionB.setPath(patchScript.getB().getPath());
+ revisionB.setRevision(itemSet.getName());
+ addComments(revisionB, commentDetail.getCommentsB(), commentDetail.getAccounts());
+ item.setTarget(revisionB);
+ }
+ item.setName(patch.getFileName());
+ result.add(item);
+ }
+ return result;
+ }
+
private void addComments(IFileRevision revision, List<PatchLineComment> comments, AccountInfoCache accountInfoCache) {
if (comments == null) {
return;
diff --git a/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/client/GerritHttpClient.java b/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/client/GerritHttpClient.java
index 9adb66cd..7847bcfd 100644
--- a/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/client/GerritHttpClient.java
+++ b/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/client/GerritHttpClient.java
@@ -78,6 +78,10 @@ public synchronized int getId() {
return id++;
}
+ public AbstractWebLocation getLocation() {
+ return location;
+ }
+
public synchronized String getXsrfKey() {
return (xsrfCookie != null) ? xsrfCookie.getValue() : null;
}
@@ -191,11 +195,16 @@ public String getContent() {
PostMethod method = postJsonRequestInternal("/gerrit/rpc/UserPassAuthService", entity, monitor);
try {
int code = method.getStatusCode();
+ if (needsReauthentication(code, monitor)) {
+ return -1;
+ }
+
if (code == HttpURLConnection.HTTP_OK) {
LoginResult result = json.parseResponse(method.getResponseBodyAsString(), LoginResult.class);
if (result.success) {
return HttpStatus.SC_TEMPORARY_REDIRECT;
} else {
+ requestCredentials(monitor, AuthenticationType.REPOSITORY);
return -1;
}
}
@@ -278,6 +287,12 @@ private boolean needsReauthentication(int code, IProgressMonitor monitor) throws
return false;
}
+ requestCredentials(monitor, authenticationType);
+ return true;
+ }
+
+ void requestCredentials(IProgressMonitor monitor, final AuthenticationType authenticationType)
+ throws GerritLoginException {
try {
location.requestCredentials(authenticationType, null, monitor);
} catch (UnsupportedRequestException e) {
@@ -285,7 +300,6 @@ private boolean needsReauthentication(int code, IProgressMonitor monitor) throws
}
hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor);
- return true;
}
protected void validateAuthenticationState(HttpClient httpClient) throws GerritLoginException {
@@ -306,4 +320,8 @@ protected void validateAuthenticationState(HttpClient httpClient) throws GerritL
throw new GerritLoginException();
}
+ public boolean isAnonymous() {
+ return getLocation().getCredentials(AuthenticationType.REPOSITORY) == null;
+ }
+
}
diff --git a/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/client/GerritService.java b/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/client/GerritService.java
index da8cb073..9c60c2dd 100644
--- a/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/client/GerritService.java
+++ b/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/client/GerritService.java
@@ -72,7 +72,7 @@ public String getServiceUri() {
return uri;
}
- public Object invoke(Object proxy, final Method method, Object[] args) throws Throwable {
+ public Object invoke(Object proxy, final Method method, Object[] args) {
final JSonSupport json = new JSonSupport();
// construct request
@@ -101,7 +101,7 @@ public String getContent() {
Object result = json.parseResponse(responseMessage, resultType);
callback.onSuccess(result);
- } catch (GerritException e) {
+ } catch (Throwable e) {
callback.onFailure(e);
}
// all methods are designed to be asynchronous and expected to return void
diff --git a/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/client/GerritSystemInfo.java b/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/client/GerritSystemInfo.java
index 9119d33b..42133973 100644
--- a/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/client/GerritSystemInfo.java
+++ b/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/client/GerritSystemInfo.java
@@ -11,7 +11,10 @@
package org.eclipse.mylyn.internal.gerrit.core.client;
+import java.util.List;
+
import com.google.gerrit.reviewdb.Account;
+import com.google.gerrit.reviewdb.ContributorAgreement;
/**
* @author Steffen Pingel
@@ -20,10 +23,17 @@ public class GerritSystemInfo {
private final Account account;
- public GerritSystemInfo(Account account) {
+ private final List<ContributorAgreement> contributorAgreements;
+
+ public GerritSystemInfo(List<ContributorAgreement> contributorAgreements, Account account) {
+ this.contributorAgreements = contributorAgreements;
this.account = account;
}
+ public List<ContributorAgreement> getContributorAgreements() {
+ return contributorAgreements;
+ }
+
public String getFullName() {
return (account != null) ? account.getFullName() : "Anonymous";
}
diff --git a/gerrit/org.eclipse.mylyn.gerrit.tests/META-INF/MANIFEST.MF b/gerrit/org.eclipse.mylyn.gerrit.tests/META-INF/MANIFEST.MF
index f055f0d7..f7c56ff4 100644
--- a/gerrit/org.eclipse.mylyn.gerrit.tests/META-INF/MANIFEST.MF
+++ b/gerrit/org.eclipse.mylyn.gerrit.tests/META-INF/MANIFEST.MF
@@ -1,6 +1,6 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
-Bundle-Name: Mylyn Gerrit Connector
+Bundle-Name: Mylyn Gerrit Connector (Incubation)
Bundle-SymbolicName: org.eclipse.mylyn.gerrit.tests;singleton:=true
Bundle-Version: 0.7.0.qualifier
Bundle-Vendor: Eclipse Mylyn
diff --git a/gerrit/org.eclipse.mylyn.gerrit.ui/META-INF/MANIFEST.MF b/gerrit/org.eclipse.mylyn.gerrit.ui/META-INF/MANIFEST.MF
index 71d5ed4d..18e4e087 100644
--- a/gerrit/org.eclipse.mylyn.gerrit.ui/META-INF/MANIFEST.MF
+++ b/gerrit/org.eclipse.mylyn.gerrit.ui/META-INF/MANIFEST.MF
@@ -1,6 +1,6 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
-Bundle-Name: Mylyn Gerrit Connector
+Bundle-Name: Mylyn Gerrit Connector (Incubation)
Bundle-SymbolicName: org.eclipse.mylyn.gerrit.ui;singleton:=true
Bundle-Version: 0.7.0.qualifier
Bundle-Activator: org.eclipse.mylyn.internal.gerrit.ui.GerritUiPlugin
diff --git a/gerrit/org.eclipse.mylyn.gerrit.ui/src/org/eclipse/mylyn/internal/gerrit/ui/editor/ReviewSection.java b/gerrit/org.eclipse.mylyn.gerrit.ui/src/org/eclipse/mylyn/internal/gerrit/ui/editor/ReviewSection.java
index 536470f3..e6e84c73 100644
--- a/gerrit/org.eclipse.mylyn.gerrit.ui/src/org/eclipse/mylyn/internal/gerrit/ui/editor/ReviewSection.java
+++ b/gerrit/org.eclipse.mylyn.gerrit.ui/src/org/eclipse/mylyn/internal/gerrit/ui/editor/ReviewSection.java
@@ -11,6 +11,7 @@
package org.eclipse.mylyn.internal.gerrit.ui.editor;
+import java.util.ArrayList;
import java.util.List;
import org.eclipse.compare.CompareConfiguration;
@@ -48,6 +49,10 @@
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.ui.forms.IFormColors;
+import org.eclipse.ui.forms.events.ExpansionAdapter;
+import org.eclipse.ui.forms.events.ExpansionEvent;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
@@ -89,104 +94,196 @@ protected IStatus run(IProgressMonitor monitor) {
}
+ private class GetChangeSetDetailsJob extends Job {
+
+ private final TaskRepository repository;
+
+ private final IReviewItemSet itemSet;
+
+ private List<IReviewItem> items;
+
+ public GetChangeSetDetailsJob(TaskRepository repository, IReviewItemSet itemSet) {
+ super("Get Review");
+ this.repository = repository;
+ this.itemSet = itemSet;
+ }
+
+ public List<IReviewItem> getItems() {
+ return items;
+ }
+
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ GerritConnector connector = (GerritConnector) TasksUi.getRepositoryConnector(repository.getConnectorKind());
+ GerritClient client = connector.getClient(repository);
+ try {
+ items = client.getChangeSetDetails(itemSet, monitor);
+ } catch (GerritException e) {
+ return new Status(IStatus.ERROR, GerritUiPlugin.PLUGIN_ID, "Review retrieval failed", e);
+ }
+ return Status.OK_STATUS;
+ }
+ }
+
private Composite composite;
- private GetReviewJob job;
+ private final List<Job> jobs;
private FormToolkit toolkit;
+ private Label progressLabel;
+
public ReviewSection() {
setPartName("Review");
+ jobs = new ArrayList<Job>();
}
@Override
public void dispose() {
- job.cancel();
+ for (Job job : jobs) {
+ job.cancel();
+ }
super.dispose();
}
@Override
public void initialize(AbstractTaskEditorPage taskEditorPage) {
super.initialize(taskEditorPage);
- job = new GetReviewJob(taskEditorPage.getTaskRepository(), taskEditorPage.getTask().getTaskId());
- job.addJobChangeListener(new JobChangeAdapter() {
- @Override
- public void done(final IJobChangeEvent event) {
- if (event.getResult().isOK()) {
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- if (getControl() != null && !getControl().isDisposed()) {
- updateContent(((GetReviewJob) event.getJob()).getReview());
- }
- }
-
- });
- }
- }
- });
}
private void updateContent(IReview review) {
+ progressLabel.dispose();
for (IReviewItem item : review.getItems()) {
if (item instanceof IReviewItemSet) {
createSubSection(review, (IReviewItemSet) item);
}
}
+ composite.layout(true, true);
getTaskEditorPage().reflow();
}
- private void createSubSection(final IReview review, IReviewItemSet item) {
- int style = ExpandableComposite.TWISTIE;
+ private void createSubSection(final IReview review, final IReviewItemSet item) {
+ int style = ExpandableComposite.TWISTIE | ExpandableComposite.CLIENT_INDENT;
if (item.getItems().size() > 0) {
style |= ExpandableComposite.EXPANDED;
}
- Section subSection = toolkit.createSection(composite, style);
+ final Section subSection = toolkit.createSection(composite, style);
GridDataFactory.fillDefaults().grab(true, false).applyTo(subSection);
subSection.setText(item.getName());
- subSection.setTextClient(toolkit.createLabel(subSection, item.getId()));
+ subSection.setTextClient(toolkit.createLabel(subSection, item.getRevision()));
if (item.getItems().size() > 0) {
- TableViewer viewer = new TableViewer(subSection, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL | SWT.VIRTUAL);
- viewer.setContentProvider(new IStructuredContentProvider() {
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- // ignore
- }
+ createSubSectionContents(review, item, subSection);
+ } else {
+ subSection.addExpansionListener(new ExpansionAdapter() {
+ @Override
+ public void expansionStateChanged(ExpansionEvent e) {
+ if (subSection.getClient() == null) {
+ final Label progressLabel = new Label(subSection, SWT.NONE);
+ progressLabel.setText("Retrieving contents...");
+ progressLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
+ subSection.setClient(progressLabel);
+ getTaskEditorPage().reflow();
- public void dispose() {
- // ignore
- }
+ final GetChangeSetDetailsJob job = new GetChangeSetDetailsJob(
+ getTaskEditorPage().getTaskRepository(), item);
+ job.addJobChangeListener(new JobChangeAdapter() {
+ @Override
+ public void done(final IJobChangeEvent event) {
+ if (event.getResult().isOK()) {
+ Display.getDefault().asyncExec(new Runnable() {
+ public void run() {
+ if (getControl() != null && !getControl().isDisposed()) {
+ if (job.getItems() != null) {
+ item.getItems().addAll(job.getItems());
- public Object[] getElements(Object inputElement) {
- return ((List) inputElement).toArray();
- }
- });
- viewer.setInput(item.getItems());
- viewer.setLabelProvider(new DelegatingStyledCellLabelProvider(new ReviewItemLabelProvider()));
- viewer.addOpenListener(new IOpenListener() {
- public void open(OpenEvent event) {
- IStructuredSelection selection = (IStructuredSelection) event.getSelection();
- IFileItem item = (IFileItem) selection.getFirstElement();
- ReviewCompareAnnotationModel model = new ReviewCompareAnnotationModel(item, review, null);
- CompareConfiguration configuration = new CompareConfiguration();
- CompareUI.openCompareEditor(new ReviewCompareEditorInput(item, model, configuration));
+ progressLabel.dispose();
+ createSubSectionContents(review, item, subSection);
+ } else {
+ progressLabel.setText("No items found");
+ }
+ getTaskEditorPage().reflow();
+ }
+ }
+ });
+ }
+ }
+ });
+ jobs.add(job);
+ job.schedule();
+ }
}
});
- subSection.setClient(viewer.getControl());
}
}
+ void createSubSectionContents(final IReview review, IReviewItemSet item, Section subSection) {
+ TableViewer viewer = new TableViewer(subSection, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL | SWT.VIRTUAL);
+ viewer.setContentProvider(new IStructuredContentProvider() {
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ // ignore
+ }
+
+ public void dispose() {
+ // ignore
+ }
+
+ public Object[] getElements(Object inputElement) {
+ return ((List) inputElement).toArray();
+ }
+ });
+ viewer.setInput(item.getItems());
+ viewer.setLabelProvider(new DelegatingStyledCellLabelProvider(new ReviewItemLabelProvider()));
+ viewer.addOpenListener(new IOpenListener() {
+ public void open(OpenEvent event) {
+ IStructuredSelection selection = (IStructuredSelection) event.getSelection();
+ IFileItem item = (IFileItem) selection.getFirstElement();
+ ReviewCompareAnnotationModel model = new ReviewCompareAnnotationModel(item, review, null);
+ CompareConfiguration configuration = new CompareConfiguration();
+ CompareUI.openCompareEditor(new ReviewCompareEditorInput(item, model, configuration));
+ }
+ });
+ subSection.setClient(viewer.getControl());
+ }
+
@Override
protected Control createContent(FormToolkit toolkit, Composite parent) {
this.toolkit = toolkit;
- job.schedule();
-
composite = toolkit.createComposite(parent);
- GridLayoutFactory.fillDefaults().applyTo(composite);
+ GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 5).applyTo(composite);
+
+ progressLabel = new Label(composite, SWT.NONE);
+ progressLabel.setText("Retrieving contents...");
+ progressLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
+
+ initializeUpdateJob();
+
return composite;
}
+ void initializeUpdateJob() {
+ GetReviewJob job = new GetReviewJob(getTaskEditorPage().getTaskRepository(), getTaskEditorPage().getTask()
+ .getTaskId());
+ job.addJobChangeListener(new JobChangeAdapter() {
+ @Override
+ public void done(final IJobChangeEvent event) {
+ if (event.getResult().isOK()) {
+ Display.getDefault().asyncExec(new Runnable() {
+ public void run() {
+ if (getControl() != null && !getControl().isDisposed()) {
+ updateContent(((GetReviewJob) event.getJob()).getReview());
+ }
+ }
+ });
+ }
+ }
+ });
+ jobs.add(job);
+ job.schedule();
+ }
+
@Override
protected boolean shouldExpandOnCreate() {
return true;
diff --git a/pom.xml b/pom.xml
index c8fee916..b88db86a 100644
--- a/pom.xml
+++ b/pom.xml
@@ -49,6 +49,7 @@
<properties>
<tycho-version>0.10.0</tycho-version>
+ <mylyn-skip-source-check>true</mylyn-skip-source-check>
</properties>
<profiles>
@@ -197,7 +198,7 @@
<configuration>
<findbugsXmlOutput>true</findbugsXmlOutput>
<failOnError>false</failOnError>
- <skip>true</skip>
+ <skip>${mylyn-skip-source-check}</skip>
</configuration>
<executions>
<execution>
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.reviews.tasks.core/META-INF/MANIFEST.MF
index ccc555f2..90bbf5e2 100644
--- a/tbr/org.eclipse.mylyn.reviews.tasks.core/META-INF/MANIFEST.MF
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/META-INF/MANIFEST.MF
@@ -1,6 +1,6 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
-Bundle-Name: Mylyn Reviews
+Bundle-Name: Mylyn Reviews (Incubation)
Bundle-Vendor: Eclipse Mylyn
Bundle-SymbolicName: org.eclipse.mylyn.reviews.tasks.core;singleton:=true
Bundle-Version: 0.7.0.qualifier
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/plugin.properties b/tbr/org.eclipse.mylyn.reviews.tasks.core/plugin.properties
index 4041a812..b04d1be4 100644
--- a/tbr/org.eclipse.mylyn.reviews.tasks.core/plugin.properties
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/plugin.properties
@@ -9,9 +9,6 @@
# Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
###############################################################################
-pluginName = Review Edit Support
-providerName = www.example.org
-
_UI_CreateChild_text = {0}
_UI_CreateChild_text2 = {1} {0}
_UI_CreateChild_text3 = {1}
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/META-INF/MANIFEST.MF
index 1b498f16..de4ab427 100644
--- a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/META-INF/MANIFEST.MF
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/META-INF/MANIFEST.MF
@@ -1,6 +1,6 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
-Bundle-Name: Mylyn Reviews
+Bundle-Name: Mylyn Reviews (Incubation)
Bundle-Vendor: Eclipse Mylyn
Bundle-Version: 0.7.0.qualifier
Bundle-SymbolicName: org.eclipse.mylyn.reviews.tasks.dsl;singleton:=true
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.reviews.tasks.ui/META-INF/MANIFEST.MF
index 2717a899..19215461 100644
--- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/META-INF/MANIFEST.MF
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/META-INF/MANIFEST.MF
@@ -1,6 +1,6 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
-Bundle-Name: Mylyn Reviews
+Bundle-Name: Mylyn Reviews (Incubation)
Bundle-Vendor: Eclipse Mylyn
Bundle-SymbolicName: org.eclipse.mylyn.reviews.tasks.ui;singleton:=true
Bundle-Version: 0.7.0.qualifier
|
006b5cd1ab45f53321ff664f46b1335ec018c807
|
intellij-community
|
IDEA-78863 Live templates are not accessible in- read-only file (e.g. versioned in Perforce or TFS)--
|
c
|
https://github.com/JetBrains/intellij-community
|
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/ListTemplatesHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/ListTemplatesHandler.java
index 6831a726575d9..7ce8a60063e86 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/ListTemplatesHandler.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/ListTemplatesHandler.java
@@ -29,6 +29,7 @@
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ex.util.EditorUtil;
+import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
@@ -40,7 +41,9 @@
public class ListTemplatesHandler implements CodeInsightActionHandler {
public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull PsiFile file) {
- if (!file.isWritable()) return;
+ if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)) {
+ return;
+ }
EditorUtil.fillVirtualSpaceUntilCaret(editor);
PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
|
0b3db7cbf5eada6176af266cc6bebfcd1332f115
|
restlet-framework-java
|
- Additional WADL refactorings.--
|
p
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/FaultInfo.java b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/FaultInfo.java
index 0752ec6751..0ad154478f 100644
--- a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/FaultInfo.java
+++ b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/FaultInfo.java
@@ -32,6 +32,7 @@
import java.util.Iterator;
import java.util.List;
+import org.restlet.data.MediaType;
import org.restlet.data.Reference;
import org.restlet.data.Status;
import org.restlet.util.XmlWriter;
@@ -47,39 +48,66 @@ public class FaultInfo extends RepresentationInfo {
/**
* Constructor.
+ *
+ * @param status
+ * The associated status code.
*/
- public FaultInfo() {
+ public FaultInfo(Status status) {
super();
+ getStatuses().add(status);
}
/**
* Constructor with a single documentation element.
*
+ * @param status
+ * The associated status code.
* @param documentation
* A single documentation element.
*/
- public FaultInfo(DocumentationInfo documentation) {
+ public FaultInfo(Status status, DocumentationInfo documentation) {
super(documentation);
+ getStatuses().add(status);
}
/**
* Constructor with a list of documentation elements.
*
+ * @param status
+ * The associated status code.
* @param documentations
* The list of documentation elements.
*/
- public FaultInfo(List<DocumentationInfo> documentations) {
+ public FaultInfo(Status status, List<DocumentationInfo> documentations) {
super(documentations);
+ getStatuses().add(status);
}
/**
* Constructor with a single documentation element.
*
+ * @param status
+ * The associated status code.
* @param documentation
* A single documentation element.
*/
- public FaultInfo(String documentation) {
- super(documentation);
+ public FaultInfo(Status status, String documentation) {
+ this(status, new DocumentationInfo(documentation));
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param status
+ * The associated status code.
+ * @param mediaType
+ * The fault representation's media type.
+ * @param documentation
+ * A single documentation element.
+ */
+ public FaultInfo(Status status, MediaType mediaType, String documentation) {
+ this(status, new DocumentationInfo(documentation));
+ setMediaType(mediaType);
}
/**
diff --git a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/MethodInfo.java b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/MethodInfo.java
index 5ac681ffc5..0aac5ee5ab 100644
--- a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/MethodInfo.java
+++ b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/MethodInfo.java
@@ -32,8 +32,10 @@
import java.util.List;
import java.util.Map;
+import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Reference;
+import org.restlet.data.Status;
import org.restlet.resource.Variant;
import org.restlet.util.XmlWriter;
import org.xml.sax.SAXException;
@@ -98,6 +100,24 @@ public MethodInfo(String documentation) {
super(documentation);
}
+ /**
+ * Adds a new fault to the response.
+ *
+ * @param status
+ * The associated status code.
+ * @param mediaType
+ * The fault representation's media type.
+ * @param documentation
+ * A single documentation element.
+ * @return The created fault description.
+ */
+ public FaultInfo addFault(Status status, MediaType mediaType,
+ String documentation) {
+ FaultInfo result = new FaultInfo(status, mediaType, documentation);
+ getResponse().getFaults().add(result);
+ return result;
+ }
+
/**
* Adds a new request parameter.
*
diff --git a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/WadlRepresentation.java b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/WadlRepresentation.java
index 9eadc8c8c6..d6af850a75 100644
--- a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/WadlRepresentation.java
+++ b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/WadlRepresentation.java
@@ -530,7 +530,8 @@ public void startElement(String uri, String localName, String qName,
}
pushState(State.DOCUMENTATION);
} else if (localName.equals("fault")) {
- this.currentFault = new FaultInfo();
+ this.currentFault = new FaultInfo(null);
+
if (attrs.getIndex("id") != -1) {
this.currentFault.setIdentifier(attrs.getValue("id"));
}
|
4fb6823b3fcc1105589f30a9376fa533fb58a39d
|
drools
|
Removed unncessary else if check; replaced with- else--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@26039 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
|
p
|
https://github.com/kiegroup/drools
|
diff --git a/drools-core/src/main/java/org/drools/reteoo/ObjectSinkNodeList.java b/drools-core/src/main/java/org/drools/reteoo/ObjectSinkNodeList.java
index 9adaf99483d..3a06acce6b0 100644
--- a/drools-core/src/main/java/org/drools/reteoo/ObjectSinkNodeList.java
+++ b/drools-core/src/main/java/org/drools/reteoo/ObjectSinkNodeList.java
@@ -86,7 +86,7 @@ public void writeExternal(ObjectOutput out) throws IOException {
public void add(final ObjectSinkNode node) {
if ( this.firstNode == null ) {
this.firstNode = node;
- this.lastNode = node;;
+ this.lastNode = node;
} else {
this.lastNode.setNextObjectSinkNode( node );
node.setPreviousObjectSinkNode( this.lastNode );
@@ -114,7 +114,7 @@ public void remove(final ObjectSinkNode node) {
} else {
if ( this.firstNode == node ) {
removeFirst();
- } else if ( this.lastNode == node ) {
+ } else {
removeLast();
}
}
|
65717a241e288778b916e2ea059151b95364e8e5
|
couchbase$couchbase-java-client
|
Refactor the ConfigurationParserJSON for clarity.
This changeset doesnt change any functionality but only refactors
and properly comments the ConfigurationParserJSON.
Change-Id: Ic534336f5421e9c0e928520665bde454cee4f653
Reviewed-on: http://review.couchbase.org/29849
Reviewed-by: Michael Nitschinger <[email protected]>
Tested-by: Michael Nitschinger <[email protected]>
|
p
|
https://github.com/couchbase/couchbase-java-client
|
diff --git a/src/main/java/com/couchbase/client/vbucket/ConfigurationProviderHTTP.java b/src/main/java/com/couchbase/client/vbucket/ConfigurationProviderHTTP.java
index a2b679ca..af3aa597 100644
--- a/src/main/java/com/couchbase/client/vbucket/ConfigurationProviderHTTP.java
+++ b/src/main/java/com/couchbase/client/vbucket/ConfigurationProviderHTTP.java
@@ -212,7 +212,7 @@ private void readPools(String bucketToFind) {
+ " response... skipping");
continue;
}
- Map<String, Pool> pools = this.configurationParser.parseBase(base);
+ Map<String, Pool> pools = this.configurationParser.parsePools(base);
// check for the default pool name
if (!pools.containsKey(DEFAULT_POOL_NAME)) {
@@ -227,7 +227,7 @@ private void readPools(String bucketToFind) {
URLConnection poolConnection = urlConnBuilder(baseUri,
pool.getUri());
String poolString = readToString(poolConnection);
- configurationParser.loadPool(pool, poolString);
+ configurationParser.parsePool(pool, poolString);
URLConnection poolBucketsConnection = urlConnBuilder(baseUri,
pool.getBucketsUri());
String sBuckets = readToString(poolBucketsConnection);
diff --git a/src/main/java/com/couchbase/client/vbucket/config/ConfigurationParser.java b/src/main/java/com/couchbase/client/vbucket/config/ConfigurationParser.java
index 78ce530e..a405e307 100644
--- a/src/main/java/com/couchbase/client/vbucket/config/ConfigurationParser.java
+++ b/src/main/java/com/couchbase/client/vbucket/config/ConfigurationParser.java
@@ -29,11 +29,11 @@
* A ConfigParser.
*/
public interface ConfigurationParser {
- Map<String, Pool> parseBase(final String base) throws ParseException;
+ Map<String, Pool> parsePools(final String base) throws ParseException;
Map<String, Bucket> parseBuckets(String buckets) throws ParseException;
Bucket parseBucket(String sBucket) throws ParseException;
- void loadPool(Pool pool, String sPool) throws ParseException;
+ void parsePool(Pool pool, String sPool) throws ParseException;
}
diff --git a/src/main/java/com/couchbase/client/vbucket/config/ConfigurationParserJSON.java b/src/main/java/com/couchbase/client/vbucket/config/ConfigurationParserJSON.java
index 7d7ecbb5..d8257633 100644
--- a/src/main/java/com/couchbase/client/vbucket/config/ConfigurationParserJSON.java
+++ b/src/main/java/com/couchbase/client/vbucket/config/ConfigurationParserJSON.java
@@ -22,7 +22,6 @@
package com.couchbase.client.vbucket.config;
-
import com.couchbase.client.vbucket.ConnectionException;
import java.net.URI;
import java.net.URISyntaxException;
@@ -39,55 +38,70 @@
import org.codehaus.jettison.json.JSONObject;
/**
- * A ConfigParserJSON.
+ * This {@link ConfigurationParser} takes JSON-based configuration information
+ * and transforms it into a {@link Bucket}.
*/
-public class ConfigurationParserJSON extends SpyObject implements
- ConfigurationParser {
- private static final String NAME_ATTR = "name";
- private static final String URI_ATTR = "uri";
- private static final String STREAMING_URI_ATTR = "streamingUri";
-
- public Map<String, Pool> parseBase(String base) throws ParseException {
- Map<String, Pool> parsedBase = new HashMap<String, Pool>();
- JSONArray poolsJA = null;
+public class ConfigurationParserJSON extends SpyObject
+ implements ConfigurationParser {
+
+ private final ConfigFactory configFactory = new DefaultConfigFactory();
+
+ /**
+ * Parses the /pools URI and returns a map of found pools.
+ *
+ * @param poolsJson the raw JSON of the pools response.
+ * @return a map of found pools.
+ * @throws ParseException if the JSON could not be parsed properly.
+ * @throws ConnectionException if a non-recoverable connect error happened.
+ */
+ public Map<String, Pool> parsePools(final String poolsJson)
+ throws ParseException {
+ final Map<String, Pool> parsedBase = new HashMap<String, Pool>();
+ final JSONArray allPools;
+
try {
- JSONObject baseJO = new JSONObject(base);
- poolsJA = baseJO.getJSONArray("pools");
+ allPools = new JSONObject(poolsJson).getJSONArray("pools");
} catch (JSONException e) {
- getLogger().debug("Received the folloing unparsable response: "
+ getLogger().info("Received the following unparsable response: "
+ e.getMessage());
throw new ConnectionException("Connection URI is either incorrect "
+ "or invalid as it cannot be parsed.");
}
- for (int i = 0; i < poolsJA.length(); ++i) {
+
+ for (int i = 0; i < allPools.length(); i++) {
try {
- JSONObject poolJO = poolsJA.getJSONObject(i);
- String name = (String) poolJO.get(NAME_ATTR);
- if (name == null || "".equals(name)) {
+ final JSONObject currentPool = allPools.getJSONObject(i);
+ final String name = currentPool.getString("name");
+ if (name == null || name.isEmpty()) {
throw new ParseException("Pool's name is missing.", 0);
}
- String uri = (String) poolJO.get(URI_ATTR);
- if (uri == null || "".equals(uri)) {
- throw new ParseException("Pool's uri is missing.", 0);
- }
- String streamingUri = (String) poolJO.get(STREAMING_URI_ATTR);
- Pool pool = new Pool(name, new URI(uri), new URI(streamingUri));
+ final URI uri = new URI(currentPool.getString("uri"));
+ final URI streamingUri = new URI(currentPool.getString("streamingUri"));
+ final Pool pool = new Pool(name, uri, streamingUri);
parsedBase.put(name, pool);
} catch (JSONException e) {
- getLogger().error("One of the pool configuration can not be parsed.",
- e);
+ getLogger().error("One of the pool configurations can not be parsed.",
+ e);
} catch (URISyntaxException e) {
getLogger().error("Server provided an incorrect uri.", e);
}
}
+
return parsedBase;
}
- public void loadPool(Pool pool, String sPool) throws ParseException {
+ /**
+ * Parses a given /pools/{pool} JSON for the buckets URI.
+ *
+ * @param pool the actual pool object to attach to.
+ * @param poolsJson the raw JSON for the pool response.
+ * @throws ParseException if the JSON could not be parsed properly.
+ */
+ public void parsePool(final Pool pool, final String poolsJson)
+ throws ParseException {
try {
- JSONObject poolJO = new JSONObject(sPool);
- JSONObject poolBucketsJO = poolJO.getJSONObject("buckets");
- URI bucketsUri = new URI((String) poolBucketsJO.get("uri"));
+ JSONObject buckets = new JSONObject(poolsJson).getJSONObject("buckets");
+ URI bucketsUri = new URI(buckets.getString("uri"));
pool.setBucketsUri(bucketsUri);
} catch (JSONException e) {
throw new ParseException(e.getMessage(), 0);
@@ -96,66 +110,115 @@ public void loadPool(Pool pool, String sPool) throws ParseException {
}
}
- public Map<String, Bucket> parseBuckets(String buckets)
+ /**
+ * Parses the /pools/{pool}/buckets URI for a list of contained buckets.
+ *
+ * @param bucketsJson the raw JSON of the buckets response.
+ * @return a map containing all found buckets.
+ * @throws ParseException if the JSON could not be parsed properly.
+ */
+ public Map<String, Bucket> parseBuckets(final String bucketsJson)
throws ParseException {
- Map<String, Bucket> bucketsMap = new HashMap<String, Bucket>();
try {
- JSONArray bucketsJA = new JSONArray(buckets);
- for (int i = 0; i < bucketsJA.length(); ++i) {
- JSONObject bucketJO = bucketsJA.getJSONObject(i);
- Bucket bucket = parseBucketFromJSON(bucketJO);
+ Map<String, Bucket> bucketsMap = new HashMap<String, Bucket>();
+ JSONArray allBuckets = new JSONArray(bucketsJson);
+
+ for (int i = 0; i < allBuckets.length(); i++) {
+ JSONObject currentBucket = allBuckets.getJSONObject(i);
+ Bucket bucket = parseBucketFromJSON(currentBucket);
bucketsMap.put(bucket.getName(), bucket);
}
+
+ return bucketsMap;
} catch (JSONException e) {
throw new ParseException(e.getMessage(), 0);
}
- return bucketsMap;
}
- public Bucket parseBucket(String sBucket) throws ParseException {
+ /**
+ * Parse a raw bucket config string into a {@link Bucket} configuration.
+ *
+ * @param bucketJson the raw JSON.
+ * @return the parsed configuration.
+ * @throws ParseException if the JSON could not be parsed properly.
+ */
+ public Bucket parseBucket(String bucketJson) throws ParseException {
try {
- return parseBucketFromJSON(new JSONObject(sBucket));
+ return parseBucketFromJSON(new JSONObject(bucketJson));
} catch (JSONException e) {
throw new ParseException(e.getMessage(), 0);
}
}
- private Bucket parseBucketFromJSON(JSONObject bucketJO)
+ /**
+ * Helper method to create a {@link Bucket} config from JSON.
+ *
+ * @param bucketJson the input as a {@link JSONObject}.
+ * @return a parsed {@link Bucket} configuration.
+ * @throws ParseException if the JSON could not be parsed properly.
+ */
+ private Bucket parseBucketFromJSON(JSONObject bucketJson)
throws ParseException {
try {
- String bucketname = bucketJO.get("name").toString();
- String streamingUri = bucketJO.get("streamingUri").toString();
- ConfigFactory cf = new DefaultConfigFactory();
- Config config = cf.create(bucketJO);
+ String bucketName = bucketJson.getString("name");
+ URI streamingUri = new URI(bucketJson.getString("streamingUri"));
+ Config config = configFactory.create(bucketJson);
+
List<Node> nodes = new ArrayList<Node>();
- JSONArray nodesJA = bucketJO.getJSONArray("nodes");
- for (int i = 0; i < nodesJA.length(); ++i) {
- JSONObject nodeJO = nodesJA.getJSONObject(i);
- String statusValue = nodeJO.get("status").toString();
- Status status = null;
- try {
- status = Status.valueOf(statusValue);
- } catch (IllegalArgumentException e) {
- getLogger().error("Unknown status value: " + statusValue);
- }
- String hostname = nodeJO.get("hostname").toString();
- JSONObject portsJO = nodeJO.getJSONObject("ports");
- Map<Port, String> ports = new HashMap<Port, String>();
- for (Port port : Port.values()) {
- String portValue = portsJO.get(port.toString()).toString();
- if (portValue == null || portValue.isEmpty()) {
- continue;
- }
- ports.put(port, portValue);
- }
- Node node = new Node(status, hostname, ports);
- nodes.add(node);
+ JSONArray allNodes = bucketJson.getJSONArray("nodes");
+ for (int i = 0; i < allNodes.length(); i++) {
+ JSONObject currentNode = allNodes.getJSONObject(i);
+ Status status = parseNodeStatus(currentNode.getString("status"));
+ String hostname = currentNode.getString("hostname");
+ Map<Port, String> ports = extractPorts(
+ currentNode.getJSONObject("ports"));
+ nodes.add(new Node(status, hostname, ports));
}
- return new Bucket(bucketname, config, new URI(streamingUri), nodes);
+ return new Bucket(bucketName, config, streamingUri, nodes);
} catch (JSONException e) {
throw new ParseException(e.getMessage(), 0);
} catch (URISyntaxException e) {
throw new ParseException(e.getMessage(), 0);
}
}
+
+ /**
+ * Helper method to parse a node {@link Status} out of the raw response.
+ *
+ * @param status the status to parse.
+ * @return the parsed status enum value.
+ */
+ private Status parseNodeStatus(String status) {
+ if (status == null || status.isEmpty()) {
+ return null;
+ }
+
+ try {
+ return Status.valueOf(status);
+ } catch (IllegalArgumentException e) {
+ getLogger().error("Unknown status value: " + status);
+ return null;
+ }
+ }
+
+ /**
+ * Helper method to extract a map of node ports from a {@link JSONObject}.
+ *
+ * @param portsJson the port information.
+ * @return the extracted port map.
+ * @throws JSONException if the JSON could not be parsed as expected.
+ */
+ private Map<Port, String> extractPorts(JSONObject portsJson)
+ throws JSONException {
+ Map<Port, String> ports = new HashMap<Port, String>();
+ for (Port port : Port.values()) {
+ String portValue = portsJson.getString(port.toString());
+ if (portValue == null || portValue.isEmpty()) {
+ continue;
+ }
+ ports.put(port, portValue);
+ }
+ return ports;
+ }
+
}
diff --git a/src/test/java/com/couchbase/client/vbucket/config/ConfigurationParserJSONTest.java b/src/test/java/com/couchbase/client/vbucket/config/ConfigurationParserJSONTest.java
index 019ca479..c20c8d66 100644
--- a/src/test/java/com/couchbase/client/vbucket/config/ConfigurationParserJSONTest.java
+++ b/src/test/java/com/couchbase/client/vbucket/config/ConfigurationParserJSONTest.java
@@ -45,7 +45,7 @@ public class ConfigurationParserJSONTest extends TestCase {
* @throws Exception the exception
*/
public void testParseBase() throws Exception {
- Map<String, Pool> base = configParser.parseBase(BASE_STRING);
+ Map<String, Pool> base = configParser.parsePools(BASE_STRING);
assertNotNull(base);
assertTrue(!base.isEmpty());
Pool pool = base.get(DEFAULT_POOL_NAME);
@@ -113,7 +113,7 @@ public void testParseBucket() throws Exception {
*/
public void testLoadPool() throws Exception {
Pool pool = new Pool(null, null, null);
- configParser.loadPool(pool, POOL_STRING);
+ configParser.parsePool(pool, POOL_STRING);
assertNotNull(pool.getBucketsUri());
}
@@ -127,7 +127,7 @@ public void testLoadPool() throws Exception {
*/
public void testInvalidURI() throws ParseException{
try {
- configParser.parseBase(INVALID_BASE_STRING);
+ configParser.parsePools(INVALID_BASE_STRING);
} catch (ConnectionException e) {
assertEquals(e.getMessage(), "Connection URI is either incorrect "
+ "or invalid as it cannot be parsed.");
diff --git a/src/test/java/com/couchbase/client/vbucket/config/ConfigurationParserMock.java b/src/test/java/com/couchbase/client/vbucket/config/ConfigurationParserMock.java
index f8a1b8e2..ed65eed1 100644
--- a/src/test/java/com/couchbase/client/vbucket/config/ConfigurationParserMock.java
+++ b/src/test/java/com/couchbase/client/vbucket/config/ConfigurationParserMock.java
@@ -54,7 +54,7 @@ public class ConfigurationParserMock implements ConfigurationParser {
private List<Node> nodes = Collections.singletonList(new Node(Status.healthy,
"localhost", Collections.singletonMap(Port.direct, "11210")));
- public Map<String, Pool> parseBase(String base) throws ParseException {
+ public Map<String, Pool> parsePools(String base) throws ParseException {
Map<String, Pool> result = new HashMap<String, Pool>();
try {
parseBaseCalled = true;
@@ -93,7 +93,7 @@ public Bucket parseBucket(String sBucket) throws ParseException {
}
- public void loadPool(Pool pool, String sPool) throws ParseException {
+ public void parsePool(Pool pool, String sPool) throws ParseException {
try {
loadPoolCalled = true;
pool.setBucketsUri(new URI(bucketsUri));
|
923c0b1f412c53564571afab968ebdcdcaff39a4
|
belaban$jgroups
|
first impl of reconnector functionality in TCPGOSSIP (https://jira.jboss.org/jira/browse/JGRP-1010)
|
p
|
https://github.com/belaban/jgroups
|
diff --git a/src/org/jgroups/protocols/TCPGOSSIP.java b/src/org/jgroups/protocols/TCPGOSSIP.java
index 3496aebcddf..772a5525ebf 100644
--- a/src/org/jgroups/protocols/TCPGOSSIP.java
+++ b/src/org/jgroups/protocols/TCPGOSSIP.java
@@ -13,6 +13,8 @@
import org.jgroups.util.Tuple;
import java.util.*;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
@@ -30,10 +32,10 @@
* FIND_INITIAL_MBRS_OK event up the stack.
*
* @author Bela Ban
- * @version $Id: TCPGOSSIP.java,v 1.40 2009/07/08 15:29:30 belaban Exp $
+ * @version $Id: TCPGOSSIP.java,v 1.41 2009/07/09 13:59:40 belaban Exp $
*/
@DeprecatedProperty(names={"gossip_refresh_rate"})
-public class TCPGOSSIP extends Discovery {
+public class TCPGOSSIP extends Discovery implements RouterStub.ConnectionListener {
private final static String name="TCPGOSSIP";
@@ -41,14 +43,20 @@ public class TCPGOSSIP extends Discovery {
@Property(description="Max time for socket creation. Default is 1000 msec")
int sock_conn_timeout=1000;
+
@Property(description="Max time in milliseconds to block on a read. 0 blocks forever")
int sock_read_timeout=3000;
+
+ @Property(description="Interval (ms) by which a disconnected stub attempts to reconnect to the GossipRouter")
+ long reconnect_interval=10000L;
/* --------------------------------------------- Fields ------------------------------------------------------ */
List<InetSocketAddress> initial_hosts=null; // (list of IpAddresses) hosts to be contacted for the initial membership
- final List<RouterStub> stubs = new ArrayList<RouterStub>();
+ final List<RouterStub> stubs=new ArrayList<RouterStub>();
+ Future<?> reconnect_future=null;
+ protected volatile boolean running=true;
public String getName() {
return name;
@@ -69,8 +77,14 @@ public void setInitialHosts(String hosts) throws UnknownHostException {
initial_hosts=Util.parseCommaDelimetedHosts2(hosts,1);
}
+ public void start() throws Exception {
+ super.start();
+ running=true;
+ }
+
public void stop() {
super.stop();
+ running=false;
for (RouterStub stub : stubs) {
try {
stub.disconnect(group_addr, local_addr);
@@ -78,7 +92,9 @@ public void stop() {
catch (Exception e) {
}
}
+ stopReconnector();
}
+
public void handleConnect() {
if(group_addr == null || local_addr == null) {
if(log.isErrorEnabled())
@@ -90,27 +106,16 @@ public void handleConnect() {
stubs.clear();
- // init stubs
- for (InetSocketAddress host : initial_hosts) {
- stubs.add(new RouterStub(host.getHostName(), host.getPort(),null));
+ for (InetSocketAddress host : initial_hosts) {
+ RouterStub stub=new RouterStub(host.getHostName(), host.getPort(), null);
+ stub.setConnectionListener(this);
+ stubs.add(stub);
}
-
- String logical_name=org.jgroups.util.UUID.get(local_addr);
- PhysicalAddress physical_addr=(PhysicalAddress)down_prot.down(new Event(Event.GET_PHYSICAL_ADDRESS, local_addr));
- List<PhysicalAddress> physical_addrs=physical_addr != null? new ArrayList<PhysicalAddress>() : null;
- if(physical_addr != null)
- physical_addrs.add(physical_addr);
-
- for (RouterStub stub : stubs) {
- try {
- stub.connect(group_addr, local_addr, logical_name, physical_addrs);
- }
- catch (Exception e) {
- }
- }
+ connect(group_addr, local_addr);
}
}
+
public void handleDisconnect() {
for (RouterStub stub : stubs) {
try {
@@ -121,24 +126,30 @@ public void handleDisconnect() {
}
}
- public void sendGetMembersRequest(String cluster_name, Promise promise) throws Exception{
- Message msg, copy;
- PingHeader hdr;
- List<Address> tmp_mbrs = new ArrayList<Address>();
- Address mbr_addr;
+ public void connectionStatusChange(RouterStub.ConnectionStatus state) {
+ if(log.isDebugEnabled())
+ log.debug("connection changed to " + state);
+ if(state == RouterStub.ConnectionStatus.CONNECTED)
+ stopReconnector();
+ else
+ startReconnector();
+ }
+ public void sendGetMembersRequest(String cluster_name, Promise promise) throws Exception{
if(group_addr == null) {
- if(log.isErrorEnabled()) log.error("[FIND_INITIAL_MBRS]: group_addr is null, cannot get mbrship");
+ if(log.isErrorEnabled()) log.error("[FIND_INITIAL_MBRS]: group_addr is null, cannot get membership");
return;
}
+
+ final List<Address> initial_mbrs=new ArrayList<Address>();
if(log.isTraceEnabled()) log.trace("fetching members from GossipRouter(s)");
- for (RouterStub stub : stubs) {
+ for(RouterStub stub : stubs) {
try {
List<PingData> rsps=stub.getMembers(group_addr);
for(PingData rsp: rsps) {
Address logical_addr=rsp.getAddress();
- tmp_mbrs.add(logical_addr);
+ initial_mbrs.add(logical_addr);
// 1. Set physical addresses
Collection<PhysicalAddress> physical_addrs=rsp.getPhysicalAddrs();
@@ -157,24 +168,65 @@ public void sendGetMembersRequest(String cluster_name, Promise promise) throws E
}
}
- if(tmp_mbrs.isEmpty()) {
- if(log.isErrorEnabled()) log.error("[FIND_INITIAL_MBRS]: gossip client found no members");
+ if(initial_mbrs.isEmpty()) {
+ if(log.isErrorEnabled()) log.error("[FIND_INITIAL_MBRS]: found no members");
return;
}
- if(log.isTraceEnabled()) log.trace("consolidated mbrs from GossipRouter(s) are " + tmp_mbrs);
-
- hdr=new PingHeader(PingHeader.GET_MBRS_REQ, cluster_name);
- msg=new Message(null);
- msg.setFlag(Message.OOB);
- msg.putHeader(name, hdr);
-
- for(Iterator<Address> it=tmp_mbrs.iterator(); it.hasNext();) {
- mbr_addr=it.next();
- copy=msg.copy();
- copy.setDest(mbr_addr);
- if(log.isTraceEnabled()) log.trace("[FIND_INITIAL_MBRS] sending PING request to " + copy.getDest());
- down_prot.down(new Event(Event.MSG, copy));
+ if(log.isTraceEnabled()) log.trace("consolidated mbrs from GossipRouter(s) are " + initial_mbrs);
+
+ for(Address mbr_addr: initial_mbrs) {
+ Message msg=new Message(mbr_addr);
+ msg.setFlag(Message.OOB);
+ PingHeader hdr=new PingHeader(PingHeader.GET_MBRS_REQ, cluster_name);
+ msg.putHeader(name, hdr);
+ if(log.isTraceEnabled()) log.trace("[FIND_INITIAL_MBRS] sending PING request to " + mbr_addr);
+ down_prot.down(new Event(Event.MSG, msg));
+ }
+ }
+
+ synchronized void startReconnector() {
+ if(running && (reconnect_future == null || reconnect_future.isDone())) {
+ if(log.isDebugEnabled())
+ log.debug("starting reconnector");
+ reconnect_future=timer.scheduleWithFixedDelay(new Runnable() {
+ public void run() {
+ connect(group_addr, local_addr);
+ }
+ }, 0, reconnect_interval, TimeUnit.MILLISECONDS);
+ }
+ }
+
+ synchronized void stopReconnector() {
+ if(reconnect_future != null) {
+ reconnect_future.cancel(true);
+ reconnect_future=null;
+ if(log.isDebugEnabled())
+ log.debug("stopping reconnector");
+ }
+ }
+
+ protected void connect(String group, Address logical_addr) {
+ String logical_name=org.jgroups.util.UUID.get(logical_addr);
+ PhysicalAddress physical_addr=(PhysicalAddress)down_prot.down(new Event(Event.GET_PHYSICAL_ADDRESS, local_addr));
+ List<PhysicalAddress> physical_addrs=physical_addr != null? new ArrayList<PhysicalAddress>() : null;
+ if(physical_addr != null)
+ physical_addrs.add(physical_addr);
+
+ int num_faulty_conns=0;
+ for (RouterStub stub : stubs) {
+ try {
+ if(log.isTraceEnabled())
+ log.trace("tring to connect to " + stub.getGossipRouterAddress());
+ stub.connect(group, logical_addr, logical_name, physical_addrs);
+ }
+ catch(Exception e) {
+ if(log.isErrorEnabled())
+ log.error("failed connecting to " + stub.getGossipRouterAddress() + ": " + e);
+ num_faulty_conns++;
+ }
}
+ if(num_faulty_conns == 0)
+ stopReconnector();
}
}
diff --git a/src/org/jgroups/stack/RouterStub.java b/src/org/jgroups/stack/RouterStub.java
index cc4ba445556..685a4bfffa0 100644
--- a/src/org/jgroups/stack/RouterStub.java
+++ b/src/org/jgroups/stack/RouterStub.java
@@ -1,27 +1,26 @@
package org.jgroups.stack;
+import org.jgroups.Address;
+import org.jgroups.PhysicalAddress;
+import org.jgroups.logging.Log;
+import org.jgroups.logging.LogFactory;
+import org.jgroups.protocols.PingData;
+import org.jgroups.protocols.TUNNEL;
+import org.jgroups.util.Util;
+
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
-import java.util.LinkedList;
-import java.util.List;
import java.util.ArrayList;
-
-import org.jgroups.logging.Log;
-import org.jgroups.logging.LogFactory;
-import org.jgroups.Address;
-import org.jgroups.PhysicalAddress;
-import org.jgroups.protocols.TUNNEL;
-import org.jgroups.protocols.PingData;
-import org.jgroups.util.Util;
+import java.util.List;
/**
* Client stub that talks to a remote GossipRouter
* @author Bela Ban
- * @version $Id: RouterStub.java,v 1.45 2009/07/08 15:30:31 belaban Exp $
+ * @version $Id: RouterStub.java,v 1.46 2009/07/09 13:59:39 belaban Exp $
*/
public class RouterStub {
@@ -51,8 +50,6 @@ public static enum ConnectionStatus {INITIAL, DISCONNECTED, CONNECTED};
private int sock_read_timeout=3000; // max number of ms to wait for socket reads (0 means block
// forever, or until the sock is closed)
- private volatile boolean intentionallyDisconnected=false;
-
public interface ConnectionListener {
void connectionStatusChange(ConnectionStatus state);
}
@@ -89,6 +86,10 @@ public boolean isConnected() {
return connectionState == ConnectionStatus.CONNECTED;
}
+ public ConnectionStatus getConnectionStatus() {
+ return connectionState;
+ }
+
public void setConnectionListener(ConnectionListener conn_listener) {
this.conn_listener=conn_listener;
}
@@ -142,9 +143,6 @@ public synchronized void destroy() {
Util.close(sock);
}
- public boolean isIntentionallyDisconnected() {
- return intentionallyDisconnected;
- }
public synchronized List<PingData> getMembers(final String group) throws Exception {
List<PingData> retval=new ArrayList<PingData>();
|
117bd32510ed29f46d2fc5c69fa0d2aeed80abe2
|
Valadoc
|
doclets/devhelp: Add full wiki-support
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/src/doclets/devhelp/doclet.vala b/src/doclets/devhelp/doclet.vala
index 4d523f8ede..2fa91f8cb8 100755
--- a/src/doclets/devhelp/doclet.vala
+++ b/src/doclets/devhelp/doclet.vala
@@ -1,6 +1,6 @@
/* doclet.vala
*
- * Copyright (C) 2008-2009 Florian Brosch
+ * Copyright (C) 2008-2012 Florian Brosch
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -28,10 +28,10 @@ using Gee;
public class Valadoc.Devhelp.Doclet : Valadoc.Html.BasicDoclet {
- private const string css_path_wiki = "../devhelpstyle.css";
+ private const string css_path_wiki = "devhelpstyle.css";
private const string css_path = "devhelpstyle.css";
- private const string js_path_wiki = "../scripts.js";
+ private const string js_path_wiki = "scripts.js";
private const string js_path = "scripts.js";
@@ -56,7 +56,7 @@ public class Valadoc.Devhelp.Doclet : Valadoc.Html.BasicDoclet {
public override void process (Settings settings, Api.Tree tree, ErrorReporter reporter) {
base.process (settings, tree, reporter);
DirUtils.create_with_parents (this.settings.path, 0777);
- write_wiki_pages (tree, css_path_wiki, js_path_wiki, Path.build_filename (this.settings.path, this.settings.pkg_name, "content"));
+ write_wiki_pages (tree, css_path_wiki, js_path_wiki, Path.build_filename (this.settings.path, this.settings.pkg_name));
tree.accept (this);
}
@@ -76,11 +76,6 @@ public class Valadoc.Devhelp.Doclet : Valadoc.Html.BasicDoclet {
string imgpath = GLib.Path.build_filename (path, "img");
string devpath = GLib.Path.build_filename (path, pkg_name + ".devhelp2");
- WikiPage wikipage = null;
- if (this.settings.pkg_name == package.name && this.tree.wikitree != null) {
- wikipage = this.tree.wikitree.search ("index.valadoc");
- }
-
this.package_dir_name = pkg_name;
var rt = DirUtils.create (path, 0777);
@@ -97,7 +92,7 @@ public class Valadoc.Devhelp.Doclet : Valadoc.Html.BasicDoclet {
writer = new Html.MarkupWriter (file);
_renderer.set_writer (writer);
write_file_header (this.css_path, this.js_path, pkg_name);
- write_package_content (package, package, wikipage);
+ write_package_content (package, package);
write_file_footer ();
file = null;
diff --git a/src/doclets/htm/doclet.vala b/src/doclets/htm/doclet.vala
index 7613f17bb0..ba6f7fe74a 100755
--- a/src/doclets/htm/doclet.vala
+++ b/src/doclets/htm/doclet.vala
@@ -1,6 +1,6 @@
/* doclet.vala
*
- * Copyright (C) 2008-2009 Florian Brosch
+ * Copyright (C) 2008-2012 Florian Brosch
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -37,6 +37,36 @@ public class Valadoc.HtmlDoclet : Valadoc.Html.BasicDoclet {
private const string js_path_wiki = "../scripts.js";
private const string js_path = "../scripts.js";
+ private class IndexLinkHelper : LinkHelper {
+ protected override string? from_wiki_to_package (WikiPage from, Api.Package to) {
+ if (from.name != "index.valadoc") {
+ return base.from_wiki_to_package (from, to);;
+ }
+
+ return Path.build_filename (to.name, to.name + ".htm");
+ }
+
+ protected override string? from_wiki_to_wiki (WikiPage from, WikiPage to) {
+ if (from.name != "index.valadoc") {
+ return base.from_wiki_to_wiki (from, to);
+ }
+
+ return Path.build_filename (_settings.pkg_name, translate_wiki_name (to));
+ }
+
+ protected override string? from_wiki_to_node (WikiPage from, Api.Node to) {
+ if (from.name != "index.valadoc") {
+ return base.from_wiki_to_node (from, to);
+ }
+
+ if (enable_browsable_check && (!to.is_browsable(_settings) || !to.package.is_browsable (_settings))) {
+ return null;
+ }
+
+ return Path.build_filename (to.package.name, to.get_full_name () + ".html");
+ }
+ }
+
private string get_real_path ( Api.Node element ) {
return GLib.Path.build_filename ( this.settings.path, element.package.name, element.get_full_name () + ".html" );
}
@@ -47,8 +77,10 @@ public class Valadoc.HtmlDoclet : Valadoc.Html.BasicDoclet {
DirUtils.create_with_parents (this.settings.path, 0777);
copy_directory (icons_dir, settings.path);
- write_wiki_pages (tree, css_path_wiki, js_path_wiki, Path.build_filename(settings.path, "content"));
+ write_wiki_pages (tree, css_path_wiki, js_path_wiki, Path.build_filename(settings.path, settings.pkg_name));
+ var tmp = _renderer;
+ _renderer = new HtmlRenderer (settings, new IndexLinkHelper (), this.cssresolver);
GLib.FileStream file = GLib.FileStream.open (GLib.Path.build_filename (settings.path, "index.html"), "w");
writer = new Html.MarkupWriter (file);
_renderer.set_writer (writer);
@@ -56,6 +88,7 @@ public class Valadoc.HtmlDoclet : Valadoc.Html.BasicDoclet {
write_navi_packages (tree);
write_package_index_content (tree);
write_file_footer ();
+ _renderer = tmp;
file = null;
tree.accept (this);
diff --git a/src/libvaladoc/html/basicdoclet.vala b/src/libvaladoc/html/basicdoclet.vala
index 04e0f59873..d2ab882ee9 100755
--- a/src/libvaladoc/html/basicdoclet.vala
+++ b/src/libvaladoc/html/basicdoclet.vala
@@ -1,6 +1,6 @@
/* basicdoclet.vala
*
- * Copyright (C) 2008-2009 Florian Brosch
+ * Copyright (C) 2008-2012 Florian Brosch
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -203,7 +203,7 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
}
protected virtual void write_wiki_page (WikiPage page, string contentp, string css_path, string js_path, string pkg_name) {
- GLib.FileStream file = GLib.FileStream.open (Path.build_filename(contentp, page.name.substring (0, page.name.length-7).replace ("/", ".")+"html"), "w");
+ GLib.FileStream file = GLib.FileStream.open (Path.build_filename(contentp, page.name.substring (0, page.name.length-7).replace ("/", ".")+"htm"), "w");
writer = new MarkupWriter (file);
_renderer.set_writer (writer);
this.write_file_header (css_path, js_path, pkg_name);
@@ -792,12 +792,14 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
writer.end_tag ("div");
}
- protected void write_package_content (Package node, Api.Node? parent, WikiPage? wikipage = null) {
+ protected void write_package_content (Package node, Api.Node? parent) {
writer.start_tag ("div", {"class", css_style_content});
writer.start_tag ("h1", {"class", css_title, "id", node.name}).text (node.name).end_tag ("h1");
writer.simple_tag ("hr", {"class", css_headline_hr});
writer.start_tag ("h2", {"class", css_title}).text ("Description:").end_tag ("h2");
+
+ WikiPage? wikipage = (tree.wikitree == null)? null : tree.wikitree.search ("index.valadoc");
if (wikipage != null) {
_renderer.set_container (parent);
_renderer.render (wikipage.documentation);
diff --git a/src/libvaladoc/html/linkhelper.vala b/src/libvaladoc/html/linkhelper.vala
index 2d29686687..f9a69034f0 100755
--- a/src/libvaladoc/html/linkhelper.vala
+++ b/src/libvaladoc/html/linkhelper.vala
@@ -1,6 +1,6 @@
/* linkhelper.vala
*
- * Copyright (C) 2008-2009 Florian Brosch
+ * Copyright (C) 2008-2012 Florian Brosch
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -25,7 +25,7 @@ using Gee;
public class Valadoc.Html.LinkHelper : Object {
- private Settings _settings = null;
+ protected Settings _settings = null;
public bool enable_browsable_check {
default = true;
@@ -82,9 +82,9 @@ public class Valadoc.Html.LinkHelper : Object {
return null;
}
- private string translate_wiki_name (WikiPage page) {
+ protected string translate_wiki_name (WikiPage page) {
var name = page.name;
- return name.substring (0, name.last_index_of_char ('.')).replace ("/", ".") + ".html";
+ return name.substring (0, name.last_index_of_char ('.')).replace ("/", ".") + ".htm";
}
@@ -103,10 +103,10 @@ public class Valadoc.Html.LinkHelper : Object {
}
protected virtual string? from_package_to_wiki (Api.Package from, WikiPage to) {
- if (from.name == "index.valadoc") {
- return Path.build_filename ("..", "index.html");
+ if (from.is_package) {
+ return Path.build_filename ("..", _settings.pkg_name, translate_wiki_name (to));
} else {
- return Path.build_filename ("..", "content", translate_wiki_name (to));
+ return translate_wiki_name (to);
}
}
@@ -129,23 +129,15 @@ public class Valadoc.Html.LinkHelper : Object {
return null;
}
- if (from.name == "index.valadoc") {
- return Path.build_filename (to.name, "index.htm");
- } else {
+ if (to.is_package) {
return Path.build_filename ("..", to.name, "index.htm");
+ } else {
+ return "index.htm";
}
}
protected virtual string? from_wiki_to_wiki (WikiPage from, WikiPage to) {
- if (from == to) {
- return "#";
- } else if (from.name == "index.valadoc") {
- return Path.build_filename ("content", translate_wiki_name (to));
- } else if (to.name == "index.valadoc") {
- return Path.build_filename ("..", "index.html");
- } else {
- return translate_wiki_name (to);
- }
+ return translate_wiki_name (to);
}
protected virtual string? from_wiki_to_node (WikiPage from, Api.Node to) {
@@ -153,10 +145,10 @@ public class Valadoc.Html.LinkHelper : Object {
return null;
}
- if (from.name == "index.valadoc") {
- return Path.build_filename (to.package.name, to.get_full_name() + ".html");
+ if (to.package.is_package) {
+ return Path.build_filename ("..", to.package.name, to.get_full_name () + ".html");
} else {
- return Path.build_filename ("..", to.package.name, to.get_full_name() + ".html");
+ return to.get_full_name () + ".html";
}
}
@@ -175,10 +167,10 @@ public class Valadoc.Html.LinkHelper : Object {
}
protected virtual string? from_node_to_wiki (Api.Node from, WikiPage to) {
- if (to.name == "index.valadoc") {
- return Path.build_filename ("..", "index.html");
+ if (from.package.is_package) {
+ return Path.build_filename ("..", _settings.pkg_name, translate_wiki_name (to));
} else {
- return Path.build_filename ("..", "content", translate_wiki_name (to));
+ return translate_wiki_name (to);
}
}
|
8c9507ec33019b88dd43ab47e1bd50d22332740b
|
Valadoc
|
girmetadata: allow to override <ONLINE>
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/src/libvaladoc/documentation/documentationparser.vala b/src/libvaladoc/documentation/documentationparser.vala
index 481ba6fd4a..c50105ba6f 100644
--- a/src/libvaladoc/documentation/documentationparser.vala
+++ b/src/libvaladoc/documentation/documentationparser.vala
@@ -173,7 +173,7 @@ public class Valadoc.DocumentationParser : Object, ResourceLocator {
metadata = new GirMetaData (gir_comment.file.relative_path, _settings.metadata_directories, _reporter);
if (metadata.index_sgml != null) {
- id_registrar.read_index_sgml_file (metadata.index_sgml, _reporter);
+ id_registrar.read_index_sgml_file (metadata.index_sgml, metadata.index_sgml_online, _reporter);
}
this.metadata.set (gir_comment.file, metadata);
diff --git a/src/libvaladoc/documentation/girmetadata.vala b/src/libvaladoc/documentation/girmetadata.vala
index 1a9909712a..61c6c4b9dd 100644
--- a/src/libvaladoc/documentation/girmetadata.vala
+++ b/src/libvaladoc/documentation/girmetadata.vala
@@ -33,7 +33,7 @@ public class Valadoc.GirMetaData : Object {
public bool is_docbook { private set; get; default = false; }
public string index_sgml { private set; get; default = null; }
-
+ public string index_sgml_online { private set; get; default = null; }
/**
* Used to manipulate paths to resources inside gir-files
@@ -98,6 +98,10 @@ public class Valadoc.GirMetaData : Object {
this.index_sgml = key_file.get_string ("General", "index_sgml");
break;
+ case "index_sgml_online":
+ this.index_sgml_online = key_file.get_string ("General", "index_sgml_online");
+ break;
+
default:
reporter.simple_warning ("%s: warning: Unknown key 'General.%s'", metadata_path, key);
break;
|
3ac3a72e910ce4734459e9359f979fbed8cb64a1
|
spring-framework
|
added test with custom repository annotation--
|
p
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.transaction/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationAdvisorTests.java b/org.springframework.transaction/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationAdvisorTests.java
index 2c6fb3d81dcd..8099156006c1 100644
--- a/org.springframework.transaction/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationAdvisorTests.java
+++ b/org.springframework.transaction/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationAdvisorTests.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2007 the original author or authors.
+ * Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,10 @@
package org.springframework.dao.annotation;
+import java.lang.annotation.Target;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
import javax.persistence.PersistenceException;
import junit.framework.TestCase;
@@ -109,6 +113,10 @@ public void testTranslationNeededForTheseExceptionsOnSuperclass() {
doTestTranslationNeededForTheseExceptions(new MyStereotypedRepositoryInterfaceImpl());
}
+ public void testTranslationNeededForTheseExceptionsWithCustomStereotype() {
+ doTestTranslationNeededForTheseExceptions(new CustomStereotypedRepositoryInterfaceImpl());
+ }
+
public void testTranslationNeededForTheseExceptionsOnInterface() {
doTestTranslationNeededForTheseExceptions(new MyInterfaceStereotypedRepositoryInterfaceImpl());
}
@@ -142,6 +150,7 @@ private void doTestTranslationNeededForTheseExceptions(RepositoryInterfaceImpl t
}
}
+
public interface RepositoryInterface {
void noThrowsClause();
@@ -149,6 +158,7 @@ public interface RepositoryInterface {
void throwsPersistenceException() throws PersistenceException;
}
+
public static class RepositoryInterfaceImpl implements RepositoryInterface {
private RuntimeException runtimeException;
@@ -170,29 +180,49 @@ public void throwsPersistenceException() throws PersistenceException {
}
}
+
@Repository
public static class StereotypedRepositoryInterfaceImpl extends RepositoryInterfaceImpl {
// Extends above class just to add repository annotation
}
+
public static class MyStereotypedRepositoryInterfaceImpl extends StereotypedRepositoryInterfaceImpl {
}
+
+ @MyRepository
+ public static class CustomStereotypedRepositoryInterfaceImpl extends RepositoryInterfaceImpl {
+
+ }
+
+
+ @Target({ElementType.TYPE})
+ @Retention(RetentionPolicy.RUNTIME)
+ @Repository
+ public @interface MyRepository {
+
+ }
+
+
@Repository
public interface StereotypedInterface {
}
+
public static class MyInterfaceStereotypedRepositoryInterfaceImpl extends RepositoryInterfaceImpl
implements StereotypedInterface {
}
+
public interface StereotypedInheritingInterface extends StereotypedInterface {
}
+
public static class MyInterfaceInheritedStereotypedRepositoryInterfaceImpl extends RepositoryInterfaceImpl
implements StereotypedInheritingInterface {
|
18e0bff6dbfd5189d2975574c273fe6f1208ba43
|
drools
|
JBRULES-313: adding fire limit option--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@12927 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
|
a
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java b/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java
index 08dd4a3e144..cf773cca262 100644
--- a/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java
+++ b/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java
@@ -2945,6 +2945,52 @@ public void testHalt() throws Exception {
}
}
+ public void testFireLimit() throws Exception {
+ final PackageBuilder builder = new PackageBuilder();
+ builder.addPackageFromDrl( new InputStreamReader( getClass().getResourceAsStream( "test_fireLimit.drl" ) ) );
+ final Package pkg = builder.getPackage();
+
+ final RuleBase ruleBase = getRuleBase();
+ ruleBase.addPackage( pkg );
+ final WorkingMemory workingMemory = ruleBase.newStatefulSession();
+
+ final List results = new ArrayList();
+ workingMemory.setGlobal( "results",
+ results );
+
+ workingMemory.insert( new Integer( 0 ) );
+ workingMemory.fireAllRules();
+
+ assertEquals( 20,
+ results.size() );
+ for( int i = 0; i < 20; i++ ) {
+ assertEquals( new Integer( i ), results.get( i ) );
+ }
+ results.clear();
+
+ workingMemory.insert( new Integer( 0 ) );
+ workingMemory.fireAllRules( 10 );
+
+ assertEquals( 10,
+ results.size() );
+ for( int i = 0; i < 10; i++ ) {
+ assertEquals( new Integer( i ), results.get( i ) );
+ }
+ results.clear();
+
+ workingMemory.insert( new Integer( 0 ) );
+ workingMemory.fireAllRules( -1 );
+
+ assertEquals( 20,
+ results.size() );
+ for( int i = 0; i < 20; i++ ) {
+ assertEquals( new Integer( i ), results.get( i ) );
+ }
+ results.clear();
+
+
+ }
+
}
\ No newline at end of file
diff --git a/drools-compiler/src/test/resources/org/drools/integrationtests/test_fireLimit.drl b/drools-compiler/src/test/resources/org/drools/integrationtests/test_fireLimit.drl
new file mode 100644
index 00000000000..20c1ea9c1ff
--- /dev/null
+++ b/drools-compiler/src/test/resources/org/drools/integrationtests/test_fireLimit.drl
@@ -0,0 +1,21 @@
+package org.drools;
+
+global java.util.List results;
+
+rule "fire"
+when
+ $old : Number( $val : intValue )
+then
+ results.add( $old );
+ insert( new Integer( $val + 1 ) );
+ retract( $old );
+end
+
+rule "stop"
+ salience 10
+when
+ $old : Number( intValue == 20 )
+then
+ retract( $old );
+ drools.halt();
+end
\ No newline at end of file
diff --git a/drools-core/src/main/java/org/drools/WorkingMemory.java b/drools-core/src/main/java/org/drools/WorkingMemory.java
index 9887e14b991..a72995fd5ca 100644
--- a/drools-core/src/main/java/org/drools/WorkingMemory.java
+++ b/drools-core/src/main/java/org/drools/WorkingMemory.java
@@ -162,6 +162,22 @@ void setGlobal(String name,
*/
void fireAllRules(AgendaFilter agendaFilter) throws FactException;
+ /**
+ * Fire all items on the agenda until empty or at most 'fireLimit' rules have fired
+ *
+ * @throws FactException
+ * If an error occurs.
+ */
+ void fireAllRules( int fireLimit ) throws FactException;
+
+ /**
+ * Fire all items on the agenda using the given AgendaFiler
+ * until empty or at most 'fireLimit' rules have fired
+ *
+ * @throws FactException
+ * If an error occurs.
+ */
+ void fireAllRules(final AgendaFilter agendaFilter, int fireLimit ) throws FactException;
/**
* Retrieve the object associated with a <code>FactHandle</code>.
diff --git a/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java b/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java
index 52d6cea401e..3acbc7deca1 100644
--- a/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java
+++ b/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java
@@ -404,10 +404,18 @@ public void halt() {
* @see WorkingMemory
*/
public synchronized void fireAllRules() throws FactException {
- fireAllRules( null );
+ fireAllRules( null, -1 );
}
- public synchronized void fireAllRules(final AgendaFilter agendaFilter) throws FactException {
+ public synchronized void fireAllRules( int fireLimit ) throws FactException {
+ fireAllRules( null, fireLimit );
+ }
+
+ public synchronized void fireAllRules( final AgendaFilter agendaFilter ) throws FactException {
+ fireAllRules( agendaFilter, -1 );
+ }
+
+ public synchronized void fireAllRules(final AgendaFilter agendaFilter, int fireLimit ) throws FactException {
// If we're already firing a rule, then it'll pick up
// the firing for any other assertObject(..) that get
// nested inside, avoiding concurrent-modification
@@ -430,7 +438,8 @@ public synchronized void fireAllRules(final AgendaFilter agendaFilter) throws Fa
try {
this.firing = true;
- while ( (!halt) && this.agenda.fireNextItem( agendaFilter ) ) {
+ while ( continueFiring( fireLimit ) && this.agenda.fireNextItem( agendaFilter ) ) {
+ fireLimit = updateFireLimit( fireLimit );
noneFired = false;
if ( !this.actionQueue.isEmpty() ) {
executeQueuedActions();
@@ -439,26 +448,34 @@ public synchronized void fireAllRules(final AgendaFilter agendaFilter) throws Fa
} finally {
this.firing = false;
if ( noneFired ) {
- doOtherwise( agendaFilter );
+ doOtherwise( agendaFilter, fireLimit );
}
}
}
}
+
+ private final boolean continueFiring( final int fireLimit ) {
+ return (!halt) && (fireLimit != 0 );
+ }
+
+ private final int updateFireLimit( final int fireLimit ) {
+ return fireLimit > 0 ? fireLimit-1 : fireLimit;
+ }
/**
* This does the "otherwise" phase of processing.
* If no items are fired, then it will assert a temporary "Otherwise"
* fact and allow any rules to fire to handle "otherwise" cases.
*/
- private void doOtherwise(final AgendaFilter agendaFilter) {
+ private void doOtherwise(final AgendaFilter agendaFilter, int fireLimit ) {
final FactHandle handle = this.insert( new Otherwise() );
if ( !this.actionQueue.isEmpty() ) {
executeQueuedActions();
}
- while ( (!halt) && this.agenda.fireNextItem( agendaFilter ) ) {
- ;
+ while ( continueFiring( fireLimit ) && this.agenda.fireNextItem( agendaFilter ) ) {
+ fireLimit = updateFireLimit( fireLimit );
}
this.retract( handle );
|
950225ed644937af40685339d143bd5da1c1e96d
|
Delta Spike
|
DELTASPIKE-312 add JavaDoc warning for @Alternative scenarios
|
p
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/provider/BeanProvider.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/provider/BeanProvider.java
index 51dff71ee..b1a9de4a7 100644
--- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/provider/BeanProvider.java
+++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/provider/BeanProvider.java
@@ -229,6 +229,9 @@ private static <T> T getContextualReference(Class<T> type, BeanManager beanManag
*
* <p><b>Attention:</b> please see the notes on manually resolving @Dependent bean
* in {@link #getContextualReference(Class, boolean, java.lang.annotation.Annotation...)}!</p>
+ * <p><b>Attention:</b> This will also return instances for beans which where an Alternative
+ * exists for! The @Alternative resolving is only done via {@link BeanManager#resolve(java.util.Set)}
+ * which we cannot use in this case!</p>
*
* @param type the type of the bean in question
* @param optional if <code>true</code> it will return an empty list if no bean could be found or created.
@@ -245,6 +248,11 @@ public static <T> List<T> getContextualReferences(Class<T> type, boolean optiona
* <p>Get a list of Contextual References by it's type independent of the qualifier.
*
* Further details are available at {@link #getContextualReferences(Class, boolean)}
+ * <p><b>Attention:</b> please see the notes on manually resolving @Dependent bean
+ * in {@link #getContextualReference(Class, boolean, java.lang.annotation.Annotation...)}!</p>
+ * <p><b>Attention:</b> This will also return instances for beans which where an Alternative
+ * exists for! The @Alternative resolving is only done via {@link BeanManager#resolve(java.util.Set)}
+ * which we cannot use in this case!</p>
*
* @param type the type of the bean in question
* @param optional if <code>true</code> it will return an empty list if no bean could be found or created.
|
d35b3e7d8b5fd7b509ed5cb78937b29dbe240210
|
ReactiveX-RxJava
|
Fix non-deterministic unit test--
|
c
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-core/src/test/java/rx/concurrency/TestSchedulers.java b/rxjava-core/src/test/java/rx/concurrency/TestSchedulers.java
index a92033dcd1..bec93cfdcd 100644
--- a/rxjava-core/src/test/java/rx/concurrency/TestSchedulers.java
+++ b/rxjava-core/src/test/java/rx/concurrency/TestSchedulers.java
@@ -17,11 +17,17 @@
import static org.junit.Assert.*;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
import org.junit.Test;
import rx.Observable;
+import rx.Observer;
+import rx.Subscription;
+import rx.subscriptions.Subscriptions;
import rx.util.functions.Action1;
import rx.util.functions.Func1;
@@ -181,7 +187,7 @@ public void call(String t) {
}
@Test
- public void testSubscribeWithScheduler1() {
+ public void testSubscribeWithScheduler1() throws InterruptedException {
final AtomicInteger count = new AtomicInteger();
@@ -204,16 +210,39 @@ public void call(Integer t) {
// now we'll subscribe with a scheduler and it should be async
+ final String currentThreadName = Thread.currentThread().getName();
+
+ // latches for deterministically controlling the test below across threads
+ final CountDownLatch latch = new CountDownLatch(5);
+ final CountDownLatch first = new CountDownLatch(1);
+
o1.subscribe(new Action1<Integer>() {
@Override
public void call(Integer t) {
+ try {
+ // we block the first one so we can assert this executes asynchronously with a count
+ first.await(1000, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ throw new RuntimeException("The latch should have released if we are async.", e);
+ }
+ assertFalse(Thread.currentThread().getName().equals(currentThreadName));
+ assertTrue(Thread.currentThread().getName().startsWith("RxComputationThreadPool"));
System.out.println("Thread: " + Thread.currentThread().getName());
System.out.println("t: " + t);
count.incrementAndGet();
+ latch.countDown();
}
}, Schedulers.threadPoolForComputation());
+ // assert we are async
assertEquals(0, count.get());
+ // release the latch so it can go forward
+ first.countDown();
+
+ // wait for all 5 responses
+ latch.await();
+ assertEquals(5, count.get());
}
+
}
|
a03ba9564082f08908fba57932b6923ece2ee169
|
Valadoc
|
Improve handling for c::this
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/src/libvaladoc/documentation/gtkdocmarkdownparser.vala b/src/libvaladoc/documentation/gtkdocmarkdownparser.vala
index 841949ddf2..9614e6c820 100644
--- a/src/libvaladoc/documentation/gtkdocmarkdownparser.vala
+++ b/src/libvaladoc/documentation/gtkdocmarkdownparser.vala
@@ -598,11 +598,6 @@ public class Valadoc.Gtkdoc.MarkdownParser : Object, ResourceLocator {
this.gir_comment = gir_comment;
this.element = element;
- bool has_instance = false;
- if (element is Api.Method) {
- has_instance = !((Api.Method) element).is_static;
- }
-
// main:
Comment? cmnt = _parse (gir_comment);
@@ -645,10 +640,9 @@ public class Valadoc.Gtkdoc.MarkdownParser : Object, ResourceLocator {
Taglets.Param? taglet = _parse_block_taglet (iter.get_value (), "param") as Taglets.Param;
string param_name = iter.get_key ();
- if (taglet != null && !(has_instance && param_name == gir_comment.instance_param_name)) {
- taglet.parameter_name = param_name;
- add_taglet (ref cmnt, taglet);
- }
+ taglet.is_c_self_param = (param_name == gir_comment.instance_param_name);
+ taglet.parameter_name = param_name;
+ add_taglet (ref cmnt, taglet);
}
diff --git a/src/libvaladoc/html/htmlrenderer.vala b/src/libvaladoc/html/htmlrenderer.vala
index d9f5a21cbf..294a977773 100644
--- a/src/libvaladoc/html/htmlrenderer.vala
+++ b/src/libvaladoc/html/htmlrenderer.vala
@@ -175,7 +175,7 @@ public class Valadoc.Html.HtmlRenderer : ContentRenderer {
(taglet) => {
var param = taglet as Taglets.Param;
string[]? unknown_parameter_css = null;
- if (param.parameter == null) {
+ if (param.parameter == null && !param.is_this) {
unknown_parameter_css = {"class", "main_parameter_table_unknown_parameter"};
}
diff --git a/src/libvaladoc/taglets/tagletparam.vala b/src/libvaladoc/taglets/tagletparam.vala
index 94c602a859..e6e5cd057a 100644
--- a/src/libvaladoc/taglets/tagletparam.vala
+++ b/src/libvaladoc/taglets/tagletparam.vala
@@ -34,6 +34,9 @@ public class Valadoc.Taglets.Param : BlockContent, Taglet, Block {
public bool is_c_self_param { internal set; get; }
+ public bool is_this { private set; get; }
+
+
public Rule? get_parser_rule (Rule run_rule) {
return Rule.seq ({
Rule.option ({ Rule.many ({ TokenType.SPACE }) }),
@@ -47,6 +50,7 @@ public class Valadoc.Taglets.Param : BlockContent, Taglet, Block {
{
// Check for the existence of such a parameter
unowned string? implicit_return_array_length = null;
+ bool has_instance = has_instance (container);
bool is_implicit = false;
this.parameter = null;
@@ -59,13 +63,16 @@ public class Valadoc.Taglets.Param : BlockContent, Taglet, Block {
return ;
}
-
- if (parameter_name == "...") {
+ if (is_c_self_param == true && has_instance) {
+ this.parameter_name = "this";
+ this.is_this = true;
+ this.position = 0;
+ } else if (parameter_name == "...") {
Gee.List<Api.Node> params = container.get_children_by_type (Api.NodeType.FORMAL_PARAMETER, false);
foreach (Api.Node param in params) {
if (((Api.FormalParameter) param).ellipsis) {
this.parameter = (Api.Symbol) param;
- this.position = params.size - 1;
+ this.position = (has_instance)? params.size : params.size - 1;
break;
}
}
@@ -73,7 +80,7 @@ public class Valadoc.Taglets.Param : BlockContent, Taglet, Block {
Gee.List<Api.Node> params = container.get_children_by_types ({Api.NodeType.FORMAL_PARAMETER,
Api.NodeType.TYPE_PARAMETER},
false);
- int pos = 0;
+ int pos = (has_instance)? 1 : 0;
foreach (Api.Node param in params) {
if (param.name == parameter_name) {
@@ -116,6 +123,14 @@ public class Valadoc.Taglets.Param : BlockContent, Taglet, Block {
base.check (api_root, container, file_path, reporter, settings);
}
+ private bool has_instance (Api.Item element) {
+ if (element is Api.Method) {
+ return !((Api.Method) element).is_static;
+ }
+
+ return false;
+ }
+
public override void accept (ContentVisitor visitor) {
visitor.visit_taglet (this);
}
|
3fa1fbf35a2e750c3b932c7721f5b820ed518adf
|
tapiji
|
updated licenses
|
p
|
https://github.com/tapiji/tapiji
|
diff --git a/at.ac.tuwien.inso.eclipse.i18n.java/epl-v10.html b/at.ac.tuwien.inso.eclipse.i18n.java/epl-v10.html
new file mode 100644
index 00000000..ed4b1966
--- /dev/null
+++ b/at.ac.tuwien.inso.eclipse.i18n.java/epl-v10.html
@@ -0,0 +1,328 @@
+<html xmlns:o="urn:schemas-microsoft-com:office:office"
+xmlns:w="urn:schemas-microsoft-com:office:word"
+xmlns="http://www.w3.org/TR/REC-html40">
+
+<head>
+<meta http-equiv=Content-Type content="text/html; charset=windows-1252">
+<meta name=ProgId content=Word.Document>
+<meta name=Generator content="Microsoft Word 9">
+<meta name=Originator content="Microsoft Word 9">
+<link rel=File-List
+href="./Eclipse%20EPL%202003_11_10%20Final_files/filelist.xml">
+<title>Eclipse Public License - Version 1.0</title>
+<!--[if gte mso 9]><xml>
+ <o:DocumentProperties>
+ <o:Revision>2</o:Revision>
+ <o:TotalTime>3</o:TotalTime>
+ <o:Created>2004-03-05T23:03:00Z</o:Created>
+ <o:LastSaved>2004-03-05T23:03:00Z</o:LastSaved>
+ <o:Pages>4</o:Pages>
+ <o:Words>1626</o:Words>
+ <o:Characters>9270</o:Characters>
+ <o:Lines>77</o:Lines>
+ <o:Paragraphs>18</o:Paragraphs>
+ <o:CharactersWithSpaces>11384</o:CharactersWithSpaces>
+ <o:Version>9.4402</o:Version>
+ </o:DocumentProperties>
+</xml><![endif]--><!--[if gte mso 9]><xml>
+ <w:WordDocument>
+ <w:TrackRevisions/>
+ </w:WordDocument>
+</xml><![endif]-->
+<style>
+<!--
+ /* Font Definitions */
+@font-face
+ {font-family:Tahoma;
+ panose-1:2 11 6 4 3 5 4 4 2 4;
+ mso-font-charset:0;
+ mso-generic-font-family:swiss;
+ mso-font-pitch:variable;
+ mso-font-signature:553679495 -2147483648 8 0 66047 0;}
+ /* Style Definitions */
+p.MsoNormal, li.MsoNormal, div.MsoNormal
+ {mso-style-parent:"";
+ margin:0in;
+ margin-bottom:.0001pt;
+ mso-pagination:widow-orphan;
+ font-size:12.0pt;
+ font-family:"Times New Roman";
+ mso-fareast-font-family:"Times New Roman";}
+p
+ {margin-right:0in;
+ mso-margin-top-alt:auto;
+ mso-margin-bottom-alt:auto;
+ margin-left:0in;
+ mso-pagination:widow-orphan;
+ font-size:12.0pt;
+ font-family:"Times New Roman";
+ mso-fareast-font-family:"Times New Roman";}
+p.BalloonText, li.BalloonText, div.BalloonText
+ {mso-style-name:"Balloon Text";
+ margin:0in;
+ margin-bottom:.0001pt;
+ mso-pagination:widow-orphan;
+ font-size:8.0pt;
+ font-family:Tahoma;
+ mso-fareast-font-family:"Times New Roman";}
+@page Section1
+ {size:8.5in 11.0in;
+ margin:1.0in 1.25in 1.0in 1.25in;
+ mso-header-margin:.5in;
+ mso-footer-margin:.5in;
+ mso-paper-source:0;}
+div.Section1
+ {page:Section1;}
+-->
+</style>
+</head>
+
+<body lang=EN-US style='tab-interval:.5in'>
+
+<div class=Section1>
+
+<p align=center style='text-align:center'><b>Eclipse Public License - v 1.0</b>
+</p>
+
+<p><span style='font-size:10.0pt'>THE ACCOMPANYING PROGRAM IS PROVIDED UNDER
+THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE,
+REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE
+OF THIS AGREEMENT.</span> </p>
+
+<p><b><span style='font-size:10.0pt'>1. DEFINITIONS</span></b> </p>
+
+<p><span style='font-size:10.0pt'>"Contribution" means:</span> </p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a)
+in the case of the initial Contributor, the initial code and documentation
+distributed under this Agreement, and<br clear=left>
+b) in the case of each subsequent Contributor:</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>i)
+changes to the Program, and</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii)
+additions to the Program;</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>where
+such changes and/or additions to the Program originate from and are distributed
+by that particular Contributor. A Contribution 'originates' from a Contributor
+if it was added to the Program by such Contributor itself or anyone acting on
+such Contributor's behalf. Contributions do not include additions to the
+Program which: (i) are separate modules of software distributed in conjunction
+with the Program under their own license agreement, and (ii) are not derivative
+works of the Program. </span></p>
+
+<p><span style='font-size:10.0pt'>"Contributor" means any person or
+entity that distributes the Program.</span> </p>
+
+<p><span style='font-size:10.0pt'>"Licensed Patents " mean patent
+claims licensable by a Contributor which are necessarily infringed by the use
+or sale of its Contribution alone or when combined with the Program. </span></p>
+
+<p><span style='font-size:10.0pt'>"Program" means the Contributions
+distributed in accordance with this Agreement.</span> </p>
+
+<p><span style='font-size:10.0pt'>"Recipient" means anyone who
+receives the Program under this Agreement, including all Contributors.</span> </p>
+
+<p><b><span style='font-size:10.0pt'>2. GRANT OF RIGHTS</span></b> </p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a)
+Subject to the terms of this Agreement, each Contributor hereby grants Recipient
+a non-exclusive, worldwide, royalty-free copyright license to<span
+style='color:red'> </span>reproduce, prepare derivative works of, publicly
+display, publicly perform, distribute and sublicense the Contribution of such
+Contributor, if any, and such derivative works, in source code and object code
+form.</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b)
+Subject to the terms of this Agreement, each Contributor hereby grants
+Recipient a non-exclusive, worldwide,<span style='color:green'> </span>royalty-free
+patent license under Licensed Patents to make, use, sell, offer to sell, import
+and otherwise transfer the Contribution of such Contributor, if any, in source
+code and object code form. This patent license shall apply to the combination
+of the Contribution and the Program if, at the time the Contribution is added
+by the Contributor, such addition of the Contribution causes such combination
+to be covered by the Licensed Patents. The patent license shall not apply to
+any other combinations which include the Contribution. No hardware per se is
+licensed hereunder. </span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>c)
+Recipient understands that although each Contributor grants the licenses to its
+Contributions set forth herein, no assurances are provided by any Contributor
+that the Program does not infringe the patent or other intellectual property
+rights of any other entity. Each Contributor disclaims any liability to Recipient
+for claims brought by any other entity based on infringement of intellectual
+property rights or otherwise. As a condition to exercising the rights and
+licenses granted hereunder, each Recipient hereby assumes sole responsibility
+to secure any other intellectual property rights needed, if any. For example,
+if a third party patent license is required to allow Recipient to distribute
+the Program, it is Recipient's responsibility to acquire that license before
+distributing the Program.</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>d)
+Each Contributor represents that to its knowledge it has sufficient copyright
+rights in its Contribution, if any, to grant the copyright license set forth in
+this Agreement. </span></p>
+
+<p><b><span style='font-size:10.0pt'>3. REQUIREMENTS</span></b> </p>
+
+<p><span style='font-size:10.0pt'>A Contributor may choose to distribute the
+Program in object code form under its own license agreement, provided that:</span>
+</p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a)
+it complies with the terms and conditions of this Agreement; and</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b)
+its license agreement:</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>i)
+effectively disclaims on behalf of all Contributors all warranties and
+conditions, express and implied, including warranties or conditions of title
+and non-infringement, and implied warranties or conditions of merchantability
+and fitness for a particular purpose; </span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii)
+effectively excludes on behalf of all Contributors all liability for damages,
+including direct, indirect, special, incidental and consequential damages, such
+as lost profits; </span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>iii)
+states that any provisions which differ from this Agreement are offered by that
+Contributor alone and not by any other party; and</span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>iv)
+states that source code for the Program is available from such Contributor, and
+informs licensees how to obtain it in a reasonable manner on or through a
+medium customarily used for software exchange.<span style='color:blue'> </span></span></p>
+
+<p><span style='font-size:10.0pt'>When the Program is made available in source
+code form:</span> </p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a)
+it must be made available under this Agreement; and </span></p>
+
+<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) a
+copy of this Agreement must be included with each copy of the Program. </span></p>
+
+<p><span style='font-size:10.0pt'>Contributors may not remove or alter any
+copyright notices contained within the Program. </span></p>
+
+<p><span style='font-size:10.0pt'>Each Contributor must identify itself as the
+originator of its Contribution, if any, in a manner that reasonably allows
+subsequent Recipients to identify the originator of the Contribution. </span></p>
+
+<p><b><span style='font-size:10.0pt'>4. COMMERCIAL DISTRIBUTION</span></b> </p>
+
+<p><span style='font-size:10.0pt'>Commercial distributors of software may
+accept certain responsibilities with respect to end users, business partners
+and the like. While this license is intended to facilitate the commercial use
+of the Program, the Contributor who includes the Program in a commercial
+product offering should do so in a manner which does not create potential
+liability for other Contributors. Therefore, if a Contributor includes the
+Program in a commercial product offering, such Contributor ("Commercial
+Contributor") hereby agrees to defend and indemnify every other
+Contributor ("Indemnified Contributor") against any losses, damages and
+costs (collectively "Losses") arising from claims, lawsuits and other
+legal actions brought by a third party against the Indemnified Contributor to
+the extent caused by the acts or omissions of such Commercial Contributor in
+connection with its distribution of the Program in a commercial product
+offering. The obligations in this section do not apply to any claims or Losses
+relating to any actual or alleged intellectual property infringement. In order
+to qualify, an Indemnified Contributor must: a) promptly notify the Commercial
+Contributor in writing of such claim, and b) allow the Commercial Contributor
+to control, and cooperate with the Commercial Contributor in, the defense and
+any related settlement negotiations. The Indemnified Contributor may participate
+in any such claim at its own expense.</span> </p>
+
+<p><span style='font-size:10.0pt'>For example, a Contributor might include the
+Program in a commercial product offering, Product X. That Contributor is then a
+Commercial Contributor. If that Commercial Contributor then makes performance
+claims, or offers warranties related to Product X, those performance claims and
+warranties are such Commercial Contributor's responsibility alone. Under this
+section, the Commercial Contributor would have to defend claims against the
+other Contributors related to those performance claims and warranties, and if a
+court requires any other Contributor to pay any damages as a result, the
+Commercial Contributor must pay those damages.</span> </p>
+
+<p><b><span style='font-size:10.0pt'>5. NO WARRANTY</span></b> </p>
+
+<p><span style='font-size:10.0pt'>EXCEPT AS EXPRESSLY SET FORTH IN THIS
+AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT
+WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING,
+WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
+MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely
+responsible for determining the appropriateness of using and distributing the
+Program and assumes all risks associated with its exercise of rights under this
+Agreement , including but not limited to the risks and costs of program errors,
+compliance with applicable laws, damage to or loss of data, programs or
+equipment, and unavailability or interruption of operations. </span></p>
+
+<p><b><span style='font-size:10.0pt'>6. DISCLAIMER OF LIABILITY</span></b> </p>
+
+<p><span style='font-size:10.0pt'>EXCEPT AS EXPRESSLY SET FORTH IN THIS
+AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING WITHOUT LIMITATION LOST PROFITS), 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 OR DISTRIBUTION OF
+THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF
+THE POSSIBILITY OF SUCH DAMAGES.</span> </p>
+
+<p><b><span style='font-size:10.0pt'>7. GENERAL</span></b> </p>
+
+<p><span style='font-size:10.0pt'>If any provision of this Agreement is invalid
+or unenforceable under applicable law, it shall not affect the validity or
+enforceability of the remainder of the terms of this Agreement, and without
+further action by the parties hereto, such provision shall be reformed to the
+minimum extent necessary to make such provision valid and enforceable.</span> </p>
+
+<p><span style='font-size:10.0pt'>If Recipient institutes patent litigation
+against any entity (including a cross-claim or counterclaim in a lawsuit)
+alleging that the Program itself (excluding combinations of the Program with
+other software or hardware) infringes such Recipient's patent(s), then such
+Recipient's rights granted under Section 2(b) shall terminate as of the date
+such litigation is filed. </span></p>
+
+<p><span style='font-size:10.0pt'>All Recipient's rights under this Agreement
+shall terminate if it fails to comply with any of the material terms or
+conditions of this Agreement and does not cure such failure in a reasonable
+period of time after becoming aware of such noncompliance. If all Recipient's
+rights under this Agreement terminate, Recipient agrees to cease use and
+distribution of the Program as soon as reasonably practicable. However,
+Recipient's obligations under this Agreement and any licenses granted by
+Recipient relating to the Program shall continue and survive. </span></p>
+
+<p><span style='font-size:10.0pt'>Everyone is permitted to copy and distribute
+copies of this Agreement, but in order to avoid inconsistency the Agreement is
+copyrighted and may only be modified in the following manner. The Agreement
+Steward reserves the right to publish new versions (including revisions) of
+this Agreement from time to time. No one other than the Agreement Steward has
+the right to modify this Agreement. The Eclipse Foundation is the initial
+Agreement Steward. The Eclipse Foundation may assign the responsibility to
+serve as the Agreement Steward to a suitable separate entity. Each new version
+of the Agreement will be given a distinguishing version number. The Program
+(including Contributions) may always be distributed subject to the version of
+the Agreement under which it was received. In addition, after a new version of
+the Agreement is published, Contributor may elect to distribute the Program
+(including its Contributions) under the new version. Except as expressly stated
+in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to
+the intellectual property of any Contributor under this Agreement, whether
+expressly, by implication, estoppel or otherwise. All rights in the Program not
+expressly granted under this Agreement are reserved.</span> </p>
+
+<p><span style='font-size:10.0pt'>This Agreement is governed by the laws of the
+State of New York and the intellectual property laws of the United States of
+America. No party to this Agreement will bring a legal action under this
+Agreement more than one year after the cause of action arose. Each party waives
+its rights to a jury trial in any resulting litigation.</span> </p>
+
+<p class=MsoNormal><![if !supportEmptyParas]> <![endif]><o:p></o:p></p>
+
+</div>
+
+</body>
+
+</html>
\ No newline at end of file
|
661fd64481a0db75c501b782a60e89f7e348a9e6
|
orientdb
|
Fixed issue -255 about hooks: wasn't called- during TX - added new test cases - check of recursive call for the same- record in hook.--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseComplex.java b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseComplex.java
index 27fc70adca5..93733836765 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseComplex.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseComplex.java
@@ -21,6 +21,7 @@
import com.orientechnologies.orient.core.command.OCommandRequest;
import com.orientechnologies.orient.core.db.object.ODatabaseObject;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
+import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.dictionary.ODictionary;
import com.orientechnologies.orient.core.hook.ORecordHook;
import com.orientechnologies.orient.core.hook.ORecordHook.TYPE;
@@ -276,5 +277,5 @@ public interface ODatabaseComplex<T extends Object> extends ODatabase, OUserObje
* POJO for {@link ODatabaseObject} implementations.
* @return True if the input record is changed, otherwise false
*/
- public boolean callbackHooks(TYPE iType, Object iObject);
+ public boolean callbackHooks(TYPE iType, OIdentifiable iObject);
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java
index 7dd62b2edb0..eba5cfcf05d 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java
@@ -33,6 +33,7 @@
import com.orientechnologies.orient.core.db.object.OLazyObjectSet;
import com.orientechnologies.orient.core.db.object.OObjectNotDetachedException;
import com.orientechnologies.orient.core.db.object.OObjectNotManagedException;
+import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.exception.OConfigurationException;
import com.orientechnologies.orient.core.hook.ORecordHook;
import com.orientechnologies.orient.core.hook.ORecordHook.TYPE;
@@ -243,7 +244,7 @@ public <DBTYPE extends ODatabaseComplex<?>> DBTYPE registerHook(final ORecordHoo
return (DBTYPE) this;
}
- public boolean callbackHooks(final TYPE iType, final Object iObject) {
+ public boolean callbackHooks(final TYPE iType, final OIdentifiable iObject) {
return underlying.callbackHooks(iType, iObject);
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseRecordWrapperAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseRecordWrapperAbstract.java
index b80187412be..00d10e2e440 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseRecordWrapperAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseRecordWrapperAbstract.java
@@ -20,6 +20,7 @@
import com.orientechnologies.orient.core.command.OCommandRequest;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
+import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.dictionary.ODictionary;
import com.orientechnologies.orient.core.hook.ORecordHook;
import com.orientechnologies.orient.core.hook.ORecordHook.TYPE;
@@ -189,7 +190,7 @@ public <DBTYPE extends ODatabaseComplex<?>> DBTYPE registerHook(final ORecordHoo
return (DBTYPE) this;
}
- public boolean callbackHooks(final TYPE iType, final Object iObject) {
+ public boolean callbackHooks(final TYPE iType, final OIdentifiable iObject) {
return underlying.callbackHooks(iType, iObject);
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseRecordAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseRecordAbstract.java
index 952727e790d..4599bb54ec7 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseRecordAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseRecordAbstract.java
@@ -33,6 +33,7 @@
import com.orientechnologies.orient.core.exception.OConfigurationException;
import com.orientechnologies.orient.core.exception.ODatabaseException;
import com.orientechnologies.orient.core.exception.OSecurityAccessException;
+import com.orientechnologies.orient.core.hook.OHookThreadLocal;
import com.orientechnologies.orient.core.hook.ORecordHook;
import com.orientechnologies.orient.core.hook.ORecordHook.TYPE;
import com.orientechnologies.orient.core.id.ORID;
@@ -108,7 +109,7 @@ public <DB extends ODatabase> DB open(final String iUserName, final String iUser
registerHook(new OPropertyIndexManager());
if (getStorage() instanceof OStorageEmbedded) {
-
+
if (!user.checkPassword(iUserPassword)) {
// WAIT A BIT TO AVOID BRUTE FORCE
Thread.sleep(200);
@@ -139,10 +140,10 @@ public <DB extends ODatabase> DB create() {
dictionary = (ODictionaryInternal<ORecordInternal<?>>) getStorage().createDictionary(this);
dictionary.create();
- //if (getStorage() instanceof OStorageEmbedded) {
- registerHook(new OUserTrigger());
- registerHook(new OPropertyIndexManager());
- //}
+ // if (getStorage() instanceof OStorageEmbedded) {
+ registerHook(new OUserTrigger());
+ registerHook(new OPropertyIndexManager());
+ // }
} catch (Exception e) {
throw new ODatabaseException("Can't create database", e);
@@ -606,13 +607,20 @@ public Set<ORecordHook> getHooks() {
* Record received in the callback
* @return True if the input record is changed, otherwise false
*/
- public boolean callbackHooks(final TYPE iType, final Object iRecord) {
- boolean recordChanged = false;
- for (ORecordHook hook : hooks)
- if (hook.onTrigger(iType, (ORecord<?>) iRecord))
- recordChanged = true;
+ public boolean callbackHooks(final TYPE iType, final OIdentifiable iRecord) {
+ if (!OHookThreadLocal.INSTANCE.push(iRecord))
+ return false;
- return recordChanged;
+ try {
+ boolean recordChanged = false;
+ for (ORecordHook hook : hooks)
+ if (hook.onTrigger(iType, (ORecord<?>) iRecord))
+ recordChanged = true;
+ return recordChanged;
+
+ } finally {
+ OHookThreadLocal.INSTANCE.pop(iRecord);
+ }
}
protected ORecordSerializer resolveFormat(final Object iObject) {
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazySet.java b/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazySet.java
index 1baf31ea7b6..09bcdd2a38a 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazySet.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazySet.java
@@ -139,4 +139,9 @@ public void clear() {
public byte getRecordType() {
return delegate.getRecordType();
}
+
+ @Override
+ public String toString() {
+ return delegate.toString();
+ }
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/hook/OHookThreadLocal.java b/core/src/main/java/com/orientechnologies/orient/core/hook/OHookThreadLocal.java
new file mode 100644
index 00000000000..36363a0ca26
--- /dev/null
+++ b/core/src/main/java/com/orientechnologies/orient/core/hook/OHookThreadLocal.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright 1999-2011 Luca Garulli (l.garulli--at--orientechnologies.com)
+ *
+ * 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.orientechnologies.orient.core.hook;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import com.orientechnologies.orient.core.db.record.OIdentifiable;
+
+/**
+ * Avoid recursion when hooks call themselves on the same record instances.
+ *
+ * @author Luca Garulli (l.garulli--at--orientechnologies.com)
+ *
+ */
+public class OHookThreadLocal extends ThreadLocal<Set<OIdentifiable>> {
+ public static OHookThreadLocal INSTANCE = new OHookThreadLocal();
+
+ @Override
+ protected Set<OIdentifiable> initialValue() {
+ return new HashSet<OIdentifiable>();
+ }
+
+ public boolean push(final OIdentifiable iRecord) {
+ Set<OIdentifiable> set = get();
+ if (set.contains(iRecord))
+ return false;
+
+ set.add(iRecord);
+ return true;
+ }
+
+ public boolean pop(final OIdentifiable iRecord) {
+ return get().remove(iRecord);
+ }
+}
\ No newline at end of file
diff --git a/core/src/main/java/com/orientechnologies/orient/core/record/ORecordSchemaAwareAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/record/ORecordSchemaAwareAbstract.java
index 5842d76740d..7347ef7ed86 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/record/ORecordSchemaAwareAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/record/ORecordSchemaAwareAbstract.java
@@ -86,6 +86,7 @@ public OClass getSchemaClass() {
}
public String getClassName() {
+ checkForLoading();
checkForFields();
return _clazz != null ? _clazz.getName() : null;
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java b/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java
index 1ee7ba8580e..80def6c7925 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java
@@ -974,7 +974,7 @@ public ORecord<?> placeholder() {
cloned._source = _source;
cloned._database = _database;
cloned._recordId = _recordId.copy();
- cloned._status = _status;
+ cloned._status = STATUS.NOT_LOADED;
return cloned;
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/object/OObjectSerializerHelper.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/object/OObjectSerializerHelper.java
index 02b2a040e5b..eacb57c309c 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/object/OObjectSerializerHelper.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/object/OObjectSerializerHelper.java
@@ -137,7 +137,7 @@ else if (o instanceof Field)
public static Class<?> getFieldType(ODocument iDocument, final OEntityManager iEntityManager) {
if (iDocument.getInternalStatus() == STATUS.NOT_LOADED)
iDocument = (ODocument) iDocument.load();
-
+
if (iDocument.getClassName() == null) {
return null;
} else {
@@ -369,9 +369,9 @@ public static String setObjectID(final ORID iIdentity, final Object iPojo) {
if (ORID.class.isAssignableFrom(fieldType))
setFieldValue(iPojo, idFieldName, iIdentity);
else if (Number.class.isAssignableFrom(fieldType))
- setFieldValue(iPojo, idFieldName, iIdentity.getClusterPosition());
+ setFieldValue(iPojo, idFieldName, iIdentity != null ? iIdentity.getClusterPosition() : null);
else if (fieldType.equals(String.class))
- setFieldValue(iPojo, idFieldName, iIdentity.toString());
+ setFieldValue(iPojo, idFieldName, iIdentity != null ? iIdentity.toString() : null);
else if (fieldType.equals(Object.class))
setFieldValue(iPojo, idFieldName, iIdentity);
else
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java
index e8e100b97cc..9fd254e72b2 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java
@@ -444,9 +444,7 @@ private List<ORecord<?>> searchIndexedProperty(final List<ORecord<?>> iResultSet
iResultSet.add(database.load((ORID) o));
else
iResultSet.add((ORecord<?>) o);
-
}
-
}
}
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/query/OSQLSynchQuery.java b/core/src/main/java/com/orientechnologies/orient/core/sql/query/OSQLSynchQuery.java
index 93ad3792461..25d94319ad6 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/query/OSQLSynchQuery.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/query/OSQLSynchQuery.java
@@ -19,6 +19,7 @@
import java.util.List;
import com.orientechnologies.orient.core.command.OCommandResultListener;
+import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.hook.ORecordHook.TYPE;
/**
@@ -53,9 +54,9 @@ public void reset() {
}
public boolean result(final Object iRecord) {
- database.callbackHooks(TYPE.BEFORE_READ, iRecord);
+ database.callbackHooks(TYPE.BEFORE_READ, (OIdentifiable) iRecord);
result.add((T) iRecord);
- database.callbackHooks(TYPE.AFTER_READ, iRecord);
+ database.callbackHooks(TYPE.AFTER_READ, (OIdentifiable) iRecord);
return true;
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java
index 045f3d519fd..110d5d636a0 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java
@@ -24,6 +24,7 @@
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.config.OStorageTxConfiguration;
import com.orientechnologies.orient.core.exception.OTransactionException;
+import com.orientechnologies.orient.core.hook.ORecordHook;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.storage.OCluster;
import com.orientechnologies.orient.core.storage.OPhysicalPosition;
@@ -154,7 +155,7 @@ protected void commitAllPendingRecords(final int iRequesterId, final OTransactio
if (tmpEntries.size() > 0) {
for (OTransactionEntry txEntry : tmpEntries)
// COMMIT ALL THE SINGLE ENTRIES ONE BY ONE
- commitEntry(iRequesterId, iTx.getId(), txEntry);
+ commitEntry(iRequesterId, iTx, txEntry);
allEntries.addAll(tmpEntries);
tmpEntries.clear();
@@ -174,7 +175,7 @@ protected void rollback() {
// TODO
}
- private void commitEntry(final int iRequesterId, final int iTxId, final OTransactionEntry txEntry) throws IOException {
+ private void commitEntry(final int iRequesterId, final OTransaction iTx, final OTransactionEntry txEntry) throws IOException {
if (txEntry.status != OTransactionEntry.DELETED && !txEntry.getRecord().isDirty())
return;
@@ -197,26 +198,44 @@ private void commitEntry(final int iRequesterId, final int iTxId, final OTransac
case OTransactionEntry.CREATED:
// CHECK 2 TIMES TO ASSURE THAT IT'S A CREATE OR AN UPDATE BASED ON RECURSIVE TO-STREAM METHOD
- final byte[] stream = txEntry.getRecord().toStream();
+ byte[] stream = txEntry.getRecord().toStream();
if (rid.isNew()) {
- rid.clusterPosition = createRecord(iRequesterId, iTxId, cluster, stream, txEntry.getRecord().getRecordType());
+ if (iTx.getDatabase().callbackHooks(ORecordHook.TYPE.BEFORE_CREATE, txEntry.getRecord()))
+ // RECORD CHANGED: RE-STREAM IT
+ stream = txEntry.getRecord().toStream();
+
+ rid.clusterPosition = createRecord(iRequesterId, iTx.getId(), cluster, stream, txEntry.getRecord().getRecordType());
rid.clusterId = cluster.getId();
+
+ iTx.getDatabase().callbackHooks(ORecordHook.TYPE.AFTER_CREATE, txEntry.getRecord());
} else {
txEntry.getRecord().setVersion(
- updateRecord(iRequesterId, iTxId, cluster, rid.clusterPosition, stream, txEntry.getRecord().getVersion(), txEntry
+ updateRecord(iRequesterId, iTx.getId(), cluster, rid.clusterPosition, stream, txEntry.getRecord().getVersion(), txEntry
.getRecord().getRecordType()));
}
break;
case OTransactionEntry.UPDATED:
+ if (iTx.getDatabase().callbackHooks(ORecordHook.TYPE.BEFORE_UPDATE, txEntry.getRecord()))
+ // RECORD CHANGED: RE-STREAM IT
+ stream = txEntry.getRecord().toStream();
+
txEntry.getRecord().setVersion(
- updateRecord(iRequesterId, iTxId, cluster, rid.clusterPosition, txEntry.getRecord().toStream(), txEntry.getRecord()
+ updateRecord(iRequesterId, iTx.getId(), cluster, rid.clusterPosition, txEntry.getRecord().toStream(), txEntry.getRecord()
.getVersion(), txEntry.getRecord().getRecordType()));
+
+ iTx.getDatabase().callbackHooks(ORecordHook.TYPE.AFTER_UPDATE, txEntry.getRecord());
break;
case OTransactionEntry.DELETED:
- deleteRecord(iRequesterId, iTxId, cluster, rid.clusterPosition, txEntry.getRecord().getVersion());
+ if (iTx.getDatabase().callbackHooks(ORecordHook.TYPE.BEFORE_DELETE, txEntry.getRecord()))
+ // RECORD CHANGED: RE-STREAM IT
+ stream = txEntry.getRecord().toStream();
+
+ deleteRecord(iRequesterId, iTx.getId(), cluster, rid.clusterPosition, txEntry.getRecord().getVersion());
+
+ iTx.getDatabase().callbackHooks(ORecordHook.TYPE.AFTER_DELETE, txEntry.getRecord());
break;
}
diff --git a/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerRecordHook.java b/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerRecordHook.java
index 56390c502be..c413f7eb923 100644
--- a/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerRecordHook.java
+++ b/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerRecordHook.java
@@ -26,6 +26,7 @@
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.tx.OTransactionEntry;
+import com.orientechnologies.orient.server.tx.OTransactionRecordProxy;
/**
* Record hook implementation. Catches all the relevant events and propagates to the cluster's slave nodes.
@@ -49,6 +50,9 @@ public boolean onTrigger(final TYPE iType, final ORecord<?> iRecord) {
// if (!manager.isDistributedConfiguration())
// return;
+ if (iRecord instanceof OTransactionRecordProxy)
+ return false;
+
try {
switch (iType) {
case BEFORE_CREATE:
@@ -66,18 +70,15 @@ public boolean onTrigger(final TYPE iType, final ORecord<?> iRecord) {
break;
case AFTER_CREATE:
- manager.distributeRequest(new OTransactionEntry((ORecordInternal<?>) iRecord,
- OTransactionEntry.CREATED, null));
+ manager.distributeRequest(new OTransactionEntry((ORecordInternal<?>) iRecord, OTransactionEntry.CREATED, null));
break;
case AFTER_UPDATE:
- manager.distributeRequest(new OTransactionEntry((ORecordInternal<?>) iRecord,
- OTransactionEntry.UPDATED, null));
+ manager.distributeRequest(new OTransactionEntry((ORecordInternal<?>) iRecord, OTransactionEntry.UPDATED, null));
break;
case AFTER_DELETE:
- manager.distributeRequest(new OTransactionEntry((ORecordInternal<?>) iRecord,
- OTransactionEntry.DELETED, null));
+ manager.distributeRequest(new OTransactionEntry((ORecordInternal<?>) iRecord, OTransactionEntry.DELETED, null));
break;
}
} catch (IOException e) {
diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/HookTxTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/HookTxTest.java
new file mode 100644
index 00000000000..36a21d6f500
--- /dev/null
+++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/HookTxTest.java
@@ -0,0 +1,165 @@
+/*
+ * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com)
+ *
+ * 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.orientechnologies.orient.test.database.auto;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.testng.Assert;
+import org.testng.annotations.Parameters;
+import org.testng.annotations.Test;
+
+import com.orientechnologies.orient.core.db.object.ODatabaseObjectTx;
+import com.orientechnologies.orient.core.hook.ORecordHookAbstract;
+import com.orientechnologies.orient.core.record.ORecord;
+import com.orientechnologies.orient.core.record.impl.ODocument;
+import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
+import com.orientechnologies.orient.test.domain.whiz.Profile;
+
+@Test(groups = "hook")
+public class HookTxTest extends ORecordHookAbstract {
+ private ODatabaseObjectTx database;
+ private int callbackCount = 0;
+ private Profile p;
+
+ @Parameters(value = "url")
+ public HookTxTest(String iURL) {
+ database = new ODatabaseObjectTx(iURL);
+ }
+
+ @Test
+ public void testRegisterHook() throws IOException {
+ database.open("writer", "writer");
+ database.registerHook(this);
+ database.getEntityManager().registerEntityClasses("com.orientechnologies.orient.test.domain");
+ }
+
+ @Test(dependsOnMethods = "testRegisterHook")
+ public void testHookCalls() throws IOException {
+
+ p = new Profile("HookTxTest");
+
+ // TEST HOOKS ON CREATE
+ Assert.assertEquals(callbackCount, 0);
+ database.begin();
+ database.save(p);
+ database.commit();
+
+ Assert.assertEquals(callbackCount, 11);
+
+ // TEST HOOKS ON READ
+ database.begin();
+ List<Profile> result = database.query(new OSQLSynchQuery<Profile>("select * from Profile where nick = 'HookTxTest'"));
+ Assert.assertFalse(result.size() == 0);
+
+ for (int i = 0; i < result.size(); ++i) {
+ Assert.assertEquals(callbackCount, 46);
+
+ p = result.get(i);
+ }
+ Assert.assertEquals(callbackCount, 46);
+ database.commit();
+
+ database.begin();
+ // TEST HOOKS ON UPDATE
+ p.setValue(p.getValue() + 1000);
+ database.save(p);
+
+ database.commit();
+ Assert.assertEquals(callbackCount, 136);
+
+ // TEST HOOKS ON DELETE
+ database.begin();
+ database.delete(p);
+ database.commit();
+ Assert.assertEquals(callbackCount, 266);
+
+ database.unregisterHook(this);
+ database.close();
+ }
+
+ @Override
+ @Test(enabled = false)
+ public boolean onRecordBeforeCreate(ORecord<?> iRecord) {
+ if (iRecord instanceof ODocument && ((ODocument) iRecord).getClassName() != null
+ && ((ODocument) iRecord).getClassName().equals("Profile"))
+ callbackCount += 1;
+ return false;
+ }
+
+ @Override
+ @Test(enabled = false)
+ public boolean onRecordAfterCreate(ORecord<?> iRecord) {
+ if (iRecord instanceof ODocument && ((ODocument) iRecord).getClassName() != null
+ && ((ODocument) iRecord).getClassName().equals("Profile"))
+ callbackCount += 10;
+ return false;
+ }
+
+ @Override
+ @Test(enabled = false)
+ public boolean onRecordBeforeRead(ORecord<?> iRecord) {
+ if (iRecord instanceof ODocument && ((ODocument) iRecord).getClassName() != null
+ && ((ODocument) iRecord).getClassName().equals("Profile"))
+ callbackCount += 20;
+ return false;
+ }
+
+ @Override
+ @Test(enabled = false)
+ public boolean onRecordAfterRead(ORecord<?> iRecord) {
+ if (iRecord instanceof ODocument && ((ODocument) iRecord).getClassName() != null
+ && ((ODocument) iRecord).getClassName().equals("Profile"))
+ callbackCount += 15;
+ return false;
+ }
+
+ @Override
+ @Test(enabled = false)
+ public boolean onRecordBeforeUpdate(ORecord<?> iRecord) {
+ if (iRecord instanceof ODocument && ((ODocument) iRecord).getClassName() != null
+ && ((ODocument) iRecord).getClassName().equals("Profile"))
+ callbackCount += 40;
+ return false;
+ }
+
+ @Override
+ @Test(enabled = false)
+ public boolean onRecordAfterUpdate(ORecord<?> iRecord) {
+ if (iRecord instanceof ODocument && ((ODocument) iRecord).getClassName() != null
+ && ((ODocument) iRecord).getClassName().equals("Profile"))
+ callbackCount += 50;
+ return false;
+ }
+
+ @Override
+ @Test(enabled = false)
+ public boolean onRecordBeforeDelete(ORecord<?> iRecord) {
+ if (iRecord instanceof ODocument && ((ODocument) iRecord).getClassName() != null
+ && ((ODocument) iRecord).getClassName().equals("Profile"))
+ callbackCount += 60;
+ return false;
+ }
+
+ @Override
+ @Test(enabled = false)
+ public boolean onRecordAfterDelete(ORecord<?> iRecord) {
+ if (iRecord instanceof ODocument && ((ODocument) iRecord).getClassName() != null
+ && ((ODocument) iRecord).getClassName().equals("Profile"))
+ callbackCount += 70;
+ return false;
+ }
+}
diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/local-test-db-from-scratch.xml b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/local-test-db-from-scratch.xml
index e1802f897fd..0d45d890070 100644
--- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/local-test-db-from-scratch.xml
+++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/local-test-db-from-scratch.xml
@@ -29,6 +29,7 @@
<test name="Hook">
<classes>
<class name="com.orientechnologies.orient.test.database.auto.HookTest" />
+ <class name="com.orientechnologies.orient.test.database.auto.HookTxTest" />
</classes>
</test>
<test name="Population">
diff --git a/tests/src/test/java/com/orientechnologies/orient/test/domain/whiz/Profile.java b/tests/src/test/java/com/orientechnologies/orient/test/domain/whiz/Profile.java
index f507625e10a..3494e71eb70 100644
--- a/tests/src/test/java/com/orientechnologies/orient/test/domain/whiz/Profile.java
+++ b/tests/src/test/java/com/orientechnologies/orient/test/domain/whiz/Profile.java
@@ -19,11 +19,14 @@
import java.util.Set;
import com.orientechnologies.orient.core.annotation.OId;
+import com.orientechnologies.orient.core.annotation.OVersion;
import com.orientechnologies.orient.test.domain.business.Address;
public class Profile {
@OId
private String id;
+ @OVersion
+ private Integer version;
private String nick;
private Set<Profile> followings = new HashSet<Profile>();
private Set<Profile> followers = new HashSet<Profile>();
|
ad2358bba102bd4e9876028cf30341ec48aabe4f
|
ReactiveX-RxJava
|
GroupBy GroupedObservables should not re-subscribe- to parent sequence--https://github.com/Netflix/RxJava/issues/282--Refactored to maintain a single subscription that propagates events to the correct child GroupedObservables.-
|
c
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-core/src/main/java/rx/operators/OperationGroupBy.java b/rxjava-core/src/main/java/rx/operators/OperationGroupBy.java
index 1c2e6e969c..edd4ef7ae4 100644
--- a/rxjava-core/src/main/java/rx/operators/OperationGroupBy.java
+++ b/rxjava-core/src/main/java/rx/operators/OperationGroupBy.java
@@ -17,12 +17,15 @@
import static org.junit.Assert.*;
-import java.util.ArrayList;
import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
+import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
import org.junit.Test;
@@ -30,6 +33,8 @@
import rx.Observer;
import rx.Subscription;
import rx.observables.GroupedObservable;
+import rx.subscriptions.Subscriptions;
+import rx.util.functions.Action1;
import rx.util.functions.Func1;
import rx.util.functions.Functions;
@@ -55,7 +60,9 @@ public static <K, T> Func1<Observer<GroupedObservable<K, T>>, Subscription> grou
}
private static class GroupBy<K, V> implements Func1<Observer<GroupedObservable<K, V>>, Subscription> {
+
private final Observable<KeyValue<K, V>> source;
+ private final ConcurrentHashMap<K, GroupedSubject<K, V>> groupedObservables = new ConcurrentHashMap<K, GroupedSubject<K, V>>();
private GroupBy(Observable<KeyValue<K, V>> source) {
this.source = source;
@@ -63,61 +70,127 @@ private GroupBy(Observable<KeyValue<K, V>> source) {
@Override
public Subscription call(final Observer<GroupedObservable<K, V>> observer) {
- return source.subscribe(new GroupByObserver(observer));
+ return source.subscribe(new Observer<KeyValue<K, V>>() {
+
+ @Override
+ public void onCompleted() {
+ // we need to propagate to all children I imagine ... we can't just leave all of those Observable/Observers hanging
+ for (GroupedSubject<K, V> o : groupedObservables.values()) {
+ o.onCompleted();
+ }
+ // now the parent
+ observer.onCompleted();
+ }
+
+ @Override
+ public void onError(Exception e) {
+ // we need to propagate to all children I imagine ... we can't just leave all of those Observable/Observers hanging
+ for (GroupedSubject<K, V> o : groupedObservables.values()) {
+ o.onError(e);
+ }
+ // now the parent
+ observer.onError(e);
+ }
+
+ @Override
+ public void onNext(KeyValue<K, V> value) {
+ GroupedSubject<K, V> gs = groupedObservables.get(value.key);
+ if (gs == null) {
+ /*
+ * Technically the source should be single-threaded so we shouldn't need to do this but I am
+ * programming defensively as most operators are so this can work with a concurrent sequence
+ * if it ends up receiving one.
+ */
+ GroupedSubject<K, V> newGs = GroupedSubject.<K, V> create(value.key);
+ GroupedSubject<K, V> existing = groupedObservables.putIfAbsent(value.key, newGs);
+ if (existing == null) {
+ // we won so use the one we created
+ gs = newGs;
+ // since we won the creation we emit this new GroupedObservable
+ observer.onNext(gs);
+ } else {
+ // another thread beat us so use the existing one
+ gs = existing;
+ }
+ }
+ gs.onNext(value.value);
+ }
+ });
}
+ }
- private class GroupByObserver implements Observer<KeyValue<K, V>> {
- private final Observer<GroupedObservable<K, V>> underlying;
+ private static class GroupedSubject<K, T> extends GroupedObservable<K, T> implements Observer<T> {
- private final ConcurrentHashMap<K, Boolean> keys = new ConcurrentHashMap<K, Boolean>();
+ static <K, T> GroupedSubject<K, T> create(K key) {
+ @SuppressWarnings("unchecked")
+ final AtomicReference<Observer<T>> subscribedObserver = new AtomicReference<Observer<T>>(EMPTY_OBSERVER);
- private GroupByObserver(Observer<GroupedObservable<K, V>> underlying) {
- this.underlying = underlying;
- }
+ return new GroupedSubject<K, T>(key, new Func1<Observer<T>, Subscription>() {
- @Override
- public void onCompleted() {
- underlying.onCompleted();
- }
+ @Override
+ public Subscription call(Observer<T> observer) {
+ // register Observer
+ subscribedObserver.set(observer);
- @Override
- public void onError(Exception e) {
- underlying.onError(e);
- }
+ return new Subscription() {
- @Override
- public void onNext(final KeyValue<K, V> args) {
- K key = args.key;
- boolean newGroup = keys.putIfAbsent(key, true) == null;
- if (newGroup) {
- underlying.onNext(buildObservableFor(source, key));
+ @SuppressWarnings("unchecked")
+ @Override
+ public void unsubscribe() {
+ // we remove the Observer so we stop emitting further events (they will be ignored if parent continues to send)
+ subscribedObserver.set(EMPTY_OBSERVER);
+ // I don't believe we need to worry about the parent here as it's a separate sequence that would
+ // be unsubscribed to directly if that needs to happen.
+ }
+ };
}
- }
+ }, subscribedObserver);
}
- }
- private static <K, R> GroupedObservable<K, R> buildObservableFor(Observable<KeyValue<K, R>> source, final K key) {
- final Observable<R> observable = source.filter(new Func1<KeyValue<K, R>, Boolean>() {
- @Override
- public Boolean call(KeyValue<K, R> pair) {
- return key.equals(pair.key);
- }
- }).map(new Func1<KeyValue<K, R>, R>() {
- @Override
- public R call(KeyValue<K, R> pair) {
- return pair.value;
- }
- });
- return new GroupedObservable<K, R>(key, new Func1<Observer<R>, Subscription>() {
+ private final AtomicReference<Observer<T>> subscribedObserver;
- @Override
- public Subscription call(Observer<R> observer) {
- return observable.subscribe(observer);
- }
+ public GroupedSubject(K key, Func1<Observer<T>, Subscription> onSubscribe, AtomicReference<Observer<T>> subscribedObserver) {
+ super(key, onSubscribe);
+ this.subscribedObserver = subscribedObserver;
+ }
+
+ @Override
+ public void onCompleted() {
+ subscribedObserver.get().onCompleted();
+ }
+
+ @Override
+ public void onError(Exception e) {
+ subscribedObserver.get().onError(e);
+ }
+
+ @Override
+ public void onNext(T v) {
+ subscribedObserver.get().onNext(v);
+ }
- });
}
+ @SuppressWarnings("rawtypes")
+ private static Observer EMPTY_OBSERVER = new Observer() {
+
+ @Override
+ public void onCompleted() {
+ // do nothing
+ }
+
+ @Override
+ public void onError(Exception e) {
+ // do nothing
+ }
+
+ @Override
+ public void onNext(Object args) {
+ // do nothing
+ }
+
+ };
+
private static class KeyValue<K, V> {
private final K key;
private final V value;
@@ -141,13 +214,12 @@ public void testGroupBy() {
Observable<String> source = Observable.from("one", "two", "three", "four", "five", "six");
Observable<GroupedObservable<Integer, String>> grouped = Observable.create(groupBy(source, length));
- Map<Integer, List<String>> map = toMap(grouped);
+ Map<Integer, Collection<String>> map = toMap(grouped);
assertEquals(3, map.size());
- assertEquals(Arrays.asList("one", "two", "six"), map.get(3));
- assertEquals(Arrays.asList("four", "five"), map.get(4));
- assertEquals(Arrays.asList("three"), map.get(5));
-
+ assertArrayEquals(Arrays.asList("one", "two", "six").toArray(), map.get(3).toArray());
+ assertArrayEquals(Arrays.asList("four", "five").toArray(), map.get(4).toArray());
+ assertArrayEquals(Arrays.asList("three").toArray(), map.get(5).toArray());
}
@Test
@@ -155,31 +227,133 @@ public void testEmpty() {
Observable<String> source = Observable.from();
Observable<GroupedObservable<Integer, String>> grouped = Observable.create(groupBy(source, length));
- Map<Integer, List<String>> map = toMap(grouped);
+ Map<Integer, Collection<String>> map = toMap(grouped);
assertTrue(map.isEmpty());
}
- private static <K, V> Map<K, List<V>> toMap(Observable<GroupedObservable<K, V>> observable) {
- Map<K, List<V>> result = new HashMap<K, List<V>>();
- for (GroupedObservable<K, V> g : observable.toBlockingObservable().toIterable()) {
- K key = g.getKey();
+ private static <K, V> Map<K, Collection<V>> toMap(Observable<GroupedObservable<K, V>> observable) {
- for (V value : g.toBlockingObservable().toIterable()) {
- List<V> values = result.get(key);
- if (values == null) {
- values = new ArrayList<V>();
- result.put(key, values);
- }
+ final ConcurrentHashMap<K, Collection<V>> result = new ConcurrentHashMap<K, Collection<V>>();
- values.add(value);
- }
+ observable.forEach(new Action1<GroupedObservable<K, V>>() {
- }
+ @Override
+ public void call(final GroupedObservable<K, V> o) {
+ result.put(o.getKey(), new ConcurrentLinkedQueue<V>());
+ o.subscribe(new Action1<V>() {
+
+ @Override
+ public void call(V v) {
+ result.get(o.getKey()).add(v);
+ }
+
+ });
+ }
+ });
return result;
}
+ /**
+ * Assert that only a single subscription to a stream occurs and that all events are received.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testGroupedEventStream() throws Exception {
+
+ final AtomicInteger eventCounter = new AtomicInteger();
+ final AtomicInteger subscribeCounter = new AtomicInteger();
+ final AtomicInteger groupCounter = new AtomicInteger();
+ final CountDownLatch latch = new CountDownLatch(1);
+ final int count = 100;
+ final int groupCount = 2;
+
+ Observable<Event> es = Observable.create(new Func1<Observer<Event>, Subscription>() {
+
+ @Override
+ public Subscription call(final Observer<Event> observer) {
+ System.out.println("*** Subscribing to EventStream ***");
+ subscribeCounter.incrementAndGet();
+ new Thread(new Runnable() {
+
+ @Override
+ public void run() {
+ for (int i = 0; i < count; i++) {
+ Event e = new Event();
+ e.source = i % groupCount;
+ e.message = "Event-" + i;
+ observer.onNext(e);
+ }
+ observer.onCompleted();
+ }
+
+ }).start();
+ return Subscriptions.empty();
+ }
+
+ });
+
+ es.groupBy(new Func1<Event, Integer>() {
+
+ @Override
+ public Integer call(Event e) {
+ return e.source;
+ }
+ }).mapMany(new Func1<GroupedObservable<Integer, Event>, Observable<String>>() {
+
+ @Override
+ public Observable<String> call(GroupedObservable<Integer, Event> eventGroupedObservable) {
+ System.out.println("GroupedObservable Key: " + eventGroupedObservable.getKey());
+ groupCounter.incrementAndGet();
+
+ return eventGroupedObservable.map(new Func1<Event, String>() {
+
+ @Override
+ public String call(Event event) {
+ return "Source: " + event.source + " Message: " + event.message;
+ }
+ });
+
+ };
+ }).subscribe(new Observer<String>() {
+
+ @Override
+ public void onCompleted() {
+ latch.countDown();
+ }
+
+ @Override
+ public void onError(Exception e) {
+ e.printStackTrace();
+ latch.countDown();
+ }
+
+ @Override
+ public void onNext(String outputMessage) {
+ System.out.println(outputMessage);
+ eventCounter.incrementAndGet();
+ }
+ });
+
+ latch.await(5000, TimeUnit.MILLISECONDS);
+ assertEquals(1, subscribeCounter.get());
+ assertEquals(groupCount, groupCounter.get());
+ assertEquals(count, eventCounter.get());
+
+ }
+
+ private static class Event {
+ int source;
+ String message;
+
+ @Override
+ public String toString() {
+ return "Event => source: " + source + " message: " + message;
+ }
+ }
+
}
}
|
57f4f664ba0bf785e9903535a4965d786cf13062
|
kotlin
|
refactored generation of static initializer--
|
p
|
https://github.com/JetBrains/kotlin
|
diff --git a/idea/src/org/jetbrains/jet/codegen/ClassBodyCodegen.java b/idea/src/org/jetbrains/jet/codegen/ClassBodyCodegen.java
index ed0735204e8d6..58a6fa5d7d4c4 100644
--- a/idea/src/org/jetbrains/jet/codegen/ClassBodyCodegen.java
+++ b/idea/src/org/jetbrains/jet/codegen/ClassBodyCodegen.java
@@ -4,8 +4,11 @@
import org.jetbrains.jet.lang.descriptors.PropertyDescriptor;
import org.jetbrains.jet.lang.psi.*;
import org.objectweb.asm.ClassVisitor;
+import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
+import org.objectweb.asm.commons.InstructionAdapter;
+import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -22,6 +25,8 @@ public abstract class ClassBodyCodegen {
protected final ClassVisitor v;
protected final ClassContext context;
+ protected final List<CodeChunk> staticInitializerChunks = new ArrayList<CodeChunk>();
+
public ClassBodyCodegen(JetClassOrObject aClass, ClassContext context, ClassVisitor v, GenerationState state) {
this.state = state;
descriptor = state.getBindingContext().getClassDescriptor(aClass);
@@ -38,6 +43,8 @@ public void generate() {
generateClassBody();
+ generateStaticInitializer();
+
v.visitEnd();
}
@@ -95,4 +102,23 @@ protected List<JetParameter> getPrimaryConstructorParameters() {
}
return Collections.emptyList();
}
+
+ private void generateStaticInitializer() {
+ if (staticInitializerChunks.size() > 0) {
+ final MethodVisitor mv = v.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC,
+ "<clinit>", "()V", null, null);
+ mv.visitCode();
+
+ InstructionAdapter v = new InstructionAdapter(mv);
+
+ for (CodeChunk chunk : staticInitializerChunks) {
+ chunk.generate(v);
+ }
+
+ mv.visitInsn(Opcodes.RETURN);
+ mv.visitMaxs(0, 0);
+
+ mv.visitEnd();
+ }
+ }
}
diff --git a/idea/src/org/jetbrains/jet/codegen/CodeChunk.java b/idea/src/org/jetbrains/jet/codegen/CodeChunk.java
new file mode 100644
index 0000000000000..eb0aa42088415
--- /dev/null
+++ b/idea/src/org/jetbrains/jet/codegen/CodeChunk.java
@@ -0,0 +1,10 @@
+package org.jetbrains.jet.codegen;
+
+import org.objectweb.asm.commons.InstructionAdapter;
+
+/**
+ * @author yole
+ */
+public interface CodeChunk {
+ void generate(InstructionAdapter v);
+}
diff --git a/idea/src/org/jetbrains/jet/codegen/ImplementationBodyCodegen.java b/idea/src/org/jetbrains/jet/codegen/ImplementationBodyCodegen.java
index f013f20e2d91a..1287090056967 100644
--- a/idea/src/org/jetbrains/jet/codegen/ImplementationBodyCodegen.java
+++ b/idea/src/org/jetbrains/jet/codegen/ImplementationBodyCodegen.java
@@ -74,29 +74,74 @@ protected String getSuperClass() {
@Override
protected void generateSyntheticParts() {
- int typeinfoStatic = descriptor.getTypeConstructor().getParameters().size() > 0 ? 0 : Opcodes.ACC_STATIC;
- v.visitField(Opcodes.ACC_PRIVATE | typeinfoStatic, "$typeInfo", "Ljet/typeinfo/TypeInfo;", null, null);
+ generateFieldForTypeInfo();
+ generateFieldForObjectInstance();
+ generateFieldForClassObject();
+ try {
+ generatePrimaryConstructor();
+ }
+ catch(RuntimeException e) {
+ throw new RuntimeException("Error generating primary constructor of class " + myClass.getName() + " with kind " + kind, e);
+ }
+
+ generateGetTypeInfo();
+ }
+
+ private void generateFieldForTypeInfo() {
+ final boolean typeInfoIsStatic = descriptor.getTypeConstructor().getParameters().size() == 0;
+ v.visitField(Opcodes.ACC_PRIVATE | (typeInfoIsStatic ? Opcodes.ACC_STATIC : 0), "$typeInfo",
+ "Ljet/typeinfo/TypeInfo;", null, null);
+ if (typeInfoIsStatic) {
+ staticInitializerChunks.add(new CodeChunk() {
+ @Override
+ public void generate(InstructionAdapter v) {
+ JetTypeMapper typeMapper = state.getTypeMapper();
+ ClassCodegen.newTypeInfo(v, false, typeMapper.jvmType(descriptor, OwnerKind.INTERFACE));
+ v.putstatic(typeMapper.jvmName(descriptor, kind), "$typeInfo", "Ljet/typeinfo/TypeInfo;");
+ }
+ });
+ }
+ }
+
+ private void generateFieldForObjectInstance() {
if (isNonLiteralObject()) {
Type type = JetTypeMapper.jetImplementationType(descriptor);
v.visitField(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "$instance", type.getDescriptor(), null, null);
+
+ staticInitializerChunks.add(new CodeChunk() {
+ @Override
+ public void generate(InstructionAdapter v) {
+ String name = jvmName();
+ v.anew(Type.getObjectType(name));
+ v.dup();
+ v.invokespecial(name, "<init>", "()V");
+ v.putstatic(name, "$instance", JetTypeMapper.jetImplementationType(descriptor).getDescriptor());
+ }
+ });
+
}
+ }
+
+ private void generateFieldForClassObject() {
final JetClassObject classObject = getClassObject();
if (classObject != null) {
Type type = Type.getObjectType(state.getTypeMapper().jvmName(classObject));
v.visitField(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "$classobj", type.getDescriptor(), null, null);
- }
-
- generateStaticInitializer();
- try {
- generatePrimaryConstructor();
- }
- catch(RuntimeException e) {
- throw new RuntimeException("Error generating primary constructor of class " + myClass.getName() + " with kind " + kind, e);
+ staticInitializerChunks.add(new CodeChunk() {
+ @Override
+ public void generate(InstructionAdapter v) {
+ String name = state.getTypeMapper().jvmName(classObject);
+ final Type classObjectType = Type.getObjectType(name);
+ v.anew(classObjectType);
+ v.dup();
+ v.invokespecial(name, "<init>", "()V");
+ v.putstatic(state.getTypeMapper().jvmName(descriptor, OwnerKind.IMPLEMENTATION), "$classobj",
+ classObjectType.getDescriptor());
+ }
+ });
}
-
- generateGetTypeInfo();
}
protected void generatePrimaryConstructor() {
@@ -409,47 +454,6 @@ else if (declaration instanceof JetFunction) {
}
}
- private void generateStaticInitializer() {
- boolean needTypeInfo = descriptor.getTypeConstructor().getParameters().size() == 0;
- boolean needInstance = isNonLiteralObject();
- JetClassObject classObject = getClassObject();
- if (!needTypeInfo && !needInstance && classObject == null) {
- return;
- }
- final MethodVisitor mv = v.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC,
- "<clinit>", "()V", null, null);
- mv.visitCode();
-
- InstructionAdapter v = new InstructionAdapter(mv);
-
- if (needTypeInfo) {
- JetTypeMapper typeMapper = state.getTypeMapper();
- ClassCodegen.newTypeInfo(v, false, typeMapper.jvmType(descriptor, OwnerKind.INTERFACE));
- v.putstatic(typeMapper.jvmName(descriptor, kind), "$typeInfo", "Ljet/typeinfo/TypeInfo;");
- }
- if (needInstance) {
- String name = jvmName();
- v.anew(Type.getObjectType(name));
- v.dup();
- v.invokespecial(name, "<init>", "()V");
- v.putstatic(name, "$instance", JetTypeMapper.jetImplementationType(descriptor).getDescriptor());
- }
- if (classObject != null) {
- String name = state.getTypeMapper().jvmName(classObject);
- final Type classObjectType = Type.getObjectType(name);
- v.anew(classObjectType);
- v.dup();
- v.invokespecial(name, "<init>", "()V");
- v.putstatic(state.getTypeMapper().jvmName(descriptor, OwnerKind.IMPLEMENTATION), "$classobj",
- classObjectType.getDescriptor());
- }
-
- mv.visitInsn(Opcodes.RETURN);
- mv.visitMaxs(0, 0);
-
- mv.visitEnd();
- }
-
@Nullable
private JetClassObject getClassObject() {
return myClass instanceof JetClass ? ((JetClass) myClass).getClassObject() : null;
|
ced35df51c980152da0d89621d8e0b099dcae644
|
belaban$jgroups
|
first impl of reconnector functionality in TCPGOSSIP (https://jira.jboss.org/jira/browse/JGRP-1010)
|
p
|
https://github.com/belaban/jgroups
|
diff --git a/src/org/jgroups/protocols/TCPGOSSIP.java b/src/org/jgroups/protocols/TCPGOSSIP.java
index 3496aebcddf..772a5525ebf 100644
--- a/src/org/jgroups/protocols/TCPGOSSIP.java
+++ b/src/org/jgroups/protocols/TCPGOSSIP.java
@@ -13,6 +13,8 @@
import org.jgroups.util.Tuple;
import java.util.*;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
@@ -30,10 +32,10 @@
* FIND_INITIAL_MBRS_OK event up the stack.
*
* @author Bela Ban
- * @version $Id: TCPGOSSIP.java,v 1.40 2009/07/08 15:29:30 belaban Exp $
+ * @version $Id: TCPGOSSIP.java,v 1.41 2009/07/09 13:59:40 belaban Exp $
*/
@DeprecatedProperty(names={"gossip_refresh_rate"})
-public class TCPGOSSIP extends Discovery {
+public class TCPGOSSIP extends Discovery implements RouterStub.ConnectionListener {
private final static String name="TCPGOSSIP";
@@ -41,14 +43,20 @@ public class TCPGOSSIP extends Discovery {
@Property(description="Max time for socket creation. Default is 1000 msec")
int sock_conn_timeout=1000;
+
@Property(description="Max time in milliseconds to block on a read. 0 blocks forever")
int sock_read_timeout=3000;
+
+ @Property(description="Interval (ms) by which a disconnected stub attempts to reconnect to the GossipRouter")
+ long reconnect_interval=10000L;
/* --------------------------------------------- Fields ------------------------------------------------------ */
List<InetSocketAddress> initial_hosts=null; // (list of IpAddresses) hosts to be contacted for the initial membership
- final List<RouterStub> stubs = new ArrayList<RouterStub>();
+ final List<RouterStub> stubs=new ArrayList<RouterStub>();
+ Future<?> reconnect_future=null;
+ protected volatile boolean running=true;
public String getName() {
return name;
@@ -69,8 +77,14 @@ public void setInitialHosts(String hosts) throws UnknownHostException {
initial_hosts=Util.parseCommaDelimetedHosts2(hosts,1);
}
+ public void start() throws Exception {
+ super.start();
+ running=true;
+ }
+
public void stop() {
super.stop();
+ running=false;
for (RouterStub stub : stubs) {
try {
stub.disconnect(group_addr, local_addr);
@@ -78,7 +92,9 @@ public void stop() {
catch (Exception e) {
}
}
+ stopReconnector();
}
+
public void handleConnect() {
if(group_addr == null || local_addr == null) {
if(log.isErrorEnabled())
@@ -90,27 +106,16 @@ public void handleConnect() {
stubs.clear();
- // init stubs
- for (InetSocketAddress host : initial_hosts) {
- stubs.add(new RouterStub(host.getHostName(), host.getPort(),null));
+ for (InetSocketAddress host : initial_hosts) {
+ RouterStub stub=new RouterStub(host.getHostName(), host.getPort(), null);
+ stub.setConnectionListener(this);
+ stubs.add(stub);
}
-
- String logical_name=org.jgroups.util.UUID.get(local_addr);
- PhysicalAddress physical_addr=(PhysicalAddress)down_prot.down(new Event(Event.GET_PHYSICAL_ADDRESS, local_addr));
- List<PhysicalAddress> physical_addrs=physical_addr != null? new ArrayList<PhysicalAddress>() : null;
- if(physical_addr != null)
- physical_addrs.add(physical_addr);
-
- for (RouterStub stub : stubs) {
- try {
- stub.connect(group_addr, local_addr, logical_name, physical_addrs);
- }
- catch (Exception e) {
- }
- }
+ connect(group_addr, local_addr);
}
}
+
public void handleDisconnect() {
for (RouterStub stub : stubs) {
try {
@@ -121,24 +126,30 @@ public void handleDisconnect() {
}
}
- public void sendGetMembersRequest(String cluster_name, Promise promise) throws Exception{
- Message msg, copy;
- PingHeader hdr;
- List<Address> tmp_mbrs = new ArrayList<Address>();
- Address mbr_addr;
+ public void connectionStatusChange(RouterStub.ConnectionStatus state) {
+ if(log.isDebugEnabled())
+ log.debug("connection changed to " + state);
+ if(state == RouterStub.ConnectionStatus.CONNECTED)
+ stopReconnector();
+ else
+ startReconnector();
+ }
+ public void sendGetMembersRequest(String cluster_name, Promise promise) throws Exception{
if(group_addr == null) {
- if(log.isErrorEnabled()) log.error("[FIND_INITIAL_MBRS]: group_addr is null, cannot get mbrship");
+ if(log.isErrorEnabled()) log.error("[FIND_INITIAL_MBRS]: group_addr is null, cannot get membership");
return;
}
+
+ final List<Address> initial_mbrs=new ArrayList<Address>();
if(log.isTraceEnabled()) log.trace("fetching members from GossipRouter(s)");
- for (RouterStub stub : stubs) {
+ for(RouterStub stub : stubs) {
try {
List<PingData> rsps=stub.getMembers(group_addr);
for(PingData rsp: rsps) {
Address logical_addr=rsp.getAddress();
- tmp_mbrs.add(logical_addr);
+ initial_mbrs.add(logical_addr);
// 1. Set physical addresses
Collection<PhysicalAddress> physical_addrs=rsp.getPhysicalAddrs();
@@ -157,24 +168,65 @@ public void sendGetMembersRequest(String cluster_name, Promise promise) throws E
}
}
- if(tmp_mbrs.isEmpty()) {
- if(log.isErrorEnabled()) log.error("[FIND_INITIAL_MBRS]: gossip client found no members");
+ if(initial_mbrs.isEmpty()) {
+ if(log.isErrorEnabled()) log.error("[FIND_INITIAL_MBRS]: found no members");
return;
}
- if(log.isTraceEnabled()) log.trace("consolidated mbrs from GossipRouter(s) are " + tmp_mbrs);
-
- hdr=new PingHeader(PingHeader.GET_MBRS_REQ, cluster_name);
- msg=new Message(null);
- msg.setFlag(Message.OOB);
- msg.putHeader(name, hdr);
-
- for(Iterator<Address> it=tmp_mbrs.iterator(); it.hasNext();) {
- mbr_addr=it.next();
- copy=msg.copy();
- copy.setDest(mbr_addr);
- if(log.isTraceEnabled()) log.trace("[FIND_INITIAL_MBRS] sending PING request to " + copy.getDest());
- down_prot.down(new Event(Event.MSG, copy));
+ if(log.isTraceEnabled()) log.trace("consolidated mbrs from GossipRouter(s) are " + initial_mbrs);
+
+ for(Address mbr_addr: initial_mbrs) {
+ Message msg=new Message(mbr_addr);
+ msg.setFlag(Message.OOB);
+ PingHeader hdr=new PingHeader(PingHeader.GET_MBRS_REQ, cluster_name);
+ msg.putHeader(name, hdr);
+ if(log.isTraceEnabled()) log.trace("[FIND_INITIAL_MBRS] sending PING request to " + mbr_addr);
+ down_prot.down(new Event(Event.MSG, msg));
+ }
+ }
+
+ synchronized void startReconnector() {
+ if(running && (reconnect_future == null || reconnect_future.isDone())) {
+ if(log.isDebugEnabled())
+ log.debug("starting reconnector");
+ reconnect_future=timer.scheduleWithFixedDelay(new Runnable() {
+ public void run() {
+ connect(group_addr, local_addr);
+ }
+ }, 0, reconnect_interval, TimeUnit.MILLISECONDS);
+ }
+ }
+
+ synchronized void stopReconnector() {
+ if(reconnect_future != null) {
+ reconnect_future.cancel(true);
+ reconnect_future=null;
+ if(log.isDebugEnabled())
+ log.debug("stopping reconnector");
+ }
+ }
+
+ protected void connect(String group, Address logical_addr) {
+ String logical_name=org.jgroups.util.UUID.get(logical_addr);
+ PhysicalAddress physical_addr=(PhysicalAddress)down_prot.down(new Event(Event.GET_PHYSICAL_ADDRESS, local_addr));
+ List<PhysicalAddress> physical_addrs=physical_addr != null? new ArrayList<PhysicalAddress>() : null;
+ if(physical_addr != null)
+ physical_addrs.add(physical_addr);
+
+ int num_faulty_conns=0;
+ for (RouterStub stub : stubs) {
+ try {
+ if(log.isTraceEnabled())
+ log.trace("tring to connect to " + stub.getGossipRouterAddress());
+ stub.connect(group, logical_addr, logical_name, physical_addrs);
+ }
+ catch(Exception e) {
+ if(log.isErrorEnabled())
+ log.error("failed connecting to " + stub.getGossipRouterAddress() + ": " + e);
+ num_faulty_conns++;
+ }
}
+ if(num_faulty_conns == 0)
+ stopReconnector();
}
}
diff --git a/src/org/jgroups/stack/RouterStub.java b/src/org/jgroups/stack/RouterStub.java
index cc4ba445556..685a4bfffa0 100644
--- a/src/org/jgroups/stack/RouterStub.java
+++ b/src/org/jgroups/stack/RouterStub.java
@@ -1,27 +1,26 @@
package org.jgroups.stack;
+import org.jgroups.Address;
+import org.jgroups.PhysicalAddress;
+import org.jgroups.logging.Log;
+import org.jgroups.logging.LogFactory;
+import org.jgroups.protocols.PingData;
+import org.jgroups.protocols.TUNNEL;
+import org.jgroups.util.Util;
+
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
-import java.util.LinkedList;
-import java.util.List;
import java.util.ArrayList;
-
-import org.jgroups.logging.Log;
-import org.jgroups.logging.LogFactory;
-import org.jgroups.Address;
-import org.jgroups.PhysicalAddress;
-import org.jgroups.protocols.TUNNEL;
-import org.jgroups.protocols.PingData;
-import org.jgroups.util.Util;
+import java.util.List;
/**
* Client stub that talks to a remote GossipRouter
* @author Bela Ban
- * @version $Id: RouterStub.java,v 1.45 2009/07/08 15:30:31 belaban Exp $
+ * @version $Id: RouterStub.java,v 1.46 2009/07/09 13:59:39 belaban Exp $
*/
public class RouterStub {
@@ -51,8 +50,6 @@ public static enum ConnectionStatus {INITIAL, DISCONNECTED, CONNECTED};
private int sock_read_timeout=3000; // max number of ms to wait for socket reads (0 means block
// forever, or until the sock is closed)
- private volatile boolean intentionallyDisconnected=false;
-
public interface ConnectionListener {
void connectionStatusChange(ConnectionStatus state);
}
@@ -89,6 +86,10 @@ public boolean isConnected() {
return connectionState == ConnectionStatus.CONNECTED;
}
+ public ConnectionStatus getConnectionStatus() {
+ return connectionState;
+ }
+
public void setConnectionListener(ConnectionListener conn_listener) {
this.conn_listener=conn_listener;
}
@@ -142,9 +143,6 @@ public synchronized void destroy() {
Util.close(sock);
}
- public boolean isIntentionallyDisconnected() {
- return intentionallyDisconnected;
- }
public synchronized List<PingData> getMembers(final String group) throws Exception {
List<PingData> retval=new ArrayList<PingData>();
|
35889c08e997c54194471256e0760ee29a54bafe
|
kotlin
|
Test data paths fixed--
|
c
|
https://github.com/JetBrains/kotlin
|
diff --git a/j2k/test/org/jetbrains/jet/j2k/StandaloneJavaToKotlinConverterTest.java b/j2k/test/org/jetbrains/jet/j2k/StandaloneJavaToKotlinConverterTest.java
index a168d150a4654..d153c24160160 100644
--- a/j2k/test/org/jetbrains/jet/j2k/StandaloneJavaToKotlinConverterTest.java
+++ b/j2k/test/org/jetbrains/jet/j2k/StandaloneJavaToKotlinConverterTest.java
@@ -14,8 +14,6 @@
import java.io.File;
import java.io.IOException;
-import static org.jetbrains.jet.j2k.TestCaseBuilder.getTestDataPathBase;
-
/**
* @author ignatov
*/
@@ -33,7 +31,7 @@ public StandaloneJavaToKotlinConverterTest(String dataPath, String name) {
@Override
protected void runTest() throws Throwable {
- String javaPath = "testData" + File.separator + getTestFilePath();
+ String javaPath = "j2k/testData" + File.separator + getTestFilePath();
String kotlinPath = javaPath.replace(".jav", ".kt");
final File kotlinFile = new File(kotlinPath);
@@ -89,7 +87,7 @@ public String getName() {
@NotNull
public static Test suite() {
TestSuite suite = new TestSuite();
- suite.addTest(TestCaseBuilder.suiteForDirectory(getTestDataPathBase(), "/ast", new TestCaseBuilder.NamedTestFactory() {
+ suite.addTest(TestCaseBuilder.suiteForDirectory("j2k/testData", "/ast", new TestCaseBuilder.NamedTestFactory() {
@NotNull
@Override
public Test createTest(@NotNull String dataPath, @NotNull String name) {
|
f119ea70438e3ff3d72678086ce4c58441a445a7
|
orientdb
|
GraphDB: supported 3 locking modes: no locking
|
a
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphDatabase.java b/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphDatabase.java
index e318c7141d9..564fcd31ea6 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphDatabase.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphDatabase.java
@@ -32,6 +32,7 @@
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;
+import com.orientechnologies.orient.core.storage.OStorage;
import com.orientechnologies.orient.core.storage.OStorageEmbedded;
import com.orientechnologies.orient.core.tx.OTransactionNoTx;
import com.orientechnologies.orient.core.type.tree.OMVRBTreeRIDSet;
@@ -47,6 +48,10 @@
*
*/
public class OGraphDatabase extends ODatabaseDocumentTx {
+ public enum LOCK_MODE {
+ NO_LOCKING, DATABASE_LEVEL_LOCKING, RECORD_LEVEL_LOCKING
+ }
+
public static final String TYPE = "graph";
public static final String VERTEX_CLASS_NAME = "OGraphVertex";
@@ -62,7 +67,7 @@ public class OGraphDatabase extends ODatabaseDocumentTx {
private boolean useCustomTypes = true;
private boolean safeMode = false;
- private boolean autoLock = true;
+ private LOCK_MODE lockMode = LOCK_MODE.DATABASE_LEVEL_LOCKING;
protected OClass vertexBaseClass;
protected OClass edgeBaseClass;
@@ -80,11 +85,6 @@ public OGraphDatabase(final ODatabaseRecordTx iSource) {
public <THISDB extends ODatabase> THISDB open(final String iUserName, final String iUserPassword) {
super.open(iUserName, iUserPassword);
checkForGraphSchema();
-
- if (autoLock && !(getStorage() instanceof OStorageEmbedded))
- // NOT YET SUPPORETD REMOTE LOCKING
- autoLock = false;
-
return (THISDB) this;
}
@@ -218,10 +218,9 @@ public ODocument createEdge(final ODocument iOutVertex, final ODocument iInVerte
edge.field(iFields[i].toString(), iFields[i + 1]);
// OUT FIELD
- if (autoLock)
- // LOCK VERTEX TO AVOID CONCURRENT ACCESS
- acquireWriteLock(iOutVertex);
+ acquireWriteLock(iOutVertex);
try {
+
final Object outField = iOutVertex.field(VERTEX_FIELD_OUT);
final OMVRBTreeRIDSet out;
if (outField instanceof OMVRBTreeRIDSet) {
@@ -235,15 +234,13 @@ public ODocument createEdge(final ODocument iOutVertex, final ODocument iInVerte
}
out.add(edge);
} finally {
- if (autoLock)
- releaseWriteLock(iOutVertex);
+ releaseWriteLock(iOutVertex);
}
// IN FIELD
- if (autoLock)
- // LOCK VERTEX TO AVOID CONCURRENT ACCESS
- acquireWriteLock(iInVertex);
+ acquireWriteLock(iInVertex);
try {
+
final Object inField = iInVertex.field(VERTEX_FIELD_IN);
final OMVRBTreeRIDSet in;
if (inField instanceof OMVRBTreeRIDSet) {
@@ -256,9 +253,9 @@ public ODocument createEdge(final ODocument iOutVertex, final ODocument iInVerte
iInVertex.field(VERTEX_FIELD_IN, in);
}
in.add(edge);
+
} finally {
- if (autoLock)
- releaseWriteLock(iInVertex);
+ releaseWriteLock(iInVertex);
}
edge.setDirty();
@@ -290,8 +287,7 @@ public boolean removeEdge(final OIdentifiable iEdge) {
// OUT VERTEX
final ODocument outVertex = edge.field(EDGE_FIELD_OUT);
- if (autoLock)
- acquireWriteLock(outVertex);
+ acquireWriteLock(outVertex);
try {
if (outVertex != null) {
@@ -302,15 +298,13 @@ public boolean removeEdge(final OIdentifiable iEdge) {
}
} finally {
- if (autoLock)
- releaseWriteLock(outVertex);
+ releaseWriteLock(outVertex);
}
// IN VERTEX
final ODocument inVertex = edge.field(EDGE_FIELD_IN);
- if (autoLock)
- acquireWriteLock(inVertex);
+ acquireWriteLock(inVertex);
try {
if (inVertex != null) {
@@ -321,8 +315,7 @@ public boolean removeEdge(final OIdentifiable iEdge) {
}
} finally {
- if (autoLock)
- releaseWriteLock(inVertex);
+ releaseWriteLock(inVertex);
}
delete(edge);
@@ -344,10 +337,9 @@ public void removeVertex(final ODocument iVertex) {
Set<ODocument> otherEdges;
// REMOVE OUT EDGES
- if (autoLock)
- // LOCK VERTEX TO AVOID CONCURRENT ACCESS
- acquireWriteLock(iVertex);
+ acquireWriteLock(iVertex);
try {
+
Set<ODocument> edges = iVertex.field(VERTEX_FIELD_OUT);
if (edges != null) {
for (ODocument edge : edges) {
@@ -383,8 +375,7 @@ public void removeVertex(final ODocument iVertex) {
delete(iVertex);
} finally {
- if (autoLock)
- releaseWriteLock(iVertex);
+ releaseWriteLock(iVertex);
}
commitBlock(safeMode);
@@ -444,9 +435,7 @@ public Set<OIdentifiable> getEdgesBetweenVertexes(final OIdentifiable iVertex1,
final Set<OIdentifiable> result = new HashSet<OIdentifiable>();
if (iVertex1 != null && iVertex2 != null) {
- if (autoLock)
- // LOCK VERTEX TO AVOID CONCURRENT ACCESS
- acquireReadLock(iVertex1);
+ acquireReadLock(iVertex1);
try {
// CHECK OUT EDGES
@@ -472,8 +461,7 @@ public Set<OIdentifiable> getEdgesBetweenVertexes(final OIdentifiable iVertex1,
}
} finally {
- if (autoLock)
- releaseReadLock(iVertex1);
+ releaseReadLock(iVertex1);
}
}
@@ -500,8 +488,7 @@ public Set<OIdentifiable> getOutEdges(final OIdentifiable iVertex, final String
OMVRBTreeRIDSet result = null;
- if (autoLock)
- acquireReadLock(iVertex);
+ acquireReadLock(iVertex);
try {
final OMVRBTreeRIDSet set = vertex.field(VERTEX_FIELD_OUT);
@@ -522,8 +509,7 @@ public Set<OIdentifiable> getOutEdges(final OIdentifiable iVertex, final String
}
} finally {
- if (autoLock)
- releaseReadLock(iVertex);
+ releaseReadLock(iVertex);
}
return result;
@@ -571,8 +557,7 @@ public Set<OIdentifiable> getInEdges(final OIdentifiable iVertex, final String i
OMVRBTreeRIDSet result = null;
- if (autoLock)
- acquireReadLock(iVertex);
+ acquireReadLock(iVertex);
try {
final OMVRBTreeRIDSet set = vertex.field(VERTEX_FIELD_IN);
@@ -593,8 +578,7 @@ public Set<OIdentifiable> getInEdges(final OIdentifiable iVertex, final String i
}
} finally {
- if (autoLock)
- releaseReadLock(iVertex);
+ releaseReadLock(iVertex);
}
return result;
}
@@ -664,8 +648,7 @@ public ODocument getOutVertex(final OIdentifiable iEdge) {
}
public Set<OIdentifiable> filterEdgesByProperties(final OMVRBTreeRIDSet iEdges, final Iterable<String> iPropertyNames) {
- if (autoLock)
- acquireReadLock(null);
+ acquireReadLock(null);
try {
if (iPropertyNames == null)
@@ -690,14 +673,12 @@ public Set<OIdentifiable> filterEdgesByProperties(final OMVRBTreeRIDSet iEdges,
return result;
} finally {
- if (autoLock)
- releaseReadLock(null);
+ releaseReadLock(null);
}
}
public Set<OIdentifiable> filterEdgesByProperties(final OMVRBTreeRIDSet iEdges, final Map<String, Object> iProperties) {
- if (autoLock)
- acquireReadLock(null);
+ acquireReadLock(null);
try {
if (iProperties == null)
@@ -727,8 +708,7 @@ public Set<OIdentifiable> filterEdgesByProperties(final OMVRBTreeRIDSet iEdges,
return result;
} finally {
- if (autoLock)
- releaseReadLock(null);
+ releaseReadLock(null);
}
}
@@ -886,14 +866,6 @@ public boolean isEdge(final ODocument iRecord) {
return iRecord != null ? iRecord.getSchemaClass().isSubClassOf(edgeBaseClass) : false;
}
- public boolean isAutoLock() {
- return autoLock;
- }
-
- public void setAutoLock(final boolean iAutoLock) {
- this.autoLock = iAutoLock;
- }
-
/**
* Locks the record in exclusive mode to avoid concurrent access.
*
@@ -902,8 +874,16 @@ public void setAutoLock(final boolean iAutoLock) {
* @return The current instance as fluent interface to allow calls in chain.
*/
public OGraphDatabase acquireWriteLock(final OIdentifiable iRecord) {
- ((OStorageEmbedded) getStorage()).getLock().acquireExclusiveLock();
- // ((OStorageEmbedded) getStorage()).acquireWriteLock(iRecord.getIdentity());
+ switch (lockMode) {
+ case DATABASE_LEVEL_LOCKING:
+ ((OStorage) getStorage()).getLock().acquireExclusiveLock();
+ break;
+ case RECORD_LEVEL_LOCKING:
+ ((OStorageEmbedded) getStorage()).acquireWriteLock(iRecord.getIdentity());
+ break;
+ case NO_LOCKING:
+ break;
+ }
return this;
}
@@ -915,8 +895,16 @@ public OGraphDatabase acquireWriteLock(final OIdentifiable iRecord) {
* @return The current instance as fluent interface to allow calls in chain.
*/
public OGraphDatabase releaseWriteLock(final OIdentifiable iRecord) {
- ((OStorageEmbedded) getStorage()).getLock().releaseExclusiveLock();
- // ((OStorageEmbedded) getStorage()).releaseWriteLock(iRecord.getIdentity());
+ switch (lockMode) {
+ case DATABASE_LEVEL_LOCKING:
+ ((OStorage) getStorage()).getLock().releaseExclusiveLock();
+ break;
+ case RECORD_LEVEL_LOCKING:
+ ((OStorageEmbedded) getStorage()).releaseWriteLock(iRecord.getIdentity());
+ break;
+ case NO_LOCKING:
+ break;
+ }
return this;
}
@@ -928,8 +916,16 @@ public OGraphDatabase releaseWriteLock(final OIdentifiable iRecord) {
* @return The current instance as fluent interface to allow calls in chain.
*/
public OGraphDatabase acquireReadLock(final OIdentifiable iRecord) {
- ((OStorageEmbedded) getStorage()).getLock().acquireSharedLock();
- // ((OStorageEmbedded) getStorage()).acquireReadLock(iRecord.getIdentity());
+ switch (lockMode) {
+ case DATABASE_LEVEL_LOCKING:
+ ((OStorage) getStorage()).getLock().acquireSharedLock();
+ break;
+ case RECORD_LEVEL_LOCKING:
+ ((OStorageEmbedded) getStorage()).acquireReadLock(iRecord.getIdentity());
+ break;
+ case NO_LOCKING:
+ break;
+ }
return this;
}
@@ -941,8 +937,16 @@ public OGraphDatabase acquireReadLock(final OIdentifiable iRecord) {
* @return The current instance as fluent interface to allow calls in chain.
*/
public OGraphDatabase releaseReadLock(final OIdentifiable iRecord) {
- ((OStorageEmbedded) getStorage()).getLock().releaseSharedLock();
- // ((OStorageEmbedded) getStorage()).releaseReadLock(iRecord.getIdentity());
+ switch (lockMode) {
+ case DATABASE_LEVEL_LOCKING:
+ ((OStorage) getStorage()).getLock().releaseSharedLock();
+ break;
+ case RECORD_LEVEL_LOCKING:
+ ((OStorageEmbedded) getStorage()).releaseReadLock(iRecord.getIdentity());
+ break;
+ case NO_LOCKING:
+ break;
+ }
return this;
}
@@ -1024,4 +1028,16 @@ protected boolean checkEdge(final ODocument iEdge, final String[] iLabels, final
}
return good;
}
+
+ public LOCK_MODE getLockMode() {
+ return lockMode;
+ }
+
+ public void setLockMode(final LOCK_MODE lockMode) {
+ if (lockMode == LOCK_MODE.RECORD_LEVEL_LOCKING && !(getStorage() instanceof OStorageEmbedded))
+ // NOT YET SUPPORETD REMOTE LOCKING
+ throw new IllegalArgumentException("Record leve locking is not supported for remote connections");
+
+ this.lockMode = lockMode;
+ }
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java b/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java
index ed8bacc60ca..0c4bae3a7f5 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java
@@ -17,6 +17,7 @@
import java.io.IOException;
+import com.orientechnologies.common.concur.lock.OLockManager.LOCK;
import com.orientechnologies.common.exception.OException;
import com.orientechnologies.orient.core.command.OCommandExecutor;
import com.orientechnologies.orient.core.command.OCommandManager;
@@ -52,10 +53,10 @@ public OStorageEmbedded(final String iName, final String iFilePath, final String
PROFILER_DELETE_RECORD = "db." + name + ".deleteRecord";
}
- protected abstract ORawBuffer readRecord(final OCluster iClusterSegment, final ORecordId iRid, boolean iAtomicLock);
-
public abstract OCluster getClusterByName(final String iClusterName);
+ protected abstract ORawBuffer readRecord(final OCluster iClusterSegment, final ORecordId iRid, boolean iAtomicLock);
+
/**
* Closes the storage freeing the lock manager first.
*/
@@ -94,14 +95,6 @@ public Object executeCommand(final OCommandRequestText iCommand, final OCommandE
}
}
- /**
- * Checks if the storage is open. If it's closed an exception is raised.
- */
- protected void checkOpeness() {
- if (status != STATUS.OPEN)
- throw new OStorageException("Storage " + name + " is not opened.");
- }
-
@Override
public long[] getClusterPositionsForEntry(int currentClusterId, long entry) {
if (currentClusterId == -1)
@@ -126,6 +119,22 @@ public long[] getClusterPositionsForEntry(int currentClusterId, long entry) {
}
}
+ public void acquireWriteLock(final ORID iRid) {
+ lockManager.acquireLock(Thread.currentThread(), iRid, LOCK.EXCLUSIVE);
+ }
+
+ public void releaseWriteLock(final ORID iRid) {
+ lockManager.releaseLock(Thread.currentThread(), iRid, LOCK.EXCLUSIVE);
+ }
+
+ public void acquireReadLock(final ORID iRid) {
+ lockManager.acquireLock(Thread.currentThread(), iRid, LOCK.SHARED);
+ }
+
+ public void releaseReadLock(final ORID iRid) {
+ lockManager.releaseLock(Thread.currentThread(), iRid, LOCK.SHARED);
+ }
+
protected OPhysicalPosition moveRecord(ORID originalId, ORID newId) throws IOException {
final OCluster originalCluster = getClusterById(originalId.getClusterId());
final OCluster destinationCluster = getClusterById(newId.getClusterId());
@@ -190,4 +199,12 @@ protected OPhysicalPosition moveRecord(ORID originalId, ORID newId) throws IOExc
return ppos;
}
+
+ /**
+ * Checks if the storage is open. If it's closed an exception is raised.
+ */
+ protected void checkOpeness() {
+ if (status != STATUS.OPEN)
+ throw new OStorageException("Storage " + name + " is not opened.");
+ }
}
|
45770596d64be289e202339bbc02ebb22aed3758
|
Delta Spike
|
DELTASPIKE-289 migrate windowhandler from CODI
|
a
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java
index b4acc468e..429fa20e2 100644
--- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java
+++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java
@@ -41,7 +41,7 @@ public class WindowBeanHolder implements Serializable
* value: the {@link ContextualStorage} which holds all the
* {@link javax.enterprise.inject.spi.Bean}s.
*/
- private volatile Map<String, ContextualStorage> storageMap = new ConcurrentHashMap<String, ContextualStorage>();
+ private Map<String, ContextualStorage> storageMap = new ConcurrentHashMap<String, ContextualStorage>();
/**
* This method will return the ContextualStorage or create a new one
@@ -67,6 +67,11 @@ public ContextualStorage getContextualStorage(BeanManager beanManager, String wi
return contextualStorage;
}
+ public Map<String, ContextualStorage> getStorageMap()
+ {
+ return storageMap;
+ }
+
/**
*
* This method will replace the storageMap and with
diff --git a/deltaspike/modules/jsf/impl/pom.xml b/deltaspike/modules/jsf/impl/pom.xml
index c71899f99..ee9947c79 100644
--- a/deltaspike/modules/jsf/impl/pom.xml
+++ b/deltaspike/modules/jsf/impl/pom.xml
@@ -65,6 +65,10 @@
<version>1.0</version>
<scope>provided</scope>
</dependency>
+ <dependency>
+ <groupId>org.apache.geronimo.specs</groupId>
+ <artifactId>geronimo-servlet_3.0_spec</artifactId>
+ </dependency>
<!-- we use Arquillian Warp to test our JSF apps -->
<dependency>
diff --git a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/listener/request/DeltaSpikeLifecycleWrapper.java b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/listener/request/DeltaSpikeLifecycleWrapper.java
index 9d4808d85..0f91b335b 100644
--- a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/listener/request/DeltaSpikeLifecycleWrapper.java
+++ b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/listener/request/DeltaSpikeLifecycleWrapper.java
@@ -19,7 +19,9 @@
package org.apache.deltaspike.jsf.impl.listener.request;
import org.apache.deltaspike.core.api.provider.BeanProvider;
+import org.apache.deltaspike.core.spi.scope.window.WindowContext;
import org.apache.deltaspike.core.util.ClassDeactivationUtils;
+import org.apache.deltaspike.jsf.spi.scope.window.ClientWindow;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseListener;
@@ -31,6 +33,9 @@ class DeltaSpikeLifecycleWrapper extends Lifecycle
private BeforeAfterJsfRequestBroadcaster beforeAfterJsfRequestBroadcaster;
+ private ClientWindow clientWindow;
+ private WindowContext windowContext;
+
private volatile Boolean initialized;
DeltaSpikeLifecycleWrapper(Lifecycle wrapped)
@@ -53,13 +58,19 @@ public void addPhaseListener(PhaseListener phaseListener)
@Override
public void execute(FacesContext facesContext)
{
+ lazyInit();
+
//TODO broadcastApplicationStartupBroadcaster();
broadcastBeforeFacesRequestEvent(facesContext);
- //X TODO add ClientWindow handling
- this.wrapped.execute(facesContext);
-
+ // ClientWindow handling
+ String windowId = clientWindow.getWindowId(facesContext);
+ if (windowId != null)
+ {
+ windowContext.activateWindow(windowId);
+ }
+ this.wrapped.execute(facesContext);
}
@Override
@@ -85,7 +96,6 @@ public void render(FacesContext facesContext)
private void broadcastBeforeFacesRequestEvent(FacesContext facesContext)
{
- lazyInit();
if (this.beforeAfterJsfRequestBroadcaster != null)
{
this.beforeAfterJsfRequestBroadcaster.broadcastBeforeJsfRequestEvent(facesContext);
@@ -103,15 +113,21 @@ private void lazyInit()
private synchronized void init()
{
// switch into paranoia mode
- if (this.initialized == null)
+ if (initialized == null)
{
if (ClassDeactivationUtils.isActivated(BeforeAfterJsfRequestBroadcaster.class))
{
- this.beforeAfterJsfRequestBroadcaster =
+ beforeAfterJsfRequestBroadcaster =
BeanProvider.getContextualReference(BeforeAfterJsfRequestBroadcaster.class, true);
+
+ clientWindow =
+ BeanProvider.getContextualReference(ClientWindow.class, true);
+
+ windowContext =
+ BeanProvider.getContextualReference(WindowContext.class, true);
}
- this.initialized = true;
+ initialized = true;
}
}
}
diff --git a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/DefaultClientWindow.java b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/DefaultClientWindow.java
index 4ab6d37f8..3ea94788a 100644
--- a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/DefaultClientWindow.java
+++ b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/DefaultClientWindow.java
@@ -19,13 +19,20 @@
package org.apache.deltaspike.jsf.impl.scope.window;
import javax.enterprise.context.ApplicationScoped;
+import javax.faces.FacesException;
import javax.faces.component.UIViewRoot;
+import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.OutputStream;
import java.util.logging.Logger;
import org.apache.deltaspike.core.spi.scope.window.WindowContext;
+import org.apache.deltaspike.jsf.impl.util.JsfUtils;
import org.apache.deltaspike.jsf.spi.scope.window.ClientWindow;
import org.apache.deltaspike.jsf.spi.scope.window.ClientWindowConfig;
@@ -46,6 +53,24 @@ public class DefaultClientWindow implements ClientWindow
{
private static final Logger logger = Logger.getLogger(DefaultClientWindow.class.getName());
+ private static final String WINDOW_ID_COOKIE_PREFIX = "dsWindowId-";
+ private static final String DELTASPIKE_REQUEST_TOKEN = "dsRid";
+
+ private static final String UNINITIALIZED_WINDOW_ID_VALUE = "uninitializedWindowId";
+ private static final String WINDOW_ID_REPLACE_PATTERN = "$$windowIdValue$$";
+ private static final String NOSCRIPT_URL_REPLACE_PATTERN = "$$noscriptUrl$$";
+
+ /**
+ * Use this parameter to force a 'direct' request from the clients without any windowId detection
+ * We keep this name for backward compat with CODI.
+ */
+ private static final String NOSCRIPT_PARAMETER = "mfDirect";
+
+ /**
+ * This windowId will be used for all requests with disabled windowId feature
+ */
+ private static final String DEFAULT_WINDOW_ID = "default";
+
@Inject
private ClientWindowConfig clientWindowConfig;
@@ -59,16 +84,36 @@ public String getWindowId(FacesContext facesContext)
{
if (ClientWindowRenderMode.NONE.equals(clientWindowConfig.getClientWindowRenderMode(facesContext)))
{
- return null;
+ // if this request should not get any window detection then we are done
+ return DEFAULT_WINDOW_ID;
}
- String windowId = null;
-
if (facesContext.isPostback())
{
+ // for POST we read the windowId from the WindowIdHolderComponent in our ViewRoot
return getPostBackWindowId(facesContext);
}
+ ExternalContext externalContext = facesContext.getExternalContext();
+
+ // and now for the GET request stuff
+ if (isNoscriptRequest(externalContext))
+ {
+ // the client has JavaScript disabled
+ clientWindowConfig.setJavaScriptEnabled(false);
+
+ return DEFAULT_WINDOW_ID;
+ }
+
+ String windowId = getVerifiedWindowIdFromCookie(externalContext);
+ if (windowId == null)
+ {
+ // GET request without windowId - send windowhandlerfilter.html to get the windowId
+ sendWindowHandlerHtml(externalContext, null);
+ facesContext.responseComplete();
+ }
+
+ // we have a valid windowId - set it and continue with the request
return windowId;
}
@@ -93,4 +138,118 @@ private String getPostBackWindowId(FacesContext facesContext)
}
+ private boolean isNoscriptRequest(ExternalContext externalContext)
+ {
+ String noscript = externalContext.getRequestParameterMap().get(NOSCRIPT_PARAMETER);
+
+ return (noscript != null && "true".equals(noscript));
+ }
+
+
+ private void sendWindowHandlerHtml(ExternalContext externalContext, String windowId)
+ {
+ HttpServletResponse httpResponse = (HttpServletResponse) externalContext.getResponse();
+
+ try
+ {
+ httpResponse.setStatus(HttpServletResponse.SC_OK);
+ httpResponse.setContentType("text/html");
+
+ String windowHandlerHtml = clientWindowConfig.getClientWindowHtml();
+
+ if (windowId == null)
+ {
+ windowId = UNINITIALIZED_WINDOW_ID_VALUE;
+ }
+
+ // set the windowId value in the javascript code
+ windowHandlerHtml = windowHandlerHtml.replace(WINDOW_ID_REPLACE_PATTERN, windowId);
+
+ // set the noscript-URL for users with no JavaScript
+ windowHandlerHtml =
+ windowHandlerHtml.replace(NOSCRIPT_URL_REPLACE_PATTERN, getNoscriptUrl(externalContext));
+
+ OutputStream os = httpResponse.getOutputStream();
+ try
+ {
+ os.write(windowHandlerHtml.getBytes());
+ }
+ finally
+ {
+ os.close();
+ }
+ }
+ catch (IOException ioe)
+ {
+ throw new FacesException(ioe);
+ }
+ }
+
+ private String getNoscriptUrl(ExternalContext externalContext)
+ {
+ String url = externalContext.getRequestPathInfo();
+ if (url == null)
+ {
+ url = "";
+ }
+
+ // only use the very last part of the url
+ int lastSlash = url.lastIndexOf('/');
+ if (lastSlash != -1)
+ {
+ url = url.substring(lastSlash + 1);
+ }
+
+ // add request parameter
+ url = JsfUtils.addPageParameters(externalContext, url, true);
+
+ // add noscript parameter
+ if (url.contains("?"))
+ {
+ url = url + "&";
+ }
+ else
+ {
+ url = url + "?";
+ }
+ url = url + NOSCRIPT_PARAMETER + "=true";
+
+ // NOTE that the url could contain data for an XSS attack
+ // like e.g. ?"></a><a href%3D"http://hacker.org/attack.html?a
+ // DO NOT REMOVE THE FOLLOWING LINES!
+ url = url.replace("\"", "");
+ url = url.replace("\'", "");
+
+ return url;
+ }
+
+ private String getVerifiedWindowIdFromCookie(ExternalContext externalContext)
+ {
+ String cookieName = WINDOW_ID_COOKIE_PREFIX + getRequestToken(externalContext);
+ Cookie cookie = (Cookie) externalContext.getRequestCookieMap().get(cookieName);
+
+ if (cookie != null)
+ {
+ // manually blast the cookie away, otherwise it pollutes the
+ // cookie storage in some browsers. E.g. Firefox doesn't
+ // cleanup properly, even if the max-age is reached.
+ cookie.setMaxAge(0);
+
+ return cookie.getValue();
+ }
+
+ return null;
+ }
+
+ private String getRequestToken(ExternalContext externalContext)
+ {
+ String requestToken = externalContext.getRequestParameterMap().get(DELTASPIKE_REQUEST_TOKEN);
+ if (requestToken != null)
+ {
+ return requestToken;
+ }
+
+ return "";
+ }
+
}
diff --git a/deltaspike/modules/jsf/impl/src/main/resources/META-INF/resources/js/windowhandler.js b/deltaspike/modules/jsf/impl/src/main/resources/META-INF/resources/js/windowhandler.js
new file mode 100644
index 000000000..b563b3120
--- /dev/null
+++ b/deltaspike/modules/jsf/impl/src/main/resources/META-INF/resources/js/windowhandler.js
@@ -0,0 +1,180 @@
+/*
+ * 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.
+ */
+(function() {
+//wrapping so that all internal functions are privately scoped
+function isHtml5() {
+ try {
+ return !!localStorage.getItem;
+ } catch(e) {
+ return false;
+ }
+}
+
+// some browsers don't understand JSON - guess which one ... :(
+function stringify(someArray) {
+ if (JSON) {
+ return JSON.stringify(someArray);
+ }
+ return someArray.join("|||");
+}
+
+// store the current body in the html5 localstorage
+function storeWindowTree() {
+ // first we store all CSS we also need on the intermediate page
+ var headNodes = document.getElementsByTagName("head")[0].childNodes;
+ var oldSS = new Array();
+ var j = 0;
+ for (var i = 0; i < headNodes.length; i++) {
+ var tagName = headNodes[i].tagName;
+ if (tagName && equalsIgnoreCase(tagName, "link") &&
+ equalsIgnoreCase(headNodes[i].getAttribute("type"), "text/css")) {
+
+ // sort out media="print" and stuff
+ var media = headNodes[i].getAttribute("media");
+ if (!media || equalsIgnoreCase(media, "all") || equalsIgnoreCase(media, 'screen')) {
+ oldSS[j++] = headNodes[i].getAttribute("href");
+ }
+ }
+ }
+ localStorage.setItem(window.name + '_css', stringify(oldSS));
+ var body = document.getElementsByTagName("body")[0];
+ localStorage.setItem(window.name + '_body', body.innerHTML);
+ //X TODO: store ALL attributes of the body tag
+ localStorage.setItem(window.name + '_bodyAttrs', body.getAttribute("class"));
+ return true;
+}
+
+function equalsIgnoreCase(source, destination) {
+ //either both are not set or null
+ if (!source && !destination) {
+ return true;
+ }
+ //source or dest is set while the other is not
+ if (!source || !destination) return false;
+
+ //in any other case we do a strong string comparison
+ return source.toLowerCase() === destination.toLowerCase();
+}
+
+/** This method will be called onWindowLoad and after AJAX success */
+function applyOnClick() {
+ var links = document.getElementsByTagName("a");
+ for (var i = 0; i < links.length; i++) {
+ if (!links[i].onclick) {
+ links[i].onclick = function() {storeWindowTree(); return true;};
+ } else {
+ // prevent double decoration
+ if (!("" + links[i].onclick).match(".*storeWindowTree().*")) {
+ //the function wrapper is important otherwise the
+ //last onclick handler would be assigned to oldonclick
+ (function storeEvent() {
+ var oldonclick = links[i].onclick;
+ links[i].onclick = function(evt) {
+ //ie handling added
+ evt = evt || window.event;
+
+ return storeWindowTree() && oldonclick(evt);
+ };
+ })();
+ }
+ }
+ }
+}
+
+function getUrlParameter(name) {
+ var url = window.location.href;
+ var vars = url.split(/&|\?/g);
+ for (var i=0; vars != null && i < vars.length; i++) {
+ var pair = vars[i].split("=");
+ if (pair[0]==name) {
+ return pair[1];
+ }
+ }
+ return null;
+}
+function setUrlParam(baseUrl, paramName, paramValue) {
+ var query = baseUrl;
+ var vars = query.split(/&|\?/g);
+ var newQuery = "";
+ var iParam = 0;
+ var paramFound = false;
+ for (var i=0; vars != null && i < vars.length; i++) {
+ var pair = vars[i].split("=");
+ if (pair.length == 1) {
+ newQuery = pair[0];
+ } else {
+ if (pair[0] != paramName) {
+ var amp = iParam++ > 0 ? "&" : "?";
+ newQuery = newQuery + amp + pair[0] + "=" + pair[1];
+ } else {
+ paramFound = true;
+ if (paramValue) {
+ var amp = iParam++ > 0 ? "&" : "?";
+ newQuery = newQuery + amp + paramName + "=" + paramValue;
+ }
+ }
+ }
+ }
+ if (!paramFound && paramValue) {
+ var amp = iParam++ > 0 ? "&" : "?";
+ newQuery = newQuery + amp + paramName + "=" + paramValue;
+ }
+ return newQuery;
+}
+// this method runs to ensure that windowIds get checked even if no windowhandler.html is used
+function assertWindowId() {
+ if (!window.name || window.name.length < 1) {
+ url = setUrlParam(window.location.href, 'windowId', null);
+ window.name = 'tempWindowId';
+ window.location = url;
+ }
+}
+
+function eraseRequestCookie() {
+ var requestToken = getUrlParameter('dsRid'); // random request param
+ if (requestToken) {
+ var cookieName = 'dsiWindowId-' + requestToken;
+ var date = new Date();
+ date.setTime(date.getTime()-(10*24*60*60*1000)); // - 10 day
+ var expires = "; expires="+date.toGMTString();
+ document.cookie = cookieName+"="+expires+"; path=/";
+ }
+}
+
+var ajaxOnClick = function ajaxDecorateClick(event) {
+ if (event.status=="success") {
+ applyOnClick();
+ }
+}
+
+var oldWindowOnLoad = window.onload;
+
+window.onload = function(evt) {
+ try {
+ (oldWindowOnLoad)? oldWindowOnLoad(evt): null;
+ } finally {
+ eraseRequestCookie(); // manually erase the old dsRid cookie because Firefox doesn't do it properly
+ assertWindowId();
+ if (isHtml5()) {
+ applyOnClick();
+ jsf.ajax.addOnEvent(ajaxOnClick);
+ }
+ }
+}
+})();
diff --git a/deltaspike/modules/jsf/impl/src/main/resources/static/windowhandler.html b/deltaspike/modules/jsf/impl/src/main/resources/static/windowhandler.html
new file mode 100644
index 000000000..c0967228f
--- /dev/null
+++ b/deltaspike/modules/jsf/impl/src/main/resources/static/windowhandler.html
@@ -0,0 +1,170 @@
+<!DOCTYPE html
+ PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<!--
+ 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.
+-->
+<html>
+
+<head><title>Loading...</title></head>
+<body $$bodyAttributes$$><div id="message" style="position:absolute;left:40%;top:40%">
+ Your browser does not support JavaScript.
+ Click <a href="$$noscriptUrl$$">here</a> to continue without JavaScript.
+</div></body>
+
+<script type="text/javascript" >
+function isHtml5() {
+ try { return !!localStorage.getItem;
+ } catch(e) { return false; }
+}
+function unstringify(serialized) {
+ if (JSON) { return JSON.parse(serialized); }
+ return serialized.split("|||");
+}
+function getOldBody() {
+ if (window.name.length != null) {
+ return localStorage.getItem(window.name + '_body');
+ }
+}
+function getOldBodyAttrs() {
+ if (window.name.length != null) {
+ return localStorage.getItem(window.name + '_bodyAttrs');
+ }
+}
+function getOldCss() {
+ if (window.name.length != null) {
+ return unstringify(localStorage.getItem(window.name + '_css'));
+ }
+}
+
+function addCss(url) {
+ var newSS = document.createElement("style");
+ newSS.setAttribute("rel", "stylesheet");
+ newSS.setAttribute("type", "text/css");
+ newSS.appendChild(document.createTextNode("@import url(" +url + ");"));
+ document.getElementsByTagName("head")[0].appendChild(newSS);
+}
+
+function loadCss(clean) {
+ if (!isHtml5()) { // only do this stuff on html browsers
+ return;
+ }
+ var oldCss = getOldCss();
+ if (window.name && oldCss) {
+ for (i=0; oldCss && i< oldCss.length; i++) {
+ addCss(oldCss[i]);
+ }
+ if (clean) {
+ localStorage.removeItem(window.name + '_css');
+ }
+ }
+}
+
+function replaceContent() {
+ if (!isHtml5()) { // only do this stuff on html browsers
+ document.getElementById('message').textContent = "Loading...";
+ return;
+ }
+ loadCss(false);
+
+ var oldBody = getOldBody();
+
+ if (window.name && oldBody) {
+ document.body.innerHTML = oldBody;
+
+ //X TODO should restore all attribs of the body tag
+ document.body.setAttribute("class", getOldBodyAttrs());
+ document.body.setAttribute("style", " cursor: wait !important;");
+
+ localStorage.removeItem(window.name + '_body');
+ localStorage.removeItem(window.name + '_bodyAttrs');
+
+ // overlay the doc with an un-clickable full-size div
+ var newDiv = document.createElement("div");
+ newDiv.setAttribute("style", "position:absolute; z-index:1000; background-color:transparent; top:0; left:0; width:100%; height: 100%");
+ newDiv.setAttribute("class", "fulldiv");
+ document.body.appendChild(newDiv);
+ } else {
+ document.getElementById('message').textContent = "Loading...";
+ }
+}
+
+function setUrlParam(baseUrl, paramName, paramValue) {
+ var query = baseUrl;
+ var vars = query.split(/&|\?/g);
+ var newQuery = "";
+ var iParam = 0;
+ var paramFound = false;
+ for (var i=0; vars != null && i < vars.length; i++) {
+ var pair = vars[i].split("=");
+ if (pair.length == 1) {
+ newQuery = pair[0];
+ } else {
+ if (pair[0] != paramName) {
+ var amp = iParam++ > 0 ? "&" : "?";
+ newQuery = newQuery + amp + pair[0] + "=" + pair[1];
+ } else {
+ paramFound = true;
+ var amp = iParam++ > 0 ? "&" : "?";
+ newQuery = newQuery + amp + paramName + "=" + paramValue;
+ }
+ }
+ }
+ if (!paramFound) {
+ var amp = iParam++ > 0 ? "&" : "?";
+ newQuery = newQuery + amp + paramName + "=" + paramValue;
+ }
+ return newQuery;
+}
+
+replaceContent();
+
+window.onload = function() {
+ loadCss(true);
+ // this will be replaced in the phase listener
+ var windowId = '$$windowIdValue$$';
+ if (windowId == 'uninitializedWindowId') {
+ windowId = window.name
+ }
+ if (!windowId || windowId.length < 1) {
+ // request a new windowId
+ windowId = 'automatedEntryPoint';
+ }
+
+ window.name = windowId;
+
+ // uncomment the following line to debug the intermediate page
+ // if (!confirm('reload?')) { return true; }
+
+ // 3 seconds expiry time
+ var expdt = new Date();
+ expdt.setTime(expdt.getTime()+(3*1000));
+ var expires = "; expires="+expdt.toGMTString();
+
+ var requestToken = Math.floor(Math.random()*1001);
+ var newUrl = setUrlParam(window.location.href, "dsRid", requestToken);
+ newUrl = setUrlParam(newUrl, "windowId", windowId);
+
+ document.cookie = 'dsWindowId-' + requestToken + '=' + windowId + expires+"; path=/";
+
+ window.location = newUrl;
+}
+</script>
+
+</html>
+
|
464fd741533548c6fec7393299185c293de0d862
|
Mylyn Reviews
|
392682: Show details for changesets
Use the ScmConnectorUi to open the correct view for the connector
Task-Url: https://bugs.eclipse.org/bugs/show_bug.cgi?id=392682
Change-Id: I98a778a7dc0edc1497194bc018536236f4f93382
|
a
|
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
|
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.versions.tasks.ui/META-INF/MANIFEST.MF
index 051aff88..00e00729 100644
--- a/tbr/org.eclipse.mylyn.versions.tasks.ui/META-INF/MANIFEST.MF
+++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/META-INF/MANIFEST.MF
@@ -11,7 +11,8 @@ Require-Bundle: org.eclipse.ui,
org.eclipse.mylyn.tasks.core;bundle-version="3.8.0",
org.eclipse.mylyn.versions.ui;bundle-version="1.0.0",
org.eclipse.mylyn.versions.tasks.core;bundle-version="1.0.0",
- org.eclipse.mylyn.commons.core;bundle-version="3.8.0"
+ org.eclipse.mylyn.commons.core;bundle-version="3.8.0",
+ org.eclipse.core.resources
Bundle-ActivationPolicy: lazy
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Export-Package: org.eclipse.mylyn.internal.versions.tasks.ui;x-internal:=true,
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/plugin.xml b/tbr/org.eclipse.mylyn.versions.tasks.ui/plugin.xml
index 3ad6e0d3..6682b310 100644
--- a/tbr/org.eclipse.mylyn.versions.tasks.ui/plugin.xml
+++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/plugin.xml
@@ -10,5 +10,18 @@
id="org.eclipse.mylyn.versions.tasks.pageFactory1">
</pageFactory>
</extension>
+ <extension
+ point="org.eclipse.ui.popupMenus">
+ <objectContribution
+ adaptable="false"
+ id="org.eclipse.mylyn.versions.tasks.ui.openCommitContribution"
+ objectClass="org.eclipse.mylyn.versions.tasks.core.TaskChangeSet">
+ <action
+ class="org.eclipse.mylyn.versions.tasks.ui.OpenCommitAction"
+ id="org.eclipse.mylyn.versions.tasks.ui.action1"
+ label="Open">
+ </action>
+ </objectContribution>
+ </extension>
</plugin>
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/AbstractChangesetMappingProvider.java b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/AbstractChangesetMappingProvider.java
index ced7defe..79a61e69 100644
--- a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/AbstractChangesetMappingProvider.java
+++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/AbstractChangesetMappingProvider.java
@@ -16,14 +16,11 @@
import org.eclipse.mylyn.versions.tasks.core.IChangeSetMapping;
/**
- *
* @author Kilian Matt
- *
*/
public abstract class AbstractChangesetMappingProvider {
- public abstract void getChangesetsForTask(IChangeSetMapping mapping, IProgressMonitor monitor) throws CoreException ;
+ public abstract void getChangesetsForTask(IChangeSetMapping mapping, IProgressMonitor monitor) throws CoreException;
public abstract int getScoreFor(ITask task);
}
-
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/OpenCommitAction.java b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/OpenCommitAction.java
new file mode 100644
index 00000000..0f76a9da
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/OpenCommitAction.java
@@ -0,0 +1,43 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.versions.tasks.ui;
+
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.mylyn.versions.core.ChangeSet;
+import org.eclipse.mylyn.versions.tasks.core.TaskChangeSet;
+import org.eclipse.mylyn.versions.ui.ScmUi;
+import org.eclipse.ui.IActionDelegate;
+
+/**
+ * @author Kilian Matt
+ */
+public class OpenCommitAction implements IActionDelegate {
+
+ private IStructuredSelection selection;
+
+ public void run(IAction action) {
+ TaskChangeSet taskChangeSet = (TaskChangeSet) selection.getFirstElement();
+
+ ChangeSet changeset = taskChangeSet.getChangeset();
+ ScmUi.getUiConnector(changeset.getRepository().getConnector()).showChangeSetInView(changeset);
+ }
+
+ public void selectionChanged(IAction action, ISelection selection) {
+ if (selection instanceof IStructuredSelection) {
+ this.selection = (IStructuredSelection) selection;
+ } else {
+ this.selection = null;
+ }
+ }
+
+}
|
94a5344305fb5e4def14642eea2ca69dbd87511e
|
tapiji
|
Adapts the namespace of all TapiJI plug-ins to org.eclipselabs.tapiji.*.
|
p
|
https://github.com/tapiji/tapiji
|
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/.project b/at.ac.tuwien.inso.eclipse.tapiji/.project
index ee2f93c2..1d440e98 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/.project
+++ b/at.ac.tuwien.inso.eclipse.tapiji/.project
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
- <name>at.ac.tuwien.inso.eclipse.tapiji</name>
+ <name>org.eclipselabs.tapiji.translator</name>
<comment></comment>
<projects>
</projects>
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/META-INF/MANIFEST.MF b/at.ac.tuwien.inso.eclipse.tapiji/META-INF/MANIFEST.MF
index 44605991..5013a625 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/META-INF/MANIFEST.MF
+++ b/at.ac.tuwien.inso.eclipse.tapiji/META-INF/MANIFEST.MF
@@ -1,9 +1,9 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: TapiJI Translator
-Bundle-SymbolicName: at.ac.tuwien.inso.eclipse.tapiji_translator;singleton:=true
+Bundle-SymbolicName: org.eclipselabs.tapiji.translator;singleton:=true
Bundle-Version: 0.0.1.qualifier
-Bundle-Activator: at.ac.tuwien.inso.eclipse.tapiji.Activator
+Bundle-Activator: org.eclipselabs.tapiji.translator.Activator
Require-Bundle: org.eclipse.ui,
org.eclipse.core.runtime,
org.eclipse.core.filesystem;bundle-version="1.3.0",
@@ -12,8 +12,8 @@ Require-Bundle: org.eclipse.ui,
org.eclipse.ui.ide;bundle-version="3.6.0",
org.junit,
com.essiembre.eclipse.i18n.resourcebundle;bundle-version="0.7.7",
- at.ac.tuwien.inso.eclipse.rbe;bundle-version="0.0.1"
+ org.eclipselabs.tapiji.translator.rbe;bundle-version="0.0.1"
Bundle-ActivationPolicy: lazy
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
-Import-Package: at.ac.tuwien.inso.eclipse.rbe.model.bundle
+Import-Package: org.eclipselabs.tapiji.translator.rbe.model.bundle
Bundle-Vendor: Vienna University of Technology
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_128.png b/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_128.png
deleted file mode 100644
index 98514e0e..00000000
Binary files a/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_128.png and /dev/null differ
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_16.png b/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_16.png
deleted file mode 100644
index 73b82c2f..00000000
Binary files a/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_16.png and /dev/null differ
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_32.png b/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_32.png
deleted file mode 100644
index 3984eba6..00000000
Binary files a/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_32.png and /dev/null differ
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_48.png b/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_48.png
deleted file mode 100644
index 190a92e4..00000000
Binary files a/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_48.png and /dev/null differ
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_64.png b/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_64.png
deleted file mode 100644
index 89988073..00000000
Binary files a/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_64.png and /dev/null differ
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/at.ac.tuwien.inso.eclipse.tapiji.product b/at.ac.tuwien.inso.eclipse.tapiji/org.eclipselabs.tapiji.translator.product
similarity index 94%
rename from at.ac.tuwien.inso.eclipse.tapiji/at.ac.tuwien.inso.eclipse.tapiji.product
rename to at.ac.tuwien.inso.eclipse.tapiji/org.eclipselabs.tapiji.translator.product
index 91649b60..1bc71ce1 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/at.ac.tuwien.inso.eclipse.tapiji.product
+++ b/at.ac.tuwien.inso.eclipse.tapiji/org.eclipselabs.tapiji.translator.product
@@ -1,10 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<?pde version="3.5"?>
-<product name="TapiJI Translator" uid="at.ac.tuwien.inso.eclipse.tapiji.product" id="at.ac.tuwien.inso.eclipse.tapiji_translator.product1" application="at.ac.tuwien.inso.eclipse.tapiji_translator.application" version="0.0.1" useFeatures="false" includeLaunchers="true">
+<product name="TapiJI Translator" uid="org.eclipselabs.tapiji.translator.product" id="org.eclipselabs.tapiji.translator.app" application="org.eclipselabs.tapiji.translator.application" version="0.0.1" useFeatures="false" includeLaunchers="true">
<aboutInfo>
- <image path="icons/TapiJI_128.png"/>
+ <image path="/org.eclipselabs.tapiji.translator/icons/TapiJI_128.png"/>
<text>
TapiJI - Translator
Version 1.0.0
@@ -19,7 +19,7 @@ by Stefan Strobl & Martin Reiterer
<vmArgsMac>-XstartOnFirstThread -Dorg.eclipse.swt.internal.carbon.smallFonts</vmArgsMac>
</launcherArgs>
- <windowImages i16="icons/TapiJI_16.png" i32="icons/TapiJI_32.png" i48="icons/TapiJI_48.png" i64="icons/TapiJI_64.png" i128="icons/TapiJI_128.png"/>
+ <windowImages i16="/org.eclipselabs.tapiji.translator/icons/TapiJI_16.png" i32="/org.eclipselabs.tapiji.translator/icons/TapiJI_32.png" i48="/org.eclipselabs.tapiji.translator/icons/TapiJI_48.png" i64="/org.eclipselabs.tapiji.translator/icons/TapiJI_64.png" i128="/org.eclipselabs.tapiji.translator/icons/TapiJI_128.png"/>
<license>
@@ -225,8 +225,6 @@ litigation.
</license>
<plugins>
- <plugin id="at.ac.tuwien.inso.eclipse.rbe"/>
- <plugin id="at.ac.tuwien.inso.eclipse.tapiji_translator"/>
<plugin id="com.essiembre.eclipse.i18n.resourcebundle"/>
<plugin id="com.ibm.icu"/>
<plugin id="org.eclipse.compare.core"/>
@@ -278,6 +276,8 @@ litigation.
<plugin id="org.eclipse.ui.win32" fragment="true"/>
<plugin id="org.eclipse.ui.workbench"/>
<plugin id="org.eclipse.ui.workbench.texteditor"/>
+ <plugin id="org.eclipselabs.tapiji.translator"/>
+ <plugin id="org.eclipselabs.tapiji.translator.rbe"/>
<plugin id="org.hamcrest.core"/>
<plugin id="org.junit"/>
</plugins>
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/plugin.xml b/at.ac.tuwien.inso.eclipse.tapiji/plugin.xml
index fe153031..d8683498 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/plugin.xml
+++ b/at.ac.tuwien.inso.eclipse.tapiji/plugin.xml
@@ -7,7 +7,7 @@
point="org.eclipse.core.runtime.applications">
<application>
<run
- class="at.ac.tuwien.inso.eclipse.tapiji.Application">
+ class="org.eclipselabs.tapiji.translator.Application">
</run>
</application>
</extension>
@@ -15,8 +15,8 @@
point="org.eclipse.ui.perspectives">
<perspective
name="Perspective"
- class="at.ac.tuwien.inso.eclipse.tapiji.Perspective"
- id="at.ac.tuwien.inso.eclipse.tapiji.perspective">
+ class="org.eclipselabs.tapiji.translator.Perspective"
+ id="org.eclipselabs.tapiji.translator.perspective">
</perspective>
</extension>
<extension
@@ -29,11 +29,11 @@
id="product"
point="org.eclipse.core.runtime.products">
<product
- application="at.ac.tuwien.inso.eclipse.tapiji.application"
+ application="org.eclipselabs.tapiji.application"
name="TapiJI Translator">
<property
name="windowImages"
- value="platform:/plugin/at.ac.tuwien.inso.eclipse.i18n/icons/TapiJI_16.png,platform:/plugin/at.ac.tuwien.inso.eclipse.i18n/icons/TapiJI_32.png,platform:/plugin/at.ac.tuwien.inso.eclipse.i18n/icons/TapiJI_48.png,platform:/plugin/at.ac.tuwien.inso.eclipse.i18n/icons/TapiJI_64.png,platform:/plugin/at.ac.tuwien.inso.eclipse.i18n/icons/TapiJI_128.png">
+ value="platform:/plugin/org.eclipselabs.tapiji.tools.core/icons/TapiJI_16.png,platform:/plugin/at.ac.tuwien.inso.eclipse.i18n/icons/TapiJI_32.png,platform:/plugin/org.eclipselabs.tapiji.tools.core/icons/TapiJI_48.png,platform:/plugin/org.eclipselabs.tapiji.tools.core/icons/TapiJI_64.png,platform:/plugin/org.eclipselabs.tapiji.tools.core/icons/TapiJI_128.png">
</property>
<property
name="appName"
@@ -41,7 +41,7 @@
</property>
<property
name="aboutImage"
- value="platform:/plugin/at.ac.tuwien.inso.eclipse.i18n/icons/TapiJI_128.png">
+ value="platform:/plugin/org.eclipselabs.tapiji.tools.core/icons/TapiJI_128.png">
</property>
<property
name="aboutText"
@@ -58,22 +58,22 @@
<command
categoryId="org.eclipse.ui.category.file"
description="Open Resource-Bundle ..."
- id="at.ac.tuwien.inso.eclipse.tapiji.Translator.fileOpen"
+ id="org.eclipselabs.tapiji.translator.fileOpen"
name="FileOpen">
</command>
<command
- id="at.ac.tuwien.inso.eclipse.tapiji.Translator.fileOpenGlossary"
+ id="org.eclipselabs.tapiji.translator.fileOpenGlossary"
name="Open Glossary ...">
</command>
<command
- id="at.ac.tuwien.inso.eclipse.tapiji.Translator.fileNewGlossary"
+ id="org.eclipselabs.tapiji.translator.fileNewGlossary"
name="New Glossary ...">
</command>
</extension>
<extension
point="org.eclipse.ui.bindings">
<key
- commandId="at.ac.tuwien.inso.eclipse.tapiji.Translator.fileOpen"
+ commandId="org.eclipselabs.tapiji.translator.fileOpen"
contextId="org.eclipse.ui.contexts.window"
schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
sequence="M1+O">
@@ -90,10 +90,10 @@
<actionSet
label="File Action Set"
visible="true"
- id="at.ac.tuwien.inso.eclipse.tapiji.translator.fileActionSet">
+ id="org.eclipselabs.tapiji.translator.fileActionSet">
<action
- class="at.ac.tuwien.inso.eclipse.tapiji.actions.OpenGlossaryAction"
- definitionId="at.ac.tuwien.inso.eclipse.tapiji.Translator.fileOpenGlossary"
+ class="org.eclipselabs.tapiji.translator.actions.OpenGlossaryAction"
+ definitionId="org.eclipselabs.tapiji.translator.fileOpenGlossary"
icon="icons/OpenGlossary5.png"
id="OpenGlossaryAction"
label="Open Glossary ..."
@@ -104,8 +104,8 @@
tooltip="Opens a Glossary definition">
</action>
<action
- class="at.ac.tuwien.inso.eclipse.tapiji.actions.NewGlossaryAction"
- definitionId="at.ac.tuwien.inso.eclipse.tapiji.Translator.fileNewGlossary"
+ class="org.eclipselabs.tapiji.translator.actions.NewGlossaryAction"
+ definitionId="org.eclipselabs.tapiji.translator.fileNewGlossary"
icon="icons/NewGlossary.png"
id="NewGlossaryAction"
label="New Glossary ..."
@@ -116,8 +116,8 @@
tooltip="Creates a new Glossary file">
</action>
<action
- class="at.ac.tuwien.inso.eclipse.tapiji.actions.FileOpenAction"
- definitionId="at.ac.tuwien.inso.eclipse.tapiji.Translator.fileOpen"
+ class="org.eclipselabs.tapiji.translator.actions.FileOpenAction"
+ definitionId="org.eclipselabs.tapiji.translator.fileOpen"
icon="icons/OpenRB.png"
id="FileOpenAction"
label="Open Resource-Bundle ..."
@@ -132,87 +132,35 @@
<extension
point="org.eclipse.ui.views">
<category
- id="at.ac.tuwien.inso.eclipse.tapiji.glossary"
+ id="org.eclipselabs.tapiji.translator.glossary"
name="Internationalization">
</category>
<view
- category="at.ac.tuwien.inso.eclipse.tapiji.glossary"
- class="at.ac.tuwien.inso.eclipse.tapiji.views.GlossaryView"
+ category="org.eclipselabs.tapiji.translator.glossary"
+ class="org.eclipselabs.tapiji.translator.views.GlossaryView"
icon="icons/sample.gif"
- id="at.ac.tuwien.inso.eclipse.tapiji.views.GlossaryView"
+ id="org.eclipselabs.tapiji.translator.views.GlossaryView"
name="Glossary">
</view>
</extension>
<extension
- id="tapiji_translator"
+ id="app"
point="org.eclipse.core.runtime.products">
<product
- application="at.ac.tuwien.inso.eclipse.tapiji_translator.application"
+ application="org.eclipselabs.tapiji.translator.application"
name="TapiJI Translator">
<property
name="windowImages"
- value="platform:/plugin/at.ac.tuwien.inso.eclipse.i18n/icons/TapiJI_16.png,platform:/plugin/at.ac.tuwien.inso.eclipse.i18n/icons/TapiJI_32.png,platform:/plugin/at.ac.tuwien.inso.eclipse.i18n/icons/TapiJI_48.png,platform:/plugin/at.ac.tuwien.inso.eclipse.i18n/icons/TapiJI_64.png,platform:/plugin/at.ac.tuwien.inso.eclipse.i18n/icons/TapiJI_128.png">
- </property>
- <property
- name="aboutText"
- value="TapiJI - Translator 
Version 1.0.0
by Stefan Strobl & Martin Reiterer">
- </property>
- <property
- name="aboutImage"
- value="platform:/plugin/at.ac.tuwien.inso.eclipse.i18n/icons/TapiJI_128.png">
- </property>
- <property
- name="appName"
- value="TapiJI Translator">
- </property>
- </product>
- </extension>
- <extension
- id="application"
- point="org.eclipse.core.runtime.products">
- <product
- application="at.ac.tuwien.inso.eclipse.deploy.application"
- name="TapiJI Translator">
- <property
- name="windowImages"
- value="platform:/plugin/at.ac.tuwien.inso.eclipse.i18n/icons/TapiJI_16.png,platform:/plugin/at.ac.tuwien.inso.eclipse.i18n/icons/TapiJI_32.png,platform:/plugin/at.ac.tuwien.inso.eclipse.i18n/icons/TapiJI_48.png,platform:/plugin/at.ac.tuwien.inso.eclipse.i18n/icons/TapiJI_64.png,platform:/plugin/at.ac.tuwien.inso.eclipse.i18n/icons/TapiJI_128.png">
+ value="icons/TapiJI_16.png,icons/TapiJI_32.png,icons/TapiJI_48.png,icons/TapiJI_64.png,icons/TapiJI_128.png">
</property>
<property
name="aboutText"
value="TapiJI - Translator 
Version 1.0.0
by Stefan Strobl & Martin Reiterer">
</property>
- <property
- name="aboutImage"
- value="platform:/plugin/at.ac.tuwien.inso.eclipse.i18n/icons/TapiJI_128.png">
- </property>
- <property
- name="appName"
- value="TapiJI Translator">
- </property>
- </product>
- </extension>
- <extension
- id="product1"
- point="org.eclipse.core.runtime.products">
- <product
- application="at.ac.tuwien.inso.eclipse.tapiji_translator.application"
- name="TapiJI Translator">
- <property
- name="appName"
- value="TapiJI Translator">
- </property>
<property
name="aboutImage"
value="icons/TapiJI_128.png">
</property>
- <property
- name="aboutText"
- value="TapiJI - Translator 
Version 1.0.0
by Stefan Strobl & Martin Reiterer">
- </property>
- <property
- name="windowImages"
- value="icons/TapiJI_16.png,icons/TapiJI_32.png,icons/TapiJI_48.png,icons/TapiJI_64.png,icons/TapiJI_128.png">
- </property>
</product>
- </extension>
+ </extension>
</plugin>
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/Activator.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/Activator.java
similarity index 86%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/Activator.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/Activator.java
index be4dcb1c..6689bdfe 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/Activator.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/Activator.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji;
+package org.eclipselabs.tapiji.translator;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
@@ -10,7 +10,7 @@
public class Activator extends AbstractUIPlugin {
// The plug-in ID
- public static final String PLUGIN_ID = "at.ac.tuwien.inso.eclipse.tapiji_translator"; //$NON-NLS-1$
+ public static final String PLUGIN_ID = "org.eclipselabs.tapiji.translator"; //$NON-NLS-1$
// The shared instance
private static Activator plugin;
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/Application.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/Application.java
similarity index 96%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/Application.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/Application.java
index 58f0615e..bd06d884 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/Application.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/Application.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji;
+package org.eclipselabs.tapiji.translator;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/ApplicationActionBarAdvisor.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/ApplicationActionBarAdvisor.java
similarity index 98%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/ApplicationActionBarAdvisor.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/ApplicationActionBarAdvisor.java
index 7e293524..bd96f8c5 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/ApplicationActionBarAdvisor.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/ApplicationActionBarAdvisor.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji;
+package org.eclipselabs.tapiji.translator;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/ApplicationWorkbenchAdvisor.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchAdvisor.java
similarity index 83%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/ApplicationWorkbenchAdvisor.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchAdvisor.java
index d0114011..666e751b 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/ApplicationWorkbenchAdvisor.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchAdvisor.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji;
+package org.eclipselabs.tapiji.translator;
import org.eclipse.ui.application.IWorkbenchConfigurer;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
@@ -7,7 +7,7 @@
public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor {
- private static final String PERSPECTIVE_ID = "at.ac.tuwien.inso.eclipse.tapiji.perspective";
+ private static final String PERSPECTIVE_ID = "org.eclipselabs.tapiji.translator.perspective";
public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(
IWorkbenchWindowConfigurer configurer) {
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/ApplicationWorkbenchWindowAdvisor.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchWindowAdvisor.java
similarity index 97%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/ApplicationWorkbenchWindowAdvisor.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchWindowAdvisor.java
index 2d6fda47..40b88788 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/ApplicationWorkbenchWindowAdvisor.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchWindowAdvisor.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji;
+package org.eclipselabs.tapiji.translator;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.SWT;
@@ -20,8 +20,8 @@
import org.eclipse.ui.application.WorkbenchWindowAdvisor;
import org.eclipse.ui.handlers.IHandlerService;
import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.eclipselabs.tapiji.translator.utils.FileUtils;
-import at.ac.tuwien.inso.eclipse.tapiji.utils.FileUtils;
public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/Perspective.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/Perspective.java
similarity index 83%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/Perspective.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/Perspective.java
index 49b9f9ec..d1fcd27a 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/Perspective.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/Perspective.java
@@ -1,9 +1,9 @@
-package at.ac.tuwien.inso.eclipse.tapiji;
+package org.eclipselabs.tapiji.translator;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
+import org.eclipselabs.tapiji.translator.views.GlossaryView;
-import at.ac.tuwien.inso.eclipse.tapiji.views.GlossaryView;
public class Perspective implements IPerspectiveFactory {
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/actions/FileOpenAction.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/actions/FileOpenAction.java
similarity index 90%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/actions/FileOpenAction.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/actions/FileOpenAction.java
index 9c427299..4bb6865c 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/actions/FileOpenAction.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/actions/FileOpenAction.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.actions;
+package org.eclipselabs.tapiji.translator.actions;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.action.Action;
@@ -10,8 +10,8 @@
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.part.FileEditorInput;
+import org.eclipselabs.tapiji.translator.utils.FileUtils;
-import at.ac.tuwien.inso.eclipse.tapiji.utils.FileUtils;
public class FileOpenAction extends Action implements IWorkbenchWindowActionDelegate {
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/actions/NewGlossaryAction.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/actions/NewGlossaryAction.java
similarity index 86%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/actions/NewGlossaryAction.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/actions/NewGlossaryAction.java
index 206da477..da1b88c6 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/actions/NewGlossaryAction.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/actions/NewGlossaryAction.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.actions;
+package org.eclipselabs.tapiji.translator.actions;
import java.io.File;
import java.text.MessageFormat;
@@ -12,9 +12,9 @@
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
+import org.eclipselabs.tapiji.translator.core.GlossaryManager;
+import org.eclipselabs.tapiji.translator.utils.FileUtils;
-import at.ac.tuwien.inso.eclipse.tapiji.core.GlossaryManager;
-import at.ac.tuwien.inso.eclipse.tapiji.utils.FileUtils;
public class NewGlossaryAction implements IWorkbenchWindowActionDelegate {
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/actions/OpenGlossaryAction.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/actions/OpenGlossaryAction.java
similarity index 84%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/actions/OpenGlossaryAction.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/actions/OpenGlossaryAction.java
index 280a8710..b2556c2c 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/actions/OpenGlossaryAction.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/actions/OpenGlossaryAction.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.actions;
+package org.eclipselabs.tapiji.translator.actions;
import java.io.File;
@@ -9,9 +9,9 @@
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
+import org.eclipselabs.tapiji.translator.core.GlossaryManager;
+import org.eclipselabs.tapiji.translator.utils.FileUtils;
-import at.ac.tuwien.inso.eclipse.tapiji.core.GlossaryManager;
-import at.ac.tuwien.inso.eclipse.tapiji.utils.FileUtils;
public class OpenGlossaryAction implements IWorkbenchWindowActionDelegate {
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/core/GlossaryManager.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/core/GlossaryManager.java
similarity index 92%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/core/GlossaryManager.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/core/GlossaryManager.java
index 3efce584..5ce5a885 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/core/GlossaryManager.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/core/GlossaryManager.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.core;
+package org.eclipselabs.tapiji.translator.core;
import java.io.BufferedOutputStream;
import java.io.File;
@@ -12,7 +12,8 @@
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Glossary;
+import org.eclipselabs.tapiji.translator.model.Glossary;
+
public class GlossaryManager {
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/core/ILoadGlossaryListener.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/core/ILoadGlossaryListener.java
similarity index 63%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/core/ILoadGlossaryListener.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/core/ILoadGlossaryListener.java
index 8a8fae4a..3d3a263f 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/core/ILoadGlossaryListener.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/core/ILoadGlossaryListener.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.core;
+package org.eclipselabs.tapiji.translator.core;
public interface ILoadGlossaryListener {
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/core/LoadGlossaryEvent.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/core/LoadGlossaryEvent.java
similarity index 86%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/core/LoadGlossaryEvent.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/core/LoadGlossaryEvent.java
index dc0acbbd..54bc3891 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/core/LoadGlossaryEvent.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/core/LoadGlossaryEvent.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.core;
+package org.eclipselabs.tapiji.translator.core;
import java.io.File;
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/model/Glossary.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/model/Glossary.java
similarity index 92%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/model/Glossary.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/model/Glossary.java
index 6fe3eecf..61607d56 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/model/Glossary.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/model/Glossary.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.model;
+package org.eclipselabs.tapiji.translator.model;
import java.io.Serializable;
import java.util.ArrayList;
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/model/Info.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/model/Info.java
similarity index 90%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/model/Info.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/model/Info.java
index dfdcda44..f7abdc18 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/model/Info.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/model/Info.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.model;
+package org.eclipselabs.tapiji.translator.model;
import java.io.Serializable;
import java.util.ArrayList;
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/model/Term.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/model/Term.java
similarity index 93%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/model/Term.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/model/Term.java
index 92c59c51..26bef6e2 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/model/Term.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/model/Term.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.model;
+package org.eclipselabs.tapiji.translator.model;
import java.io.Serializable;
import java.util.ArrayList;
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/model/Translation.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/model/Translation.java
similarity index 86%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/model/Translation.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/model/Translation.java
index 86a46f8c..624b5066 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/model/Translation.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/model/Translation.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.model;
+package org.eclipselabs.tapiji.translator.model;
import java.io.Serializable;
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/tests/JaxBTest.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/tests/JaxBTest.java
similarity index 88%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/tests/JaxBTest.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/tests/JaxBTest.java
index 3e8006fa..57872066 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/tests/JaxBTest.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/tests/JaxBTest.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.tests;
+package org.eclipselabs.tapiji.translator.tests;
import java.io.File;
import java.io.FileWriter;
@@ -8,13 +8,13 @@
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
+import org.eclipselabs.tapiji.translator.model.Glossary;
+import org.eclipselabs.tapiji.translator.model.Info;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.model.Translation;
import org.junit.Assert;
import org.junit.Test;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Glossary;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Info;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Term;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Translation;
public class JaxBTest {
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/utils/FileUtils.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/utils/FileUtils.java
similarity index 95%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/utils/FileUtils.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/utils/FileUtils.java
index 13b92146..059c1bdf 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/utils/FileUtils.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/utils/FileUtils.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.utils;
+package org.eclipselabs.tapiji.translator.utils;
import java.io.File;
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/utils/FontUtils.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/utils/FontUtils.java
similarity index 93%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/utils/FontUtils.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/utils/FontUtils.java
index 7e7923ed..92764ce8 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/utils/FontUtils.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/utils/FontUtils.java
@@ -1,12 +1,12 @@
-package at.ac.tuwien.inso.eclipse.tapiji.utils;
+package org.eclipselabs.tapiji.translator.utils;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
+import org.eclipselabs.tapiji.translator.Activator;
-import at.ac.tuwien.inso.eclipse.tapiji.Activator;
public class FontUtils {
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/GlossaryView.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/GlossaryView.java
similarity index 96%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/GlossaryView.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/GlossaryView.java
index ca92966e..793a9913 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/GlossaryView.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/GlossaryView.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.views;
+package org.eclipselabs.tapiji.translator.views;
import java.io.File;
@@ -33,24 +33,24 @@
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.dialogs.ListSelectionDialog;
import org.eclipse.ui.part.ViewPart;
+import org.eclipselabs.tapiji.translator.core.GlossaryManager;
+import org.eclipselabs.tapiji.translator.core.ILoadGlossaryListener;
+import org.eclipselabs.tapiji.translator.core.LoadGlossaryEvent;
+import org.eclipselabs.tapiji.translator.model.Glossary;
+import org.eclipselabs.tapiji.translator.views.dialog.LocaleContentProvider;
+import org.eclipselabs.tapiji.translator.views.dialog.LocaleLabelProvider;
+import org.eclipselabs.tapiji.translator.views.menus.GlossaryEntryMenuContribution;
+import org.eclipselabs.tapiji.translator.views.widgets.GlossaryWidget;
+import org.eclipselabs.tapiji.translator.views.widgets.model.GlossaryViewState;
+import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryLabelProvider;
-import at.ac.tuwien.inso.eclipse.tapiji.core.GlossaryManager;
-import at.ac.tuwien.inso.eclipse.tapiji.core.ILoadGlossaryListener;
-import at.ac.tuwien.inso.eclipse.tapiji.core.LoadGlossaryEvent;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Glossary;
-import at.ac.tuwien.inso.eclipse.tapiji.views.dialog.LocaleContentProvider;
-import at.ac.tuwien.inso.eclipse.tapiji.views.dialog.LocaleLabelProvider;
-import at.ac.tuwien.inso.eclipse.tapiji.views.menus.GlossaryEntryMenuContribution;
-import at.ac.tuwien.inso.eclipse.tapiji.views.widgets.GlossaryWidget;
-import at.ac.tuwien.inso.eclipse.tapiji.views.widgets.model.GlossaryViewState;
-import at.ac.tuwien.inso.eclipse.tapiji.views.widgets.provider.GlossaryLabelProvider;
public class GlossaryView extends ViewPart implements ILoadGlossaryListener {
/**
* The ID of the view as specified by the extension.
*/
- public static final String ID = "at.ac.tuwien.inso.eclipse.tapiji.views.GlossaryView";
+ public static final String ID = "org.eclipselabs.tapiji.translator.views.GlossaryView";
/*** Primary view controls ***/
private GlossaryWidget treeViewer;
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/dialog/LocaleContentProvider.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleContentProvider.java
similarity index 87%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/dialog/LocaleContentProvider.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleContentProvider.java
index 702b4098..cd0a4536 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/dialog/LocaleContentProvider.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleContentProvider.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.views.dialog;
+package org.eclipselabs.tapiji.translator.views.dialog;
import java.util.List;
import java.util.Locale;
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/dialog/LocaleLabelProvider.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleLabelProvider.java
similarity index 89%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/dialog/LocaleLabelProvider.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleLabelProvider.java
index 12549e77..6ba650a1 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/dialog/LocaleLabelProvider.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleLabelProvider.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.views.dialog;
+package org.eclipselabs.tapiji.translator.views.dialog;
import java.util.Locale;
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/menus/GlossaryEntryMenuContribution.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/menus/GlossaryEntryMenuContribution.java
similarity index 91%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/menus/GlossaryEntryMenuContribution.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/menus/GlossaryEntryMenuContribution.java
index ec7a45ec..658ce20a 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/menus/GlossaryEntryMenuContribution.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/menus/GlossaryEntryMenuContribution.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.views.menus;
+package org.eclipselabs.tapiji.translator.views.menus;
import org.eclipse.jface.action.ContributionItem;
import org.eclipse.jface.viewers.ISelectionChangedListener;
@@ -10,8 +10,8 @@
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
+import org.eclipselabs.tapiji.translator.views.widgets.GlossaryWidget;
-import at.ac.tuwien.inso.eclipse.tapiji.views.widgets.GlossaryWidget;
public class GlossaryEntryMenuContribution extends ContributionItem implements
ISelectionChangedListener {
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/GlossaryWidget.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/GlossaryWidget.java
similarity index 90%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/GlossaryWidget.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/GlossaryWidget.java
index c66b10ab..1007d266 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/GlossaryWidget.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/GlossaryWidget.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.views.widgets;
+package org.eclipselabs.tapiji.translator.views.widgets;
import java.awt.ComponentOrientation;
import java.util.ArrayList;
@@ -39,21 +39,21 @@
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.ui.IWorkbenchPartSite;
+import org.eclipselabs.tapiji.translator.core.GlossaryManager;
+import org.eclipselabs.tapiji.translator.model.Glossary;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.model.Translation;
+import org.eclipselabs.tapiji.translator.views.widgets.dnd.GlossaryDragSource;
+import org.eclipselabs.tapiji.translator.views.widgets.dnd.GlossaryDropTarget;
+import org.eclipselabs.tapiji.translator.views.widgets.dnd.TermTransfer;
+import org.eclipselabs.tapiji.translator.views.widgets.filter.ExactMatcher;
+import org.eclipselabs.tapiji.translator.views.widgets.filter.FuzzyMatcher;
+import org.eclipselabs.tapiji.translator.views.widgets.filter.SelectiveMatcher;
+import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryContentProvider;
+import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryLabelProvider;
+import org.eclipselabs.tapiji.translator.views.widgets.sorter.GlossaryEntrySorter;
+import org.eclipselabs.tapiji.translator.views.widgets.sorter.SortInfo;
-import at.ac.tuwien.inso.eclipse.tapiji.core.GlossaryManager;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Glossary;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Term;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Translation;
-import at.ac.tuwien.inso.eclipse.tapiji.views.widgets.dnd.GlossaryDragSource;
-import at.ac.tuwien.inso.eclipse.tapiji.views.widgets.dnd.GlossaryDropTarget;
-import at.ac.tuwien.inso.eclipse.tapiji.views.widgets.dnd.TermTransfer;
-import at.ac.tuwien.inso.eclipse.tapiji.views.widgets.filter.ExactMatcher;
-import at.ac.tuwien.inso.eclipse.tapiji.views.widgets.filter.FuzzyMatcher;
-import at.ac.tuwien.inso.eclipse.tapiji.views.widgets.filter.SelectiveMatcher;
-import at.ac.tuwien.inso.eclipse.tapiji.views.widgets.provider.GlossaryContentProvider;
-import at.ac.tuwien.inso.eclipse.tapiji.views.widgets.provider.GlossaryLabelProvider;
-import at.ac.tuwien.inso.eclipse.tapiji.views.widgets.sorter.GlossaryEntrySorter;
-import at.ac.tuwien.inso.eclipse.tapiji.views.widgets.sorter.SortInfo;
public class GlossaryWidget extends Composite implements IResourceChangeListener {
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/dnd/GlossaryDragSource.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDragSource.java
similarity index 79%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/dnd/GlossaryDragSource.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDragSource.java
index ef5c0bf8..9456837b 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/dnd/GlossaryDragSource.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDragSource.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.views.widgets.dnd;
+package org.eclipselabs.tapiji.translator.views.widgets.dnd;
import java.util.ArrayList;
import java.util.List;
@@ -7,11 +7,11 @@
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
+import org.eclipselabs.tapiji.translator.core.GlossaryManager;
+import org.eclipselabs.tapiji.translator.model.Glossary;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryContentProvider;
-import at.ac.tuwien.inso.eclipse.tapiji.core.GlossaryManager;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Glossary;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Term;
-import at.ac.tuwien.inso.eclipse.tapiji.views.widgets.provider.GlossaryContentProvider;
public class GlossaryDragSource implements DragSourceListener {
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/dnd/GlossaryDropTarget.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDropTarget.java
similarity index 82%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/dnd/GlossaryDropTarget.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDropTarget.java
index 24b44b2a..76f52fb0 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/dnd/GlossaryDropTarget.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDropTarget.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.views.widgets.dnd;
+package org.eclipselabs.tapiji.translator.views.widgets.dnd;
import org.eclipse.jface.util.LocalSelectionTransfer;
import org.eclipse.jface.viewers.TreeViewer;
@@ -6,11 +6,11 @@
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.widgets.TreeItem;
+import org.eclipselabs.tapiji.translator.core.GlossaryManager;
+import org.eclipselabs.tapiji.translator.model.Glossary;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryContentProvider;
-import at.ac.tuwien.inso.eclipse.tapiji.core.GlossaryManager;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Glossary;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Term;
-import at.ac.tuwien.inso.eclipse.tapiji.views.widgets.provider.GlossaryContentProvider;
public class GlossaryDropTarget extends DropTargetAdapter {
private final TreeViewer target;
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/dnd/TermTransfer.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/TermTransfer.java
similarity index 91%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/dnd/TermTransfer.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/TermTransfer.java
index e96f9016..aa723853 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/dnd/TermTransfer.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/TermTransfer.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.views.widgets.dnd;
+package org.eclipselabs.tapiji.translator.views.widgets.dnd;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -11,8 +11,8 @@
import org.eclipse.swt.dnd.ByteArrayTransfer;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.TransferData;
+import org.eclipselabs.tapiji.translator.model.Term;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Term;
public class TermTransfer extends ByteArrayTransfer {
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/filter/ExactMatcher.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/filter/ExactMatcher.java
similarity index 86%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/filter/ExactMatcher.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/filter/ExactMatcher.java
index e3c0060a..197aff7a 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/filter/ExactMatcher.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/filter/ExactMatcher.java
@@ -1,11 +1,11 @@
-package at.ac.tuwien.inso.eclipse.tapiji.views.widgets.filter;
+package org.eclipselabs.tapiji.translator.views.widgets.filter;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.model.Translation;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Term;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Translation;
public class ExactMatcher extends ViewerFilter {
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/filter/FilterInfo.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FilterInfo.java
similarity index 92%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/filter/FilterInfo.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FilterInfo.java
index c68959de..4d898905 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/filter/FilterInfo.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FilterInfo.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.views.widgets.filter;
+package org.eclipselabs.tapiji.translator.views.widgets.filter;
import java.util.ArrayList;
import java.util.HashMap;
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/filter/FuzzyMatcher.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java
similarity index 81%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/filter/FuzzyMatcher.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java
index 1e8e96b8..d912385d 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/filter/FuzzyMatcher.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java
@@ -1,11 +1,11 @@
-package at.ac.tuwien.inso.eclipse.tapiji.views.widgets.filter;
+package org.eclipselabs.tapiji.translator.views.widgets.filter;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.Viewer;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.model.Translation;
+import org.eclipselabs.tapiji.translator.rbe.model.analyze.ILevenshteinDistanceAnalyzer;
-import at.ac.tuwien.inso.eclipse.rbe.model.analyze.ILevenshteinDistanceAnalyzer;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Term;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Translation;
import com.essiembre.eclipse.rbe.api.AnalyzerFactory;
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/filter/SelectiveMatcher.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/filter/SelectiveMatcher.java
similarity index 86%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/filter/SelectiveMatcher.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/filter/SelectiveMatcher.java
index 7e1465c5..a2d2d7c9 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/filter/SelectiveMatcher.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/filter/SelectiveMatcher.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.views.widgets.filter;
+package org.eclipselabs.tapiji.translator.views.widgets.filter;
import java.util.Collection;
@@ -12,11 +12,11 @@
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.model.Translation;
+import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleEntry;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTreeItem;
-import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleEntry;
-import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTreeItem;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Term;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Translation;
import com.essiembre.eclipse.rbe.api.EditorUtil;
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/filter/StringMatcher.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/filter/StringMatcher.java
similarity index 96%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/filter/StringMatcher.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/filter/StringMatcher.java
index 8486eb9c..337d2c9b 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/filter/StringMatcher.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/filter/StringMatcher.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.views.widgets.filter;
+package org.eclipselabs.tapiji.translator.views.widgets.filter;
import java.util.Vector;
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/model/GlossaryViewState.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/model/GlossaryViewState.java
similarity index 94%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/model/GlossaryViewState.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/model/GlossaryViewState.java
index 21967b67..9280bd2d 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/model/GlossaryViewState.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/model/GlossaryViewState.java
@@ -1,12 +1,12 @@
-package at.ac.tuwien.inso.eclipse.tapiji.views.widgets.model;
+package org.eclipselabs.tapiji.translator.views.widgets.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.eclipse.ui.IMemento;
+import org.eclipselabs.tapiji.translator.views.widgets.sorter.SortInfo;
-import at.ac.tuwien.inso.eclipse.tapiji.views.widgets.sorter.SortInfo;
public class GlossaryViewState {
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/provider/GlossaryContentProvider.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryContentProvider.java
similarity index 87%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/provider/GlossaryContentProvider.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryContentProvider.java
index 917dc7e2..c36862fa 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/provider/GlossaryContentProvider.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryContentProvider.java
@@ -1,13 +1,13 @@
-package at.ac.tuwien.inso.eclipse.tapiji.views.widgets.provider;
+package org.eclipselabs.tapiji.translator.views.widgets.provider;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
+import org.eclipselabs.tapiji.translator.model.Glossary;
+import org.eclipselabs.tapiji.translator.model.Term;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Glossary;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Term;
public class GlossaryContentProvider implements ITreeContentProvider {
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/provider/GlossaryLabelProvider.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryLabelProvider.java
similarity index 88%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/provider/GlossaryLabelProvider.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryLabelProvider.java
index c20815ad..dafc30c0 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/provider/GlossaryLabelProvider.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryLabelProvider.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.views.widgets.provider;
+package org.eclipselabs.tapiji.translator.views.widgets.provider;
import java.util.ArrayList;
import java.util.Collection;
@@ -18,15 +18,15 @@
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.model.Translation;
+import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleEntry;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTreeItem;
+import org.eclipselabs.tapiji.translator.utils.FontUtils;
+import org.eclipselabs.tapiji.translator.views.widgets.filter.FilterInfo;
-import com.essiembre.eclipse.rbe.api.EditorUtil;
-import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleEntry;
-import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTreeItem;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Term;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Translation;
-import at.ac.tuwien.inso.eclipse.tapiji.utils.FontUtils;
-import at.ac.tuwien.inso.eclipse.tapiji.views.widgets.filter.FilterInfo;
+import com.essiembre.eclipse.rbe.api.EditorUtil;
public class GlossaryLabelProvider extends StyledCellLabelProvider implements
ISelectionListener, ISelectionChangedListener {
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/sorter/GlossaryEntrySorter.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/GlossaryEntrySorter.java
similarity index 89%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/sorter/GlossaryEntrySorter.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/GlossaryEntrySorter.java
index e204d9da..e8de6d4c 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/sorter/GlossaryEntrySorter.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/GlossaryEntrySorter.java
@@ -1,13 +1,13 @@
-package at.ac.tuwien.inso.eclipse.tapiji.views.widgets.sorter;
+package org.eclipselabs.tapiji.translator.views.widgets.sorter;
import java.util.List;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.model.Translation;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Term;
-import at.ac.tuwien.inso.eclipse.tapiji.model.Translation;
public class GlossaryEntrySorter extends ViewerSorter {
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/sorter/SortInfo.java b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/SortInfo.java
similarity index 90%
rename from at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/sorter/SortInfo.java
rename to at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/SortInfo.java
index 8e12ff8e..a5f8e99e 100644
--- a/at.ac.tuwien.inso.eclipse.tapiji/src/at/ac/tuwien/inso/eclipse/tapiji/views/widgets/sorter/SortInfo.java
+++ b/at.ac.tuwien.inso.eclipse.tapiji/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/SortInfo.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.tapiji.views.widgets.sorter;
+package org.eclipselabs.tapiji.translator.views.widgets.sorter;
import java.util.List;
import java.util.Locale;
|
8456536126f631d665ffd715dca9ae981588632e
|
intellij-community
|
correctly-sized icon in completion extender--
|
c
|
https://github.com/JetBrains/intellij-community
|
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/CompletionExtender.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/CompletionExtender.java
index 9b27fb7ef9fa1..9fffaf934164d 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/CompletionExtender.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/CompletionExtender.java
@@ -64,8 +64,7 @@ public boolean sameAsFor(LookupElement item) {
}
private static JComponent createComponent(LookupElement element, LookupImpl lookup) {
- final LookupCellRenderer renderer = new LookupCellRenderer(lookup);
- renderer.setFullSize(true);
+ final LookupCellRenderer renderer = ((LookupCellRenderer)lookup.getList().getCellRenderer()).createExtenderRenderer();
final JComponent component = (JComponent)renderer.getListCellRendererComponent(lookup.getList(), element,
lookup.getList().getSelectedIndex(),
true, false);
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupCellRenderer.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupCellRenderer.java
index c1381a5700485..0a5e258a0c146 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupCellRenderer.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupCellRenderer.java
@@ -62,8 +62,6 @@ public class LookupCellRenderer implements ListCellRenderer {
private static final Color EMPTY_ITEM_FOREGROUND_COLOR = FOREGROUND_COLOR;
- private static final int MAX_LENGTH = 70;
-
private final LookupImpl myLookup;
private final SimpleColoredComponent myNameComponent;
@@ -71,12 +69,13 @@ public class LookupCellRenderer implements ListCellRenderer {
private final SimpleColoredComponent myTypeLabel;
private final JPanel myPanel;
- public static final Color PREFERRED_BACKGROUND_COLOR = new Color(220, 245, 220);
private static final String ELLIPSIS = "\u2026";
- private boolean myFullSize;
+ private final boolean myFullSize;
private int myMaxWidth = -1;
- public LookupCellRenderer(LookupImpl lookup) {
+ public LookupCellRenderer(LookupImpl lookup, boolean fullSize) {
+ myFullSize = fullSize;
+
EditorColorsScheme scheme = lookup.getEditor().getColorsScheme();
myNormalFont = scheme.getFont(EditorFontType.PLAIN);
myBoldFont = scheme.getFont(EditorFontType.BOLD);
@@ -121,7 +120,7 @@ public Component getListCellRendererComponent(
final LookupElement item = (LookupElement)value;
final Color foreground = isSelected ? SELECTED_FOREGROUND_COLOR : FOREGROUND_COLOR;
- final Color background = getItemBackground(list, index, isSelected);
+ final Color background = isSelected ? SELECTED_BACKGROUND_COLOR : BACKGROUND_COLOR;
int allowedWidth = list.getWidth() - AFTER_TAIL - AFTER_TYPE - getIconIndent();
final LookupElementPresentation presentation = new RealLookupElementPresentation(myFullSize ? getMaxWidth() : allowedWidth, myNormalMetrics, myBoldMetrics, myLookup);
@@ -160,10 +159,6 @@ private int getMaxWidth() {
return myMaxWidth;
}
- private Color getItemBackground(JList list, int index, boolean isSelected) {
- return isSelected ? SELECTED_BACKGROUND_COLOR : BACKGROUND_COLOR;
- }
-
private void setTailTextLabel(boolean isSelected, LookupElementPresentation presentation, Color foreground, int allowedWidth) {
final Color fg = getTailTextColor(isSelected, presentation, foreground);
@@ -182,10 +177,6 @@ private void setTailTextLabel(boolean isSelected, LookupElementPresentation pres
myTailComponent.append(trimLabelText(tailText, allowedWidth, myNormalMetrics), attributes);
}
- public void setFullSize(boolean fullSize) {
- myFullSize = fullSize;
- }
-
private static String trimLabelText(@Nullable String text, int maxWidth, FontMetrics metrics) {
if (text == null || StringUtil.isEmpty(text)) {
return "";
@@ -335,6 +326,12 @@ public int updateMaximumWidth(final LookupElementPresentation p) {
return RealLookupElementPresentation.calculateWidth(p, myNormalMetrics, myBoldMetrics) + AFTER_TAIL + AFTER_TYPE;
}
+ public LookupCellRenderer createExtenderRenderer() {
+ LookupCellRenderer renderer = new LookupCellRenderer(myLookup, true);
+ renderer.myEmptyIcon = myEmptyIcon;
+ return renderer;
+ }
+
public int getIconIndent() {
return myNameComponent.getIconTextGap() + myEmptyIcon.getIconWidth();
}
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java
index 9534a81cf2b42..c4ce0492a960d 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java
@@ -161,7 +161,7 @@ public LookupImpl(Project project, Editor editor, @NotNull LookupArranger arrang
myPresentableArranger = arranger;
myIconPanel.setVisible(false);
- myCellRenderer = new LookupCellRenderer(this);
+ myCellRenderer = new LookupCellRenderer(this, false);
myList.setCellRenderer(myCellRenderer);
myList.setFocusable(false);
|
53b3787e247759a4711bd3ebe8968b830f27711a
|
Delta Spike
|
DELTAPIKE-277 first warp test for JsfMessage
|
p
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/message/JsfMessageTest.java b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/message/JsfMessageTest.java
index ed1849c30..c01ff4d7d 100644
--- a/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/message/JsfMessageTest.java
+++ b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/message/JsfMessageTest.java
@@ -22,7 +22,7 @@
import java.net.URL;
import org.apache.deltaspike.test.category.WebProfileCategory;
-import org.apache.deltaspike.test.jsf.impl.scope.view.beans.BackingBean;
+import org.apache.deltaspike.test.jsf.impl.message.beans.JsfMessageBackingBean;
import org.apache.deltaspike.test.jsf.impl.util.ArchiveUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
@@ -33,14 +33,10 @@
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
-import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
-import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.WebElement;
-import org.openqa.selenium.support.ui.ExpectedConditions;
/**
@@ -62,7 +58,8 @@ public static WebArchive deploy()
{
return ShrinkWrap
.create(WebArchive.class, "jsfMessageTest.war")
- .addPackage(BackingBean.class.getPackage())
+ .addPackage(JsfMessageBackingBean.class.getPackage())
+ .addAsResource("jsfMessageTest/UserMessage.properties")
.addAsLibraries(ArchiveUtils.getDeltaSpikeCoreAndJsfArchive())
.addAsWebInfResource("default/WEB-INF/web.xml", "web.xml")
.addAsWebResource("jsfMessageTest/page.xhtml", "page.xhtml")
@@ -76,6 +73,9 @@ public void testViewScopedContext() throws Exception
{
driver.get(new URL(contextPath, "page.xhtml").toString());
+ //X TODO remove, it's just for debugging the server side:
+ //X Thread.sleep(600000L);
+
/*X
WebElement inputField = driver.findElement(By.id("test:valueInput"));
inputField.sendKeys("23");
diff --git a/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/message/beans/JsfMessageBackingBean.java b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/message/beans/JsfMessageBackingBean.java
new file mode 100644
index 000000000..085591f67
--- /dev/null
+++ b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/message/beans/JsfMessageBackingBean.java
@@ -0,0 +1,53 @@
+/*
+* 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.deltaspike.test.jsf.impl.message.beans;
+
+import javax.annotation.PostConstruct;
+import javax.enterprise.context.RequestScoped;
+import javax.faces.bean.ViewScoped;
+import javax.inject.Inject;
+import javax.inject.Named;
+import java.io.Serializable;
+
+import org.apache.deltaspike.jsf.message.JsfMessage;
+
+/**
+ * sample backing bean for JsfMessage.
+ */
+@RequestScoped
+@Named
+public class JsfMessageBackingBean
+{
+ @Inject
+ private JsfMessage<UserMessage> msg;
+
+
+ public void init()
+ {
+ msg.addWarn().messageWithDetail("warnInfo");
+ msg.addError().messageWithoutDetail("errorInfo");
+ msg.addInfo().simpleMessageNoParam();
+ msg.addFatal().simpleMessageWithParam("fatalInfo");
+ }
+
+ public String getSomeMessage()
+ {
+ return msg.get().simpleMessageNoParam();
+ }
+}
diff --git a/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/message/beans/UserMessage.java b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/message/beans/UserMessage.java
new file mode 100644
index 000000000..f4fd92588
--- /dev/null
+++ b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/message/beans/UserMessage.java
@@ -0,0 +1,38 @@
+/*
+ * 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.deltaspike.test.jsf.impl.message.beans;
+
+import org.apache.deltaspike.core.api.message.Message;
+import org.apache.deltaspike.core.api.message.MessageContext;
+import org.apache.deltaspike.core.api.message.annotation.MessageBundle;
+import org.apache.deltaspike.core.api.message.annotation.MessageContextConfig;
+import org.apache.deltaspike.core.api.message.annotation.MessageTemplate;
+
+@MessageBundle
+@MessageContextConfig(messageSource = "jsfMessageTest.UserMessage")
+public interface UserMessage
+{
+ Message messageWithDetail(String param);
+
+ Message messageWithoutDetail(String param);
+
+ String simpleMessageWithParam(String param);
+
+ String simpleMessageNoParam();
+}
diff --git a/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/view/ViewScopedContextTest.java b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/view/ViewScopedContextTest.java
index 1fb578fc2..6a398307b 100644
--- a/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/view/ViewScopedContextTest.java
+++ b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/view/ViewScopedContextTest.java
@@ -21,7 +21,7 @@
import java.net.URL;
-import org.apache.deltaspike.test.jsf.impl.scope.view.beans.BackingBean;
+import org.apache.deltaspike.test.jsf.impl.scope.view.beans.ViewScopedBackingBean;
import org.apache.deltaspike.test.jsf.impl.util.ArchiveUtils;
import org.apache.deltaspike.test.category.WebProfileCategory;
import org.jboss.arquillian.container.test.api.Deployment;
@@ -63,7 +63,7 @@ public static WebArchive deploy()
{
return ShrinkWrap
.create(WebArchive.class, "viewScopedContextTest.war")
- .addPackage(BackingBean.class.getPackage())
+ .addPackage(ViewScopedBackingBean.class.getPackage())
.addAsLibraries(ArchiveUtils.getDeltaSpikeCoreAndJsfArchive())
.addAsWebInfResource("default/WEB-INF/web.xml", "web.xml")
.addAsWebResource("viewScopedContextTest/page.xhtml", "page.xhtml")
diff --git a/deltaspike/modules/jsf/impl/src/test/resources/jsfMessageTest/UserMessage.properties b/deltaspike/modules/jsf/impl/src/test/resources/jsfMessageTest/UserMessage.properties
new file mode 100644
index 000000000..743b5f4b9
--- /dev/null
+++ b/deltaspike/modules/jsf/impl/src/test/resources/jsfMessageTest/UserMessage.properties
@@ -0,0 +1,8 @@
+messageWithDetail = message with details %s!
+messageWithDetail.detail = message with loooong and very specific details %s!
+
+messageWithoutDetail = message without detail but parameter %s.
+
+simpleMessageWithParam = simple message with a string param %s.
+
+simpleMessageNoParam = a simple message without a param.
diff --git a/deltaspike/modules/jsf/impl/src/test/resources/jsfMessageTest/page.xhtml b/deltaspike/modules/jsf/impl/src/test/resources/jsfMessageTest/page.xhtml
index 0174237ac..1e21af2d0 100644
--- a/deltaspike/modules/jsf/impl/src/test/resources/jsfMessageTest/page.xhtml
+++ b/deltaspike/modules/jsf/impl/src/test/resources/jsfMessageTest/page.xhtml
@@ -21,19 +21,26 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
- >
+ xmlns:f="http://java.sun.com/jsf/core"
+ xmlns:ui="http://java.sun.com/jsf/facelets">
<body>
-<div>
+<f:view>
+ <f:metadata>
+ <f:event type="javax.faces.event.PreRenderViewEvent" listener="#{jsfMessageBackingBean.init}"/>
+ </f:metadata>
+ <div>
+
<h:form id="test">
- <h:outputLabel for="valueInput" value="ViewScoped value:"/>
- <h:inputText id="valueInput" value="#{viewScopedBean.i}"/>
+ <div id="messages">
+ <h:messages/>
+ </div>
<br/>
- <h:outputLabel for="valueOutput" value="backing bean value:"/>
- <h:outputText id="valueOutput" value="#{viewScopedBean.i}"/>
+ <h:outputLabel for="valueOutput" value="the message:"/>
+ <h:outputText id="valueOutput" value="#{jsfMessageBackingBean.someMessage}"/>
<br/>
- <h:commandButton id="saveButton" action="#{viewScopedBean.someAction}" value="save"/>
</h:form>
-</div>
+ </div>
+</f:view>
</body>
</html>
|
ead10c3f3e22fe313a0280ff524e639587151d3c
|
gitools$gitools
|
General clustering functionality modifications (performance, visualisation,...)
git-svn-id: https://bg.upf.edu/svn/gitools/trunk@865 1b512f91-3386-4a98-81e7-b8836ddf8916
|
p
|
https://github.com/gitools/gitools
|
diff --git a/gitools-core/src/main/java/org/gitools/analysis/clustering/ClusteringAnalysis.java b/gitools-core/src/main/java/org/gitools/analysis/clustering/ClusteringAnalysis.java
deleted file mode 100644
index 0f12eaa7..00000000
--- a/gitools-core/src/main/java/org/gitools/analysis/clustering/ClusteringAnalysis.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright 2010 xrafael.
- *
- * 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.
- * under the License.
- */
-
-package org.gitools.analysis.clustering;
-
-import java.util.Properties;
-import org.gitools.matrix.model.IMatrixView;
-
-
-public class ClusteringAnalysis {
-
- private String indexData;
-
- private boolean applyToRows;
-
- private boolean applyToColumns;
-
- private boolean applyToRowsColumns;
-
- private Properties params;
-
- private IMatrixView data;
-
- private ClusteringResult results;
-
- public ClusteringResult getResults() {
- return results;
- }
-
- public void setResults(ClusteringResult results) {
- this.results = results;
- }
-
- public boolean isApplyToRowsColumns() {
- return applyToRowsColumns;
- }
-
- public void setApplyToRowsColumns(boolean applyToRowsColumns) {
- this.applyToRowsColumns = applyToRowsColumns;
- }
-
- public IMatrixView getData() {
- return data;
- }
-
- public void setData(IMatrixView data) {
- this.data = data;
- }
-
- public boolean isApplyToColumns() {
- return applyToColumns;
- }
-
- public void setApplyToColumns(boolean applyToColumns) {
- this.applyToColumns = applyToColumns;
- }
-
- public boolean isApplyToRows() {
- return applyToRows;
- }
-
- public void setApplyToRows(boolean applyToRows) {
- this.applyToRows = applyToRows;
- }
-
- public String getIndexData() {
- return indexData;
- }
-
- public void setIndexData(String indexData) {
- this.indexData = indexData;
- }
-
- public Properties getParams() {
- return params;
- }
-
- public void setParams(Properties params) {
- this.params = params;
- }
-
-}
diff --git a/gitools-core/src/main/java/org/gitools/analysis/clustering/ClusteringProcessor.java b/gitools-core/src/main/java/org/gitools/analysis/clustering/ClusteringProcessor.java
deleted file mode 100644
index 7f37388c..00000000
--- a/gitools-core/src/main/java/org/gitools/analysis/clustering/ClusteringProcessor.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright 2010 xrafael.
- *
- * 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.
- * under the License.
- */
-
-package org.gitools.analysis.clustering;
-
-import edu.upf.bg.progressmonitor.IProgressMonitor;
-import org.gitools.analysis.AnalysisException;
-import org.gitools.analysis.clustering.methods.ClusteringMethodFactory;
-
-
-public class ClusteringProcessor {
-
- protected ClusteringAnalysis analysis;
-
- public ClusteringProcessor(ClusteringAnalysis analysis) {
- this.analysis = analysis;
- }
-
- public void run(IProgressMonitor monitor) throws AnalysisException, Exception {
-
- ClusteringMethod method = ClusteringMethodFactory.createMethod(analysis.getParams());
-
- if (analysis.isApplyToRows())
- method.buildAndCluster(analysis.getData(), "rows", monitor);
-
- if (analysis.isApplyToColumns())
- method.buildAndCluster(analysis.getData(), "cols", monitor);
- }
-
-
-}
diff --git a/gitools-core/src/main/java/org/gitools/analysis/clustering/ClusteringResult.java b/gitools-core/src/main/java/org/gitools/analysis/clustering/ClusteringResult.java
deleted file mode 100644
index cdfd7b98..00000000
--- a/gitools-core/src/main/java/org/gitools/analysis/clustering/ClusteringResult.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright 2010 xrafael.
- *
- * 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.
- * under the License.
- */
-
-package org.gitools.analysis.clustering;
-
-public class ClusteringResult {
-
- Integer[] resultList;
-
- public Integer[] getResultList() {
- return resultList;
- }
-
- public void setResultList(Integer[] resultList) {
- this.resultList = resultList;
- }
-
- public ClusteringResult(Integer[] resultList) {
- this.resultList = resultList;
- }
-
-
-}
diff --git a/gitools-core/src/main/java/org/gitools/analysis/clustering/methods/MatrixViewWekaLoader.java b/gitools-core/src/main/java/org/gitools/analysis/clustering/methods/MatrixViewWekaLoader.java
deleted file mode 100644
index b48aaff8..00000000
--- a/gitools-core/src/main/java/org/gitools/analysis/clustering/methods/MatrixViewWekaLoader.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Copyright 2010 xrafael.
- *
- * 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.
- * under the License.
- */
-
-package org.gitools.analysis.clustering.methods;
-
-import java.io.IOException;
-import org.gitools.matrix.MatrixUtils;
-import org.gitools.matrix.model.IMatrixView;
-import weka.core.Attribute;
-import weka.core.FastVector;
-import weka.core.Instance;
-import weka.core.Instances;
-import weka.core.converters.AbstractLoader;
-
-// FIXME This code is very inefficient !!! check getNextInstance and getStructure
-
-public class MatrixViewWekaLoader extends AbstractLoader {
-
- private IMatrixView matrixView;
-
- private String indexValueMatrix;
-
- //FIXME very inefficient, use integer or enum instead,
- // or better use inheritance properly
- // or even better use MatrixViewTransposed
- private String type;
-
- private int indexRows;
-
- private int indexCols;
-
-
- public MatrixViewWekaLoader(IMatrixView matrixView, String index, String type) {
-
- this.matrixView = matrixView;
-
- this.indexValueMatrix = index;
-
- this.type = type;
-
- indexRows = indexCols = -1;
-
- }
-
- // FIXME structure should be constructed ONCE in the constructor
- // and returned here whenever it is needed
- @Override
- public Instances getStructure() throws IOException {
-
- FastVector attribNames = new FastVector();
-
- Integer capacity = 0;
-
- String name = "matrix"+type;
-
- if (type.equals("cols"))
- {
- //Adding attributes (rows name)
- for (int rows = 0; rows < matrixView.getRowCount(); rows++)
-
- attribNames.addElement(new Attribute(matrixView.getRowLabel(rows)));
-
- }
- else{
- //Adding attributes (columns name)
-
- for (int cols = 0; cols < matrixView.getColumnCount(); cols++)
-
- attribNames.addElement(new Attribute(matrixView.getColumnLabel(cols)));
-
- }
-
- return new Instances(name, attribNames, capacity);
-
-
- }
-
- @Override
- public Instances getDataSet() throws IOException {
-
- Instances dataSet = getStructure();
-
- Instance current = null;
-
- Integer auxCols = indexCols, auxRows = indexRows;
-
- indexCols = -1;
- indexRows = -1;
-
- while ((current = getNextInstance(dataSet)) != null){
- dataSet.add(current);
- }
- indexCols = auxCols;
- indexRows = auxRows;
- return dataSet;
-
- }
-
-
- @Override
- //Param ds it is not modified nor altered
- public Instance getNextInstance(Instances ds) throws IOException
- {
-
- Instance current = null;
-
- if (type.equals("cols"))
- {
-
- current = new Instance(matrixView.getRowCount());
-
- if ((matrixView.getVisibleColumns().length < 1) || (indexCols >= matrixView.getVisibleColumns().length-1)) return null;
-
- indexCols++;
-
- for (int row = 0;row < current.numAttributes();row++)
- {
- current.setValue(row, MatrixUtils.doubleValue(
- matrixView.getCellValue(row,indexCols, indexValueMatrix)));
- }
-
- }
- else
- {
- current = new Instance(matrixView.getColumnCount());
-
- if ((matrixView.getVisibleRows().length < 1) || (indexRows >= matrixView.getVisibleRows().length-1)) return null;
-
- indexRows++;
-
- for (int col = 0;col < current.numAttributes();col++)
- {
- current.setValue(col, MatrixUtils.doubleValue(
- matrixView.getCellValue(indexRows, col, indexValueMatrix)));
- }
- }
-
- Instances dataset = getStructure();
- dataset.add(current);
- current.setDataset(dataset);
-
- return current;
- }
-
- @Override
- public String getRevision() {
-
- throw new UnsupportedOperationException("Not supported yet.");
-
- }
-}
diff --git a/gitools-core/src/main/java/org/gitools/analysis/clustering/methods/WekaCobWebMethod.java b/gitools-core/src/main/java/org/gitools/analysis/clustering/methods/WekaCobWebMethod.java
deleted file mode 100644
index aaeb6b32..00000000
--- a/gitools-core/src/main/java/org/gitools/analysis/clustering/methods/WekaCobWebMethod.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * Copyright 2010 xrafael.
- *
- * 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.
- * under the License.
- */
-
-package org.gitools.analysis.clustering.methods;
-
-import edu.upf.bg.progressmonitor.IProgressMonitor;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Properties;
-import org.gitools.analysis.AbstractMethod;
-import org.gitools.analysis.MethodException;
-import org.gitools.analysis.clustering.ClusteringMethod;
-import org.gitools.analysis.clustering.ClusteringResult;
-import org.gitools.matrix.model.IMatrixView;
-import weka.clusterers.Cobweb;
-import weka.core.Instance;
-import weka.core.Instances;
-
-public class WekaCobWebMethod extends AbstractMethod implements ClusteringMethod{
-
- public static final String ID = "cobweb";
-
- public WekaCobWebMethod(Properties properties) {
- super(ID,
- "CobWeb's clustering",
- "CobWeb's Weka clustering",
- ClusteringResult.class, properties);
- }
-
- //FIXME type shouldn't be an string
- @Override
- public void buildAndCluster(IMatrixView matrixView, String type, IProgressMonitor monitor) throws Exception, IOException, NumberFormatException {
-
- // FIXME valueIndex should be an integer !!!
- String valueIndex = properties.getProperty("index", "0");
- MatrixViewWekaLoader loader =
- new MatrixViewWekaLoader(matrixView, valueIndex, type);
-
- Instances structure = loader.getStructure();
-
- Cobweb clusterer = new Cobweb();
-
- // FIXME consider empty values using getProperty(key, defaultValue)
-
- clusterer.setAcuity(Float.valueOf(properties.getProperty("acuity")));
- clusterer.setCutoff(Float.valueOf(properties.getProperty("cutoff")));
- clusterer.setSeed(Integer.valueOf(properties.getProperty("seed")));
-
- clusterer.buildClusterer(structure);
-
- monitor.begin("Creating clustering model ...", structure.numInstances() + 1);
-
- Instance current;
-
- while ((current = loader.getNextInstance(structure)) != null
- && !monitor.isCancelled()) {
-
- clusterer.updateClusterer(current);
- monitor.worked(1);
- }
-
- clusterer.updateFinished();
-
- monitor.end();
-
- // Identificar el cluster de cada instancia
- Instances dataset = loader.getDataSet();
-
- monitor.begin("Classifying instances ...", dataset.numInstances());
-
- int cluster;
-
- //One cluster differnt instances
-
- HashMap<Integer, List<Integer>> clusterResults = new HashMap<Integer, List<Integer>>();
-
- for (int i=0; i < dataset.numInstances() && !monitor.isCancelled(); i++) {
-
- cluster = clusterer.clusterInstance(dataset.instance(i));
-
- List<Integer> instancesCluster = clusterResults.get(cluster);
- if (instancesCluster == null) {
- instancesCluster = new ArrayList<Integer>();
- clusterResults.put(cluster, instancesCluster);
- }
-
- instancesCluster.add(i);
-
- monitor.worked(1);
- }
-
- updateVisibility(type, matrixView, dataset.numInstances(), clusterResults);
-
- monitor.end();
- }
-
- private void updateVisibility(String type, IMatrixView matrixView, Integer numInstances, HashMap<Integer, List<Integer>> clusterResults) {
-
- int[] visibleData = null;
-
- if (type.equals("rows"))
- visibleData = matrixView.getVisibleRows();
- else
- visibleData = matrixView.getVisibleColumns();
-
- final int[] sortedVisibleData = new int[numInstances];
-
- int index = 0;
-
- //Integer[] clustersSorted = new Integer[clusterResults.keySet().size()];
- //clustersSorted = (Integer[]) clusterResults.keySet().toArray();
- Integer[] clustersSorted = (Integer[]) clusterResults.keySet().toArray(
- new Integer[clusterResults.keySet().size()]);
-
- Arrays.sort(clustersSorted);
-
- for (Integer i : clustersSorted)
- for( Integer val : clusterResults.get(i))
- sortedVisibleData[index++] = visibleData[val];
-
- if (type.equals("rows"))
- matrixView.setVisibleRows(sortedVisibleData);
- else
- matrixView.setVisibleColumns(sortedVisibleData);
-
- }
-
- @Override
- public String getId() {
- return ID;
- }
-
-
- @Override
- public void build(IMatrixView matrixView, String type, IProgressMonitor monitor) throws MethodException {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public ClusteringResult cluster() throws MethodException {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
-
-
-
-}
diff --git a/gitools-core/src/main/java/org/gitools/analysis/clustering/ClusteringMethod.java b/gitools-core/src/main/java/org/gitools/matrix/clustering/ClusteringMethod.java
similarity index 69%
rename from gitools-core/src/main/java/org/gitools/analysis/clustering/ClusteringMethod.java
rename to gitools-core/src/main/java/org/gitools/matrix/clustering/ClusteringMethod.java
index 0dfbec9f..95dce78c 100644
--- a/gitools-core/src/main/java/org/gitools/analysis/clustering/ClusteringMethod.java
+++ b/gitools-core/src/main/java/org/gitools/matrix/clustering/ClusteringMethod.java
@@ -15,20 +15,15 @@
* under the License.
*/
-package org.gitools.analysis.clustering;
+package org.gitools.matrix.clustering;
import edu.upf.bg.progressmonitor.IProgressMonitor;
import java.io.IOException;
import org.gitools.analysis.Method;
-import org.gitools.analysis.MethodException;
import org.gitools.matrix.model.IMatrixView;
public interface ClusteringMethod extends Method{
- void buildAndCluster(IMatrixView matrixView, String type, IProgressMonitor monitor) throws Exception, IOException, NumberFormatException;
-
- void build(IMatrixView matrixView, String type, IProgressMonitor monitor) throws MethodException;
-
- ClusteringResult cluster() throws MethodException;
+ void buildAndCluster(IMatrixView matrixView, IProgressMonitor monitor) throws Exception, IOException, NumberFormatException;
}
diff --git a/gitools-core/src/main/java/org/gitools/matrix/clustering/MatrixViewClusterer.java b/gitools-core/src/main/java/org/gitools/matrix/clustering/MatrixViewClusterer.java
new file mode 100644
index 00000000..d82cf81c
--- /dev/null
+++ b/gitools-core/src/main/java/org/gitools/matrix/clustering/MatrixViewClusterer.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2010 xrafael.
+ *
+ * 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.
+ * under the License.
+ */
+package org.gitools.matrix.clustering;
+
+import edu.upf.bg.progressmonitor.IProgressMonitor;
+import java.util.Properties;
+import org.gitools.analysis.AnalysisException;
+import org.gitools.matrix.clustering.methods.ClusteringMethodFactory;
+import org.gitools.matrix.MatrixViewTransposition;
+import org.gitools.matrix.model.IMatrixView;
+
+public class MatrixViewClusterer {
+
+ public static void cluster (IMatrixView matrixView, Properties clusterParameters, IProgressMonitor monitor) throws AnalysisException, Exception {
+
+ ClusteringMethod method = ClusteringMethodFactory.createMethod(clusterParameters);
+
+ if (Boolean.valueOf(clusterParameters.getProperty("transpose", "false"))) {
+
+ MatrixViewTransposition mt = new MatrixViewTransposition();
+ mt.setMatrix(matrixView);
+ matrixView = mt;
+ }
+
+ method.buildAndCluster(matrixView, monitor);
+
+ }
+}
diff --git a/gitools-core/src/main/java/org/gitools/analysis/clustering/methods/ClusteringMethodFactory.java b/gitools-core/src/main/java/org/gitools/matrix/clustering/methods/ClusteringMethodFactory.java
similarity index 85%
rename from gitools-core/src/main/java/org/gitools/analysis/clustering/methods/ClusteringMethodFactory.java
rename to gitools-core/src/main/java/org/gitools/matrix/clustering/methods/ClusteringMethodFactory.java
index f34d8f79..228d8b33 100644
--- a/gitools-core/src/main/java/org/gitools/analysis/clustering/methods/ClusteringMethodFactory.java
+++ b/gitools-core/src/main/java/org/gitools/matrix/clustering/methods/ClusteringMethodFactory.java
@@ -15,10 +15,10 @@
* under the License.
*/
-package org.gitools.analysis.clustering.methods;
+package org.gitools.matrix.clustering.methods;
-import java.util.Properties;
-import org.gitools.analysis.clustering.ClusteringMethod;
+import java.util.Properties;
+import org.gitools.matrix.clustering.ClusteringMethod;
import org.gitools.analysis.AnalysisException;
@@ -26,7 +26,7 @@ public class ClusteringMethodFactory {
public static ClusteringMethod createMethod(Properties properties) throws AnalysisException {
String methodId =properties.getProperty("method");
- if (WekaCobWebMethod.ID.equalsIgnoreCase(methodId))
+ if (methodId.toLowerCase().contains(WekaCobWebMethod.ID))
return new WekaCobWebMethod(properties);
else if (WekaKmeansMethod.ID.equalsIgnoreCase(methodId))
return new WekaKmeansMethod(properties);
diff --git a/gitools-core/src/main/java/org/gitools/matrix/clustering/methods/MatrixViewWekaLoader.java b/gitools-core/src/main/java/org/gitools/matrix/clustering/methods/MatrixViewWekaLoader.java
new file mode 100644
index 00000000..d4d6d5d0
--- /dev/null
+++ b/gitools-core/src/main/java/org/gitools/matrix/clustering/methods/MatrixViewWekaLoader.java
@@ -0,0 +1,150 @@
+/*
+ * Copyright 2010 xrafael.
+ *
+ * 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.
+ * under the License.
+ */
+package org.gitools.matrix.clustering.methods;
+
+import cern.colt.matrix.DoubleMatrix2D;
+import java.io.IOException;
+import org.gitools.matrix.MatrixUtils;
+import org.gitools.matrix.model.DoubleMatrix;
+import org.gitools.matrix.model.IMatrixView;
+import weka.core.Attribute;
+import weka.core.FastVector;
+import weka.core.Instance;
+import weka.core.Instances;
+import weka.core.converters.AbstractLoader;
+
+// FIXME This code is very inefficient !!! check getNextInstance and getStructure
+public class MatrixViewWekaLoader extends AbstractLoader {
+
+ private IMatrixView matrixView;
+ private Integer indexValueMatrix;
+ private int indexRows;
+ private int indexCols;
+ private Instances dataSet;
+ private FastVector attribNames;
+
+ public MatrixViewWekaLoader(IMatrixView matrixView, Integer index) {
+
+ this.matrixView = matrixView;
+
+ this.indexValueMatrix = index;
+
+ indexRows = indexCols = -1;
+
+ attribNames = new FastVector();
+
+ //Adding attributes (rows name)
+ for (int rows = 0; rows < matrixView.getRowCount(); rows++) {
+ attribNames.addElement(new Attribute(matrixView.getRowLabel(rows)));
+ }
+
+ dataSet = new Instances("matrixToCluster", attribNames, 0);
+
+ }
+
+ // FIXME structure should be constructed ONCE in the constructor
+ // and returned here whenever it is needed
+ @Override
+ public Instances getStructure() throws IOException {
+
+ return dataSet;
+
+ }
+
+ @Override
+ public Instances getDataSet() throws IOException {
+
+ Instance current = null;
+
+ Integer auxCols = indexCols, auxRows = indexRows;
+
+ indexCols = -1;
+ indexRows = -1;
+
+ while ((current = getNextInstance(dataSet)) != null) {
+ dataSet.add(current);
+ }
+
+ indexCols = auxCols;
+ indexRows = auxRows;
+
+ return dataSet;
+
+ }
+
+ @Override
+ //Param ds it is not modified nor altered
+ public Instance getNextInstance(Instances ds) throws IOException {
+
+ if (indexCols >= matrixView.getVisibleColumns().length - 1) {
+ return null;
+ }
+
+ indexCols++;
+
+ //MatrixViewInstance current = new MatrixViewInstance(matrixView,indexCols,indexValueMatrix);
+
+ double[] values = new double[matrixView.getRowCount()];
+ for (int row = 0; row < matrixView.getRowCount(); row++) {
+ values[row] = MatrixUtils.doubleValue(
+ matrixView.getCellValue(row, indexCols, indexValueMatrix));
+ }
+ //Instance is created once data in array values. This improves time performance
+ Instance current = new Instance(1, values);
+
+ Instances dataset = new Instances("matrixToCluster", attribNames, 0);
+ dataset.add(current);
+ current.setDataset(dataset);
+
+ return current;
+ }
+
+ @Override
+ public String getRevision() {
+
+ throw new UnsupportedOperationException("Not supported yet.");
+
+ }
+
+ /**
+ * Given an index (col,row) from the matrix we retrieve the instance
+ *
+ */
+ public Instance get(Integer index) {
+
+ if (index >= matrixView.getVisibleColumns().length - 1) {
+ return null;
+ }
+
+ double[] values = new double[matrixView.getRowCount()];
+
+ for (int row = 0; row < matrixView.getRowCount(); row++) {
+ values[row] = MatrixUtils.doubleValue(
+ matrixView.getCellValue(row, index, indexValueMatrix));
+ }
+
+ //Instance is created once data in array values. This improves time performance
+ Instance current = new Instance(1, values);
+
+ //The dataset for the instance
+ Instances dataset = new Instances("matrixToCluster", attribNames, 0);
+ dataset.add(current);
+ current.setDataset(dataset);
+
+ return current;
+ }
+}
diff --git a/gitools-core/src/main/java/org/gitools/matrix/clustering/methods/WekaCobWebMethod.java b/gitools-core/src/main/java/org/gitools/matrix/clustering/methods/WekaCobWebMethod.java
new file mode 100644
index 00000000..e5f450f7
--- /dev/null
+++ b/gitools-core/src/main/java/org/gitools/matrix/clustering/methods/WekaCobWebMethod.java
@@ -0,0 +1,141 @@
+/*
+ * Copyright 2010 xrafael.
+ *
+ * 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.
+ * under the License.
+ */
+
+package org.gitools.matrix.clustering.methods;
+
+import edu.upf.bg.progressmonitor.IProgressMonitor;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Properties;
+import org.gitools.analysis.AbstractMethod;
+import org.gitools.matrix.clustering.ClusteringMethod;
+import org.gitools.matrix.model.IMatrixView;
+import weka.clusterers.Cobweb;
+import weka.core.Instance;
+import weka.core.Instances;
+
+public class WekaCobWebMethod extends AbstractMethod implements ClusteringMethod{
+
+ public static final String ID = "hierarchical";
+
+ public WekaCobWebMethod(Properties properties) {
+ super(ID,
+ "CobWeb's clustering",
+ "CobWeb's Weka clustering",null, properties);
+ }
+
+ @Override
+ public void buildAndCluster(IMatrixView matrixView, IProgressMonitor monitor) throws Exception, IOException, NumberFormatException {
+
+ Integer valueIndex = new Integer(properties.getProperty("index", "0"));
+ MatrixViewWekaLoader loader =
+ new MatrixViewWekaLoader(matrixView, valueIndex);
+
+ Instances structure = loader.getStructure();
+
+ Cobweb clusterer = new Cobweb();
+
+ clusterer.setAcuity(Float.valueOf(properties.getProperty("acuity","1.0")));
+ clusterer.setCutoff(Float.valueOf(properties.getProperty("cutoff","0.0028")));
+ clusterer.setSeed(Integer.valueOf(properties.getProperty("seed","42")));
+
+ clusterer.buildClusterer(structure);
+
+ monitor.begin("Creating clustering model ...", matrixView.getVisibleColumns().length + 1);
+
+ Instance current = null;
+
+ int j = 0;
+ while ((j < matrixView.getVisibleColumns().length ) && !monitor.isCancelled()) {
+
+ if ((current = loader.get(j)) != null)
+ clusterer.updateClusterer(current);
+
+ monitor.worked(1);
+ j++;
+ }
+
+ clusterer.updateFinished();
+
+ monitor.end();
+
+ // Identificar el cluster de cada instancia
+
+ monitor.begin("Clustering instances ...", matrixView.getVisibleColumns().length);
+
+ int cluster;
+
+ //One cluster different instances
+ HashMap<Integer, List<Integer>> clusterResults = new HashMap<Integer, List<Integer>>();
+
+ for (int i=0; i < matrixView.getVisibleColumns().length && !monitor.isCancelled(); i++) {
+
+ if ((current = loader.get(i)) != null) {
+
+ cluster = clusterer.clusterInstance(current);
+
+ List<Integer> instancesCluster = clusterResults.get(cluster);
+ if (instancesCluster == null) {
+ instancesCluster = new ArrayList<Integer>();
+ clusterResults.put(cluster, instancesCluster);
+ }
+
+ instancesCluster.add(i);
+ }
+ monitor.worked(1);
+ }
+
+ updateVisibility(matrixView, clusterResults);
+
+ monitor.end();
+ }
+
+ private void updateVisibility(IMatrixView matrixView, HashMap<Integer, List<Integer>> clusterResults) {
+
+ int[] visibleData = matrixView.getVisibleColumns();
+
+ final int[] sortedVisibleData = new int[matrixView.getVisibleColumns().length];
+
+ int index = 0;
+
+
+ Integer[] clustersSorted = (Integer[]) clusterResults.keySet().toArray(
+ new Integer[clusterResults.keySet().size()]);
+
+ Arrays.sort(clustersSorted);
+
+ for (Integer i : clustersSorted)
+ for( Integer val : clusterResults.get(i))
+ sortedVisibleData[index++] = visibleData[val];
+
+ matrixView.setVisibleColumns(sortedVisibleData);
+
+ }
+
+ @Override
+ public String getId() {
+ return ID;
+ }
+
+
+
+
+
+}
diff --git a/gitools-core/src/main/java/org/gitools/analysis/clustering/methods/WekaKmeansMethod.java b/gitools-core/src/main/java/org/gitools/matrix/clustering/methods/WekaKmeansMethod.java
similarity index 59%
rename from gitools-core/src/main/java/org/gitools/analysis/clustering/methods/WekaKmeansMethod.java
rename to gitools-core/src/main/java/org/gitools/matrix/clustering/methods/WekaKmeansMethod.java
index b2f5d934..15421bf5 100644
--- a/gitools-core/src/main/java/org/gitools/analysis/clustering/methods/WekaKmeansMethod.java
+++ b/gitools-core/src/main/java/org/gitools/matrix/clustering/methods/WekaKmeansMethod.java
@@ -15,7 +15,7 @@
* under the License.
*/
-package org.gitools.analysis.clustering.methods;
+package org.gitools.matrix.clustering.methods;
import edu.upf.bg.progressmonitor.IProgressMonitor;
import java.io.IOException;
@@ -24,9 +24,7 @@
import java.util.List;
import java.util.Properties;
import org.gitools.analysis.AbstractMethod;
-import org.gitools.analysis.MethodException;
-import org.gitools.analysis.clustering.ClusteringMethod;
-import org.gitools.analysis.clustering.ClusteringResult;
+import org.gitools.matrix.clustering.ClusteringMethod;
import org.gitools.matrix.model.IMatrixView;
import weka.clusterers.SimpleKMeans;
import weka.core.EuclideanDistance;
@@ -42,11 +40,12 @@ public WekaKmeansMethod(Properties properties) {
super(ID,
"K-Means clustering",
"K-Means Weka clustering",
- ClusteringResult.class, properties);
+ null, properties);
}
+
@Override
- public void buildAndCluster(IMatrixView matrixView, String type, IProgressMonitor monitor) throws Exception, IOException, NumberFormatException {
+ public void buildAndCluster(IMatrixView matrixView, IProgressMonitor monitor) throws Exception, IOException, NumberFormatException {
Instance instancia;
@@ -54,34 +53,30 @@ public void buildAndCluster(IMatrixView matrixView, String type, IProgressMonito
if ((Integer.valueOf(properties.getProperty("k"))) < 2) return;
- MatrixViewWekaLoader loader = new MatrixViewWekaLoader(matrixView, properties.getProperty("index"),type);
-
- Instances structure = loader.getStructure();
-
- System.out.println("Loading clustering algorithm ...");
+ Integer valueIndex = Integer.valueOf(properties.getProperty("index", "0"));
+ MatrixViewWekaLoader loader =
+ new MatrixViewWekaLoader(matrixView, valueIndex);
SimpleKMeans clusterer = new SimpleKMeans();
- clusterer.setMaxIterations(Integer.valueOf(properties.getProperty("iterations")));
+ clusterer.setMaxIterations(Integer.valueOf(properties.getProperty("iterations","500")));
+ clusterer.setNumClusters(Integer.valueOf(properties.getProperty("k","2")));
+ clusterer.setSeed(Integer.valueOf(properties.getProperty("seed","10")));
- clusterer.setNumClusters(Integer.valueOf(properties.getProperty("k")));
-
- clusterer.setSeed(Integer.valueOf(properties.getProperty("seed")));
-
- if (properties.getProperty("distance").toLowerCase().equals("euclidean"))
+ if (properties.getProperty("distance","euclidean").toLowerCase().equals("euclidean"))
clusterer.setDistanceFunction(new EuclideanDistance());
else
- if (properties.getProperty("distance").toLowerCase().equals("manhattan"))
clusterer.setDistanceFunction(new ManhattanDistance());
+ Instances dataset = loader.getDataSet();
- System.out.println("Training clustering model...");
+ monitor.begin("Creating clustering model ...", 1);
- clusterer.buildClusterer(loader.getDataSet());
+ clusterer.buildClusterer(dataset);
- System.out.println("Setting instances into clusters ...");
+ monitor.end();
- Instances dataset = loader.getDataSet();
+ monitor.begin("Clustering instances ...", dataset.numInstances());
//Cluster -> List instances
HashMap<Integer,List<Integer>> clusterResults = new HashMap<Integer,List<Integer>>();
@@ -102,41 +97,32 @@ public void buildAndCluster(IMatrixView matrixView, String type, IProgressMonito
clusterResults.put(cluster, instancesCluster);
+ monitor.worked(1);
+
}
- rePaintHeatMap (type, matrixView, dataset.numInstances(), clusterResults);
+ updateVisibility (matrixView, dataset.numInstances(), clusterResults);
+ monitor.end();
}
- private void rePaintHeatMap (String type, IMatrixView matrixView, Integer numInstances, HashMap<Integer,List<Integer>> clusterResults){
+ private void updateVisibility (IMatrixView matrixView, Integer numInstances, HashMap<Integer,List<Integer>> clusterResults){
+ int index = 0;
int[] visibleData = null;
-
- if (type.equals("rows"))
- visibleData = matrixView.getVisibleRows();
- else
- visibleData = matrixView.getVisibleColumns();
-
final int[] sortedVisibleData = new int[numInstances];
- int index = 0;
-
- for (Integer i : clusterResults.keySet()){
+ visibleData = matrixView.getVisibleColumns();
+ for (Integer i : clusterResults.keySet())
for( Integer val : clusterResults.get(i)){
sortedVisibleData[index] = visibleData[val];
-
index++;
}
- }
-
- if (type.equals("rows"))
- matrixView.setVisibleRows(sortedVisibleData);
- else
- matrixView.setVisibleColumns(sortedVisibleData);
+ matrixView.setVisibleColumns(sortedVisibleData);
}
@@ -146,16 +132,6 @@ public String getId() {
}
- @Override
- public void build(IMatrixView matrixView, String type, IProgressMonitor monitor) throws MethodException {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public ClusteringResult cluster() throws MethodException {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
diff --git a/gitools-ui/src/main/java/org/gitools/ui/actions/AnalysisActions.java b/gitools-ui/src/main/java/org/gitools/ui/actions/AnalysisActions.java
index f9803e15..87023177 100755
--- a/gitools-ui/src/main/java/org/gitools/ui/actions/AnalysisActions.java
+++ b/gitools-ui/src/main/java/org/gitools/ui/actions/AnalysisActions.java
@@ -9,7 +9,6 @@
import org.gitools.stats.mtc.Bonferroni;
import org.gitools.ui.actions.analysis.CombinationsAction;
import org.gitools.ui.actions.analysis.CorrelationsAction;
-import org.gitools.ui.actions.analysis.ClusteringAction;
import org.gitools.ui.platform.AppFrame;
public class AnalysisActions {
@@ -17,8 +16,6 @@ public class AnalysisActions {
public static final BaseAction combinations = new CombinationsAction();
public static final BaseAction correlations = new CorrelationsAction();
-
- public static final BaseAction clusteringAction = new ClusteringAction();
public static final BaseAction mtcBonferroniAction = new MtcAction(new Bonferroni());
diff --git a/gitools-ui/src/main/java/org/gitools/ui/actions/DataActions.java b/gitools-ui/src/main/java/org/gitools/ui/actions/DataActions.java
index d7dc9706..9ec43118 100644
--- a/gitools-ui/src/main/java/org/gitools/ui/actions/DataActions.java
+++ b/gitools-ui/src/main/java/org/gitools/ui/actions/DataActions.java
@@ -1,5 +1,6 @@
package org.gitools.ui.actions;
+import org.gitools.ui.actions.data.ClusteringAction;
import org.gitools.ui.platform.actions.BaseAction;
import org.gitools.ui.actions.data.FastSortRowsAction;
import org.gitools.ui.actions.data.FilterByLabelAction;
@@ -39,4 +40,7 @@ public final class DataActions {
public static final BaseAction moveColsLeftAction = new MoveSelectionAction(MoveDirection.COL_LEFT);
public static final BaseAction moveColsRightAction = new MoveSelectionAction(MoveDirection.COL_RIGHT);
+
+ public static final BaseAction clusteringAction = new ClusteringAction();
+
}
diff --git a/gitools-ui/src/main/java/org/gitools/ui/actions/MenuActionSet.java b/gitools-ui/src/main/java/org/gitools/ui/actions/MenuActionSet.java
index 8e78e77b..999b9a77 100644
--- a/gitools-ui/src/main/java/org/gitools/ui/actions/MenuActionSet.java
+++ b/gitools-ui/src/main/java/org/gitools/ui/actions/MenuActionSet.java
@@ -86,12 +86,12 @@ public MenuActionSet() {
DataActions.hideSelectedRowsAction,
DataActions.showAllColumnsAction,
DataActions.hideSelectedColumnsAction
- })
+ }),
+ DataActions.clusteringAction
}),
new ActionSet("Analysis", new BaseAction[] {
AnalysisActions.correlations,
AnalysisActions.combinations,
- AnalysisActions.clusteringAction,
// new ActionSet("Clustering", new BaseAction[] {
// AnalysisActions.clusteringAction
// }),
diff --git a/gitools-ui/src/main/java/org/gitools/ui/actions/analysis/ClusteringAction.java b/gitools-ui/src/main/java/org/gitools/ui/actions/data/ClusteringAction.java
similarity index 78%
rename from gitools-ui/src/main/java/org/gitools/ui/actions/analysis/ClusteringAction.java
rename to gitools-ui/src/main/java/org/gitools/ui/actions/data/ClusteringAction.java
index 5764a2ed..982390fb 100644
--- a/gitools-ui/src/main/java/org/gitools/ui/actions/analysis/ClusteringAction.java
+++ b/gitools-ui/src/main/java/org/gitools/ui/actions/data/ClusteringAction.java
@@ -15,19 +15,16 @@
* under the License.
*/
-package org.gitools.ui.actions.analysis;
+package org.gitools.ui.actions.data;
import edu.upf.bg.progressmonitor.IProgressMonitor;
import java.awt.event.ActionEvent;
-import java.util.List;
-import org.gitools.analysis.clustering.ClusteringAnalysis;
-import org.gitools.analysis.clustering.ClusteringProcessor;
+import java.util.Properties;
+import org.gitools.matrix.clustering.MatrixViewClusterer;
import org.gitools.heatmap.model.Heatmap;
import org.gitools.matrix.model.IMatrixView;
-import org.gitools.matrix.model.MatrixView;
-import org.gitools.matrix.model.element.IElementAttribute;
import org.gitools.ui.actions.ActionUtils;
-import org.gitools.ui.analysis.clustering.dialog.ClusteringDialog;
+import org.gitools.ui.dialog.clustering.ClusteringDialog;
import org.gitools.ui.platform.AppFrame;
import org.gitools.ui.platform.actions.BaseAction;
import org.gitools.ui.platform.progress.JobRunnable;
@@ -48,26 +45,22 @@ public boolean isEnabledByModel(Object model) {
@Override
public void actionPerformed(ActionEvent e) {
- final IMatrixView matrixView = ActionUtils.getMatrixView();
+ final IMatrixView matrixView = ActionUtils.getMatrixView();
if (matrixView == null)
return;
-
-
ClusteringDialog dlg = new ClusteringDialog(AppFrame.instance());
dlg.setAttributes(matrixView.getContents().getCellAttributes());
dlg.setVisible(true);
if (dlg.getReturnStatus() != ClusteringDialog.RET_OK) {
- AppFrame.instance().setStatusText("Filter cancelled.");
+ AppFrame.instance().setStatusText("Clustering cancelled.");
return;
}
- final ClusteringAnalysis analysis = dlg.getAnalysis();
-
- analysis.setData(matrixView);
+ final Properties clusterParameters = dlg.getClusterParameters();
JobThread.execute(AppFrame.instance(), new JobRunnable() {
@Override public void run(IProgressMonitor monitor) {
@@ -75,10 +68,9 @@ public void actionPerformed(ActionEvent e) {
try {
monitor.begin("Clustering ...", 1);
-
- new ClusteringProcessor(analysis).run(monitor);
-
+ MatrixViewClusterer.cluster(matrixView, clusterParameters, monitor);
monitor.end();
+
}
catch (Throwable ex) {
monitor.exception(ex);
diff --git a/gitools-ui/src/main/java/org/gitools/ui/dialog/clustering/ClusteringDialog.form b/gitools-ui/src/main/java/org/gitools/ui/dialog/clustering/ClusteringDialog.form
new file mode 100644
index 00000000..ab6e60d9
--- /dev/null
+++ b/gitools-ui/src/main/java/org/gitools/ui/dialog/clustering/ClusteringDialog.form
@@ -0,0 +1,175 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JDialogFormInfo">
+ <NonVisualComponents>
+ <Component class="javax.swing.ButtonGroup" name="applayGroup">
+ </Component>
+ </NonVisualComponents>
+ <Properties>
+ <Property name="title" type="java.lang.String" value="Clustering analysis"/>
+ <Property name="locationByPlatform" type="boolean" value="true"/>
+ <Property name="minimumSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
+ <Dimension value="[397, 248]"/>
+ </Property>
+ </Properties>
+ <SyntheticProperties>
+ <SyntheticProperty name="formSizePolicy" type="int" value="2"/>
+ </SyntheticProperties>
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="jSeparator1" alignment="0" pref="373" max="32767" attributes="0"/>
+ <Group type="102" alignment="1" attributes="0">
+ <Component id="okButton" min="-2" pref="67" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="cancelButton" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <Group type="102" alignment="0" attributes="0">
+ <Component id="jLabel3" min="-2" max="-2" attributes="0"/>
+ <EmptySpace min="-2" pref="40" max="-2" attributes="0"/>
+ <Component id="algorithmTypeCombo" min="-2" pref="202" max="-2" attributes="2"/>
+ <EmptySpace type="separate" max="-2" attributes="0"/>
+ <Component id="jButton1" max="32767" attributes="0"/>
+ </Group>
+ <Group type="102" alignment="0" attributes="0">
+ <Component id="jLabel6" min="-2" max="-2" attributes="0"/>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Component id="dataClustCombo" pref="284" max="32767" attributes="3"/>
+ </Group>
+ <Component id="rowsRadio" alignment="0" min="-2" max="-2" attributes="0"/>
+ <Component id="columnsRadio" alignment="0" min="-2" max="-2" attributes="0"/>
+ <Component id="jLabel5" alignment="0" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="algorithmTypeCombo" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="jLabel3" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="jButton1" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace min="-2" pref="19" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="jLabel6" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="dataClustCombo" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace type="separate" max="-2" attributes="0"/>
+ <Component id="jLabel5" min="-2" max="-2" attributes="0"/>
+ <EmptySpace min="-2" pref="14" max="-2" attributes="0"/>
+ <Component id="columnsRadio" min="-2" max="-2" attributes="0"/>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Component id="rowsRadio" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="32767" attributes="0"/>
+ <Component id="jSeparator1" min="-2" pref="6" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="cancelButton" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="okButton" alignment="3" min="-2" pref="26" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JLabel" name="jLabel3">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Method :"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JRadioButton" name="rowsRadio">
+ <Properties>
+ <Property name="buttonGroup" type="javax.swing.ButtonGroup" editor="org.netbeans.modules.form.RADComponent$ButtonGroupPropertyEditor">
+ <ComponentRef name="applayGroup"/>
+ </Property>
+ <Property name="text" type="java.lang.String" value="rows"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JRadioButton" name="columnsRadio">
+ <Properties>
+ <Property name="buttonGroup" type="javax.swing.ButtonGroup" editor="org.netbeans.modules.form.RADComponent$ButtonGroupPropertyEditor">
+ <ComponentRef name="applayGroup"/>
+ </Property>
+ <Property name="selected" type="boolean" value="true"/>
+ <Property name="text" type="java.lang.String" value="columns"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JComboBox" name="algorithmTypeCombo">
+ <Properties>
+ <Property name="model" type="javax.swing.ComboBoxModel" editor="org.netbeans.modules.form.editors2.ComboBoxModelEditor">
+ <StringArray count="2">
+ <StringItem index="0" value="Hierarchical clustering"/>
+ <StringItem index="1" value="K-means"/>
+ </StringArray>
+ </Property>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="algorithmTypeComboActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JLabel" name="jLabel5">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Apply to :"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JLabel" name="jLabel6">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Values from :"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JComboBox" name="dataClustCombo">
+ <Properties>
+ <Property name="model" type="javax.swing.ComboBoxModel" editor="org.netbeans.modules.form.editors2.ComboBoxModelEditor">
+ <StringArray count="0"/>
+ </Property>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JSeparator" name="jSeparator1">
+ </Component>
+ <Component class="javax.swing.JButton" name="okButton">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="OK"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="okButtonActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="cancelButton">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Cancel"/>
+ <Property name="defaultCapable" type="boolean" value="false"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="cancelButtonActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="jButton1">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Config ..."/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButton1ActionPerformed"/>
+ </Events>
+ </Component>
+ </SubComponents>
+</Form>
diff --git a/gitools-ui/src/main/java/org/gitools/ui/dialog/clustering/ClusteringDialog.java b/gitools-ui/src/main/java/org/gitools/ui/dialog/clustering/ClusteringDialog.java
new file mode 100644
index 00000000..16e88286
--- /dev/null
+++ b/gitools-ui/src/main/java/org/gitools/ui/dialog/clustering/ClusteringDialog.java
@@ -0,0 +1,291 @@
+/*
+ * Copyright 2010 xrafael.
+ *
+ * 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.
+ * under the License.
+ */
+package org.gitools.ui.dialog.clustering;
+
+import java.util.List;
+import java.util.Properties;
+import javax.swing.DefaultComboBoxModel;
+import org.gitools.matrix.model.element.IElementAttribute;
+
+public class ClusteringDialog extends javax.swing.JDialog {
+
+ // model wrappers
+ private static class MatrixAttributeWrapper {
+
+ private IElementAttribute attribute;
+
+ public MatrixAttributeWrapper(IElementAttribute a) {
+ this.attribute = a;
+ }
+
+ public IElementAttribute getMatrixAttribute() {
+ return attribute;
+ }
+
+ public void setMatrixAttribute(IElementAttribute a) {
+ this.attribute = a;
+ }
+
+ @Override
+ public String toString() {
+ return attribute.getName();
+ }
+ }
+ /** A return status code - returned if Cancel button has been pressed */
+ public static final int RET_CANCEL = 0;
+ /** A return status code - returned if OK button has been pressed */
+ public static final int RET_OK = 1;
+ private int returnStatus = RET_CANCEL;
+
+ /** Creates new form clusteringPage */
+ public ClusteringDialog(java.awt.Window parent) {
+
+ super(parent);
+ setModal(true);
+
+ initComponents();
+
+ validate();
+
+ }
+
+ /** @return the return status of this dialog - one of RET_OK or RET_CANCEL */
+ public int getReturnStatus() {
+ return returnStatus;
+ }
+
+
+ private void doClose(int retStatus) {
+ returnStatus = retStatus;
+ setVisible(false);
+ dispose();
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ applayGroup = new javax.swing.ButtonGroup();
+ jLabel3 = new javax.swing.JLabel();
+ rowsRadio = new javax.swing.JRadioButton();
+ columnsRadio = new javax.swing.JRadioButton();
+ algorithmTypeCombo = new javax.swing.JComboBox();
+ jLabel5 = new javax.swing.JLabel();
+ jLabel6 = new javax.swing.JLabel();
+ dataClustCombo = new javax.swing.JComboBox();
+ jSeparator1 = new javax.swing.JSeparator();
+ okButton = new javax.swing.JButton();
+ cancelButton = new javax.swing.JButton();
+ jButton1 = new javax.swing.JButton();
+
+ setTitle("Clustering analysis");
+ setLocationByPlatform(true);
+ setMinimumSize(new java.awt.Dimension(397, 248));
+
+ jLabel3.setText("Method :");
+
+ applayGroup.add(rowsRadio);
+ rowsRadio.setText("rows");
+
+ applayGroup.add(columnsRadio);
+ columnsRadio.setSelected(true);
+ columnsRadio.setText("columns");
+
+ algorithmTypeCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Hierarchical clustering", "K-means" }));
+ algorithmTypeCombo.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ algorithmTypeComboActionPerformed(evt);
+ }
+ });
+
+ jLabel5.setText("Apply to :");
+
+ jLabel6.setText("Values from :");
+
+ okButton.setText("OK");
+ okButton.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ okButtonActionPerformed(evt);
+ }
+ });
+
+ cancelButton.setText("Cancel");
+ cancelButton.setDefaultCapable(false);
+ cancelButton.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ cancelButtonActionPerformed(evt);
+ }
+ });
+
+ jButton1.setText("Config ...");
+ jButton1.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ jButton1ActionPerformed(evt);
+ }
+ });
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 373, Short.MAX_VALUE)
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
+ .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(cancelButton))
+ .addGroup(layout.createSequentialGroup()
+ .addComponent(jLabel3)
+ .addGap(40, 40, 40)
+ .addComponent(algorithmTypeCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addGap(18, 18, 18)
+ .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ .addGroup(layout.createSequentialGroup()
+ .addComponent(jLabel6)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(dataClustCombo, 0, 284, Short.MAX_VALUE))
+ .addComponent(rowsRadio)
+ .addComponent(columnsRadio)
+ .addComponent(jLabel5))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(algorithmTypeCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addComponent(jLabel3)
+ .addComponent(jButton1))
+ .addGap(19, 19, 19)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(jLabel6)
+ .addComponent(dataClustCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addGap(18, 18, 18)
+ .addComponent(jLabel5)
+ .addGap(14, 14, 14)
+ .addComponent(columnsRadio)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(rowsRadio)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 6, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(cancelButton)
+ .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addContainerGap())
+ );
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void algorithmTypeComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_algorithmTypeComboActionPerformed
+
+
+ }//GEN-LAST:event_algorithmTypeComboActionPerformed
+
+ private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
+ doClose(RET_OK);
+}//GEN-LAST:event_okButtonActionPerformed
+
+ private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
+ doClose(RET_CANCEL);
+}//GEN-LAST:event_cancelButtonActionPerformed
+
+ private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
+
+ if (algorithmTypeCombo.getSelectedItem().toString().toLowerCase().equals("k-means")){
+ KmeansParamsDialog dlg = new KmeansParamsDialog(this);
+ dlg.setVisible(true);
+ }else{
+ CobwebParamsDialog dlg = new CobwebParamsDialog(this);
+ dlg.setVisible(true);
+ }
+
+ }//GEN-LAST:event_jButton1ActionPerformed
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JComboBox algorithmTypeCombo;
+ private javax.swing.ButtonGroup applayGroup;
+ private javax.swing.JButton cancelButton;
+ private javax.swing.JRadioButton columnsRadio;
+ private javax.swing.JComboBox dataClustCombo;
+ private javax.swing.JButton jButton1;
+ private javax.swing.JLabel jLabel3;
+ private javax.swing.JLabel jLabel5;
+ private javax.swing.JLabel jLabel6;
+ private javax.swing.JSeparator jSeparator1;
+ private javax.swing.JButton okButton;
+ private javax.swing.JRadioButton rowsRadio;
+ // End of variables declaration//GEN-END:variables
+
+ private Properties params = new Properties();
+
+ public Properties getParams() {
+ return params;
+ }
+
+ public void setParams(Properties params) {
+ this.params = params;
+ }
+
+ public Properties getClusterParameters() {
+
+ Properties clusterParams = new Properties();
+
+ clusterParams.put("method", algorithmTypeCombo.getSelectedItem().toString().toLowerCase());
+ clusterParams.put("index", dataClustCombo.getSelectedItem());
+ clusterParams.put("transpose", rowsRadio.isSelected());
+
+ if (algorithmTypeCombo.getSelectedItem().toString().toLowerCase().equals("k-means")) {
+
+ clusterParams.put("iterations", params.getProperty("iterations","500"));
+ clusterParams.put("seed", params.getProperty("seed","10"));
+ clusterParams.put("k", params.getProperty("k","2"));
+ clusterParams.put("distance", params.getProperty("distance","euclidean"));
+
+ }else{
+
+ clusterParams.put("cutoff", params.getProperty("cutoff","0.0028"));
+ clusterParams.put("seed", params.getProperty("seed","42"));
+ clusterParams.put("acuity", params.getProperty("acuity","1.0"));
+ }
+
+ return clusterParams;
+ }
+
+ public void setAttributes(List<IElementAttribute> cellAttributes) {
+
+ DefaultComboBoxModel model = new DefaultComboBoxModel();
+ MatrixAttributeWrapper attrWrapper = null;
+ for (IElementAttribute attr : cellAttributes) {
+ attrWrapper = new MatrixAttributeWrapper(attr);
+ model.addElement(attrWrapper);
+ }
+
+ dataClustCombo.setModel(model);
+
+ }
+
+ public boolean isTransposeEnabled() {
+ return rowsRadio.isSelected();
+ }
+}
diff --git a/gitools-ui/src/main/java/org/gitools/ui/dialog/clustering/CobwebParamsDialog.form b/gitools-ui/src/main/java/org/gitools/ui/dialog/clustering/CobwebParamsDialog.form
new file mode 100644
index 00000000..3f2050ac
--- /dev/null
+++ b/gitools-ui/src/main/java/org/gitools/ui/dialog/clustering/CobwebParamsDialog.form
@@ -0,0 +1,137 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JDialogFormInfo">
+ <Properties>
+ <Property name="title" type="java.lang.String" value="Hierarchical parameters"/>
+ <Property name="locationByPlatform" type="boolean" value="true"/>
+ <Property name="minimumSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
+ <Dimension value="[243, 200]"/>
+ </Property>
+ </Properties>
+ <SyntheticProperties>
+ <SyntheticProperty name="formSizePolicy" type="int" value="2"/>
+ </SyntheticProperties>
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="jLabel3" alignment="0" min="-2" max="-2" attributes="0"/>
+ <Component id="jLabel2" alignment="0" min="-2" max="-2" attributes="0"/>
+ <Component id="jLabel1" alignment="0" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="1" attributes="0">
+ <Component id="seedField" pref="171" max="32767" attributes="1"/>
+ <Component id="cutOffField" alignment="1" pref="171" max="32767" attributes="1"/>
+ <Component id="acuityField" alignment="1" pref="171" max="32767" attributes="1"/>
+ </Group>
+ </Group>
+ <Component id="jSeparator1" alignment="0" pref="229" max="32767" attributes="0"/>
+ <Group type="102" alignment="1" attributes="0">
+ <Component id="okButton" min="-2" pref="67" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="cancelButton" min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="acuityField" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace min="-2" pref="18" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="cutOffField" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="jLabel2" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace type="separate" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="seedField" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="jLabel3" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace type="separate" max="-2" attributes="0"/>
+ <Component id="jSeparator1" min="-2" pref="6" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="cancelButton" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="okButton" alignment="3" min="-2" pref="26" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="32767" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JLabel" name="jLabel1">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Acuity : "/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JTextField" name="acuityField">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="1.0"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JLabel" name="jLabel2">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Cutoff : "/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JTextField" name="cutOffField">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="0.0028"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JLabel" name="jLabel3">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Seed : "/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JTextField" name="seedField">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="42"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JSeparator" name="jSeparator1">
+ </Component>
+ <Component class="javax.swing.JButton" name="okButton">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="OK"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="okButtonActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="cancelButton">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Cancel"/>
+ <Property name="defaultCapable" type="boolean" value="false"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="cancelButtonActionPerformed"/>
+ </Events>
+ </Component>
+ </SubComponents>
+</Form>
diff --git a/gitools-ui/src/main/java/org/gitools/ui/dialog/clustering/CobwebParamsDialog.java b/gitools-ui/src/main/java/org/gitools/ui/dialog/clustering/CobwebParamsDialog.java
new file mode 100644
index 00000000..2504cc50
--- /dev/null
+++ b/gitools-ui/src/main/java/org/gitools/ui/dialog/clustering/CobwebParamsDialog.java
@@ -0,0 +1,178 @@
+/*
+ * Copyright 2010 xrafael.
+ *
+ * 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.
+ * under the License.
+ */
+
+
+package org.gitools.ui.dialog.clustering;
+
+import java.util.Properties;
+
+public class CobwebParamsDialog extends javax.swing.JDialog {
+
+ /** A return status code - returned if Cancel button has been pressed */
+ public static final int RET_CANCEL = 0;
+ /** A return status code - returned if OK button has been pressed */
+ public static final int RET_OK = 1;
+ private int returnStatus = RET_CANCEL;
+
+ private ClusteringDialog parent;
+
+
+ /** Creates new form cobwebParamsPanel */
+ public CobwebParamsDialog(ClusteringDialog parent) {
+
+ super(parent);
+ setModal(true);
+ initComponents();
+
+ this.parent = parent;
+
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jLabel1 = new javax.swing.JLabel();
+ acuityField = new javax.swing.JTextField();
+ jLabel2 = new javax.swing.JLabel();
+ cutOffField = new javax.swing.JTextField();
+ jLabel3 = new javax.swing.JLabel();
+ seedField = new javax.swing.JTextField();
+ jSeparator1 = new javax.swing.JSeparator();
+ okButton = new javax.swing.JButton();
+ cancelButton = new javax.swing.JButton();
+
+ setTitle("Hierarchical parameters");
+ setLocationByPlatform(true);
+ setMinimumSize(new java.awt.Dimension(243, 200));
+
+ jLabel1.setText("Acuity : ");
+
+ acuityField.setText("1.0");
+
+ jLabel2.setText("Cutoff : ");
+
+ cutOffField.setText("0.0028");
+
+ jLabel3.setText("Seed : ");
+
+ seedField.setText("42");
+
+ okButton.setText("OK");
+ okButton.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ okButtonActionPerformed(evt);
+ }
+ });
+
+ cancelButton.setText("Cancel");
+ cancelButton.setDefaultCapable(false);
+ cancelButton.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ cancelButtonActionPerformed(evt);
+ }
+ });
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(jLabel3)
+ .addComponent(jLabel2)
+ .addComponent(jLabel1))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
+ .addComponent(seedField, javax.swing.GroupLayout.DEFAULT_SIZE, 171, Short.MAX_VALUE)
+ .addComponent(cutOffField, javax.swing.GroupLayout.DEFAULT_SIZE, 171, Short.MAX_VALUE)
+ .addComponent(acuityField, javax.swing.GroupLayout.DEFAULT_SIZE, 171, Short.MAX_VALUE)))
+ .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 229, Short.MAX_VALUE)
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
+ .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(cancelButton)))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(acuityField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addComponent(jLabel1))
+ .addGap(18, 18, 18)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(cutOffField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addComponent(jLabel2))
+ .addGap(18, 18, 18)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(seedField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addComponent(jLabel3))
+ .addGap(18, 18, 18)
+ .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 6, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(cancelButton)
+ .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
+ Properties params = new Properties();
+ if (cutOffField.getText() != null && !cutOffField.getText().equals("")) params.put("cutoff",cutOffField.getText());
+ if (seedField.getText() != null && !seedField.getText().equals("")) params.put("seed",seedField.getText());
+ if (acuityField.getText() != null && !acuityField.getText().equals("")) params.put("acuity",acuityField.getText());
+
+ parent.setParams(params);
+ doClose(RET_OK);
+}//GEN-LAST:event_okButtonActionPerformed
+
+ private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
+ doClose(RET_CANCEL);
+}//GEN-LAST:event_cancelButtonActionPerformed
+
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JTextField acuityField;
+ private javax.swing.JButton cancelButton;
+ private javax.swing.JTextField cutOffField;
+ private javax.swing.JLabel jLabel1;
+ private javax.swing.JLabel jLabel2;
+ private javax.swing.JLabel jLabel3;
+ private javax.swing.JSeparator jSeparator1;
+ private javax.swing.JButton okButton;
+ private javax.swing.JTextField seedField;
+ // End of variables declaration//GEN-END:variables
+
+
+
+ private void doClose(int retStatus) {
+ returnStatus = retStatus;
+ setVisible(false);
+ dispose();
+ }
+}
diff --git a/gitools-ui/src/main/java/org/gitools/ui/dialog/clustering/KmeansParamsDialog.form b/gitools-ui/src/main/java/org/gitools/ui/dialog/clustering/KmeansParamsDialog.form
new file mode 100644
index 00000000..2982e493
--- /dev/null
+++ b/gitools-ui/src/main/java/org/gitools/ui/dialog/clustering/KmeansParamsDialog.form
@@ -0,0 +1,159 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JDialogFormInfo">
+ <Properties>
+ <Property name="title" type="java.lang.String" value="K-means parameters"/>
+ <Property name="locationByPlatform" type="boolean" value="true"/>
+ <Property name="minimumSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
+ <Dimension value="[297, 245]"/>
+ </Property>
+ </Properties>
+ <SyntheticProperties>
+ <SyntheticProperty name="formSizePolicy" type="int" value="2"/>
+ </SyntheticProperties>
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="jLabel7" alignment="0" min="-2" max="-2" attributes="0"/>
+ <Component id="jLabel1" alignment="0" min="-2" max="-2" attributes="0"/>
+ <Component id="jLabel2" alignment="0" min="-2" max="-2" attributes="0"/>
+ <Component id="jLabel3" alignment="0" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace min="-2" pref="12" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="distAlgCombo" alignment="0" pref="142" max="32767" attributes="1"/>
+ <Component id="seedField" alignment="0" pref="142" max="32767" attributes="1"/>
+ <Component id="iterField" alignment="0" pref="142" max="32767" attributes="1"/>
+ <Component id="kField" alignment="1" pref="142" max="32767" attributes="1"/>
+ </Group>
+ </Group>
+ <Component id="jSeparator1" alignment="0" pref="273" max="32767" attributes="0"/>
+ <Group type="102" alignment="1" attributes="0">
+ <Component id="okButton" min="-2" pref="67" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="cancelButton" min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="jLabel7" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="distAlgCombo" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace type="separate" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="kField" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace min="-2" pref="18" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="iterField" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="jLabel2" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace type="separate" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="seedField" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="jLabel3" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace type="separate" max="-2" attributes="0"/>
+ <Component id="jSeparator1" min="-2" pref="6" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="cancelButton" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="okButton" alignment="3" min="-2" pref="26" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="32767" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JLabel" name="jLabel1">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Num. Clusters : "/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JTextField" name="kField">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="2"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JLabel" name="jLabel2">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Max Iterations : "/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JTextField" name="iterField">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="500"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JLabel" name="jLabel3">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Seed : "/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JTextField" name="seedField">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="10"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JLabel" name="jLabel7">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Distance algorithm : "/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JComboBox" name="distAlgCombo">
+ <Properties>
+ <Property name="model" type="javax.swing.ComboBoxModel" editor="org.netbeans.modules.form.editors2.ComboBoxModelEditor">
+ <StringArray count="2">
+ <StringItem index="0" value="Euclidean"/>
+ <StringItem index="1" value="Manhattan"/>
+ </StringArray>
+ </Property>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JButton" name="cancelButton">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Cancel"/>
+ <Property name="defaultCapable" type="boolean" value="false"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="cancelButtonActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="okButton">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="OK"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="okButtonActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JSeparator" name="jSeparator1">
+ </Component>
+ </SubComponents>
+</Form>
diff --git a/gitools-ui/src/main/java/org/gitools/ui/dialog/clustering/KmeansParamsDialog.java b/gitools-ui/src/main/java/org/gitools/ui/dialog/clustering/KmeansParamsDialog.java
new file mode 100644
index 00000000..63a737bf
--- /dev/null
+++ b/gitools-ui/src/main/java/org/gitools/ui/dialog/clustering/KmeansParamsDialog.java
@@ -0,0 +1,192 @@
+/*
+ * Copyright 2010 xrafael.
+ *
+ * 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.
+ * under the License.
+ */
+package org.gitools.ui.dialog.clustering;
+
+import java.util.Properties;
+
+public class KmeansParamsDialog extends javax.swing.JDialog {
+
+ /** A return status code - returned if Cancel button has been pressed */
+ public static final int RET_CANCEL = 0;
+ /** A return status code - returned if OK button has been pressed */
+ public static final int RET_OK = 1;
+
+ private int returnStatus = RET_CANCEL;
+
+ private ClusteringDialog parent;
+
+ /** Creates new form cobwebParamsPanel */
+ public KmeansParamsDialog(ClusteringDialog parent) {
+
+ super(parent);
+ setModal(true);
+ initComponents();
+
+ this.parent = parent;
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jLabel1 = new javax.swing.JLabel();
+ kField = new javax.swing.JTextField();
+ jLabel2 = new javax.swing.JLabel();
+ iterField = new javax.swing.JTextField();
+ jLabel3 = new javax.swing.JLabel();
+ seedField = new javax.swing.JTextField();
+ jLabel7 = new javax.swing.JLabel();
+ distAlgCombo = new javax.swing.JComboBox();
+ cancelButton = new javax.swing.JButton();
+ okButton = new javax.swing.JButton();
+ jSeparator1 = new javax.swing.JSeparator();
+
+ setTitle("K-means parameters");
+ setLocationByPlatform(true);
+ setMinimumSize(new java.awt.Dimension(297, 245));
+
+ jLabel1.setText("Num. Clusters : ");
+
+ kField.setText("2");
+
+ jLabel2.setText("Max Iterations : ");
+
+ iterField.setText("500");
+
+ jLabel3.setText("Seed : ");
+
+ seedField.setText("10");
+
+ jLabel7.setText("Distance algorithm : ");
+
+ distAlgCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Euclidean", "Manhattan" }));
+
+ cancelButton.setText("Cancel");
+ cancelButton.setDefaultCapable(false);
+ cancelButton.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ cancelButtonActionPerformed(evt);
+ }
+ });
+
+ okButton.setText("OK");
+ okButton.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ okButtonActionPerformed(evt);
+ }
+ });
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(jLabel7)
+ .addComponent(jLabel1)
+ .addComponent(jLabel2)
+ .addComponent(jLabel3))
+ .addGap(12, 12, 12)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(distAlgCombo, 0, 142, Short.MAX_VALUE)
+ .addComponent(seedField, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE)
+ .addComponent(iterField, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE)
+ .addComponent(kField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE)))
+ .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 273, Short.MAX_VALUE)
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
+ .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(cancelButton)))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(jLabel7)
+ .addComponent(distAlgCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addGap(18, 18, 18)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(jLabel1)
+ .addComponent(kField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addGap(18, 18, 18)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(iterField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addComponent(jLabel2))
+ .addGap(18, 18, 18)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(seedField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addComponent(jLabel3))
+ .addGap(18, 18, 18)
+ .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 6, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(cancelButton)
+ .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+ }// </editor-fold>//GEN-END:initComponents
+
+private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
+ doClose(RET_CANCEL);
+}//GEN-LAST:event_cancelButtonActionPerformed
+
+private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
+
+ Properties params = new Properties();
+ if (iterField.getText() != null && !iterField.getText().equals("")) params.put("iterations", iterField.getText());
+ if (seedField.getText() != null && !seedField.getText().equals("")) params.put("seed", seedField.getText());
+ if (kField.getText() != null && !kField.getText().equals("")) params.put("k", kField.getText());
+ if (distAlgCombo.getSelectedItem() != null && !distAlgCombo.getSelectedItem().toString().equals("")) params.put("distance", distAlgCombo.getSelectedItem().toString());
+ parent.setParams(params);
+
+ doClose(RET_OK);
+}//GEN-LAST:event_okButtonActionPerformed
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JButton cancelButton;
+ private javax.swing.JComboBox distAlgCombo;
+ private javax.swing.JTextField iterField;
+ private javax.swing.JLabel jLabel1;
+ private javax.swing.JLabel jLabel2;
+ private javax.swing.JLabel jLabel3;
+ private javax.swing.JLabel jLabel7;
+ private javax.swing.JSeparator jSeparator1;
+ private javax.swing.JTextField kField;
+ private javax.swing.JButton okButton;
+ private javax.swing.JTextField seedField;
+ // End of variables declaration//GEN-END:variables
+
+
+ public String getDistanceMethod() {
+ return distAlgCombo.getSelectedItem().toString();
+ }
+
+ private void doClose(int retStatus) {
+ returnStatus = retStatus;
+ setVisible(false);
+ dispose();
+ }
+}
|
5ebbbc8a3c45010b2f52f14477785a1dd9fd02b8
|
drools
|
[DROOLS-812] properly close InputStreams--
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/main/java/org/drools/compiler/rule/builder/dialect/java/JavaRuleBuilderHelper.java b/drools-compiler/src/main/java/org/drools/compiler/rule/builder/dialect/java/JavaRuleBuilderHelper.java
index 1aeb7b2e87c..adbbfed3de5 100644
--- a/drools-compiler/src/main/java/org/drools/compiler/rule/builder/dialect/java/JavaRuleBuilderHelper.java
+++ b/drools-compiler/src/main/java/org/drools/compiler/rule/builder/dialect/java/JavaRuleBuilderHelper.java
@@ -19,22 +19,24 @@
import org.drools.compiler.compiler.DescrBuildError;
import org.drools.compiler.lang.descr.BaseDescr;
import org.drools.compiler.lang.descr.RuleDescr;
+import org.drools.compiler.rule.builder.RuleBuildContext;
import org.drools.core.definitions.rule.impl.RuleImpl;
-import org.drools.core.util.StringUtils;
import org.drools.core.reteoo.RuleTerminalNode;
import org.drools.core.rule.Declaration;
import org.drools.core.rule.JavaDialectRuntimeData;
-import org.drools.compiler.rule.builder.RuleBuildContext;
import org.drools.core.spi.AcceptsClassObjectType;
import org.drools.core.spi.KnowledgeHelper;
-import org.mvel2.ParserConfiguration;
-import org.mvel2.ParserContext;
+import org.drools.core.util.StringUtils;
import org.mvel2.integration.impl.MapVariableResolverFactory;
import org.mvel2.templates.SimpleTemplateRegistry;
import org.mvel2.templates.TemplateCompiler;
import org.mvel2.templates.TemplateRegistry;
import org.mvel2.templates.TemplateRuntime;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import java.io.IOException;
+import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@@ -42,6 +44,8 @@
public final class JavaRuleBuilderHelper {
+ private static final Logger logger = LoggerFactory.getLogger(JavaRuleBuilderHelper.class);
+
protected static TemplateRegistry RULE_REGISTRY = new SimpleTemplateRegistry();
protected static TemplateRegistry INVOKER_REGISTRY = new SimpleTemplateRegistry();
@@ -51,6 +55,7 @@ public final class JavaRuleBuilderHelper {
public static void setConsequenceTemplate( String name ) {
JAVA_RULE_MVEL = name;
RULE_REGISTRY = new SimpleTemplateRegistry();
+
}
public static void setInvokerTemplate( String name ) {
@@ -60,8 +65,14 @@ public static void setInvokerTemplate( String name ) {
public static synchronized TemplateRegistry getRuleTemplateRegistry(ClassLoader cl) {
if ( !RULE_REGISTRY.contains( "rules" ) ) {
+ InputStream javaRuleMvelStream = JavaRuleBuilderHelper.class.getResourceAsStream( JAVA_RULE_MVEL );
RULE_REGISTRY.addNamedTemplate( "rules",
- TemplateCompiler.compileTemplate( JavaRuleBuilderHelper.class.getResourceAsStream( JAVA_RULE_MVEL ) ) );
+ TemplateCompiler.compileTemplate( javaRuleMvelStream ) );
+ try {
+ javaRuleMvelStream.close();
+ } catch ( IOException ex ) {
+ logger.debug( "Failed to close stream!", ex );
+ }
TemplateRuntime.execute( RULE_REGISTRY.getNamedTemplate( "rules" ),
null,
RULE_REGISTRY );
@@ -72,8 +83,14 @@ public static synchronized TemplateRegistry getRuleTemplateRegistry(ClassLoader
public static synchronized TemplateRegistry getInvokerTemplateRegistry(ClassLoader cl) {
if ( !INVOKER_REGISTRY.contains( "invokers" ) ) {
+ InputStream javaInvokersMvelStream = JavaRuleBuilderHelper.class.getResourceAsStream( JAVA_INVOKERS_MVEL );
INVOKER_REGISTRY.addNamedTemplate( "invokers",
- TemplateCompiler.compileTemplate( JavaRuleBuilderHelper.class.getResourceAsStream( JAVA_INVOKERS_MVEL ) ) );
+ TemplateCompiler.compileTemplate( javaInvokersMvelStream ) );
+ try {
+ javaInvokersMvelStream.close();
+ } catch ( IOException ex ) {
+ logger.debug( "Failed to close stream!", ex );
+ }
TemplateRuntime.execute( INVOKER_REGISTRY.getNamedTemplate( "invokers" ),
null,
INVOKER_REGISTRY );
|
e2c0cf69ca83483c0128021a78fd82e6b5745b01
|
hadoop
|
svn merge -c 1420232 FIXES: YARN-266. RM and JHS- Web UIs are blank because AppsBlock is not escaping string properly.- Contributed by Ravi Prakash--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1420233 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/webapp/HsJobsBlock.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/webapp/HsJobsBlock.java
index 95715c7b74c20..f9048c0a4ea56 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/webapp/HsJobsBlock.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/webapp/HsJobsBlock.java
@@ -78,12 +78,12 @@ public class HsJobsBlock extends HtmlBlock {
.append(dateFormat.format(new Date(job.getFinishTime()))).append("\",\"")
.append("<a href='").append(url("job", job.getId())).append("'>")
.append(job.getId()).append("</a>\",\"")
- .append(StringEscapeUtils.escapeHtml(job.getName()))
- .append("\",\"")
- .append(StringEscapeUtils.escapeHtml(job.getUserName()))
- .append("\",\"")
- .append(StringEscapeUtils.escapeHtml(job.getQueueName()))
- .append("\",\"")
+ .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(
+ job.getName()))).append("\",\"")
+ .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(
+ job.getUserName()))).append("\",\"")
+ .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(
+ job.getQueueName()))).append("\",\"")
.append(job.getState()).append("\",\"")
.append(String.valueOf(job.getMapsTotal())).append("\",\"")
.append(String.valueOf(job.getMapsCompleted())).append("\",\"")
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index 778c807a53dd1..03b08bbe2db24 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -189,6 +189,9 @@ Release 0.23.6 - UNRELEASED
YARN-258. RM web page UI shows Invalid Date for start and finish times
(Ravi Prakash via jlowe)
+ YARN-266. RM and JHS Web UIs are blank because AppsBlock is not escaping
+ string properly (Ravi Prakash via jlowe)
+
Release 0.23.5 - UNRELEASED
INCOMPATIBLE CHANGES
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/AppsBlock.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/AppsBlock.java
index e90edae89aaa9..6fd35ec12b859 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/AppsBlock.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/AppsBlock.java
@@ -84,12 +84,12 @@ class AppsBlock extends HtmlBlock {
appsTableData.append("[\"<a href='")
.append(url("app", appInfo.getAppId())).append("'>")
.append(appInfo.getAppId()).append("</a>\",\"")
- .append(StringEscapeUtils.escapeHtml(appInfo.getUser()))
- .append("\",\"")
- .append(StringEscapeUtils.escapeHtml(appInfo.getName()))
- .append("\",\"")
- .append(StringEscapeUtils.escapeHtml(appInfo.getQueue()))
- .append("\",\"")
+ .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(
+ appInfo.getUser()))).append("\",\"")
+ .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(
+ appInfo.getName()))).append("\",\"")
+ .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(
+ appInfo.getQueue()))).append("\",\"")
.append(appInfo.getStartTime()).append("\",\"")
.append(appInfo.getFinishTime()).append("\",\"")
.append(appInfo.getState()).append("\",\"")
|
e1a3ff9470763e7c6ff5a887036390bd418f4e46
|
Vala
|
Support explicit interface methods implementation
Fixes bug 652098
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/codegen/valaccodeattribute.vala b/codegen/valaccodeattribute.vala
index 7e1c38a8a3..03ace0b7b2 100644
--- a/codegen/valaccodeattribute.vala
+++ b/codegen/valaccodeattribute.vala
@@ -1254,7 +1254,13 @@ public class Vala.CCodeAttribute : AttributeCache {
} else if (sym is Method) {
var m = (Method) sym;
if (m.base_method != null || m.base_interface_method != null) {
- return "%sreal_%s".printf (CCodeBaseModule.get_ccode_lower_case_prefix (m.parent_symbol), m.name);
+ if (m.base_interface_type != null) {
+ return "%sreal_%s%s".printf (CCodeBaseModule.get_ccode_lower_case_prefix (m.parent_symbol),
+ CCodeBaseModule.get_ccode_lower_case_prefix (m.base_interface_type.data_type),
+ m.name);
+ } else {
+ return "%sreal_%s".printf (CCodeBaseModule.get_ccode_lower_case_prefix (m.parent_symbol), m.name);
+ }
} else {
return name;
}
diff --git a/tests/Makefile.am b/tests/Makefile.am
index 4833286d85..bcf82e1afa 100644
--- a/tests/Makefile.am
+++ b/tests/Makefile.am
@@ -54,6 +54,7 @@ TESTS = \
methods/bug646345.vala \
methods/bug648320.vala \
methods/bug649562.vala \
+ methods/bug652098.vala \
methods/bug653391.vala \
methods/bug653908.vala \
methods/bug663210.vala \
diff --git a/tests/methods/bug652098.vala b/tests/methods/bug652098.vala
new file mode 100644
index 0000000000..d16f27f5d4
--- /dev/null
+++ b/tests/methods/bug652098.vala
@@ -0,0 +1,55 @@
+interface Iface1 : Object {
+ public abstract int foo ();
+}
+
+interface Iface2 : Object {
+ public abstract int foo ();
+}
+
+class Obj1 : Object, Iface1, Iface2 {
+ public int Iface1.foo () {
+ return 1;
+ }
+
+ public int Iface2.foo () {
+ return 2;
+ }
+}
+
+class Obj2 : Object, Iface1, Iface2 {
+ public int Iface1.foo () {
+ return 1;
+ }
+
+ public int foo () {
+ return 2;
+ }
+}
+
+class Base : Object {
+ public void foo () {
+ }
+}
+
+interface Iface : Object {
+ public abstract void foo ();
+}
+
+class Concrete : Base, Iface {
+}
+
+void main () {
+ var obj1 = new Obj1 ();
+ var iface1 = (Iface1) obj1;
+ var iface2 = (Iface2) obj1;
+
+ assert (iface1.foo () == 1);
+ assert (iface2.foo () == 2);
+
+ var obj2 = new Obj2 ();
+ iface1 = (Iface1) obj2;
+ iface2 = (Iface2) obj2;
+
+ assert (iface1.foo () == 1);
+ assert (iface2.foo () == 2);
+}
\ No newline at end of file
diff --git a/vala/valaclass.vala b/vala/valaclass.vala
index ba23a508fb..12a82afd0b 100644
--- a/vala/valaclass.vala
+++ b/vala/valaclass.vala
@@ -317,7 +317,12 @@ public class Vala.Class : ObjectTypeSymbol {
}
methods.add (m);
- scope.add (m.name, m);
+ if (m.base_interface_type == null) {
+ scope.add (m.name, m);
+ } else {
+ // explicit interface method implementation
+ scope.add (null, m);
+ }
}
/**
@@ -782,18 +787,22 @@ public class Vala.Class : ObjectTypeSymbol {
/* check methods */
foreach (Method m in iface.get_methods ()) {
if (m.is_abstract) {
- Symbol sym = null;
+ var implemented = false;
var base_class = this;
- while (base_class != null && !(sym is Method)) {
- sym = base_class.scope.lookup (m.name);
+ while (base_class != null) {
+ foreach (var impl in base_class.get_methods ()) {
+ if (impl.name == m.name && (impl.base_interface_type == null || impl.base_interface_type.data_type == iface)) {
+ // method is used as interface implementation, so it is not unused
+ impl.check_deprecated (source_reference);
+ impl.check_experimental (source_reference);
+ impl.used = true;
+ implemented = true;
+ break;
+ }
+ }
base_class = base_class.base_class;
}
- if (sym is Method) {
- // method is used as interface implementation, so it is not unused
- sym.check_deprecated (source_reference);
- sym.check_experimental (source_reference);
- sym.used = true;
- } else {
+ if (!implemented) {
error = true;
Report.error (source_reference, "`%s' does not implement interface method `%s'".printf (get_full_name (), m.get_full_name ()));
}
diff --git a/vala/valamethod.vala b/vala/valamethod.vala
index 3e9096a7df..afc7053875 100644
--- a/vala/valamethod.vala
+++ b/vala/valamethod.vala
@@ -109,7 +109,7 @@ public class Vala.Method : Subroutine {
return _base_method;
}
}
-
+
/**
* Specifies the abstract interface method this method implements.
*/
@@ -120,6 +120,17 @@ public class Vala.Method : Subroutine {
}
}
+ /**
+ * Specifies the explicit interface containing the method this method implements.
+ */
+ public DataType base_interface_type {
+ get { return _base_interface_type; }
+ set {
+ _base_interface_type = value;
+ _base_interface_type.parent_node = this;
+ }
+ }
+
public bool entry_point { get; private set; }
/**
@@ -181,6 +192,7 @@ public class Vala.Method : Subroutine {
private weak Method _base_method;
private weak Method _base_interface_method;
+ private DataType _base_interface_type;
private bool base_methods_valid;
Method? callback_method;
@@ -249,6 +261,10 @@ public class Vala.Method : Subroutine {
p.accept (visitor);
}
+ if (base_interface_type != null) {
+ base_interface_type.accept (visitor);
+ }
+
if (return_type != null) {
return_type.accept (visitor);
}
@@ -471,6 +487,10 @@ public class Vala.Method : Subroutine {
}
public override void replace_type (DataType old_type, DataType new_type) {
+ if (base_interface_type == old_type) {
+ base_interface_type = new_type;
+ return;
+ }
if (return_type == old_type) {
return_type = new_type;
return;
@@ -532,9 +552,12 @@ public class Vala.Method : Subroutine {
}
private void find_base_interface_method (Class cl) {
- // FIXME report error if multiple possible base methods are found
foreach (DataType type in cl.get_base_types ()) {
if (type.data_type is Interface) {
+ if (base_interface_type != null && base_interface_type.data_type != type.data_type) {
+ continue;
+ }
+
var sym = type.data_type.scope.lookup (name);
if (sym is Signal) {
var sig = (Signal) sym;
@@ -543,19 +566,37 @@ public class Vala.Method : Subroutine {
if (sym is Method) {
var base_method = (Method) sym;
if (base_method.is_abstract || base_method.is_virtual) {
- string invalid_match;
+ if (base_interface_type == null) {
+ // check for existing explicit implementation
+ var has_explicit_implementation = false;
+ foreach (var m in cl.get_methods ()) {
+ if (m.base_interface_type != null && base_method == m.base_interface_method) {
+ has_explicit_implementation = true;
+ break;
+ }
+ }
+ if (has_explicit_implementation) {
+ continue;
+ }
+ }
+
+ string invalid_match = null;
if (!compatible (base_method, out invalid_match)) {
error = true;
Report.error (source_reference, "overriding method `%s' is incompatible with base method `%s': %s.".printf (get_full_name (), base_method.get_full_name (), invalid_match));
return;
}
-
+
_base_interface_method = base_method;
return;
}
}
}
}
+
+ if (base_interface_type != null) {
+ Report.error (source_reference, "%s: no suitable interface method found to implement".printf (get_full_name ()));
+ }
}
public override bool check (CodeContext context) {
@@ -716,6 +757,20 @@ public class Vala.Method : Subroutine {
return false;
}
+ if (base_interface_type != null && base_interface_method != null && parent_symbol is Class) {
+ var cl = (Class) parent_symbol;
+ foreach (var m in cl.get_methods ()) {
+ if (m != this && m.base_interface_method == base_interface_method) {
+ m.checked = true;
+ m.error = true;
+ error = true;
+ Report.error (source_reference, "`%s' already contains an implementation for `%s'".printf (cl.get_full_name (), base_interface_method.get_full_name ()));
+ Report.notice (m.source_reference, "previous implementation of `%s' was here".printf (base_interface_method.get_full_name ()));
+ return false;
+ }
+ }
+ }
+
context.analyzer.current_source_file = old_source_file;
context.analyzer.current_symbol = old_symbol;
diff --git a/vala/valaparser.vala b/vala/valaparser.vala
index 3a478bc0c9..c465a8e623 100644
--- a/vala/valaparser.vala
+++ b/vala/valaparser.vala
@@ -2619,9 +2619,12 @@ public class Vala.Parser : CodeVisitor {
var access = parse_access_modifier ();
var flags = parse_member_declaration_modifiers ();
var type = parse_type (true, false);
- string id = parse_identifier ();
+ var sym = parse_symbol_name ();
var type_param_list = parse_type_parameter_list ();
- var method = new Method (id, type, get_src (begin), comment);
+ var method = new Method (sym.name, type, get_src (begin), comment);
+ if (sym.inner != null) {
+ method.base_interface_type = new UnresolvedType.from_symbol (sym.inner, sym.inner.source_reference);
+ }
method.access = access;
set_attributes (method, attrs);
foreach (TypeParameter type_param in type_param_list) {
|
8d6c881e5239e30a4e8d184ede2dd9ae5a439273
|
Vala
|
Fixes bug 614268.
|
c
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/clutter-1.0.vapi b/vapi/clutter-1.0.vapi
index 001159e6f8..52e392de44 100644
--- a/vapi/clutter-1.0.vapi
+++ b/vapi/clutter-1.0.vapi
@@ -104,6 +104,8 @@ namespace Clutter {
public Clutter.ActorFlags get_flags ();
public void get_geometry (Clutter.Geometry geometry);
public uint32 get_gid ();
+ [CCode (cname = "clutter_actor_has_pointer")]
+ public bool get_has_pointer ();
public uchar get_paint_opacity ();
public bool get_paint_visibility ();
public unowned Pango.Context get_pango_context ();
@@ -112,12 +114,14 @@ namespace Clutter {
public virtual void get_preferred_height (float for_width, out float min_height_p, out float natural_height_p);
public void get_preferred_size (out unowned float? min_width_p, out unowned float? min_height_p, out unowned float? natural_width_p, out unowned float? natural_height_p);
public virtual void get_preferred_width (float for_height, out float min_width_p, out float natural_width_p);
+ public Clutter.RequestMode get_request_mode ();
public double get_rotation (out Clutter.RotateAxis axis, out float x, out float y, out float z);
public void get_scale (out double scale_x, out double scale_y);
public void get_scale_center (out float center_x, out float center_y);
public unowned Clutter.Shader get_shader ();
public void get_size (out float width, out float height);
public unowned Clutter.Stage get_stage ();
+ public Clutter.TextDirection get_text_direction ();
public void get_transformation_matrix (Cogl.Matrix matrix);
public void get_transformed_position (out float x, out float y);
public void get_transformed_size (out float width, out float height);
@@ -133,8 +137,9 @@ namespace Clutter {
public void move_anchor_point (float anchor_x, float anchor_y);
public void move_anchor_point_from_gravity (Clutter.Gravity gravity);
public void move_by (float dx, float dy);
+ public void pop_internal ();
+ public void push_internal ();
public void queue_redraw ();
- public void queue_relayout ();
public void raise (Clutter.Actor below);
public void raise_top ();
public void remove_clip ();
@@ -147,6 +152,7 @@ namespace Clutter {
public void set_geometry (Clutter.Geometry geometry);
public void set_parent (Clutter.Actor parent);
public void set_position (float x, float y);
+ public void set_request_mode (Clutter.RequestMode mode);
public void set_rotation (Clutter.RotateAxis axis, double angle, float x, float y, float z);
public void set_scale (double scale_x, double scale_y);
public void set_scale_full (double scale_x, double scale_y, float center_x, float center_y);
@@ -156,6 +162,7 @@ namespace Clutter {
public void set_shader_param_float (string param, float value);
public void set_shader_param_int (string param, int value);
public void set_size (float width, float height);
+ public void set_text_direction (Clutter.TextDirection text_dir);
public void set_z_rotation_from_gravity (double angle, Clutter.Gravity gravity);
public bool should_pick_paint ();
public virtual void show_all ();
@@ -183,6 +190,8 @@ namespace Clutter {
public float fixed_y { get; set; }
[NoAccessorMethod]
public bool has_clip { get; }
+ [NoAccessorMethod]
+ public bool has_pointer { get; }
public float height { get; set; }
[NoAccessorMethod]
public bool mapped { get; }
@@ -203,11 +212,10 @@ namespace Clutter {
public float natural_width { get; set; }
[NoAccessorMethod]
public bool natural_width_set { get; set; }
- public uchar opacity { get; set; }
+ public uint opacity { get; set; }
public bool reactive { get; set; }
[NoAccessorMethod]
public bool realized { get; }
- [NoAccessorMethod]
public Clutter.RequestMode request_mode { get; set; }
[NoAccessorMethod]
public double rotation_angle_x { get; set; }
@@ -235,6 +243,7 @@ namespace Clutter {
public double scale_y { get; set; }
[NoAccessorMethod]
public bool show_on_set_parent { get; set; }
+ public Clutter.TextDirection text_direction { get; set; }
[NoAccessorMethod]
public bool visible { get; set; }
public float width { get; set; }
@@ -263,6 +272,8 @@ namespace Clutter {
[HasEmitter]
public virtual signal void pick (Clutter.Color color);
[HasEmitter]
+ public virtual signal void queue_relayout ();
+ [HasEmitter]
public virtual signal void realize ();
public virtual signal bool scroll_event (Clutter.ScrollEvent event);
[HasEmitter]
@@ -271,7 +282,7 @@ namespace Clutter {
public virtual signal void unrealize ();
}
[CCode (cheader_filename = "clutter/clutter.h")]
- public class Alpha : GLib.InitiallyUnowned {
+ public class Alpha : GLib.InitiallyUnowned, Clutter.Scriptable {
[CCode (has_construct_function = false)]
public Alpha ();
[CCode (has_construct_function = false)]
@@ -287,7 +298,7 @@ namespace Clutter {
public Clutter.Timeline timeline { get; set; }
}
[CCode (cheader_filename = "clutter/clutter.h")]
- public class Animation : GLib.Object {
+ public class Animation : GLib.Object, Clutter.Scriptable {
[CCode (has_construct_function = false)]
public Animation ();
public unowned Clutter.Animation bind (string property_name, GLib.Value final);
@@ -295,6 +306,7 @@ namespace Clutter {
public unowned Clutter.Interval get_interval (string property_name);
public bool has_property (string property_name);
public void unbind_property (string property_name);
+ public unowned Clutter.Animation update (string property_name, GLib.Value final);
public void update_interval (string property_name, Clutter.Interval interval);
public Clutter.Alpha alpha { get; set; }
public uint duration { get; set; }
@@ -307,15 +319,48 @@ namespace Clutter {
public virtual signal void started ();
}
[CCode (cheader_filename = "clutter/clutter.h")]
+ public class Animator : GLib.Object, Clutter.Scriptable {
+ [CCode (has_construct_function = false)]
+ public Animator ();
+ public bool compute_value (GLib.Object object, string property_name, double progress, GLib.Value value);
+ public uint get_duration ();
+ public unowned GLib.List get_keys (GLib.Object object, string property_name, double progress);
+ public unowned Clutter.Timeline get_timeline ();
+ public bool property_get_ease_in (GLib.Object object, string property_name);
+ public Clutter.Interpolation property_get_interpolation (GLib.Object object, string property_name);
+ public void property_set_ease_in (GLib.Object object, string property_name, bool ease_in);
+ public void property_set_interpolation (GLib.Object object, string property_name, Clutter.Interpolation interpolation);
+ public void remove_key (GLib.Object object, string property_name, double progress);
+ public void @set (void* first_object, string first_property_name, uint first_mode, ...);
+ public void set_duration (uint duration);
+ public unowned Clutter.Animator set_key (GLib.Object object, string property_name, uint mode, double progress, GLib.Value value);
+ public void set_timeline (Clutter.Timeline timeline);
+ public unowned Clutter.Timeline start ();
+ public uint duration { get; set; }
+ public Clutter.Timeline timeline { get; set; }
+ }
+ [Compact]
+ [CCode (type_id = "CLUTTER_TYPE_ANIMATOR_KEY", cheader_filename = "clutter/clutter.h")]
+ public class AnimatorKey {
+ public ulong get_mode ();
+ public unowned GLib.Object get_object ();
+ public double get_progress ();
+ public unowned string get_property_name ();
+ public GLib.Type get_property_type ();
+ public bool get_value (GLib.Value value);
+ }
+ [CCode (cheader_filename = "clutter/clutter.h")]
public class Backend : GLib.Object {
[NoWrapper]
public virtual void add_options (GLib.OptionGroup group);
[NoWrapper]
- public virtual bool create_context (bool is_offscreen) throws GLib.Error;
+ public virtual bool create_context () throws GLib.Error;
[NoWrapper]
- public virtual unowned Clutter.Actor create_stage (Clutter.Stage wrapper) throws GLib.Error;
+ public virtual unowned Clutter.StageWindow create_stage (Clutter.Stage wrapper) throws GLib.Error;
[NoWrapper]
public virtual void ensure_context (Clutter.Stage stage);
+ [NoWrapper]
+ public virtual unowned Clutter.DeviceManager get_device_manager ();
public uint get_double_click_distance ();
public uint get_double_click_time ();
[NoWrapper]
@@ -342,7 +387,7 @@ namespace Clutter {
public virtual signal void resolution_changed ();
}
[CCode (cheader_filename = "clutter/clutter.h")]
- public class Behaviour : GLib.Object {
+ public class Behaviour : GLib.Object, Clutter.Scriptable {
public void actors_foreach (Clutter.BehaviourForeachFunc func);
[NoWrapper]
public virtual void alpha_notify (double alpha_value);
@@ -358,7 +403,7 @@ namespace Clutter {
public virtual signal void removed (Clutter.Actor actor);
}
[CCode (cheader_filename = "clutter/clutter.h")]
- public class BehaviourDepth : Clutter.Behaviour {
+ public class BehaviourDepth : Clutter.Behaviour, Clutter.Scriptable {
[CCode (type = "ClutterBehaviour*", has_construct_function = false)]
public BehaviourDepth (Clutter.Alpha alpha, int depth_start, int depth_end);
public void get_bounds (out int depth_start, out int depth_end);
@@ -369,7 +414,7 @@ namespace Clutter {
public int depth_start { get; set; }
}
[CCode (cheader_filename = "clutter/clutter.h")]
- public class BehaviourEllipse : Clutter.Behaviour {
+ public class BehaviourEllipse : Clutter.Behaviour, Clutter.Scriptable {
[CCode (type = "ClutterBehaviour*", has_construct_function = false)]
public BehaviourEllipse (Clutter.Alpha alpha, int x, int y, int width, int height, Clutter.RotateDirection direction, double start, double end);
public double get_angle_tilt (Clutter.RotateAxis axis);
@@ -393,7 +438,7 @@ namespace Clutter {
public int width { get; set; }
}
[CCode (cheader_filename = "clutter/clutter.h")]
- public class BehaviourOpacity : Clutter.Behaviour {
+ public class BehaviourOpacity : Clutter.Behaviour, Clutter.Scriptable {
[CCode (type = "ClutterBehaviour*", has_construct_function = false)]
public BehaviourOpacity (Clutter.Alpha alpha, uchar opacity_start, uchar opacity_end);
public void get_bounds (out uchar opacity_start, out uchar opacity_end);
@@ -415,7 +460,7 @@ namespace Clutter {
public virtual signal void knot_reached (uint knot_num);
}
[CCode (cheader_filename = "clutter/clutter.h")]
- public class BehaviourRotate : Clutter.Behaviour {
+ public class BehaviourRotate : Clutter.Behaviour, Clutter.Scriptable {
[CCode (type = "ClutterBehaviour*", has_construct_function = false)]
public BehaviourRotate (Clutter.Alpha alpha, Clutter.RotateAxis axis, Clutter.RotateDirection direction, double angle_start, double angle_end);
public void get_bounds (out double angle_start, out double angle_end);
@@ -436,7 +481,7 @@ namespace Clutter {
public Clutter.RotateDirection direction { get; set; }
}
[CCode (cheader_filename = "clutter/clutter.h")]
- public class BehaviourScale : Clutter.Behaviour {
+ public class BehaviourScale : Clutter.Behaviour, Clutter.Scriptable {
[CCode (type = "ClutterBehaviour*", has_construct_function = false)]
public BehaviourScale (Clutter.Alpha alpha, double x_scale_start, double y_scale_start, double x_scale_end, double y_scale_end);
public void get_bounds (out double x_scale_start, out double y_scale_start, out double x_scale_end, out double y_scale_end);
@@ -451,6 +496,18 @@ namespace Clutter {
public double y_scale_start { get; set; }
}
[CCode (cheader_filename = "clutter/clutter.h")]
+ public class BinLayout : Clutter.LayoutManager {
+ [CCode (type = "ClutterLayoutManager*", has_construct_function = false)]
+ public BinLayout (Clutter.BinAlignment x_align, Clutter.BinAlignment y_align);
+ public void add (Clutter.Actor child, Clutter.BinAlignment x_align, Clutter.BinAlignment y_align);
+ public void get_alignment (Clutter.Actor child, Clutter.BinAlignment x_align, Clutter.BinAlignment y_align);
+ public void set_alignment (Clutter.Actor child, Clutter.BinAlignment x_align, Clutter.BinAlignment y_align);
+ [NoAccessorMethod]
+ public Clutter.BinAlignment x_align { get; set; }
+ [NoAccessorMethod]
+ public Clutter.BinAlignment y_align { get; set; }
+ }
+ [CCode (cheader_filename = "clutter/clutter.h")]
public class BindingPool : GLib.Object {
[CCode (has_construct_function = false)]
public BindingPool (string name);
@@ -469,6 +526,54 @@ namespace Clutter {
public string name { owned get; construct; }
}
[CCode (cheader_filename = "clutter/clutter.h")]
+ public class Box : Clutter.Actor, Clutter.Scriptable, Clutter.Container {
+ [CCode (type = "ClutterActor*", has_construct_function = false)]
+ public Box (Clutter.LayoutManager manager);
+ public void get_color (Clutter.Color color);
+ public unowned Clutter.LayoutManager get_layout_manager ();
+ public void pack (Clutter.Actor actor, ...);
+ public void pack_after (Clutter.Actor actor, Clutter.Actor sibling, ...);
+ public void pack_at (Clutter.Actor actor, int position, ...);
+ public void pack_before (Clutter.Actor actor, Clutter.Actor sibling, ...);
+ public void packv (Clutter.Actor actor, uint n_properties, string[] properties, GLib.Value values);
+ public void set_color (Clutter.Color color);
+ public void set_layout_manager (Clutter.LayoutManager manager);
+ public Clutter.Color color { get; set; }
+ [NoAccessorMethod]
+ public bool color_set { get; set; }
+ public Clutter.LayoutManager layout_manager { get; set construct; }
+ }
+ [CCode (cheader_filename = "clutter/clutter.h")]
+ public class BoxLayout : Clutter.LayoutManager {
+ [CCode (type = "ClutterLayoutManager*", has_construct_function = false)]
+ public BoxLayout ();
+ public void get_alignment (Clutter.Actor actor, Clutter.BoxAlignment x_align, Clutter.BoxAlignment y_align);
+ public uint get_easing_duration ();
+ public ulong get_easing_mode ();
+ public bool get_expand (Clutter.Actor actor);
+ public void get_fill (Clutter.Actor actor, bool x_fill, bool y_fill);
+ public bool get_pack_start ();
+ public uint get_spacing ();
+ public bool get_use_animations ();
+ public bool get_vertical ();
+ public void pack (Clutter.Actor actor, bool expand, bool x_fill, bool y_fill, Clutter.BoxAlignment x_align, Clutter.BoxAlignment y_align);
+ public void set_alignment (Clutter.Actor actor, Clutter.BoxAlignment x_align, Clutter.BoxAlignment y_align);
+ public void set_easing_duration (uint msecs);
+ public void set_easing_mode (ulong mode);
+ public void set_expand (Clutter.Actor actor, bool expand);
+ public void set_fill (Clutter.Actor actor, bool x_fill, bool y_fill);
+ public void set_pack_start (bool pack_start);
+ public void set_spacing (uint spacing);
+ public void set_use_animations (bool animate);
+ public void set_vertical (bool vertical);
+ public uint easing_duration { get; set; }
+ public ulong easing_mode { get; set; }
+ public bool pack_start { get; set; }
+ public uint spacing { get; set; }
+ public bool use_animations { get; set; }
+ public bool vertical { get; set; }
+ }
+ [CCode (cheader_filename = "clutter/clutter.h")]
public class CairoTexture : Clutter.Texture, Clutter.Scriptable {
[CCode (type = "ClutterActor*", has_construct_function = false)]
public CairoTexture (uint width, uint height);
@@ -491,7 +596,25 @@ namespace Clutter {
public class Clone : Clutter.Actor, Clutter.Scriptable {
[CCode (type = "ClutterActor*", has_construct_function = false)]
public Clone (Clutter.Actor source);
- public Clutter.Actor source { get; construct; }
+ public Clutter.Actor source { get; set construct; }
+ }
+ [CCode (cheader_filename = "clutter/clutter.h")]
+ public class DeviceManager : GLib.Object {
+ [NoWrapper]
+ public virtual void add_device (Clutter.InputDevice device);
+ public virtual unowned Clutter.InputDevice get_core_device (Clutter.InputDeviceType device_type);
+ public static unowned Clutter.DeviceManager get_default ();
+ public virtual unowned Clutter.InputDevice get_device (int device_id);
+ [NoWrapper]
+ public virtual unowned GLib.SList get_devices ();
+ public unowned GLib.SList list_devices ();
+ public unowned GLib.SList peek_devices ();
+ [NoWrapper]
+ public virtual void remove_device (Clutter.InputDevice device);
+ [NoAccessorMethod]
+ public Clutter.Backend backend { owned get; construct; }
+ public virtual signal void device_added (Clutter.InputDevice p0);
+ public virtual signal void device_removed (Clutter.InputDevice p0);
}
[Compact]
[CCode (copy_function = "clutter_event_copy", type_id = "CLUTTER_TYPE_EVENT", cheader_filename = "clutter/clutter.h")]
@@ -530,6 +653,40 @@ namespace Clutter {
public void put ();
}
[CCode (cheader_filename = "clutter/clutter.h")]
+ public class FixedLayout : Clutter.LayoutManager {
+ [CCode (type = "ClutterLayoutManager*", has_construct_function = false)]
+ public FixedLayout ();
+ }
+ [CCode (cheader_filename = "clutter/clutter.h")]
+ public class FlowLayout : Clutter.LayoutManager {
+ [CCode (type = "ClutterLayoutManager*", has_construct_function = false)]
+ public FlowLayout (Clutter.FlowOrientation orientation);
+ public float get_column_spacing ();
+ public void get_column_width (float min_width, float max_width);
+ public bool get_homogeneous ();
+ public Clutter.FlowOrientation get_orientation ();
+ public void get_row_height (float min_height, float max_height);
+ public float get_row_spacing ();
+ public void set_column_spacing (float spacing);
+ public void set_column_width (float min_width, float max_width);
+ public void set_homogeneous (bool homogeneous);
+ public void set_orientation (Clutter.FlowOrientation orientation);
+ public void set_row_height (float min_height, float max_height);
+ public void set_row_spacing (float spacing);
+ public float column_spacing { get; set; }
+ public bool homogeneous { get; set; }
+ [NoAccessorMethod]
+ public float max_column_width { get; set; }
+ [NoAccessorMethod]
+ public float max_row_height { get; set; }
+ [NoAccessorMethod]
+ public float min_column_width { get; set; }
+ [NoAccessorMethod]
+ public float min_row_height { get; set; }
+ public Clutter.FlowOrientation orientation { get; set construct; }
+ public float row_spacing { get; set; }
+ }
+ [CCode (cheader_filename = "clutter/clutter.h")]
public class Group : Clutter.Actor, Clutter.Scriptable, Clutter.Container {
[CCode (type = "ClutterActor*", has_construct_function = false)]
public Group ();
@@ -537,12 +694,22 @@ namespace Clutter {
public unowned Clutter.Actor get_nth_child (int index_);
public void remove_all ();
}
- [CCode (ref_function = "clutter_input_device_ref", unref_function = "clutter_input_device_unref", cheader_filename = "clutter/clutter.h")]
- public class InputDevice {
+ [CCode (cheader_filename = "clutter/clutter.h")]
+ public class InputDevice : GLib.Object {
+ public void get_device_coords (int x, int y);
public int get_device_id ();
+ public unowned string get_device_name ();
public Clutter.InputDeviceType get_device_type ();
[CCode (cname = "clutter_get_input_device_for_id")]
public static unowned Clutter.InputDevice get_for_id (int id);
+ public unowned Clutter.Actor get_pointer_actor ();
+ public unowned Clutter.Stage get_pointer_stage ();
+ public void update_from_event (Clutter.Event event, bool update_stage);
+ public Clutter.InputDeviceType device_type { get; construct; }
+ [NoAccessorMethod]
+ public int id { get; construct; }
+ [NoAccessorMethod]
+ public string name { owned get; construct; }
}
[CCode (cheader_filename = "clutter/clutter.h")]
public class Interval : GLib.InitiallyUnowned {
@@ -565,14 +732,45 @@ namespace Clutter {
public GLib.Type value_type { get; construct; }
}
[CCode (cheader_filename = "clutter/clutter.h")]
- public class ListModel : Clutter.Model {
+ public class LayoutManager : GLib.InitiallyUnowned {
+ public void* dummy;
+ public virtual void allocate (Clutter.Container container, Clutter.ActorBox allocation, Clutter.AllocationFlags flags);
+ public virtual unowned Clutter.Alpha begin_animation (uint duration, ulong mode);
+ public void child_get (Clutter.Container container, Clutter.Actor actor, ...);
+ public void child_get_property (Clutter.Container container, Clutter.Actor actor, string property_name, GLib.Value value);
+ public void child_set (Clutter.Container container, Clutter.Actor actor, ...);
+ public void child_set_property (Clutter.Container container, Clutter.Actor actor, string property_name, GLib.Value value);
+ [NoWrapper]
+ public virtual unowned Clutter.LayoutMeta create_child_meta (Clutter.Container container, Clutter.Actor actor);
+ public virtual void end_animation ();
+ public unowned Clutter.ParamSpecColor find_child_property (string name);
+ public virtual double get_animation_progress ();
+ public unowned Clutter.LayoutMeta get_child_meta (Clutter.Container container, Clutter.Actor actor);
+ [NoWrapper]
+ public virtual GLib.Type get_child_meta_type ();
+ public virtual void get_preferred_height (Clutter.Container container, float for_width, float min_height_p, float nat_height_p);
+ public virtual void get_preferred_width (Clutter.Container container, float for_height, float min_width_p, float nat_width_p);
+ public unowned Clutter.ParamSpecColor list_child_properties (uint n_pspecs);
+ public virtual void set_container (Clutter.Container container);
+ [HasEmitter]
+ public virtual signal void layout_changed ();
+ }
+ [CCode (cheader_filename = "clutter/clutter.h")]
+ public class LayoutMeta : Clutter.ChildMeta {
+ public int32 dummy0;
+ public void* dummy1;
+ public unowned Clutter.LayoutManager get_manager ();
+ public Clutter.LayoutManager manager { get; construct; }
+ }
+ [CCode (cheader_filename = "clutter/clutter.h")]
+ public class ListModel : Clutter.Model, Clutter.Scriptable {
[CCode (type = "ClutterModel*", has_construct_function = false)]
public ListModel (uint n_columns);
[CCode (cname = "clutter_list_model_newv", type = "ClutterModel*", has_construct_function = false)]
public ListModel.newv ([CCode (array_length_pos = 0.9)] GLib.Type[] types, [CCode (array_length_pos = 0.9)] string[] names);
}
[CCode (cheader_filename = "clutter/clutter.h")]
- public class Model : GLib.Object {
+ public class Model : GLib.Object, Clutter.Scriptable {
public void append (...);
public void appendv ([CCode (array_length_pos = 0.9)] uint[] columns, [CCode (array_length_pos = 0.9)] GLib.Value[] values);
public bool filter_iter (Clutter.ModelIter iter);
@@ -779,8 +977,10 @@ namespace Clutter {
public static unowned Clutter.Stage get_default ();
public bool get_fullscreen ();
public unowned Clutter.Actor get_key_focus ();
+ public void get_minimum_size (uint width, uint height);
public void get_perspective (out Clutter.Perspective perspective);
public bool get_throttle_motion_events ();
+ public bool get_use_alpha ();
public void hide_cursor ();
public bool is_default ();
public void queue_redraw ();
@@ -788,9 +988,11 @@ namespace Clutter {
[CCode (cname = "clutter_redraw")]
public void redraw ();
public void set_fullscreen (bool fullscreen);
- public void set_key_focus (Clutter.Actor actor);
+ public void set_key_focus (Clutter.Actor? actor);
+ public void set_minimum_size (uint width, uint height);
public void set_perspective (Clutter.Perspective perspective);
public void set_throttle_motion_events (bool throttle);
+ public void set_use_alpha (bool use_alpha);
public void show_cursor ();
public Clutter.Color color { get; set; }
[NoAccessorMethod]
@@ -798,15 +1000,18 @@ namespace Clutter {
public Clutter.Fog fog { get; set; }
[NoAccessorMethod]
public bool fullscreen_set { get; }
+ public Clutter.Actor key_focus { get; set; }
[NoAccessorMethod]
public bool offscreen { get; set; }
[NoAccessorMethod]
public Clutter.Perspective perspective { get; set; }
public string title { get; set; }
+ public bool use_alpha { get; set; }
public bool use_fog { get; set; }
public bool user_resizable { get; set; }
public virtual signal void activate ();
public virtual signal void deactivate ();
+ public virtual signal bool delete_event (Clutter.Event event);
[HasEmitter]
public virtual signal void fullscreen ();
[HasEmitter]
@@ -817,7 +1022,7 @@ namespace Clutter {
public static unowned Clutter.StageManager get_default ();
public unowned GLib.SList<Clutter.Stage> list_stages ();
public unowned GLib.SList<Clutter.Stage> peek_stages ();
- public Clutter.Stage default_stage { get; set; }
+ public Clutter.Stage default_stage { get; }
public virtual signal void stage_added (Clutter.Stage stage);
public virtual signal void stage_removed (Clutter.Stage stage);
}
@@ -827,12 +1032,12 @@ namespace Clutter {
public Text ();
public void delete_chars (uint n_chars);
public bool delete_selection ();
- public void delete_text (ssize_t start_pos, ssize_t end_pos);
[CCode (type = "ClutterActor*", has_construct_function = false)]
public Text.full (string font_name, string text, Clutter.Color color);
public unowned Pango.AttrList get_attributes ();
public unowned string get_chars (ssize_t start_pos, ssize_t end_pos);
public int get_cursor_position ();
+ public unowned Pango.FontDescription get_font_description ();
public unowned Pango.Layout get_layout ();
public unowned string get_selection ();
public void insert_text (string text, ssize_t position);
@@ -840,10 +1045,12 @@ namespace Clutter {
public bool position_to_coords (int position, float x, float y, float line_height);
public void set_attributes (Pango.AttrList attrs);
public void set_cursor_position (int position);
+ public void set_font_description (Pango.FontDescription font_desc);
public void set_markup (string markup);
+ public void set_preedit_string (string preedit_str, Pango.AttrList preedit_attrs, uint cursor_pos);
public void set_selection (ssize_t start_pos, ssize_t end_pos);
[CCode (type = "ClutterActor*", has_construct_function = false)]
- public Text.with_text (string font_name, string text);
+ public Text.with_text (string? font_name, string text);
public bool activatable { get; set; }
public Pango.AttrList attributes { get; set; }
public Clutter.Color color { get; set; }
@@ -854,6 +1061,7 @@ namespace Clutter {
public bool cursor_visible { get; set; }
public bool editable { get; set; }
public Pango.EllipsizeMode ellipsize { get; set; }
+ public Pango.FontDescription font_description { get; set; }
public string font_name { get; set; }
public bool justify { get; set; }
public Pango.Alignment line_alignment { get; set; }
@@ -874,6 +1082,8 @@ namespace Clutter {
[HasEmitter]
public virtual signal void activate ();
public virtual signal void cursor_event (Clutter.Geometry geometry);
+ [HasEmitter]
+ public virtual signal void delete_text (int p0, int p1);
public virtual signal void text_changed ();
}
[CCode (cheader_filename = "clutter/clutter.h")]
@@ -1000,11 +1210,15 @@ namespace Clutter {
public double get_duration ();
public bool get_playing ();
public double get_progress ();
+ public unowned string get_subtitle_font_name ();
+ public unowned string get_subtitle_uri ();
public unowned string get_uri ();
public void set_audio_volume (double volume);
public void set_filename (string filename);
public void set_playing (bool playing);
public void set_progress (double progress);
+ public void set_subtitle_font_name (string font_name);
+ public void set_subtitle_uri (string uri);
public void set_uri (string uri);
public signal void eos ();
public signal void error (void* error);
@@ -1015,12 +1229,46 @@ namespace Clutter {
public abstract void set_custom_property (Clutter.Script script, string name, GLib.Value value);
public abstract void set_id (string id);
}
+ [CCode (cheader_filename = "clutter/clutter.h")]
+ public interface StageWindow : GLib.Object {
+ [NoWrapper]
+ public abstract void add_redraw_clip (Clutter.Geometry stage_rectangle);
+ [NoWrapper]
+ public abstract void get_geometry (Clutter.Geometry geometry);
+ [NoWrapper]
+ public abstract int get_pending_swaps ();
+ [NoWrapper]
+ public abstract unowned Clutter.Actor get_wrapper ();
+ [NoWrapper]
+ public abstract bool has_redraw_clips ();
+ [NoWrapper]
+ public abstract void hide ();
+ [NoWrapper]
+ public abstract bool ignoring_redraw_clips ();
+ [NoWrapper]
+ public abstract bool realize ();
+ [NoWrapper]
+ public abstract void resize (int width, int height);
+ [NoWrapper]
+ public abstract void set_cursor_visible (bool cursor_visible);
+ [NoWrapper]
+ public abstract void set_fullscreen (bool is_fullscreen);
+ [NoWrapper]
+ public abstract void set_title (string title);
+ [NoWrapper]
+ public abstract void set_user_resizable (bool is_resizable);
+ [NoWrapper]
+ public abstract void show (bool do_raise);
+ [NoWrapper]
+ public abstract void unrealize ();
+ }
[CCode (type_id = "CLUTTER_TYPE_ACTOR_BOX", cheader_filename = "clutter/clutter.h")]
public struct ActorBox {
public float x1;
public float y1;
public float x2;
public float y2;
+ public void clamp_to_pixel ();
public bool contains (float x, float y);
public bool equal (Clutter.ActorBox box_b);
[CCode (cname = "clutter_actor_box_from_vertices")]
@@ -1032,6 +1280,7 @@ namespace Clutter {
public float get_width ();
public float get_x ();
public float get_y ();
+ public void interpolate (Clutter.ActorBox final, double progress, Clutter.ActorBox _result);
}
[CCode (type_id = "CLUTTER_TYPE_ANY_EVENT", cheader_filename = "clutter/clutter.h")]
public struct AnyEvent {
@@ -1219,7 +1468,8 @@ namespace Clutter {
MAPPED,
REALIZED,
REACTIVE,
- VISIBLE
+ VISIBLE,
+ NO_LAYOUT
}
[CCode (cprefix = "CLUTTER_", cheader_filename = "clutter/clutter.h")]
[Flags]
@@ -1263,6 +1513,20 @@ namespace Clutter {
EASE_IN_OUT_BOUNCE,
ANIMATION_LAST
}
+ [CCode (cprefix = "CLUTTER_BIN_ALIGNMENT_", cheader_filename = "clutter/clutter.h")]
+ public enum BinAlignment {
+ FIXED,
+ FILL,
+ START,
+ END,
+ CENTER
+ }
+ [CCode (cprefix = "CLUTTER_BOX_ALIGNMENT_", cheader_filename = "clutter/clutter.h")]
+ public enum BoxAlignment {
+ START,
+ END,
+ CENTER
+ }
[CCode (cprefix = "CLUTTER_EVENT_", cheader_filename = "clutter/clutter.h")]
[Flags]
public enum EventFlags {
@@ -1303,6 +1567,11 @@ namespace Clutter {
[CCode (cname = "clutter_feature_get_all")]
public static Clutter.FeatureFlags @get ();
}
+ [CCode (cprefix = "CLUTTER_FLOW_", cheader_filename = "clutter/clutter.h")]
+ public enum FlowOrientation {
+ HORIZONTAL,
+ VERTICAL
+ }
[CCode (cprefix = "CLUTTER_FONT_", cheader_filename = "clutter/clutter.h")]
[Flags]
public enum FontFlags {
@@ -1337,6 +1606,11 @@ namespace Clutter {
EXTENSION_DEVICE,
N_DEVICE_TYPES
}
+ [CCode (cprefix = "CLUTTER_INTERPOLATION_", cheader_filename = "clutter/clutter.h")]
+ public enum Interpolation {
+ LINEAR,
+ CUBIC
+ }
[CCode (cprefix = "CLUTTER_", cheader_filename = "clutter/clutter.h")]
[Flags]
public enum ModifierType {
@@ -1375,6 +1649,12 @@ namespace Clutter {
REACTIVE,
ALL
}
+ [CCode (cprefix = "CLUTTER_REDRAW_CLIPPED_TO_", cheader_filename = "clutter/clutter.h")]
+ [Flags]
+ public enum RedrawFlags {
+ BOX,
+ ALLOCATION
+ }
[CCode (cprefix = "CLUTTER_REQUEST_", cheader_filename = "clutter/clutter.h")]
public enum RequestMode {
HEIGHT_FOR_WIDTH,
@@ -1411,6 +1691,12 @@ namespace Clutter {
OFFSCREEN,
ACTIVATED
}
+ [CCode (cprefix = "CLUTTER_TEXT_DIRECTION_", cheader_filename = "clutter/clutter.h")]
+ public enum TextDirection {
+ DEFAULT,
+ LTR,
+ RTL
+ }
[CCode (cprefix = "CLUTTER_TEXTURE_", cheader_filename = "clutter/clutter.h")]
[Flags]
public enum TextureFlags {
@@ -1435,7 +1721,8 @@ namespace Clutter {
PIXEL,
EM,
MM,
- POINT
+ POINT,
+ CM
}
[CCode (cprefix = "CLUTTER_X11_FILTER_", cheader_filename = "clutter/clutter.h")]
public enum X11FilterReturn {
@@ -1509,12 +1796,16 @@ namespace Clutter {
[CCode (cheader_filename = "clutter/clutter.h")]
public static void cairo_set_source_color (Cairo.Context cr, Clutter.Color color);
[CCode (cheader_filename = "clutter/clutter.h")]
+ public static bool check_version (uint major, uint minor, uint micro);
+ [CCode (cheader_filename = "clutter/clutter.h")]
public static void clear_glyph_cache ();
[CCode (cheader_filename = "clutter/clutter.h")]
public static void do_event (Clutter.Event event);
[CCode (cheader_filename = "clutter/clutter.h")]
public static bool events_pending ();
[CCode (cheader_filename = "clutter/clutter.h")]
+ public static unowned Clutter.Event get_current_event ();
+ [CCode (cheader_filename = "clutter/clutter.h")]
public static uint32 get_current_event_time ();
[CCode (cheader_filename = "clutter/clutter.h")]
public static bool get_debug_enabled ();
@@ -1523,6 +1814,8 @@ namespace Clutter {
[CCode (cheader_filename = "clutter/clutter.h")]
public static uint get_default_frame_rate ();
[CCode (cheader_filename = "clutter/clutter.h")]
+ public static Clutter.TextDirection get_default_text_direction ();
+ [CCode (cheader_filename = "clutter/clutter.h")]
public static Clutter.FontFlags get_font_flags ();
[CCode (cheader_filename = "clutter/clutter.h")]
public static unowned Pango.FontMap get_font_map ();
diff --git a/vapi/packages/clutter-1.0/clutter-1.0.gi b/vapi/packages/clutter-1.0/clutter-1.0.gi
index f52ea127c0..83adb5e985 100644
--- a/vapi/packages/clutter-1.0/clutter-1.0.gi
+++ b/vapi/packages/clutter-1.0/clutter-1.0.gi
@@ -11,6 +11,14 @@
<parameter name="color" type="ClutterColor*"/>
</parameters>
</function>
+ <function name="check_version" symbol="clutter_check_version">
+ <return-type type="gboolean"/>
+ <parameters>
+ <parameter name="major" type="guint"/>
+ <parameter name="minor" type="guint"/>
+ <parameter name="micro" type="guint"/>
+ </parameters>
+ </function>
<function name="clear_glyph_cache" symbol="clutter_clear_glyph_cache">
<return-type type="void"/>
</function>
@@ -56,6 +64,9 @@
<parameter name="id" type="guint32"/>
</parameters>
</function>
+ <function name="get_current_event" symbol="clutter_get_current_event">
+ <return-type type="ClutterEvent*"/>
+ </function>
<function name="get_current_event_time" symbol="clutter_get_current_event_time">
<return-type type="guint32"/>
</function>
@@ -68,6 +79,9 @@
<function name="get_default_frame_rate" symbol="clutter_get_default_frame_rate">
<return-type type="guint"/>
</function>
+ <function name="get_default_text_direction" symbol="clutter_get_default_text_direction">
+ <return-type type="ClutterTextDirection"/>
+ </function>
<function name="get_font_flags" symbol="clutter_get_font_flags">
<return-type type="ClutterFontFlags"/>
</function>
@@ -324,12 +338,6 @@
<parameter name="id" type="gint"/>
</parameters>
</function>
- <function name="util_next_p2" symbol="clutter_util_next_p2">
- <return-type type="int"/>
- <parameters>
- <parameter name="a" type="int"/>
- </parameters>
- </function>
<function name="value_get_color" symbol="clutter_value_get_color">
<return-type type="ClutterColor*"/>
<parameters>
@@ -498,24 +506,6 @@
<parameter name="user_data" type="gpointer"/>
</parameters>
</callback>
- <callback name="JsonArrayForeach">
- <return-type type="void"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- <parameter name="index_" type="guint"/>
- <parameter name="element_node" type="JsonNode*"/>
- <parameter name="user_data" type="gpointer"/>
- </parameters>
- </callback>
- <callback name="JsonObjectForeach">
- <return-type type="void"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="member_name" type="gchar*"/>
- <parameter name="member_node" type="JsonNode*"/>
- <parameter name="user_data" type="gpointer"/>
- </parameters>
- </callback>
<struct name="ClutterAnyEvent">
<field name="type" type="ClutterEventType"/>
<field name="time" type="guint32"/>
@@ -548,20 +538,6 @@
<field name="device" type="ClutterInputDevice*"/>
<field name="related" type="ClutterActor*"/>
</struct>
- <struct name="ClutterInputDevice">
- <method name="get_device_id" symbol="clutter_input_device_get_device_id">
- <return-type type="gint"/>
- <parameters>
- <parameter name="device" type="ClutterInputDevice*"/>
- </parameters>
- </method>
- <method name="get_device_type" symbol="clutter_input_device_get_device_type">
- <return-type type="ClutterInputDeviceType"/>
- <parameters>
- <parameter name="device" type="ClutterInputDevice*"/>
- </parameters>
- </method>
- </struct>
<struct name="ClutterKeyEvent">
<field name="type" type="ClutterEventType"/>
<field name="time" type="guint32"/>
@@ -657,6 +633,12 @@
</method>
</struct>
<boxed name="ClutterActorBox" type-name="ClutterActorBox" get-type="clutter_actor_box_get_type">
+ <method name="clamp_to_pixel" symbol="clutter_actor_box_clamp_to_pixel">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="box" type="ClutterActorBox*"/>
+ </parameters>
+ </method>
<method name="contains" symbol="clutter_actor_box_contains">
<return-type type="gboolean"/>
<parameters>
@@ -737,6 +719,15 @@
<parameter name="box" type="ClutterActorBox*"/>
</parameters>
</method>
+ <method name="interpolate" symbol="clutter_actor_box_interpolate">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="initial" type="ClutterActorBox*"/>
+ <parameter name="final" type="ClutterActorBox*"/>
+ <parameter name="progress" type="gdouble"/>
+ <parameter name="result" type="ClutterActorBox*"/>
+ </parameters>
+ </method>
<constructor name="new" symbol="clutter_actor_box_new">
<return-type type="ClutterActorBox*"/>
<parameters>
@@ -751,6 +742,45 @@
<field name="x2" type="gfloat"/>
<field name="y2" type="gfloat"/>
</boxed>
+ <boxed name="ClutterAnimatorKey" type-name="ClutterAnimatorKey" get-type="clutter_animator_key_get_type">
+ <method name="get_mode" symbol="clutter_animator_key_get_mode">
+ <return-type type="gulong"/>
+ <parameters>
+ <parameter name="key" type="ClutterAnimatorKey*"/>
+ </parameters>
+ </method>
+ <method name="get_object" symbol="clutter_animator_key_get_object">
+ <return-type type="GObject*"/>
+ <parameters>
+ <parameter name="key" type="ClutterAnimatorKey*"/>
+ </parameters>
+ </method>
+ <method name="get_progress" symbol="clutter_animator_key_get_progress">
+ <return-type type="gdouble"/>
+ <parameters>
+ <parameter name="key" type="ClutterAnimatorKey*"/>
+ </parameters>
+ </method>
+ <method name="get_property_name" symbol="clutter_animator_key_get_property_name">
+ <return-type type="gchar*"/>
+ <parameters>
+ <parameter name="key" type="ClutterAnimatorKey*"/>
+ </parameters>
+ </method>
+ <method name="get_property_type" symbol="clutter_animator_key_get_property_type">
+ <return-type type="GType"/>
+ <parameters>
+ <parameter name="key" type="ClutterAnimatorKey*"/>
+ </parameters>
+ </method>
+ <method name="get_value" symbol="clutter_animator_key_get_value">
+ <return-type type="gboolean"/>
+ <parameters>
+ <parameter name="key" type="ClutterAnimatorKey*"/>
+ <parameter name="value" type="GValue*"/>
+ </parameters>
+ </method>
+ </boxed>
<boxed name="ClutterColor" type-name="ClutterColor" get-type="clutter_color_get_type">
<method name="add" symbol="clutter_color_add">
<return-type type="void"/>
@@ -1092,6 +1122,13 @@
<parameter name="units" type="ClutterUnits*"/>
</parameters>
</method>
+ <method name="from_cm" symbol="clutter_units_from_cm">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="units" type="ClutterUnits*"/>
+ <parameter name="cm" type="gfloat"/>
+ </parameters>
+ </method>
<method name="from_em" symbol="clutter_units_from_em">
<return-type type="void"/>
<parameters>
@@ -1163,7 +1200,8 @@
<field name="value" type="gfloat"/>
<field name="pixels" type="gfloat"/>
<field name="pixels_set" type="guint"/>
- <field name="__padding_1" type="gint64"/>
+ <field name="serial" type="gint32"/>
+ <field name="__padding_1" type="gint32"/>
<field name="__padding_2" type="gint64"/>
</boxed>
<boxed name="ClutterVertex" type-name="ClutterVertex" get-type="clutter_vertex_get_type">
@@ -1198,539 +1236,6 @@
<field name="y" type="gfloat"/>
<field name="z" type="gfloat"/>
</boxed>
- <boxed name="JsonArray" type-name="JsonArray" get-type="json_array_get_type">
- <method name="add_array_element" symbol="json_array_add_array_element">
- <return-type type="void"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- <parameter name="value" type="JsonArray*"/>
- </parameters>
- </method>
- <method name="add_boolean_element" symbol="json_array_add_boolean_element">
- <return-type type="void"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- <parameter name="value" type="gboolean"/>
- </parameters>
- </method>
- <method name="add_double_element" symbol="json_array_add_double_element">
- <return-type type="void"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- <parameter name="value" type="gdouble"/>
- </parameters>
- </method>
- <method name="add_element" symbol="json_array_add_element">
- <return-type type="void"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- <parameter name="node" type="JsonNode*"/>
- </parameters>
- </method>
- <method name="add_int_element" symbol="json_array_add_int_element">
- <return-type type="void"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- <parameter name="value" type="gint"/>
- </parameters>
- </method>
- <method name="add_null_element" symbol="json_array_add_null_element">
- <return-type type="void"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- </parameters>
- </method>
- <method name="add_object_element" symbol="json_array_add_object_element">
- <return-type type="void"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- <parameter name="value" type="JsonObject*"/>
- </parameters>
- </method>
- <method name="add_string_element" symbol="json_array_add_string_element">
- <return-type type="void"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- <parameter name="value" type="gchar*"/>
- </parameters>
- </method>
- <method name="dup_element" symbol="json_array_dup_element">
- <return-type type="JsonNode*"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- <parameter name="index_" type="guint"/>
- </parameters>
- </method>
- <method name="foreach_element" symbol="json_array_foreach_element">
- <return-type type="void"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- <parameter name="func" type="JsonArrayForeach"/>
- <parameter name="data" type="gpointer"/>
- </parameters>
- </method>
- <method name="get_array_element" symbol="json_array_get_array_element">
- <return-type type="JsonArray*"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- <parameter name="index_" type="guint"/>
- </parameters>
- </method>
- <method name="get_boolean_element" symbol="json_array_get_boolean_element">
- <return-type type="gboolean"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- <parameter name="index_" type="guint"/>
- </parameters>
- </method>
- <method name="get_double_element" symbol="json_array_get_double_element">
- <return-type type="gdouble"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- <parameter name="index_" type="guint"/>
- </parameters>
- </method>
- <method name="get_element" symbol="json_array_get_element">
- <return-type type="JsonNode*"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- <parameter name="index_" type="guint"/>
- </parameters>
- </method>
- <method name="get_elements" symbol="json_array_get_elements">
- <return-type type="GList*"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- </parameters>
- </method>
- <method name="get_int_element" symbol="json_array_get_int_element">
- <return-type type="gint"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- <parameter name="index_" type="guint"/>
- </parameters>
- </method>
- <method name="get_length" symbol="json_array_get_length">
- <return-type type="guint"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- </parameters>
- </method>
- <method name="get_null_element" symbol="json_array_get_null_element">
- <return-type type="gboolean"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- <parameter name="index_" type="guint"/>
- </parameters>
- </method>
- <method name="get_object_element" symbol="json_array_get_object_element">
- <return-type type="JsonObject*"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- <parameter name="index_" type="guint"/>
- </parameters>
- </method>
- <method name="get_string_element" symbol="json_array_get_string_element">
- <return-type type="gchar*"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- <parameter name="index_" type="guint"/>
- </parameters>
- </method>
- <constructor name="new" symbol="json_array_new">
- <return-type type="JsonArray*"/>
- </constructor>
- <method name="ref" symbol="json_array_ref">
- <return-type type="JsonArray*"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- </parameters>
- </method>
- <method name="remove_element" symbol="json_array_remove_element">
- <return-type type="void"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- <parameter name="index_" type="guint"/>
- </parameters>
- </method>
- <method name="sized_new" symbol="json_array_sized_new">
- <return-type type="JsonArray*"/>
- <parameters>
- <parameter name="n_elements" type="guint"/>
- </parameters>
- </method>
- <method name="unref" symbol="json_array_unref">
- <return-type type="void"/>
- <parameters>
- <parameter name="array" type="JsonArray*"/>
- </parameters>
- </method>
- </boxed>
- <boxed name="JsonNode" type-name="JsonNode" get-type="json_node_get_type">
- <method name="copy" symbol="json_node_copy">
- <return-type type="JsonNode*"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- </parameters>
- </method>
- <method name="dup_array" symbol="json_node_dup_array">
- <return-type type="JsonArray*"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- </parameters>
- </method>
- <method name="dup_object" symbol="json_node_dup_object">
- <return-type type="JsonObject*"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- </parameters>
- </method>
- <method name="dup_string" symbol="json_node_dup_string">
- <return-type type="gchar*"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- </parameters>
- </method>
- <method name="free" symbol="json_node_free">
- <return-type type="void"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- </parameters>
- </method>
- <method name="get_array" symbol="json_node_get_array">
- <return-type type="JsonArray*"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- </parameters>
- </method>
- <method name="get_boolean" symbol="json_node_get_boolean">
- <return-type type="gboolean"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- </parameters>
- </method>
- <method name="get_double" symbol="json_node_get_double">
- <return-type type="gdouble"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- </parameters>
- </method>
- <method name="get_int" symbol="json_node_get_int">
- <return-type type="gint"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- </parameters>
- </method>
- <method name="get_node_type" symbol="json_node_get_node_type">
- <return-type type="JsonNodeType"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- </parameters>
- </method>
- <method name="get_object" symbol="json_node_get_object">
- <return-type type="JsonObject*"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- </parameters>
- </method>
- <method name="get_parent" symbol="json_node_get_parent">
- <return-type type="JsonNode*"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- </parameters>
- </method>
- <method name="get_string" symbol="json_node_get_string">
- <return-type type="gchar*"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- </parameters>
- </method>
- <method name="get_value" symbol="json_node_get_value">
- <return-type type="void"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- <parameter name="value" type="GValue*"/>
- </parameters>
- </method>
- <method name="get_value_type" symbol="json_node_get_value_type">
- <return-type type="GType"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- </parameters>
- </method>
- <method name="is_null" symbol="json_node_is_null">
- <return-type type="gboolean"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- </parameters>
- </method>
- <constructor name="new" symbol="json_node_new">
- <return-type type="JsonNode*"/>
- <parameters>
- <parameter name="type" type="JsonNodeType"/>
- </parameters>
- </constructor>
- <method name="set_array" symbol="json_node_set_array">
- <return-type type="void"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- <parameter name="array" type="JsonArray*"/>
- </parameters>
- </method>
- <method name="set_boolean" symbol="json_node_set_boolean">
- <return-type type="void"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- <parameter name="value" type="gboolean"/>
- </parameters>
- </method>
- <method name="set_double" symbol="json_node_set_double">
- <return-type type="void"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- <parameter name="value" type="gdouble"/>
- </parameters>
- </method>
- <method name="set_int" symbol="json_node_set_int">
- <return-type type="void"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- <parameter name="value" type="gint"/>
- </parameters>
- </method>
- <method name="set_object" symbol="json_node_set_object">
- <return-type type="void"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- <parameter name="object" type="JsonObject*"/>
- </parameters>
- </method>
- <method name="set_string" symbol="json_node_set_string">
- <return-type type="void"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- <parameter name="value" type="gchar*"/>
- </parameters>
- </method>
- <method name="set_value" symbol="json_node_set_value">
- <return-type type="void"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- <parameter name="value" type="GValue*"/>
- </parameters>
- </method>
- <method name="take_array" symbol="json_node_take_array">
- <return-type type="void"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- <parameter name="array" type="JsonArray*"/>
- </parameters>
- </method>
- <method name="take_object" symbol="json_node_take_object">
- <return-type type="void"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- <parameter name="object" type="JsonObject*"/>
- </parameters>
- </method>
- <method name="type_name" symbol="json_node_type_name">
- <return-type type="gchar*"/>
- <parameters>
- <parameter name="node" type="JsonNode*"/>
- </parameters>
- </method>
- </boxed>
- <boxed name="JsonObject" type-name="JsonObject" get-type="json_object_get_type">
- <method name="add_member" symbol="json_object_add_member">
- <return-type type="void"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="member_name" type="gchar*"/>
- <parameter name="node" type="JsonNode*"/>
- </parameters>
- </method>
- <method name="dup_member" symbol="json_object_dup_member">
- <return-type type="JsonNode*"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="member_name" type="gchar*"/>
- </parameters>
- </method>
- <method name="foreach_member" symbol="json_object_foreach_member">
- <return-type type="void"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="func" type="JsonObjectForeach"/>
- <parameter name="data" type="gpointer"/>
- </parameters>
- </method>
- <method name="get_array_member" symbol="json_object_get_array_member">
- <return-type type="JsonArray*"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="member_name" type="gchar*"/>
- </parameters>
- </method>
- <method name="get_boolean_member" symbol="json_object_get_boolean_member">
- <return-type type="gboolean"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="member_name" type="gchar*"/>
- </parameters>
- </method>
- <method name="get_double_member" symbol="json_object_get_double_member">
- <return-type type="gdouble"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="member_name" type="gchar*"/>
- </parameters>
- </method>
- <method name="get_int_member" symbol="json_object_get_int_member">
- <return-type type="gint"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="member_name" type="gchar*"/>
- </parameters>
- </method>
- <method name="get_member" symbol="json_object_get_member">
- <return-type type="JsonNode*"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="member_name" type="gchar*"/>
- </parameters>
- </method>
- <method name="get_members" symbol="json_object_get_members">
- <return-type type="GList*"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- </parameters>
- </method>
- <method name="get_null_member" symbol="json_object_get_null_member">
- <return-type type="gboolean"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="member_name" type="gchar*"/>
- </parameters>
- </method>
- <method name="get_object_member" symbol="json_object_get_object_member">
- <return-type type="JsonObject*"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="member_name" type="gchar*"/>
- </parameters>
- </method>
- <method name="get_size" symbol="json_object_get_size">
- <return-type type="guint"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- </parameters>
- </method>
- <method name="get_string_member" symbol="json_object_get_string_member">
- <return-type type="gchar*"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="member_name" type="gchar*"/>
- </parameters>
- </method>
- <method name="get_values" symbol="json_object_get_values">
- <return-type type="GList*"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- </parameters>
- </method>
- <method name="has_member" symbol="json_object_has_member">
- <return-type type="gboolean"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="member_name" type="gchar*"/>
- </parameters>
- </method>
- <constructor name="new" symbol="json_object_new">
- <return-type type="JsonObject*"/>
- </constructor>
- <method name="ref" symbol="json_object_ref">
- <return-type type="JsonObject*"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- </parameters>
- </method>
- <method name="remove_member" symbol="json_object_remove_member">
- <return-type type="void"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="member_name" type="gchar*"/>
- </parameters>
- </method>
- <method name="set_array_member" symbol="json_object_set_array_member">
- <return-type type="void"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="member_name" type="gchar*"/>
- <parameter name="value" type="JsonArray*"/>
- </parameters>
- </method>
- <method name="set_boolean_member" symbol="json_object_set_boolean_member">
- <return-type type="void"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="member_name" type="gchar*"/>
- <parameter name="value" type="gboolean"/>
- </parameters>
- </method>
- <method name="set_double_member" symbol="json_object_set_double_member">
- <return-type type="void"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="member_name" type="gchar*"/>
- <parameter name="value" type="gdouble"/>
- </parameters>
- </method>
- <method name="set_int_member" symbol="json_object_set_int_member">
- <return-type type="void"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="member_name" type="gchar*"/>
- <parameter name="value" type="gint"/>
- </parameters>
- </method>
- <method name="set_member" symbol="json_object_set_member">
- <return-type type="void"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="member_name" type="gchar*"/>
- <parameter name="node" type="JsonNode*"/>
- </parameters>
- </method>
- <method name="set_null_member" symbol="json_object_set_null_member">
- <return-type type="void"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="member_name" type="gchar*"/>
- </parameters>
- </method>
- <method name="set_object_member" symbol="json_object_set_object_member">
- <return-type type="void"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="member_name" type="gchar*"/>
- <parameter name="value" type="JsonObject*"/>
- </parameters>
- </method>
- <method name="set_string_member" symbol="json_object_set_string_member">
- <return-type type="void"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="member_name" type="gchar*"/>
- <parameter name="value" type="gchar*"/>
- </parameters>
- </method>
- <method name="unref" symbol="json_object_unref">
- <return-type type="void"/>
- <parameters>
- <parameter name="object" type="JsonObject*"/>
- </parameters>
- </method>
- </boxed>
<enum name="ClutterAnimationMode" type-name="ClutterAnimationMode" get-type="clutter_animation_mode_get_type">
<member name="CLUTTER_CUSTOM_MODE" value="0"/>
<member name="CLUTTER_LINEAR" value="1"/>
@@ -1766,6 +1271,18 @@
<member name="CLUTTER_EASE_IN_OUT_BOUNCE" value="31"/>
<member name="CLUTTER_ANIMATION_LAST" value="32"/>
</enum>
+ <enum name="ClutterBinAlignment" type-name="ClutterBinAlignment" get-type="clutter_bin_alignment_get_type">
+ <member name="CLUTTER_BIN_ALIGNMENT_FIXED" value="0"/>
+ <member name="CLUTTER_BIN_ALIGNMENT_FILL" value="1"/>
+ <member name="CLUTTER_BIN_ALIGNMENT_START" value="2"/>
+ <member name="CLUTTER_BIN_ALIGNMENT_END" value="3"/>
+ <member name="CLUTTER_BIN_ALIGNMENT_CENTER" value="4"/>
+ </enum>
+ <enum name="ClutterBoxAlignment" type-name="ClutterBoxAlignment" get-type="clutter_box_alignment_get_type">
+ <member name="CLUTTER_BOX_ALIGNMENT_START" value="0"/>
+ <member name="CLUTTER_BOX_ALIGNMENT_END" value="1"/>
+ <member name="CLUTTER_BOX_ALIGNMENT_CENTER" value="2"/>
+ </enum>
<enum name="ClutterEventType" type-name="ClutterEventType" get-type="clutter_event_type_get_type">
<member name="CLUTTER_NOTHING" value="0"/>
<member name="CLUTTER_KEY_PRESS" value="1"/>
@@ -1781,6 +1298,10 @@
<member name="CLUTTER_CLIENT_MESSAGE" value="11"/>
<member name="CLUTTER_DELETE" value="12"/>
</enum>
+ <enum name="ClutterFlowOrientation" type-name="ClutterFlowOrientation" get-type="clutter_flow_orientation_get_type">
+ <member name="CLUTTER_FLOW_HORIZONTAL" value="0"/>
+ <member name="CLUTTER_FLOW_VERTICAL" value="1"/>
+ </enum>
<enum name="ClutterGravity" type-name="ClutterGravity" get-type="clutter_gravity_get_type">
<member name="CLUTTER_GRAVITY_NONE" value="0"/>
<member name="CLUTTER_GRAVITY_NORTH" value="1"/>
@@ -1806,6 +1327,10 @@
<member name="CLUTTER_EXTENSION_DEVICE" value="2"/>
<member name="CLUTTER_N_DEVICE_TYPES" value="3"/>
</enum>
+ <enum name="ClutterInterpolation" type-name="ClutterInterpolation" get-type="clutter_interpolation_get_type">
+ <member name="CLUTTER_INTERPOLATION_LINEAR" value="0"/>
+ <member name="CLUTTER_INTERPOLATION_CUBIC" value="1"/>
+ </enum>
<enum name="ClutterPathNodeType" type-name="ClutterPathNodeType" get-type="clutter_path_node_type_get_type">
<member name="CLUTTER_PATH_MOVE_TO" value="0"/>
<member name="CLUTTER_PATH_LINE_TO" value="1"/>
@@ -1849,6 +1374,11 @@
<member name="CLUTTER_SHADER_ERROR_NO_GLSL" value="1"/>
<member name="CLUTTER_SHADER_ERROR_COMPILE" value="2"/>
</enum>
+ <enum name="ClutterTextDirection" type-name="ClutterTextDirection" get-type="clutter_text_direction_get_type">
+ <member name="CLUTTER_TEXT_DIRECTION_DEFAULT" value="0"/>
+ <member name="CLUTTER_TEXT_DIRECTION_LTR" value="1"/>
+ <member name="CLUTTER_TEXT_DIRECTION_RTL" value="2"/>
+ </enum>
<enum name="ClutterTextureError" type-name="ClutterTextureError" get-type="clutter_texture_error_get_type">
<member name="CLUTTER_TEXTURE_ERROR_OUT_OF_MEMORY" value="0"/>
<member name="CLUTTER_TEXTURE_ERROR_NO_YUV" value="1"/>
@@ -1868,6 +1398,7 @@
<member name="CLUTTER_UNIT_EM" value="1"/>
<member name="CLUTTER_UNIT_MM" value="2"/>
<member name="CLUTTER_UNIT_POINT" value="3"/>
+ <member name="CLUTTER_UNIT_CM" value="4"/>
</enum>
<enum name="ClutterX11FilterReturn" type-name="ClutterX11FilterReturn" get-type="clutter_x11_filter_return_get_type">
<member name="CLUTTER_X11_FILTER_CONTINUE" value="0"/>
@@ -1882,28 +1413,12 @@
<member name="CLUTTER_X11_XINPUT_MOTION_NOTIFY_EVENT" value="4"/>
<member name="CLUTTER_X11_XINPUT_LAST_EVENT" value="5"/>
</enum>
- <enum name="JsonNodeType">
- <member name="JSON_NODE_OBJECT" value="0"/>
- <member name="JSON_NODE_ARRAY" value="1"/>
- <member name="JSON_NODE_VALUE" value="2"/>
- <member name="JSON_NODE_NULL" value="3"/>
- </enum>
- <enum name="JsonParserError">
- <member name="JSON_PARSER_ERROR_PARSE" value="0"/>
- <member name="JSON_PARSER_ERROR_UNKNOWN" value="1"/>
- </enum>
- <enum name="JsonTokenType">
- <member name="JSON_TOKEN_INVALID" value="270"/>
- <member name="JSON_TOKEN_TRUE" value="271"/>
- <member name="JSON_TOKEN_FALSE" value="272"/>
- <member name="JSON_TOKEN_NULL" value="273"/>
- <member name="JSON_TOKEN_LAST" value="274"/>
- </enum>
<flags name="ClutterActorFlags" type-name="ClutterActorFlags" get-type="clutter_actor_flags_get_type">
<member name="CLUTTER_ACTOR_MAPPED" value="2"/>
<member name="CLUTTER_ACTOR_REALIZED" value="4"/>
<member name="CLUTTER_ACTOR_REACTIVE" value="8"/>
<member name="CLUTTER_ACTOR_VISIBLE" value="16"/>
+ <member name="CLUTTER_ACTOR_NO_LAYOUT" value="32"/>
</flags>
<flags name="ClutterAllocationFlags" type-name="ClutterAllocationFlags" get-type="clutter_allocation_flags_get_type">
<member name="CLUTTER_ALLOCATION_NONE" value="0"/>
@@ -1924,6 +1439,7 @@
<member name="CLUTTER_FEATURE_SHADERS_GLSL" value="512"/>
<member name="CLUTTER_FEATURE_OFFSCREEN" value="1024"/>
<member name="CLUTTER_FEATURE_STAGE_MULTIPLE" value="2048"/>
+ <member name="CLUTTER_FEATURE_SWAP_EVENTS" value="4096"/>
</flags>
<flags name="ClutterFontFlags" type-name="ClutterFontFlags" get-type="clutter_font_flags_get_type">
<member name="CLUTTER_FONT_MIPMAPPING" value="1"/>
@@ -1949,6 +1465,10 @@
<member name="CLUTTER_RELEASE_MASK" value="1073741824"/>
<member name="CLUTTER_MODIFIER_MASK" value="1543512063"/>
</flags>
+ <flags name="ClutterRedrawFlags" type-name="ClutterRedrawFlags" get-type="clutter_redraw_flags_get_type">
+ <member name="CLUTTER_REDRAW_CLIPPED_TO_BOX" value="0"/>
+ <member name="CLUTTER_REDRAW_CLIPPED_TO_ALLOCATION" value="2"/>
+ </flags>
<flags name="ClutterStageState" type-name="ClutterStageState" get-type="clutter_stage_state_get_type">
<member name="CLUTTER_STAGE_STATE_FULLSCREEN" value="2"/>
<member name="CLUTTER_STAGE_STATE_OFFSCREEN" value="4"/>
@@ -2266,6 +1786,12 @@
<parameter name="actor" type="ClutterActor*"/>
</parameters>
</method>
+ <method name="get_request_mode" symbol="clutter_actor_get_request_mode">
+ <return-type type="ClutterRequestMode"/>
+ <parameters>
+ <parameter name="self" type="ClutterActor*"/>
+ </parameters>
+ </method>
<method name="get_rotation" symbol="clutter_actor_get_rotation">
<return-type type="gdouble"/>
<parameters>
@@ -2318,6 +1844,12 @@
<parameter name="actor" type="ClutterActor*"/>
</parameters>
</method>
+ <method name="get_text_direction" symbol="clutter_actor_get_text_direction">
+ <return-type type="ClutterTextDirection"/>
+ <parameters>
+ <parameter name="self" type="ClutterActor*"/>
+ </parameters>
+ </method>
<method name="get_transformation_matrix" symbol="clutter_actor_get_transformation_matrix">
<return-type type="void"/>
<parameters>
@@ -2377,6 +1909,12 @@
<parameter name="self" type="ClutterActor*"/>
</parameters>
</method>
+ <method name="has_pointer" symbol="clutter_actor_has_pointer">
+ <return-type type="gboolean"/>
+ <parameters>
+ <parameter name="self" type="ClutterActor*"/>
+ </parameters>
+ </method>
<method name="hide" symbol="clutter_actor_hide">
<return-type type="void"/>
<parameters>
@@ -2455,6 +1993,18 @@
<parameter name="self" type="ClutterActor*"/>
</parameters>
</method>
+ <method name="pop_internal" symbol="clutter_actor_pop_internal">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="self" type="ClutterActor*"/>
+ </parameters>
+ </method>
+ <method name="push_internal" symbol="clutter_actor_push_internal">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="self" type="ClutterActor*"/>
+ </parameters>
+ </method>
<method name="queue_redraw" symbol="clutter_actor_queue_redraw">
<return-type type="void"/>
<parameters>
@@ -2595,6 +2145,13 @@
<parameter name="reactive" type="gboolean"/>
</parameters>
</method>
+ <method name="set_request_mode" symbol="clutter_actor_set_request_mode">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="self" type="ClutterActor*"/>
+ <parameter name="mode" type="ClutterRequestMode"/>
+ </parameters>
+ </method>
<method name="set_rotation" symbol="clutter_actor_set_rotation">
<return-type type="void"/>
<parameters>
@@ -2672,6 +2229,13 @@
<parameter name="height" type="gfloat"/>
</parameters>
</method>
+ <method name="set_text_direction" symbol="clutter_actor_set_text_direction">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="self" type="ClutterActor*"/>
+ <parameter name="text_dir" type="ClutterTextDirection"/>
+ </parameters>
+ </method>
<method name="set_width" symbol="clutter_actor_set_width">
<return-type type="void"/>
<parameters>
@@ -2765,6 +2329,7 @@
<property name="fixed-x" type="gfloat" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="fixed-y" type="gfloat" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="has-clip" type="gboolean" readable="1" writable="0" construct="0" construct-only="0"/>
+ <property name="has-pointer" type="gboolean" readable="1" writable="0" construct="0" construct-only="0"/>
<property name="height" type="gfloat" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="mapped" type="gboolean" readable="1" writable="0" construct="0" construct-only="0"/>
<property name="min-height" type="gfloat" readable="1" writable="1" construct="0" construct-only="0"/>
@@ -2776,7 +2341,7 @@
<property name="natural-height-set" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="natural-width" type="gfloat" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="natural-width-set" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/>
- <property name="opacity" type="guchar" readable="1" writable="1" construct="0" construct-only="0"/>
+ <property name="opacity" type="guint" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="reactive" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="realized" type="gboolean" readable="1" writable="0" construct="0" construct-only="0"/>
<property name="request-mode" type="ClutterRequestMode" readable="1" writable="1" construct="0" construct-only="0"/>
@@ -2793,6 +2358,7 @@
<property name="scale-x" type="gdouble" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="scale-y" type="gdouble" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="show-on-set-parent" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/>
+ <property name="text-direction" type="ClutterTextDirection" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="visible" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="width" type="gfloat" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="x" type="gfloat" readable="1" writable="1" construct="0" construct-only="0"/>
@@ -2919,6 +2485,12 @@
<parameter name="leaf_that_queued" type="ClutterActor*"/>
</parameters>
</signal>
+ <signal name="queue-relayout" when="LAST">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="actor" type="ClutterActor*"/>
+ </parameters>
+ </signal>
<signal name="realize" when="LAST">
<return-type type="void"/>
<parameters>
@@ -3004,6 +2576,9 @@
<field name="flags" type="guint32"/>
</object>
<object name="ClutterAlpha" parent="GInitiallyUnowned" type-name="ClutterAlpha" get-type="clutter_alpha_get_type">
+ <implements>
+ <interface name="ClutterScriptable"/>
+ </implements>
<method name="get_alpha" symbol="clutter_alpha_get_alpha">
<return-type type="gdouble"/>
<parameters>
@@ -3089,6 +2664,9 @@
<property name="timeline" type="ClutterTimeline*" readable="1" writable="1" construct="0" construct-only="0"/>
</object>
<object name="ClutterAnimation" parent="GObject" type-name="ClutterAnimation" get-type="clutter_animation_get_type">
+ <implements>
+ <interface name="ClutterScriptable"/>
+ </implements>
<method name="bind" symbol="clutter_animation_bind">
<return-type type="ClutterAnimation*"/>
<parameters>
@@ -3213,6 +2791,14 @@
<parameter name="property_name" type="gchar*"/>
</parameters>
</method>
+ <method name="update" symbol="clutter_animation_update">
+ <return-type type="ClutterAnimation*"/>
+ <parameters>
+ <parameter name="animation" type="ClutterAnimation*"/>
+ <parameter name="property_name" type="gchar*"/>
+ <parameter name="final" type="GValue*"/>
+ </parameters>
+ </method>
<method name="update_interval" symbol="clutter_animation_update_interval">
<return-type type="void"/>
<parameters>
@@ -3240,45 +2826,170 @@
</parameters>
</signal>
</object>
- <object name="ClutterBackend" parent="GObject" type-name="ClutterBackend" get-type="clutter_backend_get_type">
- <method name="get_double_click_distance" symbol="clutter_backend_get_double_click_distance">
- <return-type type="guint"/>
+ <object name="ClutterAnimator" parent="GObject" type-name="ClutterAnimator" get-type="clutter_animator_get_type">
+ <implements>
+ <interface name="ClutterScriptable"/>
+ </implements>
+ <method name="compute_value" symbol="clutter_animator_compute_value">
+ <return-type type="gboolean"/>
<parameters>
- <parameter name="backend" type="ClutterBackend*"/>
+ <parameter name="animator" type="ClutterAnimator*"/>
+ <parameter name="object" type="GObject*"/>
+ <parameter name="property_name" type="gchar*"/>
+ <parameter name="progress" type="gdouble"/>
+ <parameter name="value" type="GValue*"/>
</parameters>
</method>
- <method name="get_double_click_time" symbol="clutter_backend_get_double_click_time">
+ <method name="get_duration" symbol="clutter_animator_get_duration">
<return-type type="guint"/>
<parameters>
- <parameter name="backend" type="ClutterBackend*"/>
+ <parameter name="animator" type="ClutterAnimator*"/>
</parameters>
</method>
- <method name="get_font_name" symbol="clutter_backend_get_font_name">
- <return-type type="gchar*"/>
+ <method name="get_keys" symbol="clutter_animator_get_keys">
+ <return-type type="GList*"/>
<parameters>
- <parameter name="backend" type="ClutterBackend*"/>
+ <parameter name="animator" type="ClutterAnimator*"/>
+ <parameter name="object" type="GObject*"/>
+ <parameter name="property_name" type="gchar*"/>
+ <parameter name="progress" type="gdouble"/>
</parameters>
</method>
- <method name="get_font_options" symbol="clutter_backend_get_font_options">
- <return-type type="cairo_font_options_t*"/>
+ <method name="get_timeline" symbol="clutter_animator_get_timeline">
+ <return-type type="ClutterTimeline*"/>
<parameters>
- <parameter name="backend" type="ClutterBackend*"/>
+ <parameter name="animator" type="ClutterAnimator*"/>
</parameters>
</method>
- <method name="get_resolution" symbol="clutter_backend_get_resolution">
- <return-type type="gdouble"/>
+ <constructor name="new" symbol="clutter_animator_new">
+ <return-type type="ClutterAnimator*"/>
+ </constructor>
+ <method name="property_get_ease_in" symbol="clutter_animator_property_get_ease_in">
+ <return-type type="gboolean"/>
<parameters>
- <parameter name="backend" type="ClutterBackend*"/>
+ <parameter name="animator" type="ClutterAnimator*"/>
+ <parameter name="object" type="GObject*"/>
+ <parameter name="property_name" type="gchar*"/>
</parameters>
</method>
- <method name="set_double_click_distance" symbol="clutter_backend_set_double_click_distance">
- <return-type type="void"/>
+ <method name="property_get_interpolation" symbol="clutter_animator_property_get_interpolation">
+ <return-type type="ClutterInterpolation"/>
<parameters>
- <parameter name="backend" type="ClutterBackend*"/>
- <parameter name="distance" type="guint"/>
+ <parameter name="animator" type="ClutterAnimator*"/>
+ <parameter name="object" type="GObject*"/>
+ <parameter name="property_name" type="gchar*"/>
</parameters>
</method>
- <method name="set_double_click_time" symbol="clutter_backend_set_double_click_time">
+ <method name="property_set_ease_in" symbol="clutter_animator_property_set_ease_in">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="animator" type="ClutterAnimator*"/>
+ <parameter name="object" type="GObject*"/>
+ <parameter name="property_name" type="gchar*"/>
+ <parameter name="ease_in" type="gboolean"/>
+ </parameters>
+ </method>
+ <method name="property_set_interpolation" symbol="clutter_animator_property_set_interpolation">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="animator" type="ClutterAnimator*"/>
+ <parameter name="object" type="GObject*"/>
+ <parameter name="property_name" type="gchar*"/>
+ <parameter name="interpolation" type="ClutterInterpolation"/>
+ </parameters>
+ </method>
+ <method name="remove_key" symbol="clutter_animator_remove_key">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="animator" type="ClutterAnimator*"/>
+ <parameter name="object" type="GObject*"/>
+ <parameter name="property_name" type="gchar*"/>
+ <parameter name="progress" type="gdouble"/>
+ </parameters>
+ </method>
+ <method name="set" symbol="clutter_animator_set">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="animator" type="ClutterAnimator*"/>
+ <parameter name="first_object" type="gpointer"/>
+ <parameter name="first_property_name" type="gchar*"/>
+ <parameter name="first_mode" type="guint"/>
+ <parameter name="first_progress" type="gdouble"/>
+ </parameters>
+ </method>
+ <method name="set_duration" symbol="clutter_animator_set_duration">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="animator" type="ClutterAnimator*"/>
+ <parameter name="duration" type="guint"/>
+ </parameters>
+ </method>
+ <method name="set_key" symbol="clutter_animator_set_key">
+ <return-type type="ClutterAnimator*"/>
+ <parameters>
+ <parameter name="animator" type="ClutterAnimator*"/>
+ <parameter name="object" type="GObject*"/>
+ <parameter name="property_name" type="gchar*"/>
+ <parameter name="mode" type="guint"/>
+ <parameter name="progress" type="gdouble"/>
+ <parameter name="value" type="GValue*"/>
+ </parameters>
+ </method>
+ <method name="set_timeline" symbol="clutter_animator_set_timeline">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="animator" type="ClutterAnimator*"/>
+ <parameter name="timeline" type="ClutterTimeline*"/>
+ </parameters>
+ </method>
+ <method name="start" symbol="clutter_animator_start">
+ <return-type type="ClutterTimeline*"/>
+ <parameters>
+ <parameter name="animator" type="ClutterAnimator*"/>
+ </parameters>
+ </method>
+ <property name="duration" type="guint" readable="1" writable="1" construct="0" construct-only="0"/>
+ <property name="timeline" type="ClutterTimeline*" readable="1" writable="1" construct="0" construct-only="0"/>
+ </object>
+ <object name="ClutterBackend" parent="GObject" type-name="ClutterBackend" get-type="clutter_backend_get_type">
+ <method name="get_double_click_distance" symbol="clutter_backend_get_double_click_distance">
+ <return-type type="guint"/>
+ <parameters>
+ <parameter name="backend" type="ClutterBackend*"/>
+ </parameters>
+ </method>
+ <method name="get_double_click_time" symbol="clutter_backend_get_double_click_time">
+ <return-type type="guint"/>
+ <parameters>
+ <parameter name="backend" type="ClutterBackend*"/>
+ </parameters>
+ </method>
+ <method name="get_font_name" symbol="clutter_backend_get_font_name">
+ <return-type type="gchar*"/>
+ <parameters>
+ <parameter name="backend" type="ClutterBackend*"/>
+ </parameters>
+ </method>
+ <method name="get_font_options" symbol="clutter_backend_get_font_options">
+ <return-type type="cairo_font_options_t*"/>
+ <parameters>
+ <parameter name="backend" type="ClutterBackend*"/>
+ </parameters>
+ </method>
+ <method name="get_resolution" symbol="clutter_backend_get_resolution">
+ <return-type type="gdouble"/>
+ <parameters>
+ <parameter name="backend" type="ClutterBackend*"/>
+ </parameters>
+ </method>
+ <method name="set_double_click_distance" symbol="clutter_backend_set_double_click_distance">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="backend" type="ClutterBackend*"/>
+ <parameter name="distance" type="guint"/>
+ </parameters>
+ </method>
+ <method name="set_double_click_time" symbol="clutter_backend_set_double_click_time">
<return-type type="void"/>
<parameters>
<parameter name="backend" type="ClutterBackend*"/>
@@ -3329,12 +3040,11 @@
<return-type type="gboolean"/>
<parameters>
<parameter name="backend" type="ClutterBackend*"/>
- <parameter name="is_offscreen" type="gboolean"/>
<parameter name="error" type="GError**"/>
</parameters>
</vfunc>
<vfunc name="create_stage">
- <return-type type="ClutterActor*"/>
+ <return-type type="ClutterStageWindow*"/>
<parameters>
<parameter name="backend" type="ClutterBackend*"/>
<parameter name="wrapper" type="ClutterStage*"/>
@@ -3348,6 +3058,12 @@
<parameter name="stage" type="ClutterStage*"/>
</parameters>
</vfunc>
+ <vfunc name="get_device_manager">
+ <return-type type="ClutterDeviceManager*"/>
+ <parameters>
+ <parameter name="backend" type="ClutterBackend*"/>
+ </parameters>
+ </vfunc>
<vfunc name="get_features">
<return-type type="ClutterFeatureFlags"/>
<parameters>
@@ -3389,6 +3105,9 @@
</vfunc>
</object>
<object name="ClutterBehaviour" parent="GObject" type-name="ClutterBehaviour" get-type="clutter_behaviour_get_type">
+ <implements>
+ <interface name="ClutterScriptable"/>
+ </implements>
<method name="actors_foreach" symbol="clutter_behaviour_actors_foreach">
<return-type type="void"/>
<parameters>
@@ -3480,6 +3199,9 @@
</vfunc>
</object>
<object name="ClutterBehaviourDepth" parent="ClutterBehaviour" type-name="ClutterBehaviourDepth" get-type="clutter_behaviour_depth_get_type">
+ <implements>
+ <interface name="ClutterScriptable"/>
+ </implements>
<method name="get_bounds" symbol="clutter_behaviour_depth_get_bounds">
<return-type type="void"/>
<parameters>
@@ -3508,6 +3230,9 @@
<property name="depth-start" type="gint" readable="1" writable="1" construct="0" construct-only="0"/>
</object>
<object name="ClutterBehaviourEllipse" parent="ClutterBehaviour" type-name="ClutterBehaviourEllipse" get-type="clutter_behaviour_ellipse_get_type">
+ <implements>
+ <interface name="ClutterScriptable"/>
+ </implements>
<method name="get_angle_end" symbol="clutter_behaviour_ellipse_get_angle_end">
<return-type type="gdouble"/>
<parameters>
@@ -3646,6 +3371,9 @@
<property name="width" type="gint" readable="1" writable="1" construct="0" construct-only="0"/>
</object>
<object name="ClutterBehaviourOpacity" parent="ClutterBehaviour" type-name="ClutterBehaviourOpacity" get-type="clutter_behaviour_opacity_get_type">
+ <implements>
+ <interface name="ClutterScriptable"/>
+ </implements>
<method name="get_bounds" symbol="clutter_behaviour_opacity_get_bounds">
<return-type type="void"/>
<parameters>
@@ -3722,6 +3450,9 @@
</signal>
</object>
<object name="ClutterBehaviourRotate" parent="ClutterBehaviour" type-name="ClutterBehaviourRotate" get-type="clutter_behaviour_rotate_get_type">
+ <implements>
+ <interface name="ClutterScriptable"/>
+ </implements>
<method name="get_axis" symbol="clutter_behaviour_rotate_get_axis">
<return-type type="ClutterRotateAxis"/>
<parameters>
@@ -3801,6 +3532,9 @@
<property name="direction" type="ClutterRotateDirection" readable="1" writable="1" construct="0" construct-only="0"/>
</object>
<object name="ClutterBehaviourScale" parent="ClutterBehaviour" type-name="ClutterBehaviourScale" get-type="clutter_behaviour_scale_get_type">
+ <implements>
+ <interface name="ClutterScriptable"/>
+ </implements>
<method name="get_bounds" symbol="clutter_behaviour_scale_get_bounds">
<return-type type="void"/>
<parameters>
@@ -3836,6 +3570,44 @@
<property name="y-scale-end" type="gdouble" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="y-scale-start" type="gdouble" readable="1" writable="1" construct="0" construct-only="0"/>
</object>
+ <object name="ClutterBinLayout" parent="ClutterLayoutManager" type-name="ClutterBinLayout" get-type="clutter_bin_layout_get_type">
+ <method name="add" symbol="clutter_bin_layout_add">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="self" type="ClutterBinLayout*"/>
+ <parameter name="child" type="ClutterActor*"/>
+ <parameter name="x_align" type="ClutterBinAlignment"/>
+ <parameter name="y_align" type="ClutterBinAlignment"/>
+ </parameters>
+ </method>
+ <method name="get_alignment" symbol="clutter_bin_layout_get_alignment">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="self" type="ClutterBinLayout*"/>
+ <parameter name="child" type="ClutterActor*"/>
+ <parameter name="x_align" type="ClutterBinAlignment*"/>
+ <parameter name="y_align" type="ClutterBinAlignment*"/>
+ </parameters>
+ </method>
+ <constructor name="new" symbol="clutter_bin_layout_new">
+ <return-type type="ClutterLayoutManager*"/>
+ <parameters>
+ <parameter name="x_align" type="ClutterBinAlignment"/>
+ <parameter name="y_align" type="ClutterBinAlignment"/>
+ </parameters>
+ </constructor>
+ <method name="set_alignment" symbol="clutter_bin_layout_set_alignment">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="self" type="ClutterBinLayout*"/>
+ <parameter name="child" type="ClutterActor*"/>
+ <parameter name="x_align" type="ClutterBinAlignment"/>
+ <parameter name="y_align" type="ClutterBinAlignment"/>
+ </parameters>
+ </method>
+ <property name="x-align" type="ClutterBinAlignment" readable="1" writable="1" construct="0" construct-only="0"/>
+ <property name="y-align" type="ClutterBinAlignment" readable="1" writable="1" construct="0" construct-only="0"/>
+ </object>
<object name="ClutterBindingPool" parent="GObject" type-name="ClutterBindingPool" get-type="clutter_binding_pool_get_type">
<method name="activate" symbol="clutter_binding_pool_activate">
<return-type type="gboolean"/>
@@ -3938,142 +3710,635 @@
</method>
<property name="name" type="char*" readable="1" writable="1" construct="0" construct-only="1"/>
</object>
- <object name="ClutterCairoTexture" parent="ClutterTexture" type-name="ClutterCairoTexture" get-type="clutter_cairo_texture_get_type">
+ <object name="ClutterBox" parent="ClutterActor" type-name="ClutterBox" get-type="clutter_box_get_type">
<implements>
<interface name="ClutterScriptable"/>
+ <interface name="ClutterContainer"/>
</implements>
- <method name="clear" symbol="clutter_cairo_texture_clear">
+ <method name="get_color" symbol="clutter_box_get_color">
<return-type type="void"/>
<parameters>
- <parameter name="self" type="ClutterCairoTexture*"/>
+ <parameter name="box" type="ClutterBox*"/>
+ <parameter name="color" type="ClutterColor*"/>
</parameters>
</method>
- <method name="create" symbol="clutter_cairo_texture_create">
- <return-type type="cairo_t*"/>
+ <method name="get_layout_manager" symbol="clutter_box_get_layout_manager">
+ <return-type type="ClutterLayoutManager*"/>
<parameters>
- <parameter name="self" type="ClutterCairoTexture*"/>
+ <parameter name="box" type="ClutterBox*"/>
</parameters>
</method>
- <method name="create_region" symbol="clutter_cairo_texture_create_region">
- <return-type type="cairo_t*"/>
+ <constructor name="new" symbol="clutter_box_new">
+ <return-type type="ClutterActor*"/>
<parameters>
- <parameter name="self" type="ClutterCairoTexture*"/>
- <parameter name="x_offset" type="gint"/>
- <parameter name="y_offset" type="gint"/>
- <parameter name="width" type="gint"/>
- <parameter name="height" type="gint"/>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
</parameters>
- </method>
- <method name="get_surface_size" symbol="clutter_cairo_texture_get_surface_size">
+ </constructor>
+ <method name="pack" symbol="clutter_box_pack">
<return-type type="void"/>
<parameters>
- <parameter name="self" type="ClutterCairoTexture*"/>
- <parameter name="width" type="guint*"/>
- <parameter name="height" type="guint*"/>
+ <parameter name="box" type="ClutterBox*"/>
+ <parameter name="actor" type="ClutterActor*"/>
+ <parameter name="first_property" type="gchar*"/>
</parameters>
</method>
- <constructor name="new" symbol="clutter_cairo_texture_new">
- <return-type type="ClutterActor*"/>
+ <method name="pack_after" symbol="clutter_box_pack_after">
+ <return-type type="void"/>
<parameters>
- <parameter name="width" type="guint"/>
- <parameter name="height" type="guint"/>
+ <parameter name="box" type="ClutterBox*"/>
+ <parameter name="actor" type="ClutterActor*"/>
+ <parameter name="sibling" type="ClutterActor*"/>
+ <parameter name="first_property" type="gchar*"/>
</parameters>
- </constructor>
- <method name="set_surface_size" symbol="clutter_cairo_texture_set_surface_size">
+ </method>
+ <method name="pack_at" symbol="clutter_box_pack_at">
<return-type type="void"/>
<parameters>
- <parameter name="self" type="ClutterCairoTexture*"/>
- <parameter name="width" type="guint"/>
- <parameter name="height" type="guint"/>
+ <parameter name="box" type="ClutterBox*"/>
+ <parameter name="actor" type="ClutterActor*"/>
+ <parameter name="position" type="gint"/>
+ <parameter name="first_property" type="gchar*"/>
</parameters>
</method>
- <property name="surface-height" type="guint" readable="1" writable="1" construct="0" construct-only="0"/>
- <property name="surface-width" type="guint" readable="1" writable="1" construct="0" construct-only="0"/>
- </object>
- <object name="ClutterChildMeta" parent="GObject" type-name="ClutterChildMeta" get-type="clutter_child_meta_get_type">
- <method name="get_actor" symbol="clutter_child_meta_get_actor">
- <return-type type="ClutterActor*"/>
+ <method name="pack_before" symbol="clutter_box_pack_before">
+ <return-type type="void"/>
<parameters>
- <parameter name="data" type="ClutterChildMeta*"/>
+ <parameter name="box" type="ClutterBox*"/>
+ <parameter name="actor" type="ClutterActor*"/>
+ <parameter name="sibling" type="ClutterActor*"/>
+ <parameter name="first_property" type="gchar*"/>
</parameters>
</method>
- <method name="get_container" symbol="clutter_child_meta_get_container">
- <return-type type="ClutterContainer*"/>
+ <method name="packv" symbol="clutter_box_packv">
+ <return-type type="void"/>
<parameters>
- <parameter name="data" type="ClutterChildMeta*"/>
+ <parameter name="box" type="ClutterBox*"/>
+ <parameter name="actor" type="ClutterActor*"/>
+ <parameter name="n_properties" type="guint"/>
+ <parameter name="properties" type="gchar*[]"/>
+ <parameter name="values" type="GValue*"/>
</parameters>
</method>
- <property name="actor" type="ClutterActor*" readable="1" writable="1" construct="0" construct-only="1"/>
- <property name="container" type="ClutterContainer*" readable="1" writable="1" construct="0" construct-only="1"/>
- <field name="container" type="ClutterContainer*"/>
- <field name="actor" type="ClutterActor*"/>
- </object>
- <object name="ClutterClone" parent="ClutterActor" type-name="ClutterClone" get-type="clutter_clone_get_type">
- <implements>
- <interface name="ClutterScriptable"/>
- </implements>
- <method name="get_source" symbol="clutter_clone_get_source">
- <return-type type="ClutterActor*"/>
+ <method name="set_color" symbol="clutter_box_set_color">
+ <return-type type="void"/>
<parameters>
- <parameter name="clone" type="ClutterClone*"/>
+ <parameter name="box" type="ClutterBox*"/>
+ <parameter name="color" type="ClutterColor*"/>
</parameters>
</method>
- <constructor name="new" symbol="clutter_clone_new">
- <return-type type="ClutterActor*"/>
+ <method name="set_layout_manager" symbol="clutter_box_set_layout_manager">
+ <return-type type="void"/>
<parameters>
- <parameter name="source" type="ClutterActor*"/>
+ <parameter name="box" type="ClutterBox*"/>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
</parameters>
- </constructor>
- <method name="set_source" symbol="clutter_clone_set_source">
+ </method>
+ <property name="color" type="ClutterColor*" readable="1" writable="1" construct="0" construct-only="0"/>
+ <property name="color-set" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/>
+ <property name="layout-manager" type="ClutterLayoutManager*" readable="1" writable="1" construct="1" construct-only="0"/>
+ <vfunc name="clutter_padding_1">
+ <return-type type="void"/>
+ </vfunc>
+ <vfunc name="clutter_padding_2">
+ <return-type type="void"/>
+ </vfunc>
+ <vfunc name="clutter_padding_3">
+ <return-type type="void"/>
+ </vfunc>
+ <vfunc name="clutter_padding_4">
+ <return-type type="void"/>
+ </vfunc>
+ <vfunc name="clutter_padding_5">
+ <return-type type="void"/>
+ </vfunc>
+ <vfunc name="clutter_padding_6">
+ <return-type type="void"/>
+ </vfunc>
+ </object>
+ <object name="ClutterBoxLayout" parent="ClutterLayoutManager" type-name="ClutterBoxLayout" get-type="clutter_box_layout_get_type">
+ <method name="get_alignment" symbol="clutter_box_layout_get_alignment">
<return-type type="void"/>
<parameters>
- <parameter name="clone" type="ClutterClone*"/>
- <parameter name="source" type="ClutterActor*"/>
+ <parameter name="layout" type="ClutterBoxLayout*"/>
+ <parameter name="actor" type="ClutterActor*"/>
+ <parameter name="x_align" type="ClutterBoxAlignment*"/>
+ <parameter name="y_align" type="ClutterBoxAlignment*"/>
</parameters>
</method>
- <property name="source" type="ClutterActor*" readable="1" writable="1" construct="0" construct-only="1"/>
- </object>
- <object name="ClutterGroup" parent="ClutterActor" type-name="ClutterGroup" get-type="clutter_group_get_type">
- <implements>
- <interface name="ClutterScriptable"/>
- <interface name="ClutterContainer"/>
- </implements>
- <method name="get_n_children" symbol="clutter_group_get_n_children">
- <return-type type="gint"/>
+ <method name="get_easing_duration" symbol="clutter_box_layout_get_easing_duration">
+ <return-type type="guint"/>
<parameters>
- <parameter name="self" type="ClutterGroup*"/>
+ <parameter name="layout" type="ClutterBoxLayout*"/>
</parameters>
</method>
- <method name="get_nth_child" symbol="clutter_group_get_nth_child">
- <return-type type="ClutterActor*"/>
+ <method name="get_easing_mode" symbol="clutter_box_layout_get_easing_mode">
+ <return-type type="gulong"/>
<parameters>
- <parameter name="self" type="ClutterGroup*"/>
- <parameter name="index_" type="gint"/>
+ <parameter name="layout" type="ClutterBoxLayout*"/>
</parameters>
</method>
- <constructor name="new" symbol="clutter_group_new">
- <return-type type="ClutterActor*"/>
- </constructor>
- <method name="remove_all" symbol="clutter_group_remove_all">
- <return-type type="void"/>
+ <method name="get_expand" symbol="clutter_box_layout_get_expand">
+ <return-type type="gboolean"/>
<parameters>
- <parameter name="group" type="ClutterGroup*"/>
+ <parameter name="layout" type="ClutterBoxLayout*"/>
+ <parameter name="actor" type="ClutterActor*"/>
</parameters>
</method>
- </object>
- <object name="ClutterInterval" parent="GInitiallyUnowned" type-name="ClutterInterval" get-type="clutter_interval_get_type">
- <method name="clone" symbol="clutter_interval_clone">
- <return-type type="ClutterInterval*"/>
+ <method name="get_fill" symbol="clutter_box_layout_get_fill">
+ <return-type type="void"/>
<parameters>
- <parameter name="interval" type="ClutterInterval*"/>
+ <parameter name="layout" type="ClutterBoxLayout*"/>
+ <parameter name="actor" type="ClutterActor*"/>
+ <parameter name="x_fill" type="gboolean*"/>
+ <parameter name="y_fill" type="gboolean*"/>
</parameters>
</method>
- <method name="compute_value" symbol="clutter_interval_compute_value">
+ <method name="get_pack_start" symbol="clutter_box_layout_get_pack_start">
<return-type type="gboolean"/>
<parameters>
- <parameter name="interval" type="ClutterInterval*"/>
- <parameter name="factor" type="gdouble"/>
- <parameter name="value" type="GValue*"/>
+ <parameter name="layout" type="ClutterBoxLayout*"/>
+ </parameters>
+ </method>
+ <method name="get_spacing" symbol="clutter_box_layout_get_spacing">
+ <return-type type="guint"/>
+ <parameters>
+ <parameter name="layout" type="ClutterBoxLayout*"/>
+ </parameters>
+ </method>
+ <method name="get_use_animations" symbol="clutter_box_layout_get_use_animations">
+ <return-type type="gboolean"/>
+ <parameters>
+ <parameter name="layout" type="ClutterBoxLayout*"/>
+ </parameters>
+ </method>
+ <method name="get_vertical" symbol="clutter_box_layout_get_vertical">
+ <return-type type="gboolean"/>
+ <parameters>
+ <parameter name="layout" type="ClutterBoxLayout*"/>
+ </parameters>
+ </method>
+ <constructor name="new" symbol="clutter_box_layout_new">
+ <return-type type="ClutterLayoutManager*"/>
+ </constructor>
+ <method name="pack" symbol="clutter_box_layout_pack">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="layout" type="ClutterBoxLayout*"/>
+ <parameter name="actor" type="ClutterActor*"/>
+ <parameter name="expand" type="gboolean"/>
+ <parameter name="x_fill" type="gboolean"/>
+ <parameter name="y_fill" type="gboolean"/>
+ <parameter name="x_align" type="ClutterBoxAlignment"/>
+ <parameter name="y_align" type="ClutterBoxAlignment"/>
+ </parameters>
+ </method>
+ <method name="set_alignment" symbol="clutter_box_layout_set_alignment">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="layout" type="ClutterBoxLayout*"/>
+ <parameter name="actor" type="ClutterActor*"/>
+ <parameter name="x_align" type="ClutterBoxAlignment"/>
+ <parameter name="y_align" type="ClutterBoxAlignment"/>
+ </parameters>
+ </method>
+ <method name="set_easing_duration" symbol="clutter_box_layout_set_easing_duration">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="layout" type="ClutterBoxLayout*"/>
+ <parameter name="msecs" type="guint"/>
+ </parameters>
+ </method>
+ <method name="set_easing_mode" symbol="clutter_box_layout_set_easing_mode">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="layout" type="ClutterBoxLayout*"/>
+ <parameter name="mode" type="gulong"/>
+ </parameters>
+ </method>
+ <method name="set_expand" symbol="clutter_box_layout_set_expand">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="layout" type="ClutterBoxLayout*"/>
+ <parameter name="actor" type="ClutterActor*"/>
+ <parameter name="expand" type="gboolean"/>
+ </parameters>
+ </method>
+ <method name="set_fill" symbol="clutter_box_layout_set_fill">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="layout" type="ClutterBoxLayout*"/>
+ <parameter name="actor" type="ClutterActor*"/>
+ <parameter name="x_fill" type="gboolean"/>
+ <parameter name="y_fill" type="gboolean"/>
+ </parameters>
+ </method>
+ <method name="set_pack_start" symbol="clutter_box_layout_set_pack_start">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="layout" type="ClutterBoxLayout*"/>
+ <parameter name="pack_start" type="gboolean"/>
+ </parameters>
+ </method>
+ <method name="set_spacing" symbol="clutter_box_layout_set_spacing">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="layout" type="ClutterBoxLayout*"/>
+ <parameter name="spacing" type="guint"/>
+ </parameters>
+ </method>
+ <method name="set_use_animations" symbol="clutter_box_layout_set_use_animations">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="layout" type="ClutterBoxLayout*"/>
+ <parameter name="animate" type="gboolean"/>
+ </parameters>
+ </method>
+ <method name="set_vertical" symbol="clutter_box_layout_set_vertical">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="layout" type="ClutterBoxLayout*"/>
+ <parameter name="vertical" type="gboolean"/>
+ </parameters>
+ </method>
+ <property name="easing-duration" type="guint" readable="1" writable="1" construct="0" construct-only="0"/>
+ <property name="easing-mode" type="gulong" readable="1" writable="1" construct="0" construct-only="0"/>
+ <property name="pack-start" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/>
+ <property name="spacing" type="guint" readable="1" writable="1" construct="0" construct-only="0"/>
+ <property name="use-animations" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/>
+ <property name="vertical" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/>
+ </object>
+ <object name="ClutterCairoTexture" parent="ClutterTexture" type-name="ClutterCairoTexture" get-type="clutter_cairo_texture_get_type">
+ <implements>
+ <interface name="ClutterScriptable"/>
+ </implements>
+ <method name="clear" symbol="clutter_cairo_texture_clear">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="self" type="ClutterCairoTexture*"/>
+ </parameters>
+ </method>
+ <method name="create" symbol="clutter_cairo_texture_create">
+ <return-type type="cairo_t*"/>
+ <parameters>
+ <parameter name="self" type="ClutterCairoTexture*"/>
+ </parameters>
+ </method>
+ <method name="create_region" symbol="clutter_cairo_texture_create_region">
+ <return-type type="cairo_t*"/>
+ <parameters>
+ <parameter name="self" type="ClutterCairoTexture*"/>
+ <parameter name="x_offset" type="gint"/>
+ <parameter name="y_offset" type="gint"/>
+ <parameter name="width" type="gint"/>
+ <parameter name="height" type="gint"/>
+ </parameters>
+ </method>
+ <method name="get_surface_size" symbol="clutter_cairo_texture_get_surface_size">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="self" type="ClutterCairoTexture*"/>
+ <parameter name="width" type="guint*"/>
+ <parameter name="height" type="guint*"/>
+ </parameters>
+ </method>
+ <constructor name="new" symbol="clutter_cairo_texture_new">
+ <return-type type="ClutterActor*"/>
+ <parameters>
+ <parameter name="width" type="guint"/>
+ <parameter name="height" type="guint"/>
+ </parameters>
+ </constructor>
+ <method name="set_surface_size" symbol="clutter_cairo_texture_set_surface_size">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="self" type="ClutterCairoTexture*"/>
+ <parameter name="width" type="guint"/>
+ <parameter name="height" type="guint"/>
+ </parameters>
+ </method>
+ <property name="surface-height" type="guint" readable="1" writable="1" construct="0" construct-only="0"/>
+ <property name="surface-width" type="guint" readable="1" writable="1" construct="0" construct-only="0"/>
+ </object>
+ <object name="ClutterChildMeta" parent="GObject" type-name="ClutterChildMeta" get-type="clutter_child_meta_get_type">
+ <method name="get_actor" symbol="clutter_child_meta_get_actor">
+ <return-type type="ClutterActor*"/>
+ <parameters>
+ <parameter name="data" type="ClutterChildMeta*"/>
+ </parameters>
+ </method>
+ <method name="get_container" symbol="clutter_child_meta_get_container">
+ <return-type type="ClutterContainer*"/>
+ <parameters>
+ <parameter name="data" type="ClutterChildMeta*"/>
+ </parameters>
+ </method>
+ <property name="actor" type="ClutterActor*" readable="1" writable="1" construct="0" construct-only="1"/>
+ <property name="container" type="ClutterContainer*" readable="1" writable="1" construct="0" construct-only="1"/>
+ <field name="container" type="ClutterContainer*"/>
+ <field name="actor" type="ClutterActor*"/>
+ </object>
+ <object name="ClutterClone" parent="ClutterActor" type-name="ClutterClone" get-type="clutter_clone_get_type">
+ <implements>
+ <interface name="ClutterScriptable"/>
+ </implements>
+ <method name="get_source" symbol="clutter_clone_get_source">
+ <return-type type="ClutterActor*"/>
+ <parameters>
+ <parameter name="clone" type="ClutterClone*"/>
+ </parameters>
+ </method>
+ <constructor name="new" symbol="clutter_clone_new">
+ <return-type type="ClutterActor*"/>
+ <parameters>
+ <parameter name="source" type="ClutterActor*"/>
+ </parameters>
+ </constructor>
+ <method name="set_source" symbol="clutter_clone_set_source">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="clone" type="ClutterClone*"/>
+ <parameter name="source" type="ClutterActor*"/>
+ </parameters>
+ </method>
+ <property name="source" type="ClutterActor*" readable="1" writable="1" construct="1" construct-only="0"/>
+ </object>
+ <object name="ClutterDeviceManager" parent="GObject" type-name="ClutterDeviceManager" get-type="clutter_device_manager_get_type">
+ <method name="get_core_device" symbol="clutter_device_manager_get_core_device">
+ <return-type type="ClutterInputDevice*"/>
+ <parameters>
+ <parameter name="device_manager" type="ClutterDeviceManager*"/>
+ <parameter name="device_type" type="ClutterInputDeviceType"/>
+ </parameters>
+ </method>
+ <method name="get_default" symbol="clutter_device_manager_get_default">
+ <return-type type="ClutterDeviceManager*"/>
+ </method>
+ <method name="get_device" symbol="clutter_device_manager_get_device">
+ <return-type type="ClutterInputDevice*"/>
+ <parameters>
+ <parameter name="device_manager" type="ClutterDeviceManager*"/>
+ <parameter name="device_id" type="gint"/>
+ </parameters>
+ </method>
+ <method name="list_devices" symbol="clutter_device_manager_list_devices">
+ <return-type type="GSList*"/>
+ <parameters>
+ <parameter name="device_manager" type="ClutterDeviceManager*"/>
+ </parameters>
+ </method>
+ <method name="peek_devices" symbol="clutter_device_manager_peek_devices">
+ <return-type type="GSList*"/>
+ <parameters>
+ <parameter name="device_manager" type="ClutterDeviceManager*"/>
+ </parameters>
+ </method>
+ <property name="backend" type="ClutterBackend*" readable="1" writable="1" construct="0" construct-only="1"/>
+ <signal name="device-added" when="LAST">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="object" type="ClutterDeviceManager*"/>
+ <parameter name="p0" type="ClutterInputDevice*"/>
+ </parameters>
+ </signal>
+ <signal name="device-removed" when="LAST">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="object" type="ClutterDeviceManager*"/>
+ <parameter name="p0" type="ClutterInputDevice*"/>
+ </parameters>
+ </signal>
+ <vfunc name="add_device">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="manager" type="ClutterDeviceManager*"/>
+ <parameter name="device" type="ClutterInputDevice*"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="get_core_device">
+ <return-type type="ClutterInputDevice*"/>
+ <parameters>
+ <parameter name="manager" type="ClutterDeviceManager*"/>
+ <parameter name="type" type="ClutterInputDeviceType"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="get_device">
+ <return-type type="ClutterInputDevice*"/>
+ <parameters>
+ <parameter name="manager" type="ClutterDeviceManager*"/>
+ <parameter name="id" type="gint"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="get_devices">
+ <return-type type="GSList*"/>
+ <parameters>
+ <parameter name="manager" type="ClutterDeviceManager*"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="remove_device">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="manager" type="ClutterDeviceManager*"/>
+ <parameter name="device" type="ClutterInputDevice*"/>
+ </parameters>
+ </vfunc>
+ </object>
+ <object name="ClutterFixedLayout" parent="ClutterLayoutManager" type-name="ClutterFixedLayout" get-type="clutter_fixed_layout_get_type">
+ <constructor name="new" symbol="clutter_fixed_layout_new">
+ <return-type type="ClutterLayoutManager*"/>
+ </constructor>
+ </object>
+ <object name="ClutterFlowLayout" parent="ClutterLayoutManager" type-name="ClutterFlowLayout" get-type="clutter_flow_layout_get_type">
+ <method name="get_column_spacing" symbol="clutter_flow_layout_get_column_spacing">
+ <return-type type="gfloat"/>
+ <parameters>
+ <parameter name="layout" type="ClutterFlowLayout*"/>
+ </parameters>
+ </method>
+ <method name="get_column_width" symbol="clutter_flow_layout_get_column_width">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="layout" type="ClutterFlowLayout*"/>
+ <parameter name="min_width" type="gfloat*"/>
+ <parameter name="max_width" type="gfloat*"/>
+ </parameters>
+ </method>
+ <method name="get_homogeneous" symbol="clutter_flow_layout_get_homogeneous">
+ <return-type type="gboolean"/>
+ <parameters>
+ <parameter name="layout" type="ClutterFlowLayout*"/>
+ </parameters>
+ </method>
+ <method name="get_orientation" symbol="clutter_flow_layout_get_orientation">
+ <return-type type="ClutterFlowOrientation"/>
+ <parameters>
+ <parameter name="layout" type="ClutterFlowLayout*"/>
+ </parameters>
+ </method>
+ <method name="get_row_height" symbol="clutter_flow_layout_get_row_height">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="layout" type="ClutterFlowLayout*"/>
+ <parameter name="min_height" type="gfloat*"/>
+ <parameter name="max_height" type="gfloat*"/>
+ </parameters>
+ </method>
+ <method name="get_row_spacing" symbol="clutter_flow_layout_get_row_spacing">
+ <return-type type="gfloat"/>
+ <parameters>
+ <parameter name="layout" type="ClutterFlowLayout*"/>
+ </parameters>
+ </method>
+ <constructor name="new" symbol="clutter_flow_layout_new">
+ <return-type type="ClutterLayoutManager*"/>
+ <parameters>
+ <parameter name="orientation" type="ClutterFlowOrientation"/>
+ </parameters>
+ </constructor>
+ <method name="set_column_spacing" symbol="clutter_flow_layout_set_column_spacing">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="layout" type="ClutterFlowLayout*"/>
+ <parameter name="spacing" type="gfloat"/>
+ </parameters>
+ </method>
+ <method name="set_column_width" symbol="clutter_flow_layout_set_column_width">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="layout" type="ClutterFlowLayout*"/>
+ <parameter name="min_width" type="gfloat"/>
+ <parameter name="max_width" type="gfloat"/>
+ </parameters>
+ </method>
+ <method name="set_homogeneous" symbol="clutter_flow_layout_set_homogeneous">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="layout" type="ClutterFlowLayout*"/>
+ <parameter name="homogeneous" type="gboolean"/>
+ </parameters>
+ </method>
+ <method name="set_orientation" symbol="clutter_flow_layout_set_orientation">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="layout" type="ClutterFlowLayout*"/>
+ <parameter name="orientation" type="ClutterFlowOrientation"/>
+ </parameters>
+ </method>
+ <method name="set_row_height" symbol="clutter_flow_layout_set_row_height">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="layout" type="ClutterFlowLayout*"/>
+ <parameter name="min_height" type="gfloat"/>
+ <parameter name="max_height" type="gfloat"/>
+ </parameters>
+ </method>
+ <method name="set_row_spacing" symbol="clutter_flow_layout_set_row_spacing">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="layout" type="ClutterFlowLayout*"/>
+ <parameter name="spacing" type="gfloat"/>
+ </parameters>
+ </method>
+ <property name="column-spacing" type="gfloat" readable="1" writable="1" construct="0" construct-only="0"/>
+ <property name="homogeneous" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/>
+ <property name="max-column-width" type="gfloat" readable="1" writable="1" construct="0" construct-only="0"/>
+ <property name="max-row-height" type="gfloat" readable="1" writable="1" construct="0" construct-only="0"/>
+ <property name="min-column-width" type="gfloat" readable="1" writable="1" construct="0" construct-only="0"/>
+ <property name="min-row-height" type="gfloat" readable="1" writable="1" construct="0" construct-only="0"/>
+ <property name="orientation" type="ClutterFlowOrientation" readable="1" writable="1" construct="1" construct-only="0"/>
+ <property name="row-spacing" type="gfloat" readable="1" writable="1" construct="0" construct-only="0"/>
+ </object>
+ <object name="ClutterGroup" parent="ClutterActor" type-name="ClutterGroup" get-type="clutter_group_get_type">
+ <implements>
+ <interface name="ClutterScriptable"/>
+ <interface name="ClutterContainer"/>
+ </implements>
+ <method name="get_n_children" symbol="clutter_group_get_n_children">
+ <return-type type="gint"/>
+ <parameters>
+ <parameter name="self" type="ClutterGroup*"/>
+ </parameters>
+ </method>
+ <method name="get_nth_child" symbol="clutter_group_get_nth_child">
+ <return-type type="ClutterActor*"/>
+ <parameters>
+ <parameter name="self" type="ClutterGroup*"/>
+ <parameter name="index_" type="gint"/>
+ </parameters>
+ </method>
+ <constructor name="new" symbol="clutter_group_new">
+ <return-type type="ClutterActor*"/>
+ </constructor>
+ <method name="remove_all" symbol="clutter_group_remove_all">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="group" type="ClutterGroup*"/>
+ </parameters>
+ </method>
+ </object>
+ <object name="ClutterInputDevice" parent="GObject" type-name="ClutterInputDevice" get-type="clutter_input_device_get_type">
+ <method name="get_device_coords" symbol="clutter_input_device_get_device_coords">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="device" type="ClutterInputDevice*"/>
+ <parameter name="x" type="gint*"/>
+ <parameter name="y" type="gint*"/>
+ </parameters>
+ </method>
+ <method name="get_device_id" symbol="clutter_input_device_get_device_id">
+ <return-type type="gint"/>
+ <parameters>
+ <parameter name="device" type="ClutterInputDevice*"/>
+ </parameters>
+ </method>
+ <method name="get_device_name" symbol="clutter_input_device_get_device_name">
+ <return-type type="gchar*"/>
+ <parameters>
+ <parameter name="device" type="ClutterInputDevice*"/>
+ </parameters>
+ </method>
+ <method name="get_device_type" symbol="clutter_input_device_get_device_type">
+ <return-type type="ClutterInputDeviceType"/>
+ <parameters>
+ <parameter name="device" type="ClutterInputDevice*"/>
+ </parameters>
+ </method>
+ <method name="get_pointer_actor" symbol="clutter_input_device_get_pointer_actor">
+ <return-type type="ClutterActor*"/>
+ <parameters>
+ <parameter name="device" type="ClutterInputDevice*"/>
+ </parameters>
+ </method>
+ <method name="get_pointer_stage" symbol="clutter_input_device_get_pointer_stage">
+ <return-type type="ClutterStage*"/>
+ <parameters>
+ <parameter name="device" type="ClutterInputDevice*"/>
+ </parameters>
+ </method>
+ <method name="update_from_event" symbol="clutter_input_device_update_from_event">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="device" type="ClutterInputDevice*"/>
+ <parameter name="event" type="ClutterEvent*"/>
+ <parameter name="update_stage" type="gboolean"/>
+ </parameters>
+ </method>
+ <property name="device-type" type="ClutterInputDeviceType" readable="1" writable="1" construct="0" construct-only="1"/>
+ <property name="id" type="gint" readable="1" writable="1" construct="0" construct-only="1"/>
+ <property name="name" type="char*" readable="1" writable="1" construct="0" construct-only="1"/>
+ </object>
+ <object name="ClutterInterval" parent="GInitiallyUnowned" type-name="ClutterInterval" get-type="clutter_interval_get_type">
+ <method name="clone" symbol="clutter_interval_clone">
+ <return-type type="ClutterInterval*"/>
+ <parameters>
+ <parameter name="interval" type="ClutterInterval*"/>
+ </parameters>
+ </method>
+ <method name="compute_value" symbol="clutter_interval_compute_value">
+ <return-type type="gboolean"/>
+ <parameters>
+ <parameter name="interval" type="ClutterInterval*"/>
+ <parameter name="factor" type="gdouble"/>
+ <parameter name="value" type="GValue*"/>
</parameters>
</method>
<method name="get_final_value" symbol="clutter_interval_get_final_value">
@@ -4171,15 +4436,231 @@
<parameter name="value" type="GValue*"/>
</parameters>
</vfunc>
- <vfunc name="validate">
- <return-type type="gboolean"/>
+ <vfunc name="validate">
+ <return-type type="gboolean"/>
+ <parameters>
+ <parameter name="interval" type="ClutterInterval*"/>
+ <parameter name="pspec" type="GParamSpec*"/>
+ </parameters>
+ </vfunc>
+ </object>
+ <object name="ClutterLayoutManager" parent="GInitiallyUnowned" type-name="ClutterLayoutManager" get-type="clutter_layout_manager_get_type">
+ <method name="allocate" symbol="clutter_layout_manager_allocate">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ <parameter name="container" type="ClutterContainer*"/>
+ <parameter name="allocation" type="ClutterActorBox*"/>
+ <parameter name="flags" type="ClutterAllocationFlags"/>
+ </parameters>
+ </method>
+ <method name="begin_animation" symbol="clutter_layout_manager_begin_animation">
+ <return-type type="ClutterAlpha*"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ <parameter name="duration" type="guint"/>
+ <parameter name="mode" type="gulong"/>
+ </parameters>
+ </method>
+ <method name="child_get" symbol="clutter_layout_manager_child_get">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ <parameter name="container" type="ClutterContainer*"/>
+ <parameter name="actor" type="ClutterActor*"/>
+ <parameter name="first_property" type="gchar*"/>
+ </parameters>
+ </method>
+ <method name="child_get_property" symbol="clutter_layout_manager_child_get_property">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ <parameter name="container" type="ClutterContainer*"/>
+ <parameter name="actor" type="ClutterActor*"/>
+ <parameter name="property_name" type="gchar*"/>
+ <parameter name="value" type="GValue*"/>
+ </parameters>
+ </method>
+ <method name="child_set" symbol="clutter_layout_manager_child_set">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ <parameter name="container" type="ClutterContainer*"/>
+ <parameter name="actor" type="ClutterActor*"/>
+ <parameter name="first_property" type="gchar*"/>
+ </parameters>
+ </method>
+ <method name="child_set_property" symbol="clutter_layout_manager_child_set_property">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ <parameter name="container" type="ClutterContainer*"/>
+ <parameter name="actor" type="ClutterActor*"/>
+ <parameter name="property_name" type="gchar*"/>
+ <parameter name="value" type="GValue*"/>
+ </parameters>
+ </method>
+ <method name="end_animation" symbol="clutter_layout_manager_end_animation">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ </parameters>
+ </method>
+ <method name="find_child_property" symbol="clutter_layout_manager_find_child_property">
+ <return-type type="GParamSpec*"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ <parameter name="name" type="gchar*"/>
+ </parameters>
+ </method>
+ <method name="get_animation_progress" symbol="clutter_layout_manager_get_animation_progress">
+ <return-type type="gdouble"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ </parameters>
+ </method>
+ <method name="get_child_meta" symbol="clutter_layout_manager_get_child_meta">
+ <return-type type="ClutterLayoutMeta*"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ <parameter name="container" type="ClutterContainer*"/>
+ <parameter name="actor" type="ClutterActor*"/>
+ </parameters>
+ </method>
+ <method name="get_preferred_height" symbol="clutter_layout_manager_get_preferred_height">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ <parameter name="container" type="ClutterContainer*"/>
+ <parameter name="for_width" type="gfloat"/>
+ <parameter name="min_height_p" type="gfloat*"/>
+ <parameter name="nat_height_p" type="gfloat*"/>
+ </parameters>
+ </method>
+ <method name="get_preferred_width" symbol="clutter_layout_manager_get_preferred_width">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ <parameter name="container" type="ClutterContainer*"/>
+ <parameter name="for_height" type="gfloat"/>
+ <parameter name="min_width_p" type="gfloat*"/>
+ <parameter name="nat_width_p" type="gfloat*"/>
+ </parameters>
+ </method>
+ <method name="layout_changed" symbol="clutter_layout_manager_layout_changed">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ </parameters>
+ </method>
+ <method name="list_child_properties" symbol="clutter_layout_manager_list_child_properties">
+ <return-type type="GParamSpec**"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ <parameter name="n_pspecs" type="guint*"/>
+ </parameters>
+ </method>
+ <method name="set_container" symbol="clutter_layout_manager_set_container">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ <parameter name="container" type="ClutterContainer*"/>
+ </parameters>
+ </method>
+ <signal name="layout-changed" when="LAST">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ </parameters>
+ </signal>
+ <vfunc name="allocate">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ <parameter name="container" type="ClutterContainer*"/>
+ <parameter name="allocation" type="ClutterActorBox*"/>
+ <parameter name="flags" type="ClutterAllocationFlags"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="begin_animation">
+ <return-type type="ClutterAlpha*"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ <parameter name="duration" type="guint"/>
+ <parameter name="mode" type="gulong"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="create_child_meta">
+ <return-type type="ClutterLayoutMeta*"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ <parameter name="container" type="ClutterContainer*"/>
+ <parameter name="actor" type="ClutterActor*"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="end_animation">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="get_animation_progress">
+ <return-type type="gdouble"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="get_child_meta_type">
+ <return-type type="GType"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="get_preferred_height">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ <parameter name="container" type="ClutterContainer*"/>
+ <parameter name="for_width" type="gfloat"/>
+ <parameter name="minimum_height_p" type="gfloat*"/>
+ <parameter name="natural_height_p" type="gfloat*"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="get_preferred_width">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ <parameter name="container" type="ClutterContainer*"/>
+ <parameter name="for_height" type="gfloat"/>
+ <parameter name="minimum_width_p" type="gfloat*"/>
+ <parameter name="natural_width_p" type="gfloat*"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="set_container">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="manager" type="ClutterLayoutManager*"/>
+ <parameter name="container" type="ClutterContainer*"/>
+ </parameters>
+ </vfunc>
+ <field name="dummy" type="gpointer"/>
+ </object>
+ <object name="ClutterLayoutMeta" parent="ClutterChildMeta" type-name="ClutterLayoutMeta" get-type="clutter_layout_meta_get_type">
+ <method name="get_manager" symbol="clutter_layout_meta_get_manager">
+ <return-type type="ClutterLayoutManager*"/>
<parameters>
- <parameter name="interval" type="ClutterInterval*"/>
- <parameter name="pspec" type="GParamSpec*"/>
+ <parameter name="data" type="ClutterLayoutMeta*"/>
</parameters>
- </vfunc>
+ </method>
+ <property name="manager" type="ClutterLayoutManager*" readable="1" writable="1" construct="0" construct-only="1"/>
+ <field name="manager" type="ClutterLayoutManager*"/>
+ <field name="dummy0" type="gint32"/>
+ <field name="dummy1" type="gpointer"/>
</object>
<object name="ClutterListModel" parent="ClutterModel" type-name="ClutterListModel" get-type="clutter_list_model_get_type">
+ <implements>
+ <interface name="ClutterScriptable"/>
+ </implements>
<constructor name="new" symbol="clutter_list_model_new">
<return-type type="ClutterModel*"/>
<parameters>
@@ -4196,6 +4677,9 @@
</constructor>
</object>
<object name="ClutterModel" parent="GObject" type-name="ClutterModel" get-type="clutter_model_get_type">
+ <implements>
+ <interface name="ClutterScriptable"/>
+ </implements>
<method name="append" symbol="clutter_model_append">
<return-type type="void"/>
<parameters>
@@ -5262,6 +5746,14 @@
<parameter name="stage" type="ClutterStage*"/>
</parameters>
</method>
+ <method name="get_minimum_size" symbol="clutter_stage_get_minimum_size">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="stage" type="ClutterStage*"/>
+ <parameter name="width" type="guint*"/>
+ <parameter name="height" type="guint*"/>
+ </parameters>
+ </method>
<method name="get_perspective" symbol="clutter_stage_get_perspective">
<return-type type="void"/>
<parameters>
@@ -5281,6 +5773,12 @@
<parameter name="stage" type="ClutterStage*"/>
</parameters>
</method>
+ <method name="get_use_alpha" symbol="clutter_stage_get_use_alpha">
+ <return-type type="gboolean"/>
+ <parameters>
+ <parameter name="stage" type="ClutterStage*"/>
+ </parameters>
+ </method>
<method name="get_use_fog" symbol="clutter_stage_get_use_fog">
<return-type type="gboolean"/>
<parameters>
@@ -5352,6 +5850,14 @@
<parameter name="actor" type="ClutterActor*"/>
</parameters>
</method>
+ <method name="set_minimum_size" symbol="clutter_stage_set_minimum_size">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="stage" type="ClutterStage*"/>
+ <parameter name="width" type="guint"/>
+ <parameter name="height" type="guint"/>
+ </parameters>
+ </method>
<method name="set_perspective" symbol="clutter_stage_set_perspective">
<return-type type="void"/>
<parameters>
@@ -5373,6 +5879,13 @@
<parameter name="title" type="gchar*"/>
</parameters>
</method>
+ <method name="set_use_alpha" symbol="clutter_stage_set_use_alpha">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="stage" type="ClutterStage*"/>
+ <parameter name="use_alpha" type="gboolean"/>
+ </parameters>
+ </method>
<method name="set_use_fog" symbol="clutter_stage_set_use_fog">
<return-type type="void"/>
<parameters>
@@ -5397,9 +5910,11 @@
<property name="cursor-visible" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="fog" type="ClutterFog*" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="fullscreen-set" type="gboolean" readable="1" writable="0" construct="0" construct-only="0"/>
+ <property name="key-focus" type="ClutterActor*" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="offscreen" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="perspective" type="ClutterPerspective*" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="title" type="char*" readable="1" writable="1" construct="0" construct-only="0"/>
+ <property name="use-alpha" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="use-fog" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="user-resizable" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/>
<signal name="activate" when="LAST">
@@ -5414,6 +5929,13 @@
<parameter name="stage" type="ClutterStage*"/>
</parameters>
</signal>
+ <signal name="delete-event" when="LAST">
+ <return-type type="gboolean"/>
+ <parameters>
+ <parameter name="stage" type="ClutterStage*"/>
+ <parameter name="event" type="ClutterEvent*"/>
+ </parameters>
+ </signal>
<signal name="fullscreen" when="FIRST">
<return-type type="void"/>
<parameters>
@@ -5449,14 +5971,7 @@
<parameter name="stage_manager" type="ClutterStageManager*"/>
</parameters>
</method>
- <method name="set_default_stage" symbol="clutter_stage_manager_set_default_stage">
- <return-type type="void"/>
- <parameters>
- <parameter name="stage_manager" type="ClutterStageManager*"/>
- <parameter name="stage" type="ClutterStage*"/>
- </parameters>
- </method>
- <property name="default-stage" type="ClutterStage*" readable="1" writable="1" construct="0" construct-only="0"/>
+ <property name="default-stage" type="ClutterStage*" readable="1" writable="0" construct="0" construct-only="0"/>
<signal name="stage-added" when="LAST">
<return-type type="void"/>
<parameters>
@@ -5567,6 +6082,12 @@
<parameter name="self" type="ClutterText*"/>
</parameters>
</method>
+ <method name="get_font_description" symbol="clutter_text_get_font_description">
+ <return-type type="PangoFontDescription*"/>
+ <parameters>
+ <parameter name="self" type="ClutterText*"/>
+ </parameters>
+ </method>
<method name="get_font_name" symbol="clutter_text_get_font_name">
<return-type type="gchar*"/>
<parameters>
@@ -5764,6 +6285,13 @@
<parameter name="mode" type="PangoEllipsizeMode"/>
</parameters>
</method>
+ <method name="set_font_description" symbol="clutter_text_set_font_description">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="self" type="ClutterText*"/>
+ <parameter name="font_desc" type="PangoFontDescription*"/>
+ </parameters>
+ </method>
<method name="set_font_name" symbol="clutter_text_set_font_name">
<return-type type="void"/>
<parameters>
@@ -5820,6 +6348,15 @@
<parameter name="wc" type="gunichar"/>
</parameters>
</method>
+ <method name="set_preedit_string" symbol="clutter_text_set_preedit_string">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="self" type="ClutterText*"/>
+ <parameter name="preedit_str" type="gchar*"/>
+ <parameter name="preedit_attrs" type="PangoAttrList*"/>
+ <parameter name="cursor_pos" type="guint"/>
+ </parameters>
+ </method>
<method name="set_selectable" symbol="clutter_text_set_selectable">
<return-type type="void"/>
<parameters>
@@ -5879,6 +6416,7 @@
<property name="cursor-visible" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="editable" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="ellipsize" type="PangoEllipsizeMode" readable="1" writable="1" construct="0" construct-only="0"/>
+ <property name="font-description" type="PangoFontDescription*" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="font-name" type="char*" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="justify" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/>
<property name="line-alignment" type="PangoAlignment" readable="1" writable="1" construct="0" construct-only="0"/>
@@ -5907,6 +6445,23 @@
<parameter name="geometry" type="ClutterGeometry*"/>
</parameters>
</signal>
+ <signal name="delete-text" when="LAST">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="object" type="ClutterText*"/>
+ <parameter name="p0" type="gint"/>
+ <parameter name="p1" type="gint"/>
+ </parameters>
+ </signal>
+ <signal name="insert-text" when="LAST">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="object" type="ClutterText*"/>
+ <parameter name="p0" type="char*"/>
+ <parameter name="p1" type="gint"/>
+ <parameter name="p2" type="gpointer"/>
+ </parameters>
+ </signal>
<signal name="text-changed" when="LAST">
<return-type type="void"/>
<parameters>
@@ -6357,139 +6912,6 @@
</parameters>
</signal>
</object>
- <object name="JsonGenerator" parent="GObject" type-name="JsonGenerator" get-type="json_generator_get_type">
- <constructor name="new" symbol="json_generator_new">
- <return-type type="JsonGenerator*"/>
- </constructor>
- <method name="set_root" symbol="json_generator_set_root">
- <return-type type="void"/>
- <parameters>
- <parameter name="generator" type="JsonGenerator*"/>
- <parameter name="node" type="JsonNode*"/>
- </parameters>
- </method>
- <method name="to_data" symbol="json_generator_to_data">
- <return-type type="gchar*"/>
- <parameters>
- <parameter name="generator" type="JsonGenerator*"/>
- <parameter name="length" type="gsize*"/>
- </parameters>
- </method>
- <method name="to_file" symbol="json_generator_to_file">
- <return-type type="gboolean"/>
- <parameters>
- <parameter name="generator" type="JsonGenerator*"/>
- <parameter name="filename" type="gchar*"/>
- <parameter name="error" type="GError**"/>
- </parameters>
- </method>
- <property name="indent" type="guint" readable="1" writable="1" construct="0" construct-only="0"/>
- <property name="pretty" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/>
- </object>
- <object name="JsonParser" parent="GObject" type-name="JsonParser" get-type="json_parser_get_type">
- <method name="error_quark" symbol="json_parser_error_quark">
- <return-type type="GQuark"/>
- </method>
- <method name="get_current_line" symbol="json_parser_get_current_line">
- <return-type type="guint"/>
- <parameters>
- <parameter name="parser" type="JsonParser*"/>
- </parameters>
- </method>
- <method name="get_current_pos" symbol="json_parser_get_current_pos">
- <return-type type="guint"/>
- <parameters>
- <parameter name="parser" type="JsonParser*"/>
- </parameters>
- </method>
- <method name="get_root" symbol="json_parser_get_root">
- <return-type type="JsonNode*"/>
- <parameters>
- <parameter name="parser" type="JsonParser*"/>
- </parameters>
- </method>
- <method name="load_from_data" symbol="json_parser_load_from_data">
- <return-type type="gboolean"/>
- <parameters>
- <parameter name="parser" type="JsonParser*"/>
- <parameter name="data" type="gchar*"/>
- <parameter name="length" type="gssize"/>
- <parameter name="error" type="GError**"/>
- </parameters>
- </method>
- <method name="load_from_file" symbol="json_parser_load_from_file">
- <return-type type="gboolean"/>
- <parameters>
- <parameter name="parser" type="JsonParser*"/>
- <parameter name="filename" type="gchar*"/>
- <parameter name="error" type="GError**"/>
- </parameters>
- </method>
- <constructor name="new" symbol="json_parser_new">
- <return-type type="JsonParser*"/>
- </constructor>
- <signal name="array-element" when="LAST">
- <return-type type="void"/>
- <parameters>
- <parameter name="parser" type="JsonParser*"/>
- <parameter name="array" type="JsonArray*"/>
- <parameter name="index_" type="gint"/>
- </parameters>
- </signal>
- <signal name="array-end" when="LAST">
- <return-type type="void"/>
- <parameters>
- <parameter name="parser" type="JsonParser*"/>
- <parameter name="array" type="JsonArray*"/>
- </parameters>
- </signal>
- <signal name="array-start" when="LAST">
- <return-type type="void"/>
- <parameters>
- <parameter name="parser" type="JsonParser*"/>
- </parameters>
- </signal>
- <signal name="error" when="LAST">
- <return-type type="void"/>
- <parameters>
- <parameter name="parser" type="JsonParser*"/>
- <parameter name="error" type="gpointer"/>
- </parameters>
- </signal>
- <signal name="object-end" when="LAST">
- <return-type type="void"/>
- <parameters>
- <parameter name="parser" type="JsonParser*"/>
- <parameter name="object" type="JsonObject*"/>
- </parameters>
- </signal>
- <signal name="object-member" when="LAST">
- <return-type type="void"/>
- <parameters>
- <parameter name="parser" type="JsonParser*"/>
- <parameter name="object" type="JsonObject*"/>
- <parameter name="member_name" type="char*"/>
- </parameters>
- </signal>
- <signal name="object-start" when="LAST">
- <return-type type="void"/>
- <parameters>
- <parameter name="parser" type="JsonParser*"/>
- </parameters>
- </signal>
- <signal name="parse-end" when="LAST">
- <return-type type="void"/>
- <parameters>
- <parameter name="parser" type="JsonParser*"/>
- </parameters>
- </signal>
- <signal name="parse-start" when="LAST">
- <return-type type="void"/>
- <parameters>
- <parameter name="parser" type="JsonParser*"/>
- </parameters>
- </signal>
- </object>
<interface name="ClutterAnimatable" type-name="ClutterAnimatable" get-type="clutter_animatable_get_type">
<method name="animate_property" symbol="clutter_animatable_animate_property">
<return-type type="gboolean"/>
@@ -6590,6 +7012,20 @@
<parameter name="n_properties" type="guint*"/>
</parameters>
</method>
+ <method name="create_child_meta" symbol="clutter_container_create_child_meta">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="container" type="ClutterContainer*"/>
+ <parameter name="actor" type="ClutterActor*"/>
+ </parameters>
+ </method>
+ <method name="destroy_child_meta" symbol="clutter_container_destroy_child_meta">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="container" type="ClutterContainer*"/>
+ <parameter name="actor" type="ClutterActor*"/>
+ </parameters>
+ </method>
<method name="find_child_by_name" symbol="clutter_container_find_child_by_name">
<return-type type="ClutterActor*"/>
<parameters>
@@ -6803,6 +7239,18 @@
<parameter name="media" type="ClutterMedia*"/>
</parameters>
</method>
+ <method name="get_subtitle_font_name" symbol="clutter_media_get_subtitle_font_name">
+ <return-type type="gchar*"/>
+ <parameters>
+ <parameter name="media" type="ClutterMedia*"/>
+ </parameters>
+ </method>
+ <method name="get_subtitle_uri" symbol="clutter_media_get_subtitle_uri">
+ <return-type type="gchar*"/>
+ <parameters>
+ <parameter name="media" type="ClutterMedia*"/>
+ </parameters>
+ </method>
<method name="get_uri" symbol="clutter_media_get_uri">
<return-type type="gchar*"/>
<parameters>
@@ -6837,6 +7285,20 @@
<parameter name="progress" type="gdouble"/>
</parameters>
</method>
+ <method name="set_subtitle_font_name" symbol="clutter_media_set_subtitle_font_name">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="media" type="ClutterMedia*"/>
+ <parameter name="font_name" type="char*"/>
+ </parameters>
+ </method>
+ <method name="set_subtitle_uri" symbol="clutter_media_set_subtitle_uri">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="media" type="ClutterMedia*"/>
+ <parameter name="uri" type="gchar*"/>
+ </parameters>
+ </method>
<method name="set_uri" symbol="clutter_media_set_uri">
<return-type type="void"/>
<parameters>
@@ -6924,15 +7386,119 @@
</parameters>
</vfunc>
</interface>
+ <interface name="ClutterStageWindow" type-name="ClutterStageWindow" get-type="clutter_stage_window_get_type">
+ <requires>
+ <interface name="GObject"/>
+ </requires>
+ <vfunc name="add_redraw_clip">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="stage_window" type="ClutterStageWindow*"/>
+ <parameter name="stage_rectangle" type="ClutterGeometry*"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="get_geometry">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="stage_window" type="ClutterStageWindow*"/>
+ <parameter name="geometry" type="ClutterGeometry*"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="get_pending_swaps">
+ <return-type type="int"/>
+ <parameters>
+ <parameter name="stage_window" type="ClutterStageWindow*"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="get_wrapper">
+ <return-type type="ClutterActor*"/>
+ <parameters>
+ <parameter name="stage_window" type="ClutterStageWindow*"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="has_redraw_clips">
+ <return-type type="gboolean"/>
+ <parameters>
+ <parameter name="stage_window" type="ClutterStageWindow*"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="hide">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="stage_window" type="ClutterStageWindow*"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="ignoring_redraw_clips">
+ <return-type type="gboolean"/>
+ <parameters>
+ <parameter name="stage_window" type="ClutterStageWindow*"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="realize">
+ <return-type type="gboolean"/>
+ <parameters>
+ <parameter name="stage_window" type="ClutterStageWindow*"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="resize">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="stage_window" type="ClutterStageWindow*"/>
+ <parameter name="width" type="gint"/>
+ <parameter name="height" type="gint"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="set_cursor_visible">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="stage_window" type="ClutterStageWindow*"/>
+ <parameter name="cursor_visible" type="gboolean"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="set_fullscreen">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="stage_window" type="ClutterStageWindow*"/>
+ <parameter name="is_fullscreen" type="gboolean"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="set_title">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="stage_window" type="ClutterStageWindow*"/>
+ <parameter name="title" type="gchar*"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="set_user_resizable">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="stage_window" type="ClutterStageWindow*"/>
+ <parameter name="is_resizable" type="gboolean"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="show">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="stage_window" type="ClutterStageWindow*"/>
+ <parameter name="do_raise" type="gboolean"/>
+ </parameters>
+ </vfunc>
+ <vfunc name="unrealize">
+ <return-type type="void"/>
+ <parameters>
+ <parameter name="stage_window" type="ClutterStageWindow*"/>
+ </parameters>
+ </vfunc>
+ </interface>
<constant name="CLUTTER_COGL" type="char*" value="gl"/>
<constant name="CLUTTER_CURRENT_TIME" type="int" value="0"/>
<constant name="CLUTTER_FLAVOUR" type="char*" value="glx"/>
<constant name="CLUTTER_MAJOR_VERSION" type="int" value="1"/>
- <constant name="CLUTTER_MICRO_VERSION" type="int" value="6"/>
- <constant name="CLUTTER_MINOR_VERSION" type="int" value="0"/>
+ <constant name="CLUTTER_MICRO_VERSION" type="int" value="4"/>
+ <constant name="CLUTTER_MINOR_VERSION" type="int" value="2"/>
<constant name="CLUTTER_PATH_RELATIVE" type="int" value="32"/>
<constant name="CLUTTER_PRIORITY_REDRAW" type="int" value="50"/>
<constant name="CLUTTER_VERSION_HEX" type="int" value="0"/>
- <constant name="CLUTTER_VERSION_S" type="char*" value="1.0.6"/>
+ <constant name="CLUTTER_VERSION_S" type="char*" value="1.2.4"/>
</namespace>
</api>
diff --git a/vapi/packages/clutter-1.0/clutter-1.0.metadata b/vapi/packages/clutter-1.0/clutter-1.0.metadata
index fc989742f1..7bdd7ea968 100644
--- a/vapi/packages/clutter-1.0/clutter-1.0.metadata
+++ b/vapi/packages/clutter-1.0/clutter-1.0.metadata
@@ -8,6 +8,7 @@ ClutterActor::hide has_emitter="1"
ClutterActor::paint has_emitter="1"
ClutterActor::pick has_emitter="1"
ClutterActor::queue_redraw hidden="1"
+ClutterActor::queue_relayout has_emitter="1"
ClutterActor::realize has_emitter="1"
ClutterActor::show has_emitter="1"
ClutterActor::unrealize has_emitter="1"
@@ -33,6 +34,7 @@ clutter_actor_apply_relative_transform_to_point.ancestor nullable="1"
clutter_actor_apply_relative_transform_to_point.vertex is_out="1" transfer_ownership="1"
clutter_actor_apply_transform_to_point.vertex is_out="1" transfer_ownership="1"
clutter_actor_has_clip name="get_has_clip" hidden="1"
+clutter_actor_has_pointer name="get_has_pointer"
clutter_actor_get_allocation_box.box is_out="1"
clutter_actor_get_allocation_geometry.geom is_out="1"
clutter_actor_get_anchor_point.anchor_* is_out="1"
@@ -154,6 +156,8 @@ clutter_binding_pool_override_action.data hidden="1"
clutter_binding_pool_override_action.callback transfer_ownership="1"
clutter_binding_pool_override_action.notify hidden="1"
+clutter_box_clutter_padding_* hidden="1"
+
ClutterButtonEvent is_value_type="1"
clutter_cairo_texture_create transfer_ownership="1"
@@ -232,6 +236,8 @@ clutter_interval_get_value_type hidden="1"
ClutterKeyEvent is_value_type="1"
ClutterKnot is_value_type="1"
+ClutterLayoutManager::layout_changed has_emitter="1"
+
clutter_list_model_newv.n_columns hidden="1"
clutter_list_model_newv.types array_length_pos="0.9"
clutter_list_model_newv.names array_length_pos="0.9"
@@ -321,10 +327,13 @@ clutter_stage_manager_get_default_stage hidden="1"
clutter_stage_manager_list_stages type_arguments="Stage"
clutter_stage_manager_peek_stages type_arguments="Stage"
clutter_stage_manager_set_default_stage hidden="1"
+clutter_stage_set_key_focus.actor nullable="1"
ClutterStageStateEvent is_value_type="1"
ClutterText::activate has_emitter="1"
+ClutterText::delete_text has_emitter="1"
+ClutterText::insert_text hidden="1"
clutter_text_get_activatable hidden="1"
clutter_text_get_color hidden="1"
clutter_text_get_cursor_color hidden="1"
@@ -345,6 +354,7 @@ clutter_text_get_selection_color hidden="1"
clutter_text_get_single_line_mode hidden="1"
clutter_text_get_text hidden="1"
clutter_text_get_use_markup hidden="1"
+clutter_text_new_with_text.font_name nullable="1"
clutter_text_set_activatable hidden="1"
clutter_text_set_color hidden="1"
clutter_text_set_cursor_color hidden="1"
|
041af28166c270b29b51f5f42fb3269c2dbe1159
|
kotlin
|
Deprecate and don't write KotlinClass$Kind
|
c
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java b/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java
index 8106ba4385088..89662512950c8 100644
--- a/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java
+++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java
@@ -43,7 +43,6 @@
import org.jetbrains.kotlin.lexer.JetTokens;
import org.jetbrains.kotlin.load.java.JvmAbi;
import org.jetbrains.kotlin.load.java.JvmAnnotationNames;
-import org.jetbrains.kotlin.load.java.JvmAnnotationNames.KotlinClass;
import org.jetbrains.kotlin.load.java.descriptors.JavaCallableMemberDescriptor;
import org.jetbrains.kotlin.name.FqName;
import org.jetbrains.kotlin.name.FqNameUnsafe;
@@ -256,17 +255,12 @@ protected void generateBody() {
protected void generateKotlinAnnotation() {
if (state.getClassBuilderMode() != ClassBuilderMode.FULL) return;
- KotlinClass.Kind kind;
- if (isAnonymousObject(descriptor)) {
- kind = KotlinClass.Kind.ANONYMOUS_OBJECT;
- }
- else if (isTopLevelOrInnerClass(descriptor)) {
- // Default value is Kind.CLASS
- kind = null;
- }
- else {
- // LOCAL_CLASS is also written to inner classes of local classes
- kind = KotlinClass.Kind.LOCAL_CLASS;
+ if (!isTopLevelOrInnerClass(descriptor)) {
+ AnnotationVisitor av = v.getVisitor().visitAnnotation(
+ asmDescByFqNameWithoutInnerClasses(JvmAnnotationNames.KOTLIN_LOCAL_CLASS), true
+ );
+ av.visit(JvmAnnotationNames.VERSION_FIELD_NAME, JvmAbi.VERSION.toArray());
+ av.visitEnd();
}
DescriptorSerializer serializer =
@@ -276,13 +270,6 @@ else if (isTopLevelOrInnerClass(descriptor)) {
AnnotationVisitor av = v.getVisitor().visitAnnotation(asmDescByFqNameWithoutInnerClasses(JvmAnnotationNames.KOTLIN_CLASS), true);
writeAnnotationData(av, serializer, classProto);
- if (kind != null) {
- av.visitEnum(
- JvmAnnotationNames.KIND_FIELD_NAME,
- Type.getObjectType(KotlinClass.KIND_INTERNAL_NAME).getDescriptor(),
- kind.toString()
- );
- }
av.visitEnd();
}
diff --git a/compiler/frontend.java/src/org/jetbrains/kotlin/load/kotlin/FileBasedKotlinClass.java b/compiler/frontend.java/src/org/jetbrains/kotlin/load/kotlin/FileBasedKotlinClass.java
index 67a9529da12fd..f59d77e8bf604 100644
--- a/compiler/frontend.java/src/org/jetbrains/kotlin/load/kotlin/FileBasedKotlinClass.java
+++ b/compiler/frontend.java/src/org/jetbrains/kotlin/load/kotlin/FileBasedKotlinClass.java
@@ -270,9 +270,6 @@ private static ClassId resolveNameByInternalName(@NotNull String name, @NotNull
if (name.equals(JvmAnnotationNames.KotlinSyntheticClass.KIND_INTERNAL_NAME)) {
return JvmAnnotationNames.KotlinSyntheticClass.KIND_CLASS_ID;
}
- else if (name.equals(JvmAnnotationNames.KotlinClass.KIND_INTERNAL_NAME)) {
- return JvmAnnotationNames.KotlinClass.KIND_CLASS_ID;
- }
List<String> classes = new ArrayList<String>(1);
boolean local = false;
diff --git a/compiler/testData/codegen/bytecodeListing/annotations/literals.txt b/compiler/testData/codegen/bytecodeListing/annotations/literals.txt
index 7ceb93edb710b..6666962805c18 100644
--- a/compiler/testData/codegen/bytecodeListing/annotations/literals.txt
+++ b/compiler/testData/codegen/bytecodeListing/annotations/literals.txt
@@ -20,7 +20,7 @@
method <init>(p0: int): void
}
[email protected] LiteralsKt$foo$3 {
[email protected] @kotlin.jvm.internal.KotlinClass LiteralsKt$foo$3 {
inner class LiteralsKt$foo$3
field $kotlinClass: kotlin.reflect.KClass
method <clinit>(): void
diff --git a/compiler/tests/org/jetbrains/kotlin/codegen/InlineTestUtil.kt b/compiler/tests/org/jetbrains/kotlin/codegen/InlineTestUtil.kt
index 3c09b0e4d375d..ccb23e253a03a 100644
--- a/compiler/tests/org/jetbrains/kotlin/codegen/InlineTestUtil.kt
+++ b/compiler/tests/org/jetbrains/kotlin/codegen/InlineTestUtil.kt
@@ -185,7 +185,7 @@ public object InlineTestUtil {
}
private fun isClassOrPackagePartKind(header: KotlinClassHeader): Boolean {
- return header.classKind == JvmAnnotationNames.KotlinClass.Kind.CLASS || header.isInterfaceDefaultImpls
+ return (header.kind == KotlinClassHeader.Kind.CLASS && !header.isLocalClass) || header.isInterfaceDefaultImpls
}
private fun getClassHeader(file: OutputFile): KotlinClassHeader {
diff --git a/compiler/tests/org/jetbrains/kotlin/codegen/KotlinSyntheticClassAnnotationTest.java b/compiler/tests/org/jetbrains/kotlin/codegen/KotlinSyntheticClassAnnotationTest.java
index c02e8d2ff2afd..9ec16af4125cf 100644
--- a/compiler/tests/org/jetbrains/kotlin/codegen/KotlinSyntheticClassAnnotationTest.java
+++ b/compiler/tests/org/jetbrains/kotlin/codegen/KotlinSyntheticClassAnnotationTest.java
@@ -19,14 +19,12 @@
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.backend.common.output.OutputFile;
import org.jetbrains.kotlin.load.java.AbiVersionUtil;
import org.jetbrains.kotlin.load.java.JvmAbi;
-import org.jetbrains.kotlin.load.java.JvmAnnotationNames.KotlinClass;
+import org.jetbrains.kotlin.load.java.JvmAnnotationNames;
import org.jetbrains.kotlin.load.java.JvmAnnotationNames.KotlinSyntheticClass;
import org.jetbrains.kotlin.name.FqName;
-import org.jetbrains.kotlin.resolve.jvm.JvmClassName;
import org.jetbrains.kotlin.serialization.deserialization.BinaryVersion;
import org.jetbrains.kotlin.test.ConfigurationKind;
@@ -34,9 +32,6 @@
import java.util.Collection;
import java.util.List;
-import static org.jetbrains.kotlin.load.java.JvmAnnotationNames.KIND_FIELD_NAME;
-import static org.jetbrains.kotlin.load.java.JvmAnnotationNames.KotlinClass.Kind.ANONYMOUS_OBJECT;
-import static org.jetbrains.kotlin.load.java.JvmAnnotationNames.KotlinClass.Kind.LOCAL_CLASS;
import static org.jetbrains.kotlin.load.java.JvmAnnotationNames.VERSION_FIELD_NAME;
public class KotlinSyntheticClassAnnotationTest extends CodegenTestCase {
@@ -93,8 +88,7 @@ public void testAnonymousFunction() {
public void testLocalClass() {
doTestKotlinClass(
"fun foo() { class Local }",
- "Local",
- LOCAL_CLASS
+ "Local"
);
}
@@ -108,24 +102,21 @@ public void testLocalTraitImpl() {
public void testLocalTraitInterface() {
doTestKotlinClass(
"fun foo() { interface Local { fun bar() = 42 } }",
- "Local.class",
- LOCAL_CLASS
+ "Local.class"
);
}
public void testInnerClassOfLocalClass() {
doTestKotlinClass(
"fun foo() { class Local { inner class Inner } }",
- "Inner",
- LOCAL_CLASS
+ "Inner"
);
}
public void testAnonymousObject() {
doTestKotlinClass(
"val o = object {}",
- "$1",
- ANONYMOUS_OBJECT
+ "$1"
);
}
@@ -138,22 +129,17 @@ public void testWhenMappings() {
}
private void doTestKotlinSyntheticClass(@NotNull String code, @NotNull String classFilePart) {
- doTest(code, classFilePart, KotlinSyntheticClass.CLASS_NAME, null);
+ doTest(code, classFilePart, KotlinSyntheticClass.CLASS_NAME.getFqNameForClassNameWithoutDollars());
}
- private void doTestKotlinClass(
- @NotNull String code,
- @NotNull String classFilePart,
- @NotNull KotlinClass.Kind expectedKind
- ) {
- doTest(code, classFilePart, KotlinClass.CLASS_NAME, expectedKind.toString());
+ private void doTestKotlinClass(@NotNull String code, @NotNull String classFilePart) {
+ doTest(code, classFilePart, JvmAnnotationNames.KOTLIN_CLASS, JvmAnnotationNames.KOTLIN_LOCAL_CLASS);
}
private void doTest(
@NotNull String code,
@NotNull final String classFilePart,
- @NotNull JvmClassName annotationName,
- @Nullable String expectedKind
+ @NotNull FqName... annotationFqNames
) {
loadText("package " + PACKAGE_NAME + "\n\n" + code);
List<OutputFile> output = generateClassesInFile().asList();
@@ -169,14 +155,12 @@ public boolean apply(OutputFile file) {
String path = files.iterator().next().getRelativePath();
String fqName = path.substring(0, path.length() - ".class".length()).replace('/', '.');
Class<?> aClass = generateClass(fqName);
- assertAnnotatedWithKind(aClass, annotationName.getFqNameForClassNameWithoutDollars().asString(), expectedKind);
+ for (FqName annotationFqName : annotationFqNames) {
+ assertAnnotatedWith(aClass, annotationFqName.asString());
+ }
}
- private void assertAnnotatedWithKind(
- @NotNull Class<?> aClass,
- @NotNull String annotationFqName,
- @Nullable String expectedKind
- ) {
+ private void assertAnnotatedWith(@NotNull Class<?> aClass, @NotNull String annotationFqName) {
Class<? extends Annotation> annotationClass = loadAnnotationClassQuietly(annotationFqName);
assertTrue("No annotation " + annotationFqName + " found in " + aClass, aClass.isAnnotationPresent(annotationClass));
@@ -186,9 +170,5 @@ private void assertAnnotatedWithKind(
assertNotNull(version);
assertTrue("Annotation " + annotationFqName + " is written with an unsupported format",
AbiVersionUtil.isAbiVersionCompatible(BinaryVersion.create(version)));
-
- Object actualKind = CodegenTestUtil.getAnnotationAttribute(annotation, KIND_FIELD_NAME);
- assertNotNull(actualKind);
- assertEquals("Annotation " + annotationFqName + " has the wrong kind", expectedKind, actualKind.toString());
}
}
diff --git a/compiler/tests/org/jetbrains/kotlin/jvm/runtime/AbstractJvmRuntimeDescriptorLoaderTest.kt b/compiler/tests/org/jetbrains/kotlin/jvm/runtime/AbstractJvmRuntimeDescriptorLoaderTest.kt
index 44836798c9779..21dc941dda869 100644
--- a/compiler/tests/org/jetbrains/kotlin/jvm/runtime/AbstractJvmRuntimeDescriptorLoaderTest.kt
+++ b/compiler/tests/org/jetbrains/kotlin/jvm/runtime/AbstractJvmRuntimeDescriptorLoaderTest.kt
@@ -150,11 +150,10 @@ public abstract class AbstractJvmRuntimeDescriptorLoaderTest : TestCaseWithTmpdi
val packageView = module.getPackage(LoadDescriptorUtil.TEST_PACKAGE_FQNAME)
packageScopes.add(packageView.memberScope)
}
- else if (header == null ||
- (header.kind == KotlinClassHeader.Kind.CLASS && header.classKind == JvmAnnotationNames.KotlinClass.Kind.CLASS)) {
+ else if (header == null || (header.kind == KotlinClassHeader.Kind.CLASS && !header.isLocalClass)) {
// Either a normal Kotlin class or a Java class
val classId = klass.classId
- if (!classId.isLocal()) {
+ if (!classId.isLocal) {
val classDescriptor = module.findClassAcrossModuleDependencies(classId).sure { "Couldn't resolve class $className" }
if (DescriptorUtils.isTopLevelDeclaration(classDescriptor)) {
classes.add(classDescriptor)
diff --git a/compiler/tests/org/jetbrains/kotlin/serialization/AbstractLocalClassProtoTest.kt b/compiler/tests/org/jetbrains/kotlin/serialization/AbstractLocalClassProtoTest.kt
index fbd1246cba2b0..f1899b6a4fc20 100644
--- a/compiler/tests/org/jetbrains/kotlin/serialization/AbstractLocalClassProtoTest.kt
+++ b/compiler/tests/org/jetbrains/kotlin/serialization/AbstractLocalClassProtoTest.kt
@@ -76,17 +76,13 @@ public abstract class AbstractLocalClassProtoTest : TestCaseWithTmpdir() {
)
}
+ @Suppress("UNCHECKED_CAST")
private fun assertHasAnnotationData(clazz: Class<*>) {
- @Suppress("UNCHECKED_CAST")
- val annotation = clazz.getAnnotation(
+ checkNotNull(clazz.getAnnotation(
clazz.classLoader.loadClass(JvmAnnotationNames.KOTLIN_CLASS.asString()) as Class<Annotation>
- )
- assert(annotation != null) { "KotlinClass annotation is not found for class $clazz" }
-
- val kindMethod = annotation.annotationType().getDeclaredMethod("kind")
- val kind = kindMethod(annotation)
- assert(kind.toString() != JvmAnnotationNames.KotlinClass.Kind.CLASS.toString()) {
- "'kind' should not be CLASS: $clazz (was $kind)"
- }
+ )) { "KotlinClass annotation is not found for class $clazz" }
+ checkNotNull(clazz.getAnnotation(
+ clazz.classLoader.loadClass(JvmAnnotationNames.KOTLIN_LOCAL_CLASS.asString()) as Class<Annotation>
+ )) { "KotlinLocalClass annotation is not found for class $clazz" }
}
}
diff --git a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/JvmAnnotationNames.java b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/JvmAnnotationNames.java
index c690ccb0d1496..4c28d1f533236 100644
--- a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/JvmAnnotationNames.java
+++ b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/JvmAnnotationNames.java
@@ -28,13 +28,14 @@
import java.util.Set;
public final class JvmAnnotationNames {
- public static final FqName KOTLIN_CLASS = KotlinClass.CLASS_NAME.getFqNameForClassNameWithoutDollars();
+ public static final FqName KOTLIN_CLASS = new FqName("kotlin.jvm.internal.KotlinClass");
public static final FqName KOTLIN_PACKAGE = new FqName("kotlin.jvm.internal.KotlinPackage");
public static final FqName KOTLIN_FILE_FACADE = new FqName("kotlin.jvm.internal.KotlinFileFacade");
public static final FqName KOTLIN_MULTIFILE_CLASS = new FqName("kotlin.jvm.internal.KotlinMultifileClass");
public static final FqName KOTLIN_MULTIFILE_CLASS_PART = new FqName("kotlin.jvm.internal.KotlinMultifileClassPart");
public static final FqName KOTLIN_CALLABLE = new FqName("kotlin.jvm.internal.KotlinCallable");
public static final FqName KOTLIN_INTERFACE_DEFAULT_IMPLS = new FqName("kotlin.jvm.internal.KotlinInterfaceDefaultImpls");
+ public static final FqName KOTLIN_LOCAL_CLASS = new FqName("kotlin.jvm.internal.KotlinLocalClass");
public static final FqName JAVA_LANG_DEPRECATED = new FqName("java.lang.Deprecated");
@@ -68,23 +69,6 @@ public final class JvmAnnotationNames {
public static final FqName ENHANCED_NULLABILITY_ANNOTATION = new FqName("kotlin.jvm.internal.EnhancedNullability");
public static final FqName ENHANCED_MUTABILITY_ANNOTATION = new FqName("kotlin.jvm.internal.EnhancedMutability");
- public static class KotlinClass {
- public static final JvmClassName CLASS_NAME = JvmClassName.byInternalName("kotlin/jvm/internal/KotlinClass");
- public static final ClassId KIND_CLASS_ID =
- ClassId.topLevel(CLASS_NAME.getFqNameForClassNameWithoutDollars()).createNestedClassId(Name.identifier("Kind"));
- public static final String KIND_INTERNAL_NAME = JvmClassName.byClassId(KIND_CLASS_ID).getInternalName();
-
- /**
- * This enum duplicates {@link kotlin.jvm.internal.KotlinClass.Kind}. Both places should be updated simultaneously.
- */
- public enum Kind {
- CLASS,
- LOCAL_CLASS,
- ANONYMOUS_OBJECT,
- ;
- }
- }
-
public static class KotlinSyntheticClass {
public static final JvmClassName CLASS_NAME = JvmClassName.byInternalName("kotlin/jvm/internal/KotlinSyntheticClass");
public static final ClassId KIND_CLASS_ID =
@@ -125,6 +109,7 @@ public static class KotlinSyntheticClass {
}
SPECIAL_ANNOTATIONS.add(KotlinSyntheticClass.CLASS_NAME);
SPECIAL_ANNOTATIONS.add(JvmClassName.byFqNameWithoutInnerClasses(KOTLIN_INTERFACE_DEFAULT_IMPLS));
+ SPECIAL_ANNOTATIONS.add(JvmClassName.byFqNameWithoutInnerClasses(KOTLIN_LOCAL_CLASS));
for (FqName fqName : Arrays.asList(JETBRAINS_NOT_NULL_ANNOTATION, JETBRAINS_NULLABLE_ANNOTATION)) {
NULLABILITY_ANNOTATIONS.add(JvmClassName.byFqNameWithoutInnerClasses(fqName));
diff --git a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/header/KotlinClassHeader.kt b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/header/KotlinClassHeader.kt
index f12bc55a7a6fc..dadad589ede50 100644
--- a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/header/KotlinClassHeader.kt
+++ b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/header/KotlinClassHeader.kt
@@ -17,24 +17,22 @@
package org.jetbrains.kotlin.load.kotlin.header
import org.jetbrains.kotlin.load.java.AbiVersionUtil
-import org.jetbrains.kotlin.load.java.JvmAnnotationNames.KotlinClass
-import org.jetbrains.kotlin.load.java.JvmAnnotationNames.KotlinSyntheticClass
import org.jetbrains.kotlin.serialization.deserialization.BinaryVersion
-public class KotlinClassHeader(
- public val kind: KotlinClassHeader.Kind,
- public val version: BinaryVersion,
- public val annotationData: Array<String>?,
- public val strings: Array<String>?,
- public val classKind: KotlinClass.Kind?,
- public val syntheticClassKind: String?,
- public val filePartClassNames: Array<String>?,
- public val multifileClassName: String?,
- public val isInterfaceDefaultImpls: Boolean
+class KotlinClassHeader(
+ val kind: KotlinClassHeader.Kind,
+ val version: BinaryVersion,
+ val annotationData: Array<String>?,
+ val strings: Array<String>?,
+ val syntheticClassKind: String?,
+ val filePartClassNames: Array<String>?,
+ val multifileClassName: String?,
+ val isInterfaceDefaultImpls: Boolean,
+ val isLocalClass: Boolean
) {
- public val isCompatibleAbiVersion: Boolean get() = AbiVersionUtil.isAbiVersionCompatible(version)
+ val isCompatibleAbiVersion: Boolean get() = AbiVersionUtil.isAbiVersionCompatible(version)
- public enum class Kind {
+ enum class Kind {
CLASS,
PACKAGE_FACADE,
FILE_FACADE,
@@ -45,13 +43,13 @@ public class KotlinClassHeader(
override fun toString() =
"$kind " +
- (if (classKind != null) "$classKind " else "") +
+ (if (isLocalClass) "(local) " else "") +
(if (syntheticClassKind != null) "$syntheticClassKind " else "") +
"version=$version"
}
-public fun KotlinClassHeader.isCompatibleClassKind(): Boolean = isCompatibleAbiVersion && kind == KotlinClassHeader.Kind.CLASS
-public fun KotlinClassHeader.isCompatiblePackageFacadeKind(): Boolean = isCompatibleAbiVersion && kind == KotlinClassHeader.Kind.PACKAGE_FACADE
-public fun KotlinClassHeader.isCompatibleFileFacadeKind(): Boolean = isCompatibleAbiVersion && kind == KotlinClassHeader.Kind.FILE_FACADE
-public fun KotlinClassHeader.isCompatibleMultifileClassKind(): Boolean = isCompatibleAbiVersion && kind == KotlinClassHeader.Kind.MULTIFILE_CLASS
-public fun KotlinClassHeader.isCompatibleMultifileClassPartKind(): Boolean = isCompatibleAbiVersion && kind == KotlinClassHeader.Kind.MULTIFILE_CLASS_PART
+fun KotlinClassHeader.isCompatibleClassKind(): Boolean = isCompatibleAbiVersion && kind == KotlinClassHeader.Kind.CLASS
+fun KotlinClassHeader.isCompatiblePackageFacadeKind(): Boolean = isCompatibleAbiVersion && kind == KotlinClassHeader.Kind.PACKAGE_FACADE
+fun KotlinClassHeader.isCompatibleFileFacadeKind(): Boolean = isCompatibleAbiVersion && kind == KotlinClassHeader.Kind.FILE_FACADE
+fun KotlinClassHeader.isCompatibleMultifileClassKind(): Boolean = isCompatibleAbiVersion && kind == KotlinClassHeader.Kind.MULTIFILE_CLASS
+fun KotlinClassHeader.isCompatibleMultifileClassPartKind(): Boolean = isCompatibleAbiVersion && kind == KotlinClassHeader.Kind.MULTIFILE_CLASS_PART
diff --git a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/header/ReadKotlinClassHeaderAnnotationVisitor.java b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/header/ReadKotlinClassHeaderAnnotationVisitor.java
index ecbb2d71effe9..384d96eafee46 100644
--- a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/header/ReadKotlinClassHeaderAnnotationVisitor.java
+++ b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/header/ReadKotlinClassHeaderAnnotationVisitor.java
@@ -21,6 +21,7 @@
import org.jetbrains.kotlin.descriptors.SourceElement;
import org.jetbrains.kotlin.load.java.AbiVersionUtil;
import org.jetbrains.kotlin.name.ClassId;
+import org.jetbrains.kotlin.name.FqName;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.resolve.jvm.JvmClassName;
import org.jetbrains.kotlin.serialization.deserialization.BinaryVersion;
@@ -39,7 +40,7 @@ public class ReadKotlinClassHeaderAnnotationVisitor implements AnnotationVisitor
private static final Map<JvmClassName, KotlinClassHeader.Kind> OLD_DEPRECATED_ANNOTATIONS_KINDS = new HashMap<JvmClassName, KotlinClassHeader.Kind>();
static {
- HEADER_KINDS.put(KotlinClass.CLASS_NAME, CLASS);
+ HEADER_KINDS.put(JvmClassName.byFqNameWithoutInnerClasses(KOTLIN_CLASS), CLASS);
HEADER_KINDS.put(JvmClassName.byFqNameWithoutInnerClasses(KOTLIN_PACKAGE), PACKAGE_FACADE);
HEADER_KINDS.put(JvmClassName.byFqNameWithoutInnerClasses(KOTLIN_FILE_FACADE), FILE_FACADE);
HEADER_KINDS.put(JvmClassName.byFqNameWithoutInnerClasses(KOTLIN_MULTIFILE_CLASS), MULTIFILE_CLASS);
@@ -66,9 +67,9 @@ private static void initOldAnnotations() {
private String[] annotationData = null;
private String[] strings = null;
private KotlinClassHeader.Kind headerKind = null;
- private KotlinClass.Kind classKind = null;
private String syntheticClassKind = null;
private boolean isInterfaceDefaultImpls = false;
+ private boolean isLocalClass = false;
@Nullable
public KotlinClassHeader createHeader() {
@@ -76,11 +77,6 @@ public KotlinClassHeader createHeader() {
return null;
}
- if (headerKind == CLASS && classKind == null) {
- // Default class kind is Kind.CLASS
- classKind = KotlinClass.Kind.CLASS;
- }
-
if (!AbiVersionUtil.isAbiVersionCompatible(version)) {
annotationData = null;
}
@@ -91,8 +87,8 @@ else if (shouldHaveData() && annotationData == null) {
}
return new KotlinClassHeader(
- headerKind, version, annotationData, strings, classKind, syntheticClassKind, filePartClassNames, multifileClassName,
- isInterfaceDefaultImpls
+ headerKind, version, annotationData, strings, syntheticClassKind, filePartClassNames, multifileClassName,
+ isInterfaceDefaultImpls, isLocalClass
);
}
@@ -106,10 +102,15 @@ private boolean shouldHaveData() {
@Nullable
@Override
public AnnotationArgumentVisitor visitAnnotation(@NotNull ClassId classId, @NotNull SourceElement source) {
- if (KOTLIN_INTERFACE_DEFAULT_IMPLS.equals(classId.asSingleFqName())) {
+ FqName fqName = classId.asSingleFqName();
+ if (KOTLIN_INTERFACE_DEFAULT_IMPLS.equals(fqName)) {
isInterfaceDefaultImpls = true;
return null;
}
+ else if (KOTLIN_LOCAL_CLASS.equals(fqName)) {
+ isLocalClass = true;
+ return null;
+ }
if (headerKind != null) {
// Ignore all Kotlin annotations except the first found
@@ -269,14 +270,7 @@ public void visitEnd() {
private class ClassHeaderReader extends HeaderAnnotationArgumentVisitor {
public ClassHeaderReader() {
- super(KotlinClass.CLASS_NAME);
- }
-
- @Override
- public void visitEnum(@NotNull Name name, @NotNull ClassId enumClassId, @NotNull Name enumEntryName) {
- if (KotlinClass.KIND_CLASS_ID.equals(enumClassId) && KIND_FIELD_NAME.equals(name.asString())) {
- classKind = valueOfOrNull(KotlinClass.Kind.class, enumEntryName.asString());
- }
+ super(JvmClassName.byFqNameWithoutInnerClasses(KOTLIN_CLASS));
}
}
@@ -316,16 +310,4 @@ public void visitEnum(@NotNull Name name, @NotNull ClassId enumClassId, @NotNull
}
}
}
-
- // This function is needed here because Enum.valueOf() throws exception if there's no such value,
- // but we don't want to fail if we're loading the header with an _incompatible_ ABI version
- @Nullable
- private static <E extends Enum<E>> E valueOfOrNull(@NotNull Class<E> enumClass, @NotNull String entry) {
- try {
- return Enum.valueOf(enumClass, entry);
- }
- catch (IllegalArgumentException e) {
- return null;
- }
- }
}
diff --git a/core/runtime.jvm/src/kotlin/jvm/internal/KotlinClass.java b/core/runtime.jvm/src/kotlin/jvm/internal/KotlinClass.java
index 77270d3e02bad..b54eaa1db1586 100644
--- a/core/runtime.jvm/src/kotlin/jvm/internal/KotlinClass.java
+++ b/core/runtime.jvm/src/kotlin/jvm/internal/KotlinClass.java
@@ -29,12 +29,14 @@
int[] version() default {};
- Kind kind() default Kind.CLASS;
-
String[] data();
String[] strings();
+ @Deprecated
+ Kind kind() default Kind.CLASS;
+
+ @Deprecated
enum Kind {
CLASS,
diff --git a/core/runtime.jvm/src/kotlin/jvm/internal/KotlinLocalClass.java b/core/runtime.jvm/src/kotlin/jvm/internal/KotlinLocalClass.java
new file mode 100644
index 0000000000000..8086c610a9fa3
--- /dev/null
+++ b/core/runtime.jvm/src/kotlin/jvm/internal/KotlinLocalClass.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2010-2015 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package kotlin.jvm.internal;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.TYPE)
+public @interface KotlinLocalClass {
+ int[] version() default {};
+}
diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/DecompiledUtils.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/DecompiledUtils.kt
index 091bf3d523067..ef6644f7dae19 100644
--- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/DecompiledUtils.kt
+++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/DecompiledUtils.kt
@@ -21,7 +21,6 @@ import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.ClassFileViewProvider
import org.jetbrains.kotlin.idea.caches.JarUserDataManager
import org.jetbrains.kotlin.idea.decompiler.textBuilder.DirectoryBasedClassFinder
-import org.jetbrains.kotlin.load.java.JvmAnnotationNames.KotlinClass
import org.jetbrains.kotlin.load.kotlin.KotlinBinaryClassCache
import org.jetbrains.kotlin.load.kotlin.KotlinJvmBinaryClass
import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader
@@ -71,9 +70,8 @@ public fun isKotlinInternalCompiledFile(file: VirtualFile): Boolean {
val header = KotlinBinaryClassCache.getKotlinBinaryClass(file)?.classHeader ?: return false
return header.kind == KotlinClassHeader.Kind.SYNTHETIC_CLASS ||
- (header.kind == KotlinClassHeader.Kind.CLASS && header.classKind != null && header.classKind != KotlinClass.Kind.CLASS) ||
header.kind == KotlinClassHeader.Kind.MULTIFILE_CLASS_PART ||
- header.syntheticClassKind == "PACKAGE_PART"
+ header.isLocalClass || header.syntheticClassKind == "PACKAGE_PART"
}
public fun isKotlinJavaScriptInternalCompiledFile(file: VirtualFile): Boolean =
diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/KotlinClsStubBuilder.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/KotlinClsStubBuilder.kt
index 997e8179139b3..fc5cb8d7fd70a 100644
--- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/KotlinClsStubBuilder.kt
+++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/KotlinClsStubBuilder.kt
@@ -27,7 +27,6 @@ import org.jetbrains.kotlin.idea.decompiler.isKotlinInternalCompiledFile
import org.jetbrains.kotlin.idea.decompiler.textBuilder.DirectoryBasedClassFinder
import org.jetbrains.kotlin.idea.decompiler.textBuilder.DirectoryBasedDataFinder
import org.jetbrains.kotlin.idea.decompiler.textBuilder.LoggingErrorReporter
-import org.jetbrains.kotlin.load.java.JvmAnnotationNames
import org.jetbrains.kotlin.load.kotlin.KotlinBinaryClassCache
import org.jetbrains.kotlin.load.kotlin.header.isCompatibleClassKind
import org.jetbrains.kotlin.load.kotlin.header.isCompatibleFileFacadeKind
@@ -82,7 +81,7 @@ public open class KotlinClsStubBuilder : ClsStubBuilder() {
createPackageFacadeStub(packageProto, packageFqName, context)
}
header.isCompatibleClassKind() -> {
- if (header.classKind != JvmAnnotationNames.KotlinClass.Kind.CLASS) return null
+ if (header.isLocalClass) return null
val (nameResolver, classProto) = JvmProtoBufUtil.readClassDataFrom(annotationData, strings)
val context = components.createContext(nameResolver, packageFqName)
createTopLevelClassStub(classId, classProto, context)
diff --git a/idea/tests/org/jetbrains/kotlin/idea/decompiler/AbstractInternalCompiledClassesTest.kt b/idea/tests/org/jetbrains/kotlin/idea/decompiler/AbstractInternalCompiledClassesTest.kt
index 974a0a30eaa60..ffae3ec46d1fe 100644
--- a/idea/tests/org/jetbrains/kotlin/idea/decompiler/AbstractInternalCompiledClassesTest.kt
+++ b/idea/tests/org/jetbrains/kotlin/idea/decompiler/AbstractInternalCompiledClassesTest.kt
@@ -20,7 +20,6 @@ import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiManager
import org.jetbrains.kotlin.idea.decompiler.navigation.NavigateToDecompiledLibraryTest
import org.jetbrains.kotlin.idea.test.JetLightCodeInsightFixtureTestCase
-import org.jetbrains.kotlin.load.java.JvmAnnotationNames.KotlinClass
import org.jetbrains.kotlin.load.kotlin.KotlinBinaryClassCache
import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader
import org.junit.Assert
@@ -34,11 +33,8 @@ public abstract class AbstractInternalCompiledClassesTest : JetLightCodeInsightF
protected fun isSyntheticClass(): VirtualFile.() -> Boolean =
isFileWithHeader { it.kind == KotlinClassHeader.Kind.SYNTHETIC_CLASS }
- private fun isClassOfKind(kind: KotlinClass.Kind): VirtualFile.() -> Boolean =
- isFileWithHeader { it.classKind == kind }
-
- protected fun doTestNoPsiFilesAreBuiltForLocalClass(kind: KotlinClass.Kind): Unit =
- doTestNoPsiFilesAreBuiltFor(kind.name(), isClassOfKind(kind))
+ protected fun doTestNoPsiFilesAreBuiltForLocalClass(): Unit =
+ doTestNoPsiFilesAreBuiltFor("local", isFileWithHeader { it.isLocalClass })
protected fun doTestNoPsiFilesAreBuiltForSyntheticClasses(): Unit =
doTestNoPsiFilesAreBuiltFor("synthetic", isSyntheticClass())
diff --git a/idea/tests/org/jetbrains/kotlin/idea/decompiler/InternalCompiledClassesTest.kt b/idea/tests/org/jetbrains/kotlin/idea/decompiler/InternalCompiledClassesTest.kt
index 37b930949c5cd..5c372773f053c 100644
--- a/idea/tests/org/jetbrains/kotlin/idea/decompiler/InternalCompiledClassesTest.kt
+++ b/idea/tests/org/jetbrains/kotlin/idea/decompiler/InternalCompiledClassesTest.kt
@@ -20,17 +20,13 @@ import com.intellij.psi.ClassFileViewProvider
import com.intellij.testFramework.LightProjectDescriptor
import org.jetbrains.kotlin.idea.test.JdkAndMockLibraryProjectDescriptor
import org.jetbrains.kotlin.idea.test.PluginTestCaseBase
-import org.jetbrains.kotlin.load.java.JvmAnnotationNames.KotlinClass.Kind.ANONYMOUS_OBJECT
-import org.jetbrains.kotlin.load.java.JvmAnnotationNames.KotlinClass.Kind.LOCAL_CLASS
public class InternalCompiledClassesTest : AbstractInternalCompiledClassesTest() {
private val TEST_DATA_PATH = PluginTestCaseBase.getTestDataPathBase() + "/decompiler/internalClasses"
fun testSyntheticClassesAreInvisible() = doTestNoPsiFilesAreBuiltForSyntheticClasses()
- fun testLocalClassIsInvisible() = doTestNoPsiFilesAreBuiltForLocalClass(LOCAL_CLASS)
-
- fun testAnonymousObjectIsInvisible() = doTestNoPsiFilesAreBuiltForLocalClass(ANONYMOUS_OBJECT)
+ fun testLocalClassesAreInvisible() = doTestNoPsiFilesAreBuiltForLocalClass()
fun testInnerClassIsInvisible() = doTestNoPsiFilesAreBuiltFor("inner or nested class") {
ClassFileViewProvider.isInnerClass(this)
diff --git a/jps-plugin/src/org/jetbrains/kotlin/jps/incremental/IncrementalCacheImpl.kt b/jps-plugin/src/org/jetbrains/kotlin/jps/incremental/IncrementalCacheImpl.kt
index 6a1573694f045..093349ccec181 100644
--- a/jps-plugin/src/org/jetbrains/kotlin/jps/incremental/IncrementalCacheImpl.kt
+++ b/jps-plugin/src/org/jetbrains/kotlin/jps/incremental/IncrementalCacheImpl.kt
@@ -31,7 +31,6 @@ import org.jetbrains.kotlin.jps.build.GeneratedJvmClass
import org.jetbrains.kotlin.jps.build.KotlinBuilder
import org.jetbrains.kotlin.jps.incremental.storage.BasicMap
import org.jetbrains.kotlin.jps.incremental.storage.BasicStringMap
-import org.jetbrains.kotlin.load.java.JvmAnnotationNames
import org.jetbrains.kotlin.load.kotlin.KotlinJvmBinaryClass
import org.jetbrains.kotlin.load.kotlin.ModuleMapping
import org.jetbrains.kotlin.load.kotlin.PackageClassUtils
@@ -216,10 +215,11 @@ public class IncrementalCacheImpl(
constantsMap.process(kotlinClass) +
inlineFunctionsMap.process(kotlinClass)
}
- header.isCompatibleClassKind() && JvmAnnotationNames.KotlinClass.Kind.CLASS == header.classKind ->
+ header.isCompatibleClassKind() && !header.isLocalClass -> {
protoMap.process(kotlinClass, isPackage = false) +
constantsMap.process(kotlinClass) +
inlineFunctionsMap.process(kotlinClass)
+ }
else -> ChangesInfo.NO_CHANGES
}
|
d2a3f29496d22df52ba4bf66aa5c408cf286d4bc
|
ReactiveX-RxJava
|
Implement Scheduler method with dueTime--- added method: schedule(T state
|
a
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-core/src/main/java/rx/Scheduler.java b/rxjava-core/src/main/java/rx/Scheduler.java
index f3edfd6a0a..afc35b6a32 100644
--- a/rxjava-core/src/main/java/rx/Scheduler.java
+++ b/rxjava-core/src/main/java/rx/Scheduler.java
@@ -15,6 +15,7 @@
*/
package rx;
+import java.util.Date;
import java.util.concurrent.TimeUnit;
import rx.subscriptions.Subscriptions;
@@ -37,7 +38,8 @@
* <ol>
* <li>Java doesn't support extension methods and there are many overload methods needing default implementations.</li>
* <li>Virtual extension methods aren't available until Java8 which RxJava will not set as a minimum target for a long time.</li>
- * <li>If only an interface were used Scheduler implementations would then need to extend from an AbstractScheduler pair that gives all of the functionality unless they intend on copy/pasting the functionality.</li>
+ * <li>If only an interface were used Scheduler implementations would then need to extend from an AbstractScheduler pair that gives all of the functionality unless they intend on copy/pasting the
+ * functionality.</li>
* <li>Without virtual extension methods even additive changes are breaking and thus severely impede library maintenance.</li>
* </ol>
*/
@@ -69,6 +71,27 @@ public abstract class Scheduler {
*/
public abstract <T> Subscription schedule(T state, Func2<Scheduler, T, Subscription> action, long delayTime, TimeUnit unit);
+ /**
+ * Schedules a cancelable action to be executed at dueTime.
+ *
+ * @param state
+ * State to pass into the action.
+ * @param action
+ * Action to schedule.
+ * @param dueTime
+ * Time the action is to be executed. If in the past it will be executed immediately.
+ * @return a subscription to be able to unsubscribe from action.
+ */
+ public <T> Subscription schedule(T state, Func2<Scheduler, T, Subscription> action, Date dueTime) {
+ long scheduledTime = dueTime.getTime();
+ long timeInFuture = scheduledTime - now();
+ if (timeInFuture <= 0) {
+ return schedule(state, action);
+ } else {
+ return schedule(state, action, timeInFuture, TimeUnit.MILLISECONDS);
+ }
+ }
+
/**
* Schedules a cancelable action to be executed.
*
diff --git a/rxjava-core/src/test/java/rx/concurrency/TestSchedulers.java b/rxjava-core/src/test/java/rx/concurrency/TestSchedulers.java
index a4760ff65e..59edfade39 100644
--- a/rxjava-core/src/test/java/rx/concurrency/TestSchedulers.java
+++ b/rxjava-core/src/test/java/rx/concurrency/TestSchedulers.java
@@ -18,6 +18,7 @@
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
+import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -359,4 +360,39 @@ public void onNext(Integer args) {
assertTrue(completed.get());
}
+ @Test
+ public void testSchedulingWithDueTime() throws InterruptedException {
+
+ final CountDownLatch latch = new CountDownLatch(5);
+ final AtomicInteger counter = new AtomicInteger();
+
+ long start = System.currentTimeMillis();
+
+ Schedulers.threadPoolForComputation().schedule(null, new Func2<Scheduler, String, Subscription>() {
+
+ @Override
+ public Subscription call(Scheduler scheduler, String state) {
+ System.out.println("doing work");
+ latch.countDown();
+ counter.incrementAndGet();
+ if (latch.getCount() == 0) {
+ return Subscriptions.empty();
+ } else {
+ return scheduler.schedule(state, this, new Date(System.currentTimeMillis() + 50));
+ }
+ }
+ }, new Date(System.currentTimeMillis() + 100));
+
+ if (!latch.await(3000, TimeUnit.MILLISECONDS)) {
+ fail("didn't execute ... timed out");
+ }
+
+ long end = System.currentTimeMillis();
+
+ assertEquals(5, counter.get());
+ if ((end - start) < 250) {
+ fail("it should have taken over 250ms since each step was scheduled 50ms in the future");
+ }
+ }
+
}
|
ece368462243d7b4721029e31a261b450e026296
|
kotlin
|
Lazy receiver parameter descriptor: to avoid- eager computation of default types--
|
p
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/frontend/serialization/src/org/jetbrains/jet/descriptors/serialization/descriptors/DeserializedClassDescriptor.java b/compiler/frontend/serialization/src/org/jetbrains/jet/descriptors/serialization/descriptors/DeserializedClassDescriptor.java
index 510eb55f10e83..bab1998e33c47 100644
--- a/compiler/frontend/serialization/src/org/jetbrains/jet/descriptors/serialization/descriptors/DeserializedClassDescriptor.java
+++ b/compiler/frontend/serialization/src/org/jetbrains/jet/descriptors/serialization/descriptors/DeserializedClassDescriptor.java
@@ -21,14 +21,15 @@
import org.jetbrains.jet.descriptors.serialization.*;
import org.jetbrains.jet.lang.descriptors.*;
import org.jetbrains.jet.lang.descriptors.annotations.AnnotationDescriptor;
+import org.jetbrains.jet.lang.descriptors.impl.AbstractReceiverParameterDescriptor;
import org.jetbrains.jet.lang.descriptors.impl.ClassDescriptorBase;
-import org.jetbrains.jet.lang.descriptors.impl.ReceiverParameterDescriptorImpl;
import org.jetbrains.jet.lang.resolve.OverrideResolver;
import org.jetbrains.jet.lang.resolve.TraceUtil;
import org.jetbrains.jet.lang.resolve.lazy.storage.*;
import org.jetbrains.jet.lang.resolve.name.Name;
import org.jetbrains.jet.lang.resolve.scopes.JetScope;
import org.jetbrains.jet.lang.resolve.scopes.receivers.ClassReceiver;
+import org.jetbrains.jet.lang.resolve.scopes.receivers.ReceiverValue;
import org.jetbrains.jet.lang.types.JetType;
import org.jetbrains.jet.lang.types.TypeConstructor;
@@ -77,7 +78,7 @@ public DeserializedClassDescriptor(
this.containingDeclaration = containingDeclaration;
this.typeConstructor = new DeserializedClassTypeConstructor();
this.memberScope = new DeserializedClassMemberScope(this);
- this.thisAsReceiverParameter = new ReceiverParameterDescriptorImpl(this, getDefaultType(), new ClassReceiver(this));
+ this.thisAsReceiverParameter = new LazyClassReceiverParameterDescriptor();
this.name = nameResolver.getName(classProto.getName());
int flags = classProto.getFlags();
@@ -433,5 +434,27 @@ public Collection<ClassDescriptor> getAllDescriptors() {
return result;
}
}
+
+ private class LazyClassReceiverParameterDescriptor extends AbstractReceiverParameterDescriptor {
+ private final ClassReceiver classReceiver = new ClassReceiver(DeserializedClassDescriptor.this);
+
+ @NotNull
+ @Override
+ public JetType getType() {
+ return getDefaultType();
+ }
+
+ @NotNull
+ @Override
+ public ReceiverValue getValue() {
+ return classReceiver;
+ }
+
+ @NotNull
+ @Override
+ public DeclarationDescriptor getContainingDeclaration() {
+ return DeserializedClassDescriptor.this;
+ }
+ }
}
|
77e111dc3131b44bd7ef9edca5fd31dd2e27e67a
|
Delta Spike
|
DELTASPIKE-277 fix missing license header
|
p
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/modules/jsf/impl/src/test/resources/jsfMessageTest/UserMessage.properties b/deltaspike/modules/jsf/impl/src/test/resources/jsfMessageTest/UserMessage.properties
index 743b5f4b9..bfdbed9fc 100644
--- a/deltaspike/modules/jsf/impl/src/test/resources/jsfMessageTest/UserMessage.properties
+++ b/deltaspike/modules/jsf/impl/src/test/resources/jsfMessageTest/UserMessage.properties
@@ -1,3 +1,20 @@
+#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.
+
messageWithDetail = message with details %s!
messageWithDetail.detail = message with loooong and very specific details %s!
|
b6eb90370ad063bff5f74d4dc90632fe7ac6ccd3
|
hadoop
|
YARN-1555. Fixed test failures in- applicationhistoryservice.* (Vinod Kumar Vavilapalli via mayank) svn merge- --ignore-ancestry -c 1556753 ../YARN-321--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1562207 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index ac11f9c9b73ba..ca2b99d8a52c1 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -519,6 +519,9 @@ Branch YARN-321: Generic ApplicationHistoryService
YARN-1413. Implemented serving of aggregated-logs in the ApplicationHistory
server. (Mayank Bansal via vinodkv)
+ YARN-1555. Fixed test failures in applicationhistoryservice.* (Vinod Kumar
+ Vavilapalli via mayank)
+
Release 2.2.0 - 2013-10-13
INCOMPATIBLE CHANGES
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/ApplicationHistoryStoreTestUtils.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/ApplicationHistoryStoreTestUtils.java
index ca68eb63ca672..f90ae0946ef19 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/ApplicationHistoryStoreTestUtils.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/ApplicationHistoryStoreTestUtils.java
@@ -86,7 +86,7 @@ protected void writeContainerFinishData(ContainerId containerId)
throws IOException {
store.containerFinished(
ContainerFinishData.newInstance(containerId, 0, containerId.toString(),
- "http://localhost:0/", 0, ContainerState.COMPLETE));
+ "http://localhost:0/log", 0, ContainerState.COMPLETE));
}
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/TestApplicationHistoryServer.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/TestApplicationHistoryServer.java
index 3c6d69d2d6477..0ad48e262e73f 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/TestApplicationHistoryServer.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/TestApplicationHistoryServer.java
@@ -40,7 +40,7 @@ public void testStartStopServer() throws Exception {
Configuration config = new YarnConfiguration();
historyServer.init(config);
assertEquals(STATE.INITED, historyServer.getServiceState());
- assertEquals(3, historyServer.getServices().size());
+ assertEquals(2, historyServer.getServices().size());
ApplicationHistoryClientService historyService = historyServer
.getClientService();
assertNotNull(historyServer.getClientService());
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/webapp/TestAHSWebServices.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/webapp/TestAHSWebServices.java
index 2de688139a384..c5633fb30cd8c 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/webapp/TestAHSWebServices.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/webapp/TestAHSWebServices.java
@@ -287,7 +287,7 @@ public void testSingleContainer() throws Exception {
container.getString("assignedNodeId"));
assertEquals(Priority.newInstance(containerId.getId()).toString(),
container.getString("priority"));
- assertEquals("http://localhost:0/", container.getString("logUrl"));
+ assertEquals("http://localhost:0/log", container.getString("logUrl"));
assertEquals(ContainerState.COMPLETE.toString(),
container.getString("containerState"));
}
|
ebe1a4663d41adf670239bf2765b316a2e46f12d
|
elasticsearch
|
[TEST] renamed variables in ScriptServiceTests--
|
p
|
https://github.com/elastic/elasticsearch
|
diff --git a/src/test/java/org/elasticsearch/script/ScriptServiceTests.java b/src/test/java/org/elasticsearch/script/ScriptServiceTests.java
index fad39746f9f93..6339874c52b94 100644
--- a/src/test/java/org/elasticsearch/script/ScriptServiceTests.java
+++ b/src/test/java/org/elasticsearch/script/ScriptServiceTests.java
@@ -99,10 +99,10 @@ public void testScriptsWithoutExtensions() throws IOException {
@Test
public void testScriptsSameNameDifferentLanguage() throws IOException {
- Path testFileNoExt = scriptsFilePath.resolve("script.groovy");
- Path testFileWithExt = scriptsFilePath.resolve("script.expression");
- Streams.copy("10".getBytes("UTF-8"), Files.newOutputStream(testFileNoExt));
- Streams.copy("20".getBytes("UTF-8"), Files.newOutputStream(testFileWithExt));
+ Path groovyScriptPath = scriptsFilePath.resolve("script.groovy");
+ Path expScriptPath = scriptsFilePath.resolve("script.expression");
+ Streams.copy("10".getBytes("UTF-8"), Files.newOutputStream(groovyScriptPath));
+ Streams.copy("20".getBytes("UTF-8"), Files.newOutputStream(expScriptPath));
resourceWatcherService.notifyNow();
CompiledScript groovyScript = scriptService.compile(GroovyScriptEngineService.NAME, "script", ScriptService.ScriptType.FILE);
@@ -120,8 +120,8 @@ public void testInlineScriptCompiledOnceMultipleLangAcronyms() throws IOExceptio
@Test
public void testFileScriptCompiledOnceMultipleLangAcronyms() throws IOException {
- Path testFileWithExt = scriptsFilePath.resolve("test_script.tst");
- Streams.copy("test_file".getBytes("UTF-8"), Files.newOutputStream(testFileWithExt));
+ Path scriptPath = scriptsFilePath.resolve("test_script.tst");
+ Streams.copy("test_file".getBytes("UTF-8"), Files.newOutputStream(scriptPath));
resourceWatcherService.notifyNow();
CompiledScript compiledScript1 = scriptService.compile("test", "test_script", ScriptService.ScriptType.FILE);
|
c72f0ce11f641f30ef334aaa43d925f480692375
|
Vala
|
gobject: Add Binding.unbind
Fixes bug 730967
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/gobject-2.0.vapi b/vapi/gobject-2.0.vapi
index bf5b6d79b6..b0c02299bc 100644
--- a/vapi/gobject-2.0.vapi
+++ b/vapi/gobject-2.0.vapi
@@ -314,6 +314,7 @@ namespace GLib {
public weak GLib.Object target { get; }
public string target_property { get; }
public GLib.BindingFlags flags { get; }
+ public void unbind ();
}
[CCode (has_target = false)]
|
7819aeccba263171444ca56c1621aca3f7d649e8
|
intellij-community
|
NPE--
|
c
|
https://github.com/JetBrains/intellij-community
|
diff --git a/lang-impl/src/com/intellij/codeInspection/ex/InspectionRVContentProvider.java b/lang-impl/src/com/intellij/codeInspection/ex/InspectionRVContentProvider.java
index 8da0e755dfc7f..3ec11d5a283e0 100644
--- a/lang-impl/src/com/intellij/codeInspection/ex/InspectionRVContentProvider.java
+++ b/lang-impl/src/com/intellij/codeInspection/ex/InspectionRVContentProvider.java
@@ -99,13 +99,18 @@ protected <T> List<InspectionTreeNode> buildTree(final Map<String, Set<T>> packa
if (packageNode.getChildCount() > 0) {
InspectionModuleNode moduleNode = moduleNodes.get(moduleName);
if (moduleNode == null) {
- final Module module = ModuleManager.getInstance(myProject).findModuleByName(moduleName);
- if (module != null) {
- moduleNode = new InspectionModuleNode(module);
- moduleNodes.put(moduleName, moduleNode);
- }
- else { //module content was removed ?
- continue;
+ if (moduleName != null) {
+ final Module module = ModuleManager.getInstance(myProject).findModuleByName(moduleName);
+ if (module != null) {
+ moduleNode = new InspectionModuleNode(module);
+ moduleNodes.put(moduleName, moduleNode);
+ }
+ else { //module content was removed ?
+ continue;
+ }
+ } else {
+ content.addAll(packageNodes.values());
+ break;
}
}
if (packageNode.getPackageName() != null) {
|
fa18d6c9584bc1bc8ce6d001162dac4ab72009ff
|
restlet-framework-java
|
Added warning message when no client connector- supports the request's protocol.--
|
p
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/component/ClientRouter.java b/modules/com.noelios.restlet/src/com/noelios/restlet/component/ClientRouter.java
index cdbb84b329..b921c6c9c2 100644
--- a/modules/com.noelios.restlet/src/com/noelios/restlet/component/ClientRouter.java
+++ b/modules/com.noelios.restlet/src/com/noelios/restlet/component/ClientRouter.java
@@ -29,7 +29,10 @@
import org.restlet.Client;
import org.restlet.Component;
+import org.restlet.Restlet;
import org.restlet.Router;
+import org.restlet.data.Request;
+import org.restlet.data.Response;
/**
* Router that collects calls from all applications and dispatches them to the
@@ -57,6 +60,19 @@ public ClientRouter(Component component) {
this.component = component;
}
+ @Override
+ public Restlet getNext(Request request, Response response) {
+ Restlet result = super.getNext(request, response);
+ if (result == null) {
+ getLogger()
+ .warning(
+ "The protocol used by this request is not declared in the list of client connectors. ("
+ + request.getResourceRef().getSchemeProtocol()
+ + ")");
+ }
+ return result;
+ }
+
/**
* Returns the parent component.
*
diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/component/ComponentClientDispatcher.java b/modules/com.noelios.restlet/src/com/noelios/restlet/component/ComponentClientDispatcher.java
index 400b1129b2..fc66f6e836 100644
--- a/modules/com.noelios.restlet/src/com/noelios/restlet/component/ComponentClientDispatcher.java
+++ b/modules/com.noelios.restlet/src/com/noelios/restlet/component/ComponentClientDispatcher.java
@@ -125,7 +125,7 @@ protected void doHandle(Request request, Response response) {
}
} else {
getLogger().warning(
- "No compoent is available to route the RIAP request.");
+ "No component is available to route the RIAP request.");
}
} else {
getComponentContext().getComponentHelper().getClientRouter()
|
521bbfcf5613232af5f907843db0d54b5f9b493f
|
spring-framework
|
Allow configuring custom ThreadPoolTaskExecutor--Issue: SPR-12272-
|
a
|
https://github.com/spring-projects/spring-framework
|
diff --git a/spring-messaging/src/main/java/org/springframework/messaging/simp/config/ChannelRegistration.java b/spring-messaging/src/main/java/org/springframework/messaging/simp/config/ChannelRegistration.java
index f1b2e1374184..6ced0579be99 100644
--- a/spring-messaging/src/main/java/org/springframework/messaging/simp/config/ChannelRegistration.java
+++ b/spring-messaging/src/main/java/org/springframework/messaging/simp/config/ChannelRegistration.java
@@ -21,6 +21,7 @@
import java.util.List;
import org.springframework.messaging.support.ChannelInterceptor;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
* A registration class for customizing the configuration for a
@@ -46,6 +47,17 @@ public TaskExecutorRegistration taskExecutor() {
return this.registration;
}
+ /**
+ * Configure the thread pool backing this message channel using a custom
+ * ThreadPoolTaskExecutor.
+ */
+ public TaskExecutorRegistration taskExecutor(ThreadPoolTaskExecutor taskExecutor) {
+ if (this.registration == null) {
+ this.registration = new TaskExecutorRegistration(taskExecutor);
+ }
+ return this.registration;
+ }
+
/**
* Configure interceptors for the message channel.
*/
diff --git a/spring-messaging/src/main/java/org/springframework/messaging/simp/config/TaskExecutorRegistration.java b/spring-messaging/src/main/java/org/springframework/messaging/simp/config/TaskExecutorRegistration.java
index e8a5e050673e..d7ec1bcca15c 100644
--- a/spring-messaging/src/main/java/org/springframework/messaging/simp/config/TaskExecutorRegistration.java
+++ b/spring-messaging/src/main/java/org/springframework/messaging/simp/config/TaskExecutorRegistration.java
@@ -26,6 +26,8 @@
*/
public class TaskExecutorRegistration {
+ private ThreadPoolTaskExecutor taskExecutor;
+
private int corePoolSize = Runtime.getRuntime().availableProcessors() * 2;
private int maxPoolSize = Integer.MAX_VALUE;
@@ -35,6 +37,13 @@ public class TaskExecutorRegistration {
private int keepAliveSeconds = 60;
+ public TaskExecutorRegistration() {
+ }
+
+ public TaskExecutorRegistration(ThreadPoolTaskExecutor taskExecutor) {
+ this.taskExecutor = taskExecutor;
+ }
+
/**
* Set the core pool size of the ThreadPoolExecutor.
* <p><strong>NOTE:</strong> The core pool size is effectively the max pool size
@@ -93,7 +102,7 @@ public TaskExecutorRegistration keepAliveSeconds(int keepAliveSeconds) {
}
protected ThreadPoolTaskExecutor getTaskExecutor() {
- ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
+ ThreadPoolTaskExecutor executor = (this.taskExecutor != null ? this.taskExecutor : new ThreadPoolTaskExecutor());
executor.setCorePoolSize(this.corePoolSize);
executor.setMaxPoolSize(this.maxPoolSize);
executor.setKeepAliveSeconds(this.keepAliveSeconds);
diff --git a/spring-messaging/src/main/java/org/springframework/messaging/support/Test.java b/spring-messaging/src/main/java/org/springframework/messaging/support/Test.java
deleted file mode 100644
index 2a7cf38575ad..000000000000
--- a/spring-messaging/src/main/java/org/springframework/messaging/support/Test.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright 2002-2014 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.messaging.support;
-
-/**
- * @author Rossen Stoyanchev
- * @since 4.1
- */
-public class Test {
-
- public static void main(String[] args) {
-
- ExecutorSubscribableChannel.ExecutorSubscribableChannelTask task = null;
-
- }
-
-}
diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/config/MessageBrokerConfigurationTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/config/MessageBrokerConfigurationTests.java
index ce4aceb30dbe..a7684b97e221 100644
--- a/spring-messaging/src/test/java/org/springframework/messaging/simp/config/MessageBrokerConfigurationTests.java
+++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/config/MessageBrokerConfigurationTests.java
@@ -132,8 +132,8 @@ public void clientInboundChannelCustomized() {
assertEquals(2, channel.getInterceptors().size());
- ThreadPoolTaskExecutor taskExecutor = this.customContext.getBean(
- "clientInboundChannelExecutor", ThreadPoolTaskExecutor.class);
+ CustomThreadPoolTaskExecutor taskExecutor = this.customContext.getBean(
+ "clientInboundChannelExecutor", CustomThreadPoolTaskExecutor.class);
assertEquals(11, taskExecutor.getCorePoolSize());
assertEquals(12, taskExecutor.getMaxPoolSize());
@@ -489,7 +489,8 @@ static class CustomConfig extends AbstractMessageBrokerConfiguration {
@Override
protected void configureClientInboundChannel(ChannelRegistration registration) {
registration.setInterceptors(this.interceptor);
- registration.taskExecutor().corePoolSize(11).maxPoolSize(12).keepAliveSeconds(13).queueCapacity(14);
+ registration.taskExecutor(new CustomThreadPoolTaskExecutor())
+ .corePoolSize(11).maxPoolSize(12).keepAliveSeconds(13).queueCapacity(14);
}
@Override
@@ -540,4 +541,7 @@ public void validate(Object target, Errors errors) {
}
}
+ private static class CustomThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {
+ }
+
}
|
e4bbfd537a63a52a6094491504fc7b0bb54bcb0e
|
drools
|
fixing reflection constructor to use int instead of- long for ksessionId--
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/KnowledgeStoreServiceImpl.java b/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/KnowledgeStoreServiceImpl.java
index 02cd409adc2..3343babc7b3 100644
--- a/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/KnowledgeStoreServiceImpl.java
+++ b/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/KnowledgeStoreServiceImpl.java
@@ -81,7 +81,7 @@ private CommandExecutor buildCommanService(long sessionId,
try {
Class< ? extends CommandExecutor> serviceClass = getCommandServiceClass();
- Constructor< ? extends CommandExecutor> constructor = serviceClass.getConstructor( int.class,
+ Constructor< ? extends CommandExecutor> constructor = serviceClass.getConstructor( long.class,
KnowledgeBase.class,
KnowledgeSessionConfiguration.class,
Environment.class );
|
48053b56631374d50fc9075e39fea70da419a5c8
|
orientdb
|
implemented integration of globla property with- binary serialization--
|
a
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializerBinaryV0.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializerBinaryV0.java
index ba347d5bf49..90d03f9984a 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializerBinaryV0.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializerBinaryV0.java
@@ -22,10 +22,12 @@
import com.orientechnologies.orient.core.db.record.OTrackedMap;
import com.orientechnologies.orient.core.db.record.OTrackedSet;
import com.orientechnologies.orient.core.db.record.ridbag.ORidBag;
+import com.orientechnologies.orient.core.exception.ODatabaseException;
import com.orientechnologies.orient.core.id.OClusterPositionLong;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.metadata.schema.OClass;
+import com.orientechnologies.orient.core.metadata.schema.OGlobalProperty;
import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.ORecordInternal;
@@ -52,15 +54,38 @@ public void deserialize(final ODocument document, final BytesContainer bytes) {
document.setClassNameIfExists(className);
int last = 0;
String field;
- while ((field = readString(bytes)).length() != 0) {
+ while (true) {
+ OGlobalProperty prop = null;
+ final int len = OVarIntSerializer.readAsInteger(bytes);
+ if (len == 0)
+ break;
+ else if (len > 0) {
+ final String res = new String(bytes.bytes, bytes.offset, len, utf8);
+ bytes.skip(len);
+ field = res;
+ } else {
+ ODatabaseRecord db = document.getDatabase();
+ if (db == null || db.isClosed())
+ throw new ODatabaseException("Impossible deserialize the document no database present");
+ prop = db.getMetadata().getSchema().getGlobalPropertyById((len * -1) - 1);
+ field = prop.getName();
+ }
+
if (document.containsField(field)) {
// SKIP FIELD
- bytes.skip(OIntegerSerializer.INT_SIZE + 1);
+ if (prop != null && prop.getType() != OType.ANY)
+ bytes.skip(OIntegerSerializer.INT_SIZE);
+ else
+ bytes.skip(OIntegerSerializer.INT_SIZE + 1);
continue;
}
final int valuePos = readInteger(bytes);
- final OType type = readOType(bytes);
+ final OType type;
+ if (prop != null && prop.getType() != OType.ANY)
+ type = prop.getType();
+ else
+ type = readOType(bytes);
if (valuePos != 0) {
int headerCursor = bytes.offset;
@@ -89,11 +114,21 @@ public void serialize(ODocument document, BytesContainer bytes) {
else
writeEmptyString(bytes);
int[] pos = new int[document.fields()];
+ OProperty[] properties = new OProperty[document.fields()];
int i = 0;
Entry<String, ?> values[] = new Entry[document.fields()];
for (Entry<String, Object> entry : document) {
- writeString(bytes, entry.getKey());
- pos[i] = bytes.alloc(OIntegerSerializer.INT_SIZE + 1);
+ properties[i] = getSchemaProperty(document, entry.getKey());
+ if (properties[i] != null) {
+ OVarIntSerializer.write(bytes, (properties[i].getId() + 1) * -1);
+ if (properties[i].getType() != OType.ANY)
+ pos[i] = bytes.alloc(OIntegerSerializer.INT_SIZE);
+ else
+ pos[i] = bytes.alloc(OIntegerSerializer.INT_SIZE + 1);
+ } else {
+ writeString(bytes, entry.getKey());
+ pos[i] = bytes.alloc(OIntegerSerializer.INT_SIZE + 1);
+ }
values[i] = entry;
i++;
}
@@ -109,7 +144,8 @@ public void serialize(ODocument document, BytesContainer bytes) {
continue;
pointer = writeSingleValue(bytes, value, type, getLinkedType(document, type, values[i].getKey()));
OIntegerSerializer.INSTANCE.serialize(pointer, bytes.bytes, pos[i]);
- writeOType(bytes, (pos[i] + OIntegerSerializer.INT_SIZE), type);
+ if (properties[i] == null || properties[i].getType() == OType.ANY)
+ writeOType(bytes, (pos[i] + OIntegerSerializer.INT_SIZE), type);
}
}
@@ -539,6 +575,13 @@ private int writeEmbeddedCollection(BytesContainer bytes, Collection<?> value, O
return pos;
}
+ private OProperty getSchemaProperty(ODocument document, String key) {
+ OClass clazz = document.getSchemaClass();
+ if (clazz != null)
+ return clazz.getProperty(key);
+ return null;
+ }
+
private OType getFieldType(ODocument document, String key, Object fieldValue) {
OType type = document.fieldType(key);
if (type == null) {
|
f3aeabaf16a5e9a9ad0aa5d64b18652c203c602e
|
Vala
|
codegen: Inherit array_{length,null_terminated} from base parameter
First commit to start inheriting ccode attributes of parameters
from base parameters of base methods.
Partially fixes bug 642885.
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/codegen/valaccodeattribute.vala b/codegen/valaccodeattribute.vala
index 82a74f7c3b..05745df0cf 100644
--- a/codegen/valaccodeattribute.vala
+++ b/codegen/valaccodeattribute.vala
@@ -468,9 +468,36 @@ public class Vala.CCodeAttribute : AttributeCache {
}
}
- public bool array_length { get; private set; }
+ public bool array_length {
+ get {
+ if (_array_length == null) {
+ if (node.get_attribute ("NoArrayLength") != null) {
+ // deprecated
+ _array_length = false;
+ } else if (ccode != null && ccode.has_argument ("array_length")) {
+ _array_length = ccode.get_bool ("array_length");
+ } else {
+ _array_length = get_default_array_length ();
+ }
+ }
+ return _array_length;
+ }
+ }
+
+ public bool array_null_terminated {
+ get {
+ if (_array_null_terminated == null) {
+ if (ccode != null && ccode.has_argument ("array_null_terminated")) {
+ _array_null_terminated = ccode.get_bool ("array_null_terminated");
+ } else {
+ _array_null_terminated = get_default_array_null_terminated ();
+ }
+ }
+ return _array_null_terminated;
+ }
+ }
+
public string? array_length_type { get; private set; }
- public bool array_null_terminated { get; private set; }
public string? array_length_name { get; private set; }
public string? array_length_expr { get; private set; }
public bool delegate_target { get; private set; }
@@ -512,6 +539,8 @@ public class Vala.CCodeAttribute : AttributeCache {
private string _delegate_target_name;
private string _ctype;
private bool ctype_set = false;
+ private bool? _array_length;
+ private bool? _array_null_terminated;
private static int dynamic_method_id;
@@ -519,13 +548,10 @@ public class Vala.CCodeAttribute : AttributeCache {
this.node = node;
this.sym = node as Symbol;
- array_length = true;
delegate_target = true;
ccode = node.get_attribute ("CCode");
if (ccode != null) {
- array_length = ccode.get_bool ("array_length", true);
array_length_type = ccode.get_string ("array_length_type");
- array_null_terminated = ccode.get_bool ("array_null_terminated");
array_length_name = ccode.get_string ("array_length_cname");
array_length_expr = ccode.get_string ("array_length_cexpr");
if (ccode.has_argument ("pos")) {
@@ -534,10 +560,6 @@ public class Vala.CCodeAttribute : AttributeCache {
delegate_target = ccode.get_bool ("delegate_target", true);
sentinel = ccode.get_string ("sentinel");
}
- if (node.get_attribute ("NoArrayLength") != null) {
- // deprecated
- array_length = false;
- }
if (sentinel == null) {
sentinel = "NULL";
}
@@ -1274,4 +1296,24 @@ public class Vala.CCodeAttribute : AttributeCache {
}
}
}
+
+ private bool get_default_array_length () {
+ if (node is Parameter) {
+ var param = (Parameter) node;
+ if (param.base_parameter != null) {
+ return CCodeBaseModule.get_ccode_array_length (param.base_parameter);
+ }
+ }
+ return true;
+ }
+
+ private bool get_default_array_null_terminated () {
+ if (node is Parameter) {
+ var param = (Parameter) node;
+ if (param.base_parameter != null) {
+ return CCodeBaseModule.get_ccode_array_null_terminated (param.base_parameter);
+ }
+ }
+ return false;
+ }
}
diff --git a/tests/Makefile.am b/tests/Makefile.am
index b84d433ebd..de7e823236 100644
--- a/tests/Makefile.am
+++ b/tests/Makefile.am
@@ -48,6 +48,7 @@ TESTS = \
methods/bug620673.vala \
methods/bug622570.vala \
methods/bug639054.vala \
+ methods/bug642885.vala \
methods/bug642899.vala \
methods/bug646345.vala \
methods/bug648320.vala \
diff --git a/tests/methods/bug642885.vala b/tests/methods/bug642885.vala
new file mode 100644
index 0000000000..4acf97db53
--- /dev/null
+++ b/tests/methods/bug642885.vala
@@ -0,0 +1,36 @@
+public class Foo : Application {
+ public bool activated = false;
+
+ public Foo () {
+ Object (application_id: "org.foo.bar");
+ }
+
+ protected override void activate () {
+ activated = true;
+ }
+
+ protected override bool local_command_line (ref unowned string[] arguments, out int exit_status) {
+ var option_context = new OptionContext ();
+
+ // FIXME: https://bugzilla.gnome.org/show_bug.cgi?id=642885
+ unowned string[] args = arguments;
+
+ try {
+ option_context.parse (ref args);
+ } catch (OptionError e) {
+ exit_status = 1;
+ return true;
+ }
+
+ return base.local_command_line (ref arguments, out exit_status);
+ }
+}
+
+void main () {
+ string[] args = {""};
+ var app = new Foo ();
+ app.run (args);
+ assert (app.activated);
+}
+
+
diff --git a/vala/valaparameter.vala b/vala/valaparameter.vala
index c42d6f33a5..e65703dc28 100644
--- a/vala/valaparameter.vala
+++ b/vala/valaparameter.vala
@@ -44,6 +44,11 @@ public class Vala.Parameter : Variable {
public bool captured { get; set; }
+ /**
+ * The base parameter of this parameter relative to the base method.
+ */
+ public Parameter base_parameter { get; set; }
+
/**
* Creates a new formal parameter.
*
@@ -180,6 +185,17 @@ public class Vala.Parameter : Variable {
}
}
+ var m = parent_symbol as Method;
+ if (m != null) {
+ Method base_method = m.base_method != null ? m.base_method : m.base_interface_method;
+ if (base_method != null && base_method != m) {
+ int index = m.get_parameters ().index_of (this);
+ if (index >= 0) {
+ base_parameter = base_method.get_parameters ().get (index);
+ }
+ }
+ }
+
context.analyzer.current_source_file = old_source_file;
context.analyzer.current_symbol = old_symbol;
|
0a6b2c11738cb54c89771c6d663bd4bfb71511a8
|
Valadoc
|
Improve CTypeResolver for virtual/abstract methods
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/src/libvaladoc/ctyperesolver.vala b/src/libvaladoc/ctyperesolver.vala
index b9c4d8cc16..c5604276a3 100644
--- a/src/libvaladoc/ctyperesolver.vala
+++ b/src/libvaladoc/ctyperesolver.vala
@@ -20,10 +20,10 @@
* Florian Brosch <[email protected]>
*/
-
using Valadoc.Api;
using Gee;
+
/**
* Resolves symbols by C-names
*/
@@ -120,9 +120,9 @@ public class Valadoc.CTypeResolver : Visitor {
* @return the resolved node or null
*/
public Api.Node? resolve_symbol (Api.Node? element, string _name) {
- string name = _name.replace ("-", "_");
+ string name = _name.replace ("->", ".").replace ("-", "_");
- if (element != null && _name.has_prefix (":")) {
+ if (element != null && name.has_prefix (":")) {
Item parent = element;
while (parent != null && !(parent is Class || parent is Interface)) {
parent = parent.parent;
@@ -143,16 +143,16 @@ public class Valadoc.CTypeResolver : Visitor {
return node;
}
- string? alternative = translate_cname_to_g (_name);
+ string? alternative = translate_cname_to_g (name);
if (alternative != null) {
return nodes.get (alternative);
}
- if (element != null && _name.has_prefix (":")) {
+ if (element != null && name.has_prefix (":")) {
if (element is Class && ((Class) element).get_cname () != null) {
- return nodes.get (((Class) element).get_cname () + "." + _name);
+ return nodes.get (((Class) element).get_cname () + "." + name);
} else if (element is Struct && ((Struct) element).get_cname () != null) {
- return nodes.get (((Struct) element).get_cname () + "." + _name);
+ return nodes.get (((Struct) element).get_cname () + "." + name);
}
}
@@ -162,10 +162,10 @@ public class Valadoc.CTypeResolver : Visitor {
return this.tree.search_symbol_str (null, "GLib.FileStream.printf");
}
- int dotpos = _name.index_of_char ('.');
+ int dotpos = name.index_of_char ('.');
if (dotpos > 0) {
- string fst = _name.substring (0, dotpos);
- string snd = _name.substring (dotpos + 1);
+ string fst = name.substring (0, dotpos);
+ string snd = name.substring (dotpos + 1);
return nodes.get (fst + ":" + snd);
}
@@ -289,7 +289,7 @@ public class Valadoc.CTypeResolver : Visitor {
} else {
string parent_cname = get_parent_type_cname (item);
if (parent_cname != null) {
- register_symbol (parent_cname+"->"+item.get_cname (), item);
+ register_symbol (parent_cname + "." + item.get_cname (), item);
}
}
}
@@ -345,7 +345,16 @@ public class Valadoc.CTypeResolver : Visitor {
public override void visit_method (Method item) {
if (item.is_abstract || item.is_virtual || item.is_override) {
string parent_cname = get_parent_type_cname (item);
- register_symbol (parent_cname + "->" + item.name, item);
+
+ if (item.parent is Class) {
+ register_symbol (parent_cname + "Class." + item.name, item);
+ } else {
+ register_symbol (parent_cname + "Iface." + item.name, item);
+ }
+
+ // Allow to resolve invalid links:
+ register_symbol (parent_cname + "." + item.name, item);
+
Collection<Interface> interfaces = null;
Collection<Class> classes = null;
@@ -359,11 +368,13 @@ public class Valadoc.CTypeResolver : Visitor {
}
foreach (Interface iface in interfaces) {
- register_symbol (iface.get_cname () + "->" + item.name, item);
+ register_symbol (iface.get_cname () + "Iface." + item.name, item);
+ register_symbol (iface.get_cname () + "." + item.name, item);
}
foreach (Class cl in classes) {
- register_symbol (cl.get_cname () + "->" + item.name, item);
+ register_symbol (cl.get_cname () + "Class." + item.name, item);
+ register_symbol (cl.get_cname () + "." + item.name, item);
}
}
|
8224d5da129b8b634056da77f552aae7a3fc946b
|
searls$jasmine-maven-plugin
|
Changed the implementation of spec runner html generator to first see if a preloaded source file exists; if it doesn't, it'll trust exactly what is written into the POM. This should result in more flexibility for preload edge cases, like trying to load a remote resource on an entirely different protocol (like http/https/ftp), or from the test source directory.
|
p
|
https://github.com/searls/jasmine-maven-plugin
|
diff --git a/src/main/java/searls/jasmine/runner/SpecRunnerHtmlGenerator.java b/src/main/java/searls/jasmine/runner/SpecRunnerHtmlGenerator.java
index de371c42..04870fae 100644
--- a/src/main/java/searls/jasmine/runner/SpecRunnerHtmlGenerator.java
+++ b/src/main/java/searls/jasmine/runner/SpecRunnerHtmlGenerator.java
@@ -32,7 +32,7 @@ public class SpecRunnerHtmlGenerator {
private File sourceDir;
private File specDir;
private List<String> sourcesToLoadFirst;
- private List<File> fileNamesAlreadyWrittenAsScriptTags = new ArrayList<File>();
+ private List<String> fileNamesAlreadyWrittenAsScriptTags = new ArrayList<String>();
public SpecRunnerHtmlGenerator(List<String> sourcesToLoadFirst, File sourceDir, File specDir) {
this.sourcesToLoadFirst = sourcesToLoadFirst;
@@ -83,33 +83,48 @@ private void setJavaScriptSourcesAttribute(StringTemplate template) throws IOExc
template.setAttribute(SOURCES_TEMPLATE_ATTR_NAME, scriptTags.toString());
}
- private List<File> expandSourcesToLoadFirstRelativeToSourceDir() {
- List<File> files = new ArrayList<File>();
+ private List<String> expandSourcesToLoadFirstRelativeToSourceDir() {
+ List<String> files = new ArrayList<String>();
if (sourcesToLoadFirst != null) {
for (String sourceToLoadFirst : sourcesToLoadFirst) {
- files.add(new File(sourceDir, sourceToLoadFirst));
+ File file = new File(sourceDir, sourceToLoadFirst);
+ if(file.exists()) {
+ files.add(fileToString(file));
+ } else {
+ files.add(sourceToLoadFirst);
+ }
}
}
return files;
}
- private List<File> filesForScriptsInDirectory(File directory) throws IOException {
- List<File> files = new ArrayList<File>();
+ private List<String> filesForScriptsInDirectory(File directory) throws IOException {
+ List<String> fileNames = new ArrayList<String>();
if (directory != null) {
fileUtilsWrapper.forceMkdir(directory);
- files = new ArrayList<File>(fileUtilsWrapper.listFiles(directory, new String[] { "js" }, true));
+ List<File> files = new ArrayList<File>(fileUtilsWrapper.listFiles(directory, new String[] { "js" }, true));
Collections.sort(files);
+ for (File file : files) {
+ fileNames.add(fileToString(file));
+ }
}
- return files;
+ return fileNames;
}
- private void appendScriptTagsForFiles(StringBuilder sb, List<File> sourceFiles) throws MalformedURLException {
- for (File sourceFile : sourceFiles) {
+ private void appendScriptTagsForFiles(StringBuilder sb, List<String> sourceFiles) {
+ for (String sourceFile : sourceFiles) {
if (!fileNamesAlreadyWrittenAsScriptTags.contains(sourceFile)) {
- sb.append("<script type=\"text/javascript\" src=\"").append(sourceFile.toURI().toURL().toString()).append("\"></script>");
+ sb.append("<script type=\"text/javascript\" src=\"").append(sourceFile).append("\"></script>");
fileNamesAlreadyWrittenAsScriptTags.add(sourceFile);
}
}
}
+ private String fileToString(File file) {
+ try {
+ return file.toURI().toURL().toString();
+ } catch (MalformedURLException e) {
+ throw new RuntimeException(e);
+ }
+ }
}
diff --git a/src/test/resources/examples/jasmine-webapp-load-remote/pom.xml b/src/test/resources/examples/jasmine-webapp-load-remote/pom.xml
new file mode 100644
index 00000000..91f2922f
--- /dev/null
+++ b/src/test/resources/examples/jasmine-webapp-load-remote/pom.xml
@@ -0,0 +1,63 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>searls</groupId>
+ <artifactId>jasmine-example-superpom</artifactId>
+ <version>1.0.1-SNAPSHOT</version>
+ </parent>
+ <artifactId>jasmine-webapp-load-remote</artifactId>
+ <packaging>war</packaging>
+ <name>Example Webapp using Jasmine Maven Plugin where remote scripts need to be loaded into the runners.</name>
+ <dependencies>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.8.1</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+ <build>
+ <finalName>jasmine-webapp-example</finalName>
+ <plugins>
+ <plugin>
+ <groupId>searls</groupId>
+ <artifactId>jasmine-maven-plugin</artifactId>
+ <version>${project.version}</version>
+ <executions>
+ <execution>
+ <goals>
+ <goal>generateManualRunner</goal>
+ <goal>resources</goal>
+ <goal>testResources</goal>
+ <goal>test</goal>
+ <goal>preparePackage</goal>
+ </goals>
+ <configuration>
+ <preloadSources>
+ <source>https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js</source>
+ </preloadSources>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+
+ <repositories>
+ <repository>
+ <id>searls-maven-thirdparty</id>
+ <url>http://searls-maven-repository.googlecode.com/svn/trunk/thirdparty</url>
+ </repository>
+ </repositories>
+ <pluginRepositories>
+ <pluginRepository>
+ <id>searls-maven-releases</id>
+ <url>http://searls-maven-repository.googlecode.com/svn/trunk/releases</url>
+ </pluginRepository>
+ <pluginRepository>
+ <id>searls-maven-snapshots</id>
+ <url>http://searls-maven-repository.googlecode.com/svn/trunk/snapshots</url>
+ </pluginRepository>
+ </pluginRepositories>
+</project>
diff --git a/src/test/resources/examples/jasmine-webapp-load-remote/src/main/webapp/META-INF/MANIFEST.MF b/src/test/resources/examples/jasmine-webapp-load-remote/src/main/webapp/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..254272e1
--- /dev/null
+++ b/src/test/resources/examples/jasmine-webapp-load-remote/src/main/webapp/META-INF/MANIFEST.MF
@@ -0,0 +1,3 @@
+Manifest-Version: 1.0
+Class-Path:
+
diff --git a/src/test/resources/examples/jasmine-webapp-load-remote/src/main/webapp/WEB-INF/web.xml b/src/test/resources/examples/jasmine-webapp-load-remote/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 00000000..9f88c1f9
--- /dev/null
+++ b/src/test/resources/examples/jasmine-webapp-load-remote/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,7 @@
+<!DOCTYPE web-app PUBLIC
+ "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
+ "http://java.sun.com/dtd/web-app_2_3.dtd" >
+
+<web-app>
+ <display-name>Archetype Created Web Application</display-name>
+</web-app>
diff --git a/src/test/resources/examples/jasmine-webapp-load-remote/src/main/webapp/index.jsp b/src/test/resources/examples/jasmine-webapp-load-remote/src/main/webapp/index.jsp
new file mode 100644
index 00000000..c38169bb
--- /dev/null
+++ b/src/test/resources/examples/jasmine-webapp-load-remote/src/main/webapp/index.jsp
@@ -0,0 +1,5 @@
+<html>
+<body>
+<h2>Hello World!</h2>
+</body>
+</html>
diff --git a/src/test/resources/examples/jasmine-webapp-load-remote/src/test/javascript/jQuerySpec.js b/src/test/resources/examples/jasmine-webapp-load-remote/src/test/javascript/jQuerySpec.js
new file mode 100644
index 00000000..ddd6f812
--- /dev/null
+++ b/src/test/resources/examples/jasmine-webapp-load-remote/src/test/javascript/jQuerySpec.js
@@ -0,0 +1,7 @@
+describe('jQuery',function(){
+
+ it('should see that jQuery is defined',function() {
+ expect(jQuery).toBeDefined();
+ });
+
+});
\ No newline at end of file
|
68ed95699ec80261f21d90a0c3c6d40b6b26f3b3
|
apache$httpclient
|
HTTPCLIENT-1035: begin adding functionality for flushing updated
entries mentioned by Content-Location in responses. Not yet hooked
in to be used.
git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@1051865 13f79535-47bb-0310-9956-ffa450edef68
|
p
|
https://github.com/apache/httpcomponents-client
|
diff --git a/httpclient-cache/src/main/java/org/apache/http/impl/client/cache/CacheInvalidator.java b/httpclient-cache/src/main/java/org/apache/http/impl/client/cache/CacheInvalidator.java
index 4309e7f893..a97cf8acaf 100644
--- a/httpclient-cache/src/main/java/org/apache/http/impl/client/cache/CacheInvalidator.java
+++ b/httpclient-cache/src/main/java/org/apache/http/impl/client/cache/CacheInvalidator.java
@@ -29,16 +29,20 @@
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
+import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
+import org.apache.http.HttpResponse;
import org.apache.http.annotation.ThreadSafe;
import org.apache.http.client.cache.HeaderConstants;
import org.apache.http.client.cache.HttpCacheEntry;
import org.apache.http.client.cache.HttpCacheStorage;
+import org.apache.http.impl.cookie.DateParseException;
+import org.apache.http.impl.cookie.DateUtils;
/**
* Given a particular HttpRequest, flush any cache entries that this request
@@ -150,4 +154,45 @@ private boolean notGetOrHeadRequest(String method) {
return !(HeaderConstants.GET_METHOD.equals(method) || HeaderConstants.HEAD_METHOD
.equals(method));
}
+
+ /** Flushes entries that were invalidated by the given response
+ * received for the given host/request pair.
+ * @throws IOException
+ */
+ public void flushInvalidatedCacheEntries(HttpHost host,
+ HttpRequest request, HttpResponse response) throws IOException {
+ Header contentLocation = response.getFirstHeader("Content-Location");
+ if (contentLocation == null) return;
+ HttpCacheEntry entry = storage.getEntry(contentLocation.getValue());
+ if (entry == null) return;
+
+ if (!responseDateNewerThanEntryDate(response, entry)) return;
+ if (!responseAndEntryEtagsDiffer(response, entry)) return;
+
+ storage.removeEntry(contentLocation.getValue());
+ }
+
+ private boolean responseAndEntryEtagsDiffer(HttpResponse response,
+ HttpCacheEntry entry) {
+ Header entryEtag = entry.getFirstHeader("ETag");
+ Header responseEtag = response.getFirstHeader("ETag");
+ if (entryEtag == null || responseEtag == null) return false;
+ return (!entryEtag.getValue().equals(responseEtag.getValue()));
+ }
+
+ private boolean responseDateNewerThanEntryDate(HttpResponse response,
+ HttpCacheEntry entry) {
+ Header entryDateHeader = entry.getFirstHeader("Date");
+ Header responseDateHeader = response.getFirstHeader("Date");
+ if (entryDateHeader == null || responseDateHeader == null) {
+ return false;
+ }
+ try {
+ Date entryDate = DateUtils.parseDate(entryDateHeader.getValue());
+ Date responseDate = DateUtils.parseDate(responseDateHeader.getValue());
+ return responseDate.after(entryDate);
+ } catch (DateParseException e) {
+ return false;
+ }
+ }
}
diff --git a/httpclient-cache/src/test/java/org/apache/http/impl/client/cache/TestCacheInvalidator.java b/httpclient-cache/src/test/java/org/apache/http/impl/client/cache/TestCacheInvalidator.java
index e9157fc685..49a1a61b0c 100644
--- a/httpclient-cache/src/test/java/org/apache/http/impl/client/cache/TestCacheInvalidator.java
+++ b/httpclient-cache/src/test/java/org/apache/http/impl/client/cache/TestCacheInvalidator.java
@@ -27,17 +27,24 @@
package org.apache.http.impl.client.cache;
import java.io.IOException;
+import java.util.Date;
import java.util.HashMap;
import java.util.Map;
+
+import org.apache.http.Header;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
+import org.apache.http.HttpResponse;
import org.apache.http.ProtocolVersion;
import org.apache.http.client.cache.HttpCacheEntry;
import org.apache.http.client.cache.HttpCacheStorage;
+import static org.apache.http.impl.cookie.DateUtils.formatDate;
+
+import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.message.BasicHttpRequest;
-import org.easymock.classextension.EasyMock;
+import static org.easymock.classextension.EasyMock.*;
import org.junit.Before;
import org.junit.Test;
@@ -48,34 +55,42 @@ public class TestCacheInvalidator {
private CacheInvalidator impl;
private HttpCacheStorage mockStorage;
private HttpHost host;
- private CacheKeyGenerator extractor;
+ private CacheKeyGenerator cacheKeyGenerator;
private HttpCacheEntry mockEntry;
+ private HttpRequest request;
+ private HttpResponse response;
+
+ private Date now;
+ private Date tenSecondsAgo;
@Before
public void setUp() {
+ now = new Date();
+ tenSecondsAgo = new Date(now.getTime() - 10 * 1000L);
+
host = new HttpHost("foo.example.com");
- mockStorage = EasyMock.createMock(HttpCacheStorage.class);
- extractor = new CacheKeyGenerator();
- mockEntry = EasyMock.createMock(HttpCacheEntry.class);
+ mockStorage = createMock(HttpCacheStorage.class);
+ cacheKeyGenerator = new CacheKeyGenerator();
+ mockEntry = createMock(HttpCacheEntry.class);
+ response = HttpTestUtils.make200Response();
- impl = new CacheInvalidator(extractor, mockStorage);
+ impl = new CacheInvalidator(cacheKeyGenerator, mockStorage);
}
private void replayMocks() {
- EasyMock.replay(mockStorage);
- EasyMock.replay(mockEntry);
+ replay(mockStorage);
+ replay(mockEntry);
}
private void verifyMocks() {
- EasyMock.verify(mockStorage);
- EasyMock.verify(mockEntry);
+ verify(mockStorage);
+ verify(mockEntry);
}
// Tests
@Test
public void testInvalidatesRequestsThatArentGETorHEAD() throws Exception {
- HttpRequest request = new BasicHttpRequest("POST","/path", HTTP_1_1);
-
+ request = new BasicHttpRequest("POST","/path", HTTP_1_1);
final String theUri = "http://foo.example.com:80/path";
Map<String,String> variantMap = new HashMap<String,String>();
cacheEntryHasVariantMap(variantMap);
@@ -126,7 +141,7 @@ public void testInvalidatesUrisInLocationHeadersOnPUTs() throws Exception {
cacheReturnsEntryForUri(theUri);
entryIsRemoved(theUri);
- entryIsRemoved(extractor.canonicalizeUri(contentLocation));
+ entryIsRemoved(cacheKeyGenerator.canonicalizeUri(contentLocation));
replayMocks();
@@ -182,54 +197,41 @@ public void testDoesNotInvalidateUrisInContentLocationHeadersOnPUTsToDifferentHo
@Test
public void testDoesNotInvalidateGETRequest() throws Exception {
- HttpRequest request = new BasicHttpRequest("GET","/",HTTP_1_1);
-
+ request = new BasicHttpRequest("GET","/",HTTP_1_1);
replayMocks();
-
impl.flushInvalidatedCacheEntries(host, request);
-
verifyMocks();
}
@Test
public void testDoesNotInvalidateHEADRequest() throws Exception {
- HttpRequest request = new BasicHttpRequest("HEAD","/",HTTP_1_1);
-
+ request = new BasicHttpRequest("HEAD","/",HTTP_1_1);
replayMocks();
-
impl.flushInvalidatedCacheEntries(host, request);
-
verifyMocks();
}
@Test
public void testDoesNotInvalidateRequestsWithClientCacheControlHeaders() throws Exception {
- HttpRequest request = new BasicHttpRequest("GET","/",HTTP_1_1);
+ request = new BasicHttpRequest("GET","/",HTTP_1_1);
request.setHeader("Cache-Control","no-cache");
-
replayMocks();
-
impl.flushInvalidatedCacheEntries(host, request);
-
verifyMocks();
}
@Test
public void testDoesNotInvalidateRequestsWithClientPragmaHeaders() throws Exception {
- HttpRequest request = new BasicHttpRequest("GET","/",HTTP_1_1);
+ request = new BasicHttpRequest("GET","/",HTTP_1_1);
request.setHeader("Pragma","no-cache");
-
replayMocks();
-
impl.flushInvalidatedCacheEntries(host, request);
-
verifyMocks();
}
@Test
public void testVariantURIsAreFlushedAlso() throws Exception {
- HttpRequest request = new BasicHttpRequest("POST","/",HTTP_1_1);
-
+ request = new BasicHttpRequest("POST","/",HTTP_1_1);
final String theUri = "http://foo.example.com:80/";
final String variantUri = "theVariantURI";
@@ -249,7 +251,7 @@ public void testVariantURIsAreFlushedAlso() throws Exception {
@Test(expected=IOException.class)
public void testCacheFlushException() throws Exception {
- HttpRequest request = new BasicHttpRequest("POST","/",HTTP_1_1);
+ request = new BasicHttpRequest("POST","/",HTTP_1_1);
String theURI = "http://foo.example.com:80/";
cacheReturnsExceptionForUri(theURI);
@@ -257,18 +259,182 @@ public void testCacheFlushException() throws Exception {
replayMocks();
impl.flushInvalidatedCacheEntries(host, request);
}
+
+ @Test
+ public void doesNotFlushForResponsesWithoutContentLocation()
+ throws Exception {
+ request = HttpTestUtils.makeDefaultRequest();
+ replayMocks();
+ impl.flushInvalidatedCacheEntries(host, request, response);
+ verifyMocks();
+ }
+
+ @Test
+ public void flushesEntryIfFresherAndSpecifiedByContentLocation()
+ throws Exception {
+ response.setHeader("ETag","\"new-etag\"");
+ response.setHeader("Date", formatDate(now));
+ String theURI = "http://foo.example.com:80/bar";
+ response.setHeader("Content-Location", theURI);
+
+ HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(new Header[] {
+ new BasicHeader("Date", formatDate(tenSecondsAgo)),
+ new BasicHeader("ETag", "\"old-etag\"")
+ });
+
+ expect(mockStorage.getEntry(theURI)).andReturn(entry).anyTimes();
+ mockStorage.removeEntry(theURI);
+
+ replayMocks();
+ impl.flushInvalidatedCacheEntries(host, request, response);
+ verifyMocks();
+ }
+
+ @Test
+ public void doesNotFlushEntrySpecifiedByContentLocationIfEtagsMatch()
+ throws Exception {
+ response.setHeader("ETag","\"same-etag\"");
+ response.setHeader("Date", formatDate(now));
+ String theURI = "http://foo.example.com:80/bar";
+ response.setHeader("Content-Location", theURI);
+
+ HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(new Header[] {
+ new BasicHeader("Date", formatDate(tenSecondsAgo)),
+ new BasicHeader("ETag", "\"same-etag\"")
+ });
+
+ expect(mockStorage.getEntry(theURI)).andReturn(entry).anyTimes();
+
+ replayMocks();
+ impl.flushInvalidatedCacheEntries(host, request, response);
+ verifyMocks();
+ }
+
+ @Test
+ public void doesNotFlushEntrySpecifiedByContentLocationIfNotNewer()
+ throws Exception {
+ response.setHeader("ETag","\"new-etag\"");
+ response.setHeader("Date", formatDate(now));
+ String theURI = "http://foo.example.com:80/bar";
+ response.setHeader("Content-Location", theURI);
+
+ HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(new Header[] {
+ new BasicHeader("Date", formatDate(now)),
+ new BasicHeader("ETag", "\"old-etag\"")
+ });
+
+ expect(mockStorage.getEntry(theURI)).andReturn(entry).anyTimes();
+
+ replayMocks();
+ impl.flushInvalidatedCacheEntries(host, request, response);
+ verifyMocks();
+ }
+
+ @Test
+ public void doesNotFlushEntryIfNotInCache()
+ throws Exception {
+ response.setHeader("ETag","\"new-etag\"");
+ response.setHeader("Date", formatDate(now));
+ String theURI = "http://foo.example.com:80/bar";
+ response.setHeader("Content-Location", theURI);
+
+ expect(mockStorage.getEntry(theURI)).andReturn(null).anyTimes();
+
+ replayMocks();
+ impl.flushInvalidatedCacheEntries(host, request, response);
+ verifyMocks();
+ }
+
+ @Test
+ public void doesNotFlushEntrySpecifiedByContentLocationIfResponseHasNoEtag()
+ throws Exception {
+ response.removeHeaders("ETag");
+ response.setHeader("Date", formatDate(now));
+ String theURI = "http://foo.example.com:80/bar";
+ response.setHeader("Content-Location", theURI);
+
+ HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(new Header[] {
+ new BasicHeader("Date", formatDate(tenSecondsAgo)),
+ new BasicHeader("ETag", "\"old-etag\"")
+ });
+
+ expect(mockStorage.getEntry(theURI)).andReturn(entry).anyTimes();
+
+ replayMocks();
+ impl.flushInvalidatedCacheEntries(host, request, response);
+ verifyMocks();
+ }
+
+ @Test
+ public void doesNotFlushEntrySpecifiedByContentLocationIfEntryHasNoEtag()
+ throws Exception {
+ response.setHeader("ETag", "\"some-etag\"");
+ response.setHeader("Date", formatDate(now));
+ String theURI = "http://foo.example.com:80/bar";
+ response.setHeader("Content-Location", theURI);
+
+ HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(new Header[] {
+ new BasicHeader("Date", formatDate(tenSecondsAgo)),
+ });
+
+ expect(mockStorage.getEntry(theURI)).andReturn(entry).anyTimes();
+
+ replayMocks();
+ impl.flushInvalidatedCacheEntries(host, request, response);
+ verifyMocks();
+ }
+
+ @Test
+ public void doesNotFlushEntrySpecifiedByContentLocationIfResponseHasNoDate()
+ throws Exception {
+ response.setHeader("ETag", "\"new-etag\"");
+ response.removeHeaders("Date");
+ String theURI = "http://foo.example.com:80/bar";
+ response.setHeader("Content-Location", theURI);
+
+ HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(new Header[] {
+ new BasicHeader("ETag", "\"old-etag\""),
+ new BasicHeader("Date", formatDate(tenSecondsAgo)),
+ });
+
+ expect(mockStorage.getEntry(theURI)).andReturn(entry).anyTimes();
+
+ replayMocks();
+ impl.flushInvalidatedCacheEntries(host, request, response);
+ verifyMocks();
+ }
+
+ @Test
+ public void doesNotFlushEntrySpecifiedByContentLocationIfEntryHasNoDate()
+ throws Exception {
+ response.setHeader("ETag","\"new-etag\"");
+ response.setHeader("Date", formatDate(now));
+ String theURI = "http://foo.example.com:80/bar";
+ response.setHeader("Content-Location", theURI);
+
+ HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(new Header[] {
+ new BasicHeader("ETag", "\"old-etag\"")
+ });
+
+ expect(mockStorage.getEntry(theURI)).andReturn(entry).anyTimes();
+
+ replayMocks();
+ impl.flushInvalidatedCacheEntries(host, request, response);
+ verifyMocks();
+ }
+
// Expectations
private void cacheEntryHasVariantMap(Map<String,String> variantMap) {
- org.easymock.EasyMock.expect(mockEntry.getVariantMap()).andReturn(variantMap);
+ expect(mockEntry.getVariantMap()).andReturn(variantMap);
}
private void cacheReturnsEntryForUri(String theUri) throws IOException {
- org.easymock.EasyMock.expect(mockStorage.getEntry(theUri)).andReturn(mockEntry);
+ expect(mockStorage.getEntry(theUri)).andReturn(mockEntry);
}
private void cacheReturnsExceptionForUri(String theUri) throws IOException {
- org.easymock.EasyMock.expect(mockStorage.getEntry(theUri)).andThrow(
+ expect(mockStorage.getEntry(theUri)).andThrow(
new IOException("TOTAL FAIL"));
}
|
f6bfcd9709fac61e3c4efe537f0b634bd9f6a09f
|
restlet-framework-java
|
- Continued NIO connector--
|
a
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/InboundWay.java b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/InboundWay.java
index 79ba5f667b..5a69bb8dda 100644
--- a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/InboundWay.java
+++ b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/InboundWay.java
@@ -232,7 +232,7 @@ public void onSelected() {
if (getIoState() == IoState.READ_INTEREST) {
int result = readSocketBytes();
- while (getBuffer().hasRemaining()
+ while (getByteBuffer().hasRemaining()
&& (getMessageState() != MessageState.BODY)) {
if (getMessageState() == MessageState.START_LINE) {
readStartLine();
@@ -241,7 +241,7 @@ public void onSelected() {
}
// Attempt to read more available bytes
- if (!getBuffer().hasRemaining()
+ if (!getByteBuffer().hasRemaining()
&& (getMessageState() != MessageState.BODY)) {
result = readSocketBytes();
}
@@ -268,8 +268,8 @@ public void onSelected() {
* @throws IOException
*/
protected Parameter readHeader() throws IOException {
- Parameter header = HeaderReader.readHeader(getBuilder());
- getBuilder().delete(0, getBuilder().length());
+ Parameter header = HeaderReader.readHeader(getLineBuilder());
+ getLineBuilder().delete(0, getLineBuilder().length());
return header;
}
@@ -349,11 +349,11 @@ protected boolean readLine() throws IOException {
boolean result = false;
int next;
- while (!result && getBuffer().hasRemaining()) {
- next = (int) getBuffer().get();
+ while (!result && getByteBuffer().hasRemaining()) {
+ next = (int) getByteBuffer().get();
if (HeaderUtils.isCarriageReturn(next)) {
- next = (int) getBuffer().get();
+ next = (int) getByteBuffer().get();
if (HeaderUtils.isLineFeed(next)) {
result = true;
@@ -362,7 +362,7 @@ protected boolean readLine() throws IOException {
"Missing carriage return character at the end of HTTP line");
}
} else {
- getBuilder().append((char) next);
+ getLineBuilder().append((char) next);
}
}
@@ -376,9 +376,9 @@ protected boolean readLine() throws IOException {
* @throws IOException
*/
protected int readSocketBytes() throws IOException {
- getBuffer().clear();
- int result = getConnection().getSocketChannel().read(getBuffer());
- getBuffer().flip();
+ getByteBuffer().clear();
+ int result = getConnection().getSocketChannel().read(getByteBuffer());
+ getByteBuffer().flip();
return result;
}
diff --git a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/MessageState.java b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/MessageState.java
index dc6e4532d2..d2f35bda1a 100644
--- a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/MessageState.java
+++ b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/MessageState.java
@@ -44,6 +44,9 @@ public enum MessageState {
HEADERS,
/** The body is being processed. */
- BODY;
+ BODY,
+
+ /** The end has been reached. */
+ END;
}
diff --git a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/OutboundWay.java b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/OutboundWay.java
index a06ef2ff30..74a4f294c0 100644
--- a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/OutboundWay.java
+++ b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/OutboundWay.java
@@ -237,48 +237,82 @@ public int getSocketInterestOps() {
@Override
public void onSelected() {
try {
- if (getIoState() == IoState.WRITE_INTEREST) {
- Response message = getMessage();
+ Response message = getMessage();
- if (message != null) {
- boolean canWrite = true;
+ if (message != null) {
+ boolean canWrite = (getIoState() == IoState.WRITE_INTEREST);
+ boolean filling = getByteBuffer().hasRemaining();
- while (canWrite) {
- if (getBuffer().hasRemaining()
- && (getMessageState() != MessageState.BODY)) {
- if (getBuilder().length() == 0) {
+ while (canWrite) {
+ if (filling) {
+ // Before writing the byte buffer, we need to try
+ // to fill it as much as possible
+
+ if (getMessageState() == MessageState.BODY) {
+ // Writing the body doesn't rely on the line builder
+ // ...
+ } else {
+ // Write the start line or the headers relies on the
+ // line builder
+ if (getLineBuilder().length() == 0) {
+ // A new line can be written in the builder
writeLine();
}
- if (getBuilder().length() > 0) {
- int remaining = getBuffer().remaining();
+ if (getLineBuilder().length() > 0) {
+ // We can fill the byte buffer with the
+ // remaining line builder
+ int remaining = getByteBuffer().remaining();
- if (remaining >= getBuilder().length()) {
+ if (remaining >= getLineBuilder().length()) {
// Put the whole builder line in the buffer
- getBuffer()
+ getByteBuffer()
.put(
StringUtils
- .getLatin1Bytes(getBuilder()
+ .getLatin1Bytes(getLineBuilder()
.toString()));
- getBuilder().delete(0,
- getBuilder().length());
+ getLineBuilder().delete(0,
+ getLineBuilder().length());
} else {
- // Fill the buffer with part of the builder
- // line
- getBuffer()
+ // Put the maximum number of characters
+ // into the byte buffer
+ getByteBuffer()
.put(
StringUtils
- .getLatin1Bytes(getBuilder()
+ .getLatin1Bytes(getLineBuilder()
.substring(
0,
remaining)));
- getBuilder().delete(0, remaining);
+ getLineBuilder().delete(0, remaining);
}
}
+ }
+
+ canWrite = (getIoState() == IoState.WRITE_INTEREST);
+ filling = (getMessageState() != MessageState.END)
+ && getByteBuffer().hasRemaining();
+ } else {
+ // After filling the byte buffer, we can now flip it
+ // and start draining it.
+ getByteBuffer().flip();
+ int bytesWritten = getConnection().getSocketChannel()
+ .write(getByteBuffer());
+
+ if (bytesWritten == 0) {
+ // The byte buffer hasn't been written, the socket
+ // channel can't write more. We needs to put the
+ // byte buffer in the filling state again and wait
+ // for a new NIO selection.
+ getByteBuffer().flip();
+ canWrite = false;
+ } else if (getByteBuffer().hasRemaining()) {
+ // All the buffer couldn't be written. Compact the
+ // remaining
+ // bytes so that filling can happen again.
+ getByteBuffer().compact();
} else {
- getBuffer().flip();
- canWrite = (getConnection().getSocketChannel()
- .write(getBuffer()) > 0);
+ // The byte buffer has been fully written, but the
+ // socket channel wants more.
}
}
@@ -493,18 +527,18 @@ protected boolean writeLine() throws IOException {
if (getHeaderIndex() < getHeaders().size()) {
// Write header
Parameter header = getHeaders().get(getHeaderIndex());
- getBuilder().append(header.getName());
- getBuilder().append(": ");
- getBuilder().append(header.getValue());
- getBuilder().append('\r'); // CR
- getBuilder().append('\n'); // LF
+ getLineBuilder().append(header.getName());
+ getLineBuilder().append(": ");
+ getLineBuilder().append(header.getValue());
+ getLineBuilder().append('\r'); // CR
+ getLineBuilder().append('\n'); // LF
// Move to the next header
setHeaderIndex(getHeaderIndex() + 1);
} else {
// Write the end of the headers section
- getBuilder().append('\r'); // CR
- getBuilder().append('\n'); // LF
+ getLineBuilder().append('\r'); // CR
+ getLineBuilder().append('\n'); // LF
// Change state
setMessageState(MessageState.BODY);
@@ -530,18 +564,19 @@ protected void writeStartLine() throws IOException {
String protocolVersion = protocol.getVersion();
String version = protocol.getTechnicalName() + '/'
+ ((protocolVersion == null) ? "1.1" : protocolVersion);
- getBuilder().append(version);
- getBuilder().append(' ');
- getBuilder().append(getMessage().getStatus().getCode());
- getBuilder().append(' ');
+ getLineBuilder().append(version);
+ getLineBuilder().append(' ');
+ getLineBuilder().append(getMessage().getStatus().getCode());
+ getLineBuilder().append(' ');
if (getMessage().getStatus().getDescription() != null) {
- getBuilder().append(getMessage().getStatus().getDescription());
+ getLineBuilder().append(getMessage().getStatus().getDescription());
} else {
- getBuilder().append("Status " + getMessage().getStatus().getCode());
+ getLineBuilder().append(
+ "Status " + getMessage().getStatus().getCode());
}
- getBuilder().append("\r\n");
+ getLineBuilder().append("\r\n");
}
}
diff --git a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/ServerInboundWay.java b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/ServerInboundWay.java
index 27cdf3577f..f903b7a56b 100644
--- a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/ServerInboundWay.java
+++ b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/ServerInboundWay.java
@@ -67,7 +67,7 @@ protected void readStartLine() throws IOException {
int i = 0;
int start = 0;
- int size = getBuilder().length();
+ int size = getLineBuilder().length();
char next;
if (size == 0) {
@@ -75,10 +75,10 @@ protected void readStartLine() throws IOException {
} else {
// Parse the request method
for (i = start; (requestMethod == null) && (i < size); i++) {
- next = getBuilder().charAt(i);
+ next = getLineBuilder().charAt(i);
if (HeaderUtils.isSpace(next)) {
- requestMethod = getBuilder().substring(start, i);
+ requestMethod = getLineBuilder().substring(start, i);
start = i + 1;
}
}
@@ -90,10 +90,10 @@ protected void readStartLine() throws IOException {
// Parse the request URI
for (i = start; (requestUri == null) && (i < size); i++) {
- next = getBuilder().charAt(i);
+ next = getLineBuilder().charAt(i);
if (HeaderUtils.isSpace(next)) {
- requestUri = getBuilder().substring(start, i);
+ requestUri = getLineBuilder().substring(start, i);
start = i + 1;
}
}
@@ -109,11 +109,11 @@ protected void readStartLine() throws IOException {
// Parse the protocol version
for (i = start; (version == null) && (i < size); i++) {
- next = getBuilder().charAt(i);
+ next = getLineBuilder().charAt(i);
}
if (i == size) {
- version = getBuilder().substring(start, i);
+ version = getLineBuilder().substring(start, i);
start = i + 1;
}
@@ -129,7 +129,7 @@ protected void readStartLine() throws IOException {
setMessage(response);
setMessageState(MessageState.HEADERS);
- getBuilder().delete(0, getBuilder().length());
+ getLineBuilder().delete(0, getLineBuilder().length());
}
} else {
// We need more characters before parsing
diff --git a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/Way.java b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/Way.java
index 05f73ebf0d..be76f5b3a9 100644
--- a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/Way.java
+++ b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/Way.java
@@ -51,10 +51,7 @@
public abstract class Way {
/** The byte buffer. */
- private final ByteBuffer buffer;
-
- /** The line builder. */
- private final StringBuilder builder;
+ private final ByteBuffer byteBuffer;
/** The parent connection. */
private final Connection<?> connection;
@@ -62,6 +59,9 @@ public abstract class Way {
/** The IO state. */
private volatile IoState ioState;
+ /** The line builder. */
+ private final StringBuilder lineBuilder;
+
/** The current message exchanged. */
private volatile Response message;
@@ -84,8 +84,8 @@ public abstract class Way {
* The parent connection.
*/
public Way(Connection<?> connection) {
- this.buffer = ByteBuffer.allocate(NioUtils.BUFFER_SIZE);
- this.builder = new StringBuilder();
+ this.byteBuffer = ByteBuffer.allocate(NioUtils.BUFFER_SIZE);
+ this.lineBuilder = new StringBuilder();
this.connection = connection;
this.messageState = MessageState.START_LINE;
this.ioState = IoState.IDLE;
@@ -99,17 +99,8 @@ public Way(Connection<?> connection) {
*
* @return The byte buffer.
*/
- protected ByteBuffer getBuffer() {
- return buffer;
- }
-
- /**
- * Returns the line builder.
- *
- * @return The line builder.
- */
- protected StringBuilder getBuilder() {
- return builder;
+ protected ByteBuffer getByteBuffer() {
+ return byteBuffer;
}
/**
@@ -139,6 +130,15 @@ protected IoState getIoState() {
return ioState;
}
+ /**
+ * Returns the line builder.
+ *
+ * @return The line builder.
+ */
+ protected StringBuilder getLineBuilder() {
+ return lineBuilder;
+ }
+
/**
* Returns the logger.
*
|
88cb6d10438fe158268c3ad3a6bed65feb95b9d9
|
coremedia$jangaroo-tools
|
re-animated -enableassertions (-ea) conditional compilation flag
including runtime support and integration test
[git-p4: depot-paths = "//coremedia/jangaroo/": change = 142226]
|
a
|
https://github.com/coremedia/jangaroo-tools
|
diff --git a/jooc/src/it-helper/it-parent/pom.xml b/jooc/src/it-helper/it-parent/pom.xml
index 5fe9f8b3b..521e1aecd 100644
--- a/jooc/src/it-helper/it-parent/pom.xml
+++ b/jooc/src/it-helper/it-parent/pom.xml
@@ -109,7 +109,7 @@
<artifactId>maven-antrun-plugin</artifactId>
<executions>
- <!-- compile the test .js2 files in target/joo -->
+ <!-- compile the test .as files in target/joo -->
<execution>
<id>compile-test-joo</id>
<phase>process-test-resources</phase>
diff --git a/jooc/src/main/cup/net/jangaroo/jooc/joo.cup b/jooc/src/main/cup/net/jangaroo/jooc/joo.cup
index 03a928574..a8092ce8a 100644
--- a/jooc/src/main/cup/net/jangaroo/jooc/joo.cup
+++ b/jooc/src/main/cup/net/jangaroo/jooc/joo.cup
@@ -641,10 +641,8 @@ statement ::=
{: RESULT = new ReturnStatement(r,e,s); :}
| DELETE:d lvalue:e SEMICOLON:s
{: RESULT = new DeleteStatement(d,e,s); :}
-/*
- | ASSERT:a exprOrObjectLiteral:e SEMICOLON:s
- {: RESULT = new AssertStatement(a,e,s); :}
-*/
+ | ASSERT:a LPAREN:lp exprOrObjectLiteral:e RPAREN:rp SEMICOLON:s
+ {: RESULT = new AssertStatement(a,lp,e,rp,s); :}
| THROW:t commaExpr:e SEMICOLON:s
{: RESULT = new ThrowStatement(t,e,s); :}
| SUPER:s LPAREN:lp arguments:args RPAREN:rp
diff --git a/jooc/src/main/java/net/jangaroo/jooc/AssertStatement.java b/jooc/src/main/java/net/jangaroo/jooc/AssertStatement.java
index e0fdf830b..8dff365cd 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/AssertStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/AssertStatement.java
@@ -22,19 +22,31 @@
*/
class AssertStatement extends KeywordExprStatement {
+ JooSymbol lParen;
+ JooSymbol rParen;
- public AssertStatement(JooSymbol symAssert, Expr expr, JooSymbol symSemicolon) {
+ public AssertStatement(JooSymbol symAssert, JooSymbol lParen, Expr expr, JooSymbol rParen, JooSymbol symSemicolon) {
super(symAssert, expr, symSemicolon);
+ this.lParen = lParen;
+ this.rParen = rParen;
}
public void generateCode(JsWriter out) throws IOException {
if (out.getEnableAssertions()) {
out.writeSymbolWhitespace(symKeyword);
- out.writeToken("_joo_assert(");
+ out.writeToken("assert");
+ out.writeSymbol(lParen);
+ out.write("(");
optExpr.generateCode(out);
+ out.write(")");
out.write(", ");
- out.writeString(symKeyword.getFileName()+"("+symKeyword.getLine()+","+symKeyword.getColumn()+")");
- out.write(");");
+ out.writeString(symKeyword.getFileName());
+ out.write(", ");
+ out.writeInt(symKeyword.getLine());
+ out.write(", ");
+ out.writeInt(symKeyword.getColumn());
+ out.writeSymbol(rParen);
+ out.writeSymbol(symSemicolon);
} else {
out.beginComment();
super.generateCode(out);
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ant/JoocTask.java b/jooc/src/main/java/net/jangaroo/jooc/ant/JoocTask.java
index 9d683c4c9..66603f8d7 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ant/JoocTask.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ant/JoocTask.java
@@ -280,8 +280,8 @@ protected String[] getJoocArgs() {
if (verbose) {
args.add("-v");
}
- // TODO: reenable assertions
- //if (enableAssertions) args.add("-ea");
+ if (enableAssertions)
+ args.add("-ea");
if (destDir != null) {
args.add("-d");
args.add(destDir.getAbsolutePath());
diff --git a/jooc/src/main/java/net/jangaroo/jooc/config/JoocCommandLineParser.java b/jooc/src/main/java/net/jangaroo/jooc/config/JoocCommandLineParser.java
index f850cf2dd..7f35865e0 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/config/JoocCommandLineParser.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/config/JoocCommandLineParser.java
@@ -43,20 +43,16 @@ public JoocConfiguration parse(String[] argv) throws Exception {
.hasArg()
.withDescription("destination directory for generated JavaScript files")
.create("d");
- /*
Option enableAssertionsOption = OptionBuilder.withLongOpt("enableassertions")
.withDescription("enable assertions")
.create("ea");
- */
Options options = new Options();
options.addOption(help);
options.addOption(version);
options.addOption(verboseOption);
options.addOption(debugOption);
options.addOption(destinationDir);
- /*
options.addOption(enableAssertionsOption);
- */
CommandLineParser parser = new GnuParser();
CommandLine line = null;
@@ -84,11 +80,8 @@ public JoocConfiguration parse(String[] argv) throws Exception {
config.setOutputDirectory(destDir);
}
- config.setEnableAssertions(false); // TODO: use option
- /*
if (line.hasOption(enableAssertionsOption.getOpt()))
- enableAssertions = true;
- */
+ config.setEnableAssertions(true);
if (line.hasOption(debugOption.getOpt())) {
String[] values = line.getOptionValues(debugOption.getOpt());
diff --git a/jooc/src/main/js/joo/Class.js b/jooc/src/main/js/joo/Class.js
index d5397f391..3c20f5fcd 100644
--- a/jooc/src/main/js/joo/Class.js
+++ b/jooc/src/main/js/joo/Class.js
@@ -361,7 +361,11 @@ Function.prototype.bind = function(object) {
var superName = classPrefix+"super";
// static part:
var publicConstructor = this.publicConstructor;
- var privateStatic = {_super: superName};
+ var assert = function(cond, file, line, column) {
+ if (!cond)
+ throw new Error(file+"("+line+":"+column+"): assertion failed");
+ }
+ var privateStatic = {_super: superName, assert: assert};
if (this.superClassDescription) {
// init super class:
@@ -567,6 +571,9 @@ Function.prototype.bind = function(object) {
return ClassDescription.$static.dumpClasses();
}
};
+ theGlobalObject.joo.assert = function(condition, filename, line, column, msg) {
+
+ }
})(this);
// alert("runtime loaded!");
joo.typeOf = function typeOf(obj){
diff --git a/jooc/src/test/java/net/jangaroo/test/JooTestCase.java b/jooc/src/test/java/net/jangaroo/test/JooTestCase.java
index 660b6578f..d8fd7211c 100644
--- a/jooc/src/test/java/net/jangaroo/test/JooTestCase.java
+++ b/jooc/src/test/java/net/jangaroo/test/JooTestCase.java
@@ -33,6 +33,8 @@ public JooTestCase(String name) {
}
protected boolean debug = false;
+ protected boolean ea = false;
+
protected String sourceDir = null;
protected String destinationDir = null;
@@ -85,6 +87,7 @@ protected String[] prependSourceDir(String[] fileNames) {
protected int runJooc(String[] fileNames) {
String[] args = prependSourceDir(fileNames);
if (debug) args = concat("-g", args);
+ if (ea) args = concat("-ea", args);
if (destinationDir != null) args = concat(new String[]{"-d", destinationDir}, args);
Jooc compiler = new Jooc();
System.out.println("jooc " + toString(args));
diff --git a/jooc/src/test/java/net/jangaroo/test/integration/JooRuntimeTestCase.java b/jooc/src/test/java/net/jangaroo/test/integration/JooRuntimeTestCase.java
index 1a04e6e37..32f84ac56 100644
--- a/jooc/src/test/java/net/jangaroo/test/integration/JooRuntimeTestCase.java
+++ b/jooc/src/test/java/net/jangaroo/test/integration/JooRuntimeTestCase.java
@@ -15,6 +15,8 @@
package net.jangaroo.test.integration;
+import net.jangaroo.jooc.Jooc;
+import net.jangaroo.test.JooTestCase;
import org.mozilla.javascript.*;
import java.io.File;
@@ -22,9 +24,6 @@
import java.io.Reader;
import java.io.StringReader;
-import net.jangaroo.jooc.Jooc;
-import net.jangaroo.test.JooTestCase;
-
/**
* A JooTestCase to be executed at runtime
*
@@ -98,10 +97,18 @@ protected Object load(File jsFile) throws Exception {
}
protected void loadClass(String qualifiedJooClassName) throws Exception {
- String jsFileName = qualifiedJooClassName.replace('.',File.separatorChar) + Jooc.OUTPUT_FILE_SUFFIX;
+ String jsFileName = jsFileName(qualifiedJooClassName);
load(jsFileName);
}
+ protected String jsFileName(final String qualifiedJooClassName) {
+ return qualifiedJooClassName.replace('.', File.separatorChar) + Jooc.OUTPUT_FILE_SUFFIX;
+ }
+
+ protected String asFileName(final String qualifiedJooClassName) {
+ return qualifiedJooClassName.replace('.', File.separatorChar) + Jooc.AS_SUFFIX;
+ }
+
protected void initClass(String qualifiedJooClassName) throws Exception {
eval(Jooc.CLASS_FULLY_QUALIFIED_NAME + ".init("+qualifiedJooClassName+")");
}
@@ -147,6 +154,17 @@ protected void expectString(String expected, String script) throws Exception {
}
}
+ protected void expectSubstring(String expected, String script) throws Exception {
+ Object result = eval(script);
+ String actual = null;
+ if (result instanceof String)
+ actual = (String)result;
+ else fail("expected string result, found: " + result.getClass().getName());
+ if (!actual.contains(expected)) {
+ fail("expected substring '" + expected + "' not found within: '" + result + "'");
+ }
+ }
+
protected void expectNumber(double expected, String script) throws Exception {
Object result = eval(script);
double actual = 0;
diff --git a/jooc/src/test/java/net/jangaroo/test/integration/JooTest.java b/jooc/src/test/java/net/jangaroo/test/integration/JooTest.java
index 1fffa49d4..f4a90ed41 100644
--- a/jooc/src/test/java/net/jangaroo/test/integration/JooTest.java
+++ b/jooc/src/test/java/net/jangaroo/test/integration/JooTest.java
@@ -15,6 +15,8 @@
package net.jangaroo.test.integration;
+import java.io.File;
+
/**
* Some basic test cases for JangarooScript compiler and runtime correctness.
*
@@ -36,6 +38,29 @@ public void testIdentityMethod() throws Exception {
expectNumber(43, "obj.m(43)");
}
+ public void testAssert() throws Exception {
+ String qualifiedName = "package1.TestAssert";
+ String asFileName = asFileName(qualifiedName);
+ String jsFileName = jsFileName(qualifiedName);
+ loadClass(qualifiedName);
+
+ String canonicalJsFileName = new File(jsFileName).getCanonicalPath();
+ boolean assertionsEnabled = canonicalJsFileName.contains(File.separatorChar + "debug-and-assert" + File.separatorChar);
+
+ final String script = qualifiedName + ".testAssert()";
+ System.out.println("\ncanonicalJsFileName: " + canonicalJsFileName);
+ System.out.println("\nassertions enabled: " + assertionsEnabled);
+
+ if (!assertionsEnabled) {
+ expectString("no exception thrown", script);
+ } else {
+ int line = 30;
+ int column = 9;
+ String expectedErrorMsgTail = asFileName + "(" + line + ":" + column + "): assertion failed";
+ expectSubstring(expectedErrorMsgTail, qualifiedName + ".testAssert()");
+ }
+ }
+
public void testInheritance() throws Exception {
loadClass("package1.TestInheritanceSuperClass");
loadClass("package1.TestInheritanceSubClass");
diff --git a/jooc/src/test/joo/package1/TestAssert.as b/jooc/src/test/joo/package1/TestAssert.as
new file mode 100644
index 000000000..8ca3c8a21
--- /dev/null
+++ b/jooc/src/test/joo/package1/TestAssert.as
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2008 CoreMedia AG
+ *
+ * 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 package1 /*blubber*/ {
+
+/**
+* a comment
+*/
+public class TestAssert {
+
+ public function TestAssert() {
+ }
+
+ static public function testAssert() :String {
+ try {
+ assert(1 < 2);
+ try {
+ assert(2 < 1);
+ return "no exception thrown";
+ } catch(ex) {
+ return ex.message;
+ }
+ } catch(ex) {
+ return ex.message;
+ }
+ }
+
+}
+}
\ No newline at end of file
diff --git a/maven-plugin/src/main/java/net/jangaroo/jooc/mvnplugin/AbstractCompilerMojo.java b/maven-plugin/src/main/java/net/jangaroo/jooc/mvnplugin/AbstractCompilerMojo.java
index 8027b7cab..dc6ff2546 100644
--- a/maven-plugin/src/main/java/net/jangaroo/jooc/mvnplugin/AbstractCompilerMojo.java
+++ b/maven-plugin/src/main/java/net/jangaroo/jooc/mvnplugin/AbstractCompilerMojo.java
@@ -36,6 +36,12 @@ public abstract class AbstractCompilerMojo extends AbstractMojo {
* @parameter expression="${maven.compile.debug}" default-value="true"
*/
private boolean debug;
+ /**
+ * Set "enableAssertions" to "true" in order to generate runtime checks for assert statements.
+ *
+ * @parameter expression="${maven.compile.ea}" default-value="false"
+ */
+ private boolean enableAssertions;
/**
* If set to "true", the compiler will generate more detailed progress information.
* @parameter expression="${maven.compiler.verbose}" default-value="false"
@@ -88,6 +94,7 @@ public void execute() throws MojoExecutionException, MojoFailureException {
JoocConfiguration configuration = new JoocConfiguration();
configuration.setDebug(debug);
+ configuration.setEnableAssertions(enableAssertions);
configuration.setVerbose(verbose);
configuration.setOutputDirectory(getOutputDirectory());
|
bc6ad67d673dfdebd216b021193f736dcf5a76f8
|
hbase
|
HBASE-1386 NPE in housekeeping--git-svn-id: https://svn.apache.org/repos/asf/hadoop/hbase/trunk@772703 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/CHANGES.txt b/CHANGES.txt
index 537c12dea555..254a4e31494d 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -115,6 +115,7 @@ Release 0.20.0 - Unreleased
HBASE-1377 RS address is null in master web UI
HBASE-1344 WARN IllegalStateException: Cannot set a region as open if it has
not been pending
+ HBASE-1386 NPE in housekeeping
IMPROVEMENTS
HBASE-1089 Add count of regions on filesystem to master UI; add percentage
diff --git a/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java b/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
index 656c395d81ae..9f6b1db91e1b 100644
--- a/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
+++ b/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
@@ -1124,6 +1124,7 @@ private boolean isHealthy() {
}
return true;
}
+
/*
* Run some housekeeping tasks before we go into 'hibernation' sleeping at
* the end of the main HRegionServer run loop.
@@ -1132,12 +1133,16 @@ private void housekeeping() {
// 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) {
+ if (this.toDo.isEmpty()) {
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) {
+ HMsg msg = e.msg;
+ if (msg == null) {
+ LOG.warn("Message is empty: " + e);
+ }
if (e.msg.isType(HMsg.Type.MSG_REGION_OPEN)) {
addProcessingMessage(e.msg.getRegionInfo());
}
@@ -1299,15 +1304,16 @@ void reportSplit(HRegionInfo oldRegion, HRegionInfo newRegionA,
/*
* Data structure to hold a HMsg and retries count.
*/
- private static class ToDoEntry {
- protected int tries;
+ private static final class ToDoEntry {
+ protected volatile int tries;
protected final HMsg msg;
- ToDoEntry(HMsg msg) {
+
+ ToDoEntry(final HMsg msg) {
this.tries = 0;
this.msg = msg;
}
}
-
+
final BlockingQueue<ToDoEntry> toDo = new LinkedBlockingQueue<ToDoEntry>();
private Worker worker;
private Thread workerThread;
|
2a52decbbc8391f97ae443bb63032048ce2ae6c3
|
spring-framework
|
Polishing (including removal of javadoc imports- that show as package cycles in IntelliJ)--
|
p
|
https://github.com/spring-projects/spring-framework
|
diff --git a/spring-context/src/main/java/org/springframework/scheduling/config/CronTask.java b/spring-context/src/main/java/org/springframework/scheduling/config/CronTask.java
index cf859ab42739..b00b48060e84 100644
--- a/spring-context/src/main/java/org/springframework/scheduling/config/CronTask.java
+++ b/spring-context/src/main/java/org/springframework/scheduling/config/CronTask.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,7 +16,6 @@
package org.springframework.scheduling.config;
-import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.support.CronTrigger;
/**
@@ -26,13 +25,13 @@
*
* @author Chris Beams
* @since 3.2
- * @see Scheduled#cron()
+ * @see org.springframework.scheduling.annotation.Scheduled#cron()
* @see ScheduledTaskRegistrar#setCronTasksList(java.util.List)
* @see org.springframework.scheduling.TaskScheduler
*/
public class CronTask extends TriggerTask {
- private String expression;
+ private final String expression;
/**
@@ -54,7 +53,9 @@ public CronTask(Runnable runnable, CronTrigger cronTrigger) {
this.expression = cronTrigger.getExpression();
}
+
public String getExpression() {
- return expression;
+ return this.expression;
}
+
}
diff --git a/spring-test/src/main/java/org/springframework/test/util/XmlExpectationsHelper.java b/spring-test/src/main/java/org/springframework/test/util/XmlExpectationsHelper.java
index 744a6cd2b9e6..44dccafe90fc 100644
--- a/spring-test/src/main/java/org/springframework/test/util/XmlExpectationsHelper.java
+++ b/spring-test/src/main/java/org/springframework/test/util/XmlExpectationsHelper.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,11 +16,8 @@
package org.springframework.test.util;
-import static org.springframework.test.util.MatcherAssertionErrors.assertThat;
-
import java.io.StringReader;
import java.util.Map;
-
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
@@ -29,11 +26,12 @@
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.XMLUnit;
import org.hamcrest.Matcher;
-import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
+import static org.springframework.test.util.MatcherAssertionErrors.*;
+
/**
* A helper class for assertions on XML content.
*
@@ -73,15 +71,12 @@ public void assertSource(String content, Matcher<? super Source> matcher) throws
* Parse the expected and actual content strings as XML and assert that the
* two are "similar" -- i.e. they contain the same elements and attributes
* regardless of order.
- *
* <p>Use of this method assumes the
* <a href="http://xmlunit.sourceforge.net/">XMLUnit<a/> library is available.
- *
* @param expected the expected XML content
* @param actual the actual XML content
- *
- * @see MockMvcResultMatchers#xpath(String, Object...)
- * @see MockMvcResultMatchers#xpath(String, Map, Object...)
+ * @see org.springframework.test.web.servlet.result.MockMvcResultMatchers#xpath(String, Object...)
+ * @see org.springframework.test.web.servlet.result.MockMvcResultMatchers#xpath(String, Map, Object...)
*/
public void assertXmlEqual(String expected, String actual) throws Exception {
diff --git a/spring-tx/src/main/java/org/springframework/transaction/config/TransactionManagementConfigUtils.java b/spring-tx/src/main/java/org/springframework/transaction/config/TransactionManagementConfigUtils.java
index 744a57ebf025..c680c27f7e30 100644
--- a/spring-tx/src/main/java/org/springframework/transaction/config/TransactionManagementConfigUtils.java
+++ b/spring-tx/src/main/java/org/springframework/transaction/config/TransactionManagementConfigUtils.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2011 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,10 @@
package org.springframework.transaction.config;
+/**
+ * @author Chris Beams
+ * @since 3.1
+ */
public abstract class TransactionManagementConfigUtils {
/**
diff --git a/spring-web/src/main/java/org/springframework/http/converter/support/AllEncompassingFormHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/support/AllEncompassingFormHttpMessageConverter.java
index 438b88a4b6e8..ec1173d73fcb 100644
--- a/spring-web/src/main/java/org/springframework/http/converter/support/AllEncompassingFormHttpMessageConverter.java
+++ b/spring-web/src/main/java/org/springframework/http/converter/support/AllEncompassingFormHttpMessageConverter.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,6 +32,9 @@
*/
public class AllEncompassingFormHttpMessageConverter extends FormHttpMessageConverter {
+ private static final boolean jaxb2Present =
+ ClassUtils.isPresent("javax.xml.bind.Binder", AllEncompassingFormHttpMessageConverter.class.getClassLoader());
+
private static final boolean jackson2Present =
ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", AllEncompassingFormHttpMessageConverter.class.getClassLoader()) &&
ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", AllEncompassingFormHttpMessageConverter.class.getClassLoader());
@@ -40,9 +43,6 @@ public class AllEncompassingFormHttpMessageConverter extends FormHttpMessageConv
ClassUtils.isPresent("org.codehaus.jackson.map.ObjectMapper", AllEncompassingFormHttpMessageConverter.class.getClassLoader()) &&
ClassUtils.isPresent("org.codehaus.jackson.JsonGenerator", AllEncompassingFormHttpMessageConverter.class.getClassLoader());
- private static final boolean jaxb2Present =
- ClassUtils.isPresent("javax.xml.bind.Binder", AllEncompassingFormHttpMessageConverter.class.getClassLoader());
-
@SuppressWarnings("deprecation")
public AllEncompassingFormHttpMessageConverter() {
diff --git a/spring-web/src/main/java/org/springframework/http/converter/xml/XmlAwareFormHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/xml/XmlAwareFormHttpMessageConverter.java
index e534359a6cb8..5f0f6fc308f8 100644
--- a/spring-web/src/main/java/org/springframework/http/converter/xml/XmlAwareFormHttpMessageConverter.java
+++ b/spring-web/src/main/java/org/springframework/http/converter/xml/XmlAwareFormHttpMessageConverter.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,7 +19,6 @@
import javax.xml.transform.Source;
import org.springframework.http.converter.FormHttpMessageConverter;
-import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
/**
* Extension of {@link org.springframework.http.converter.FormHttpMessageConverter},
@@ -27,7 +26,8 @@
*
* @author Juergen Hoeller
* @since 3.0.3
- * @deprecated in favor of {@link AllEncompassingFormHttpMessageConverter}
+ * @deprecated in favor of
+ * {@link org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter}
*/
@Deprecated
public class XmlAwareFormHttpMessageConverter extends FormHttpMessageConverter {
diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/support/WebContentGenerator.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/WebContentGenerator.java
index e0ec640619c0..7b67dc163a31 100644
--- a/spring-webmvc/src/main/java/org/springframework/web/servlet/support/WebContentGenerator.java
+++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/WebContentGenerator.java
@@ -28,7 +28,6 @@
import org.springframework.web.HttpSessionRequiredException;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.support.WebApplicationObjectSupport;
-import org.springframework.web.servlet.mvc.LastModified;
/**
* Convenient superclass for any kind of web content generator,
@@ -204,7 +203,7 @@ public final boolean isUseCacheControlNoStore() {
* programmatically do a lastModified calculation as described in
* {@link WebRequest#checkNotModified(long)}. Default is "false",
* effectively relying on whether the handler implements
- * {@link LastModified} or not.
+ * {@link org.springframework.web.servlet.mvc.LastModified} or not.
*/
public void setAlwaysMustRevalidate(boolean mustRevalidate) {
this.alwaysMustRevalidate = mustRevalidate;
diff --git a/spring-webmvc/src/main/resources/META-INF/spring.handlers b/spring-webmvc/src/main/resources/META-INF/spring.handlers
index b92dfeebba72..565c2c2c7671 100644
--- a/spring-webmvc/src/main/resources/META-INF/spring.handlers
+++ b/spring-webmvc/src/main/resources/META-INF/spring.handlers
@@ -1 +1 @@
-http\://www.springframework.org/schema/mvc=org.springframework.web.servlet.config.MvcNamespaceHandler
\ No newline at end of file
+http\://www.springframework.org/schema/mvc=org.springframework.web.servlet.config.MvcNamespaceHandler
|
de9c73d84625565731b5b92f0534ca1a09b032df
|
Delta Spike
|
DELTASPIKE-157 log Test Class for @Deployment
|
c
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/test-utils/src/main/java/org/apache/deltaspike/test/utils/ShrinkWrapArchiveUtil.java b/deltaspike/test-utils/src/main/java/org/apache/deltaspike/test/utils/ShrinkWrapArchiveUtil.java
index edece79cf..8e445f6f7 100644
--- a/deltaspike/test-utils/src/main/java/org/apache/deltaspike/test/utils/ShrinkWrapArchiveUtil.java
+++ b/deltaspike/test-utils/src/main/java/org/apache/deltaspike/test/utils/ShrinkWrapArchiveUtil.java
@@ -45,6 +45,7 @@
public class ShrinkWrapArchiveUtil
{
private static final Logger LOG = Logger.getLogger(ShrinkWrapArchiveUtil.class.getName());
+ private static String testName;
private ShrinkWrapArchiveUtil()
{
@@ -54,8 +55,9 @@ private ShrinkWrapArchiveUtil()
/**
* Resolve all markerFiles from the current ClassPath and package the root nodes
* into a JavaArchive.
- * @param classLoader to use
- * @param markerFile finding this marker file will trigger creating the JavaArchive.
+ *
+ * @param classLoader to use
+ * @param markerFile finding this marker file will trigger creating the JavaArchive.
* @param includeIfPackageExists if not null, we will only create JavaArchives if the given package exists
* @param excludeIfPackageExists if not null, we will <b>not</b> create JavaArchives if the given package exists.
* This has a higher precedence than includeIfPackageExists.
@@ -85,7 +87,8 @@ public static JavaArchive[] getArchives(ClassLoader classLoader,
= createArchive(foundFile, markerFile, includeIfPackageExists, excludeIfPackageExists);
if (archive != null)
{
- LOG.info("Adding Java ClassPath URL as JavaArchive " + foundFile.toExternalForm());
+ LOG.info("Test " + getTestName()
+ + " Adding Java ClassPath URL as JavaArchive " + foundFile.toExternalForm());
archives.add(archive);
}
}
@@ -366,4 +369,19 @@ private static String pathToClassName(String pathName)
}
+ public static String getTestName()
+ {
+ StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
+ String testName = "unknown";
+ for (StackTraceElement ste : stackTraceElements)
+ {
+ if (ste.getClassName().contains("Test"))
+ {
+ testName = ste.getClassName();
+ break;
+ }
+ }
+
+ return testName;
+ }
}
|
a2cdf208dd53a77eeb2a87ffe9a71fd19d8fd164
|
hadoop
|
YARN-1757. NM Recovery. Auxiliary service support.- (Jason Lowe via kasha)--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1585784 13f79535-47bb-0310-9956-ffa450edef68-
|
a
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index 835500278cbd3..7589cfc4a2d8d 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -6,6 +6,8 @@ Release 2.5.0 - UNRELEASED
NEW FEATURES
+ YARN-1757. NM Recovery. Auxiliary service support. (Jason Lowe via kasha)
+
IMPROVEMENTS
YARN-1479. Invalid NaN values in Hadoop REST API JSON response (Chen He via
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java
index f7d6b6ba97e7b..0a11948fc23f9 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java
@@ -884,6 +884,13 @@ public class YarnConfiguration extends Configuration {
public static final String DEFAULT_NM_USER_HOME_DIR= "/home/";
+ public static final String NM_RECOVERY_PREFIX = NM_PREFIX + "recovery.";
+ public static final String NM_RECOVERY_ENABLED =
+ NM_RECOVERY_PREFIX + "enabled";
+ public static final boolean DEFAULT_NM_RECOVERY_ENABLED = false;
+
+ public static final String NM_RECOVERY_DIR = NM_RECOVERY_PREFIX + "dir";
+
////////////////////////////////
// Web Proxy Configs
////////////////////////////////
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/server/api/AuxiliaryService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/server/api/AuxiliaryService.java
index 58b06e274a8a5..58b1d4a61a317 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/server/api/AuxiliaryService.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/server/api/AuxiliaryService.java
@@ -22,6 +22,7 @@
import org.apache.hadoop.classification.InterfaceAudience.Public;
import org.apache.hadoop.classification.InterfaceStability.Evolving;
+import org.apache.hadoop.fs.Path;
import org.apache.hadoop.service.AbstractService;
import org.apache.hadoop.yarn.api.ContainerManagementProtocol;
import org.apache.hadoop.yarn.api.protocolrecords.StartContainersRequest;
@@ -38,10 +39,21 @@
@Evolving
public abstract class AuxiliaryService extends AbstractService {
+ private Path recoveryPath = null;
+
protected AuxiliaryService(String name) {
super(name);
}
+ /**
+ * Get the path specific to this auxiliary service to use for recovery.
+ *
+ * @return state storage path or null if recovery is not enabled
+ */
+ protected Path getRecoveryPath() {
+ return recoveryPath;
+ }
+
/**
* A new application is started on this NodeManager. This is a signal to
* this {@link AuxiliaryService} about the application initialization.
@@ -102,4 +114,13 @@ public void initializeContainer(ContainerInitializationContext
public void stopContainer(ContainerTerminationContext stopContainerContext) {
}
+ /**
+ * Set the path for this auxiliary service to use for storing state
+ * that will be used during recovery.
+ *
+ * @param recoveryPath where recoverable state should be stored
+ */
+ public void setRecoveryPath(Path recoveryPath) {
+ this.recoveryPath = recoveryPath;
+ }
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/resources/yarn-default.xml b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/resources/yarn-default.xml
index 325c7a166d54a..4a9b03af8971f 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/resources/yarn-default.xml
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/resources/yarn-default.xml
@@ -1019,6 +1019,19 @@
<value>500</value>
</property>
+ <property>
+ <description>Enable the node manager to recover after starting</description>
+ <name>yarn.nodemanager.recovery.enabled</name>
+ <value>false</value>
+ </property>
+
+ <property>
+ <description>The local filesystem directory in which the node manager will
+ store state when recovery is enabled.</description>
+ <name>yarn.nodemanager.recovery.dir</name>
+ <value>${hadoop.tmp.dir}/yarn-nm-recovery</value>
+ </property>
+
<!--Map Reduce configuration-->
<property>
<name>yarn.nodemanager.aux-services.mapreduce_shuffle.class</name>
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeManager.java
index 9688290acd7c4..57ff127dbaa8d 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeManager.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeManager.java
@@ -28,6 +28,9 @@
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.service.CompositeService;
@@ -127,6 +130,20 @@ protected void serviceInit(Configuration conf) throws Exception {
conf.setBoolean(Dispatcher.DISPATCHER_EXIT_ON_ERROR_KEY, true);
+ boolean recoveryEnabled = conf.getBoolean(
+ YarnConfiguration.NM_RECOVERY_ENABLED,
+ YarnConfiguration.DEFAULT_NM_RECOVERY_ENABLED);
+ if (recoveryEnabled) {
+ FileSystem recoveryFs = FileSystem.getLocal(conf);
+ String recoveryDirName = conf.get(YarnConfiguration.NM_RECOVERY_DIR);
+ if (recoveryDirName == null) {
+ throw new IllegalArgumentException("Recovery is enabled but " +
+ YarnConfiguration.NM_RECOVERY_DIR + " is not set.");
+ }
+ Path recoveryRoot = new Path(recoveryDirName);
+ recoveryFs.mkdirs(recoveryRoot, new FsPermission((short)0700));
+ }
+
NMContainerTokenSecretManager containerTokenSecretManager =
new NMContainerTokenSecretManager(conf);
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/AuxServices.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/AuxServices.java
index 5fe5b141bc00d..bf026796bf4ad 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/AuxServices.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/AuxServices.java
@@ -29,15 +29,18 @@
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.fs.permission.FsPermission;
import org.apache.hadoop.service.AbstractService;
import org.apache.hadoop.service.Service;
import org.apache.hadoop.service.ServiceStateChangeListener;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.event.EventHandler;
+import org.apache.hadoop.yarn.server.api.ApplicationInitializationContext;
import org.apache.hadoop.yarn.server.api.ApplicationTerminationContext;
import org.apache.hadoop.yarn.server.api.AuxiliaryService;
-import org.apache.hadoop.yarn.server.api.ApplicationInitializationContext;
import org.apache.hadoop.yarn.server.api.ContainerInitializationContext;
import org.apache.hadoop.yarn.server.api.ContainerTerminationContext;
@@ -46,6 +49,8 @@
public class AuxServices extends AbstractService
implements ServiceStateChangeListener, EventHandler<AuxServicesEvent> {
+ static final String STATE_STORE_ROOT_NAME = "nm-aux-services";
+
private static final Log LOG = LogFactory.getLog(AuxServices.class);
protected final Map<String,AuxiliaryService> serviceMap;
@@ -91,6 +96,17 @@ public Map<String, ByteBuffer> getMetaData() {
@Override
public void serviceInit(Configuration conf) throws Exception {
+ final FsPermission storeDirPerms = new FsPermission((short)0700);
+ Path stateStoreRoot = null;
+ FileSystem stateStoreFs = null;
+ boolean recoveryEnabled = conf.getBoolean(
+ YarnConfiguration.NM_RECOVERY_ENABLED,
+ YarnConfiguration.DEFAULT_NM_RECOVERY_ENABLED);
+ if (recoveryEnabled) {
+ stateStoreRoot = new Path(conf.get(YarnConfiguration.NM_RECOVERY_DIR),
+ STATE_STORE_ROOT_NAME);
+ stateStoreFs = FileSystem.getLocal(conf);
+ }
Collection<String> auxNames = conf.getStringCollection(
YarnConfiguration.NM_AUX_SERVICES);
for (final String sName : auxNames) {
@@ -119,6 +135,11 @@ public void serviceInit(Configuration conf) throws Exception {
+"the name in the config.");
}
addService(sName, s);
+ if (recoveryEnabled) {
+ Path storePath = new Path(stateStoreRoot, sName);
+ stateStoreFs.mkdirs(storePath, storeDirPerms);
+ s.setRecoveryPath(storePath);
+ }
s.init(conf);
} catch (RuntimeException e) {
LOG.fatal("Failed to initialize " + sName, e);
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestAuxServices.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestAuxServices.java
index e14fddf00f235..b464dcc06f0ab 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestAuxServices.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestAuxServices.java
@@ -26,6 +26,8 @@
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import java.io.File;
+import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
@@ -36,6 +38,10 @@
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.FileUtil;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.service.Service;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.ApplicationId;
@@ -56,6 +62,10 @@
public class TestAuxServices {
private static final Log LOG = LogFactory.getLog(TestAuxServices.class);
+ private static final File TEST_DIR = new File(
+ System.getProperty("test.build.data",
+ System.getProperty("java.io.tmpdir")),
+ TestAuxServices.class.getName());
static class LightService extends AuxiliaryService implements Service
{
@@ -319,4 +329,81 @@ public void testValidAuxServiceName() {
"should only contain a-zA-Z0-9_ and can not start with numbers"));
}
}
+
+ @Test
+ public void testAuxServiceRecoverySetup() throws IOException {
+ Configuration conf = new YarnConfiguration();
+ conf.setBoolean(YarnConfiguration.NM_RECOVERY_ENABLED, true);
+ conf.set(YarnConfiguration.NM_RECOVERY_DIR, TEST_DIR.toString());
+ conf.setStrings(YarnConfiguration.NM_AUX_SERVICES,
+ new String[] { "Asrv", "Bsrv" });
+ conf.setClass(String.format(YarnConfiguration.NM_AUX_SERVICE_FMT, "Asrv"),
+ RecoverableServiceA.class, Service.class);
+ conf.setClass(String.format(YarnConfiguration.NM_AUX_SERVICE_FMT, "Bsrv"),
+ RecoverableServiceB.class, Service.class);
+ try {
+ final AuxServices aux = new AuxServices();
+ aux.init(conf);
+ Assert.assertEquals(2, aux.getServices().size());
+ File auxStorageDir = new File(TEST_DIR,
+ AuxServices.STATE_STORE_ROOT_NAME);
+ Assert.assertEquals(2, auxStorageDir.listFiles().length);
+ aux.close();
+ } finally {
+ FileUtil.fullyDelete(TEST_DIR);
+ }
+ }
+
+ static class RecoverableAuxService extends AuxiliaryService {
+ static final FsPermission RECOVERY_PATH_PERMS =
+ new FsPermission((short)0700);
+
+ String auxName;
+
+ RecoverableAuxService(String name, String auxName) {
+ super(name);
+ this.auxName = auxName;
+ }
+
+ @Override
+ protected void serviceInit(Configuration conf) throws Exception {
+ super.serviceInit(conf);
+ Path storagePath = getRecoveryPath();
+ Assert.assertNotNull("Recovery path not present when aux service inits",
+ storagePath);
+ Assert.assertTrue(storagePath.toString().contains(auxName));
+ FileSystem fs = FileSystem.getLocal(conf);
+ Assert.assertTrue("Recovery path does not exist",
+ fs.exists(storagePath));
+ Assert.assertEquals("Recovery path has wrong permissions",
+ new FsPermission((short)0700),
+ fs.getFileStatus(storagePath).getPermission());
+ }
+
+ @Override
+ public void initializeApplication(
+ ApplicationInitializationContext initAppContext) {
+ }
+
+ @Override
+ public void stopApplication(ApplicationTerminationContext stopAppContext) {
+ }
+
+ @Override
+ public ByteBuffer getMetaData() {
+ return null;
+ }
+ }
+
+ static class RecoverableServiceA extends RecoverableAuxService {
+ RecoverableServiceA() {
+ super("RecoverableServiceA", "Asrv");
+ }
+ }
+
+ static class RecoverableServiceB extends RecoverableAuxService {
+ RecoverableServiceB() {
+ super("RecoverableServiceB", "Bsrv");
+ }
+ }
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.