gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
/*
* 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.commons.lang3;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Arrays;
import org.junit.Test;
/**
* Tests ArrayUtils add methods.
*/
public class ArrayUtilsAddTest {
@Test
public void testJira567(){
Number[] n;
// Valid array construction
n = ArrayUtils.addAll(new Number[]{Integer.valueOf(1)}, new Long[]{Long.valueOf(2)});
assertEquals(2,n.length);
assertEquals(Number.class,n.getClass().getComponentType());
try {
// Invalid - can't store Long in Integer array
n = ArrayUtils.addAll(new Integer[]{Integer.valueOf(1)}, new Long[]{Long.valueOf(2)});
fail("Should have generated IllegalArgumentException");
} catch (final IllegalArgumentException expected) {
}
}
@Test
public void testAddObjectArrayBoolean() {
boolean[] newArray;
newArray = ArrayUtils.add(null, false);
assertTrue(Arrays.equals(new boolean[]{false}, newArray));
assertEquals(Boolean.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(null, true);
assertTrue(Arrays.equals(new boolean[]{true}, newArray));
assertEquals(Boolean.TYPE, newArray.getClass().getComponentType());
final boolean[] array1 = new boolean[]{true, false, true};
newArray = ArrayUtils.add(array1, false);
assertTrue(Arrays.equals(new boolean[]{true, false, true, false}, newArray));
assertEquals(Boolean.TYPE, newArray.getClass().getComponentType());
}
@Test
public void testAddObjectArrayByte() {
byte[] newArray;
newArray = ArrayUtils.add((byte[])null, (byte)0);
assertTrue(Arrays.equals(new byte[]{0}, newArray));
assertEquals(Byte.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add((byte[])null, (byte)1);
assertTrue(Arrays.equals(new byte[]{1}, newArray));
assertEquals(Byte.TYPE, newArray.getClass().getComponentType());
final byte[] array1 = new byte[]{1, 2, 3};
newArray = ArrayUtils.add(array1, (byte)0);
assertTrue(Arrays.equals(new byte[]{1, 2, 3, 0}, newArray));
assertEquals(Byte.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(array1, (byte)4);
assertTrue(Arrays.equals(new byte[]{1, 2, 3, 4}, newArray));
assertEquals(Byte.TYPE, newArray.getClass().getComponentType());
}
@Test
public void testAddObjectArrayChar() {
char[] newArray;
newArray = ArrayUtils.add((char[])null, (char)0);
assertTrue(Arrays.equals(new char[]{0}, newArray));
assertEquals(Character.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add((char[])null, (char)1);
assertTrue(Arrays.equals(new char[]{1}, newArray));
assertEquals(Character.TYPE, newArray.getClass().getComponentType());
final char[] array1 = new char[]{1, 2, 3};
newArray = ArrayUtils.add(array1, (char)0);
assertTrue(Arrays.equals(new char[]{1, 2, 3, 0}, newArray));
assertEquals(Character.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(array1, (char)4);
assertTrue(Arrays.equals(new char[]{1, 2, 3, 4}, newArray));
assertEquals(Character.TYPE, newArray.getClass().getComponentType());
}
@Test
public void testAddObjectArrayDouble() {
double[] newArray;
newArray = ArrayUtils.add((double[])null, 0);
assertTrue(Arrays.equals(new double[]{0}, newArray));
assertEquals(Double.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add((double[])null, 1);
assertTrue(Arrays.equals(new double[]{1}, newArray));
assertEquals(Double.TYPE, newArray.getClass().getComponentType());
final double[] array1 = new double[]{1, 2, 3};
newArray = ArrayUtils.add(array1, 0);
assertTrue(Arrays.equals(new double[]{1, 2, 3, 0}, newArray));
assertEquals(Double.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(array1, 4);
assertTrue(Arrays.equals(new double[]{1, 2, 3, 4}, newArray));
assertEquals(Double.TYPE, newArray.getClass().getComponentType());
}
@Test
public void testAddObjectArrayFloat() {
float[] newArray;
newArray = ArrayUtils.add((float[])null, 0);
assertTrue(Arrays.equals(new float[]{0}, newArray));
assertEquals(Float.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add((float[])null, 1);
assertTrue(Arrays.equals(new float[]{1}, newArray));
assertEquals(Float.TYPE, newArray.getClass().getComponentType());
final float[] array1 = new float[]{1, 2, 3};
newArray = ArrayUtils.add(array1, 0);
assertTrue(Arrays.equals(new float[]{1, 2, 3, 0}, newArray));
assertEquals(Float.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(array1, 4);
assertTrue(Arrays.equals(new float[]{1, 2, 3, 4}, newArray));
assertEquals(Float.TYPE, newArray.getClass().getComponentType());
}
@Test
public void testAddObjectArrayInt() {
int[] newArray;
newArray = ArrayUtils.add((int[])null, 0);
assertTrue(Arrays.equals(new int[]{0}, newArray));
assertEquals(Integer.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add((int[])null, 1);
assertTrue(Arrays.equals(new int[]{1}, newArray));
assertEquals(Integer.TYPE, newArray.getClass().getComponentType());
final int[] array1 = new int[]{1, 2, 3};
newArray = ArrayUtils.add(array1, 0);
assertTrue(Arrays.equals(new int[]{1, 2, 3, 0}, newArray));
assertEquals(Integer.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(array1, 4);
assertTrue(Arrays.equals(new int[]{1, 2, 3, 4}, newArray));
assertEquals(Integer.TYPE, newArray.getClass().getComponentType());
}
@Test
public void testAddObjectArrayLong() {
long[] newArray;
newArray = ArrayUtils.add((long[])null, 0);
assertTrue(Arrays.equals(new long[]{0}, newArray));
assertEquals(Long.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add((long[])null, 1);
assertTrue(Arrays.equals(new long[]{1}, newArray));
assertEquals(Long.TYPE, newArray.getClass().getComponentType());
final long[] array1 = new long[]{1, 2, 3};
newArray = ArrayUtils.add(array1, 0);
assertTrue(Arrays.equals(new long[]{1, 2, 3, 0}, newArray));
assertEquals(Long.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(array1, 4);
assertTrue(Arrays.equals(new long[]{1, 2, 3, 4}, newArray));
assertEquals(Long.TYPE, newArray.getClass().getComponentType());
}
@Test
public void testAddObjectArrayShort() {
short[] newArray;
newArray = ArrayUtils.add((short[])null, (short)0);
assertTrue(Arrays.equals(new short[]{0}, newArray));
assertEquals(Short.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add((short[])null, (short)1);
assertTrue(Arrays.equals(new short[]{1}, newArray));
assertEquals(Short.TYPE, newArray.getClass().getComponentType());
final short[] array1 = new short[]{1, 2, 3};
newArray = ArrayUtils.add(array1, (short)0);
assertTrue(Arrays.equals(new short[]{1, 2, 3, 0}, newArray));
assertEquals(Short.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(array1, (short)4);
assertTrue(Arrays.equals(new short[]{1, 2, 3, 4}, newArray));
assertEquals(Short.TYPE, newArray.getClass().getComponentType());
}
@Test
public void testAddObjectArrayObject() {
Object[] newArray;
//show that not casting is okay
newArray = ArrayUtils.add((Object[])null, "a");
assertTrue(Arrays.equals(new String[]{"a"}, newArray));
assertTrue(Arrays.equals(new Object[]{"a"}, newArray));
assertEquals(String.class, newArray.getClass().getComponentType());
//show that not casting to Object[] is okay and will assume String based on "a"
final String[] newStringArray = ArrayUtils.add(null, "a");
assertTrue(Arrays.equals(new String[]{"a"}, newStringArray));
assertTrue(Arrays.equals(new Object[]{"a"}, newStringArray));
assertEquals(String.class, newStringArray.getClass().getComponentType());
final String[] stringArray1 = new String[]{"a", "b", "c"};
newArray = ArrayUtils.add(stringArray1, null);
assertTrue(Arrays.equals(new String[]{"a", "b", "c", null}, newArray));
assertEquals(String.class, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(stringArray1, "d");
assertTrue(Arrays.equals(new String[]{"a", "b", "c", "d"}, newArray));
assertEquals(String.class, newArray.getClass().getComponentType());
Number[] numberArray1 = new Number[]{Integer.valueOf(1), Double.valueOf(2)};
newArray = ArrayUtils.add(numberArray1, Float.valueOf(3));
assertTrue(Arrays.equals(new Number[]{Integer.valueOf(1), Double.valueOf(2), Float.valueOf(3)}, newArray));
assertEquals(Number.class, newArray.getClass().getComponentType());
numberArray1 = null;
newArray = ArrayUtils.add(numberArray1, Float.valueOf(3));
assertTrue(Arrays.equals(new Float[]{Float.valueOf(3)}, newArray));
assertEquals(Float.class, newArray.getClass().getComponentType());
}
@Test
public void testLANG571(){
final String[] stringArray=null;
final String aString=null;
try {
@SuppressWarnings("unused")
final
String[] sa = ArrayUtils.add(stringArray, aString);
fail("Should have caused IllegalArgumentException");
} catch (final IllegalArgumentException iae){
//expected
}
try {
@SuppressWarnings({ "unused", "deprecation" })
final
String[] sa = ArrayUtils.add(stringArray, 0, aString);
fail("Should have caused IllegalArgumentException");
} catch (final IllegalArgumentException iae){
//expected
}
}
@Test
public void testAddObjectArrayToObjectArray() {
assertNull(ArrayUtils.addAll(null, (Object[]) null));
Object[] newArray;
final String[] stringArray1 = new String[]{"a", "b", "c"};
final String[] stringArray2 = new String[]{"1", "2", "3"};
newArray = ArrayUtils.addAll(stringArray1, (String[]) null);
assertNotSame(stringArray1, newArray);
assertTrue(Arrays.equals(stringArray1, newArray));
assertTrue(Arrays.equals(new String[]{"a", "b", "c"}, newArray));
assertEquals(String.class, newArray.getClass().getComponentType());
newArray = ArrayUtils.addAll(null, stringArray2);
assertNotSame(stringArray2, newArray);
assertTrue(Arrays.equals(stringArray2, newArray));
assertTrue(Arrays.equals(new String[]{"1", "2", "3"}, newArray));
assertEquals(String.class, newArray.getClass().getComponentType());
newArray = ArrayUtils.addAll(stringArray1, stringArray2);
assertTrue(Arrays.equals(new String[]{"a", "b", "c", "1", "2", "3"}, newArray));
assertEquals(String.class, newArray.getClass().getComponentType());
newArray = ArrayUtils.addAll(ArrayUtils.EMPTY_STRING_ARRAY, (String[]) null);
assertTrue(Arrays.equals(ArrayUtils.EMPTY_STRING_ARRAY, newArray));
assertTrue(Arrays.equals(new String[]{}, newArray));
assertEquals(String.class, newArray.getClass().getComponentType());
newArray = ArrayUtils.addAll(null, ArrayUtils.EMPTY_STRING_ARRAY);
assertTrue(Arrays.equals(ArrayUtils.EMPTY_STRING_ARRAY, newArray));
assertTrue(Arrays.equals(new String[]{}, newArray));
assertEquals(String.class, newArray.getClass().getComponentType());
newArray = ArrayUtils.addAll(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.EMPTY_STRING_ARRAY);
assertTrue(Arrays.equals(ArrayUtils.EMPTY_STRING_ARRAY, newArray));
assertTrue(Arrays.equals(new String[]{}, newArray));
assertEquals(String.class, newArray.getClass().getComponentType());
final String[] stringArrayNull = new String []{null};
newArray = ArrayUtils.addAll(stringArrayNull, stringArrayNull);
assertTrue(Arrays.equals(new String[]{null, null}, newArray));
assertEquals(String.class, newArray.getClass().getComponentType());
// boolean
assertTrue( Arrays.equals( new boolean[] { true, false, false, true },
ArrayUtils.addAll( new boolean[] { true, false }, false, true) ) );
assertTrue( Arrays.equals( new boolean[] { false, true },
ArrayUtils.addAll( null, new boolean[] { false, true } ) ) );
assertTrue( Arrays.equals( new boolean[] { true, false },
ArrayUtils.addAll( new boolean[] { true, false }, null ) ) );
// char
assertTrue( Arrays.equals( new char[] { 'a', 'b', 'c', 'd' },
ArrayUtils.addAll( new char[] { 'a', 'b' }, 'c', 'd') ) );
assertTrue( Arrays.equals( new char[] { 'c', 'd' },
ArrayUtils.addAll( null, new char[] { 'c', 'd' } ) ) );
assertTrue( Arrays.equals( new char[] { 'a', 'b' },
ArrayUtils.addAll( new char[] { 'a', 'b' }, null ) ) );
// byte
assertTrue( Arrays.equals( new byte[] { (byte) 0, (byte) 1, (byte) 2, (byte) 3 },
ArrayUtils.addAll( new byte[] { (byte) 0, (byte) 1 }, (byte) 2, (byte) 3) ) );
assertTrue( Arrays.equals( new byte[] { (byte) 2, (byte) 3 },
ArrayUtils.addAll( null, new byte[] { (byte) 2, (byte) 3 } ) ) );
assertTrue( Arrays.equals( new byte[] { (byte) 0, (byte) 1 },
ArrayUtils.addAll( new byte[] { (byte) 0, (byte) 1 }, null ) ) );
// short
assertTrue( Arrays.equals( new short[] { (short) 10, (short) 20, (short) 30, (short) 40 },
ArrayUtils.addAll( new short[] { (short) 10, (short) 20 }, (short) 30, (short) 40) ) );
assertTrue( Arrays.equals( new short[] { (short) 30, (short) 40 },
ArrayUtils.addAll( null, new short[] { (short) 30, (short) 40 } ) ) );
assertTrue( Arrays.equals( new short[] { (short) 10, (short) 20 },
ArrayUtils.addAll( new short[] { (short) 10, (short) 20 }, null ) ) );
// int
assertTrue( Arrays.equals( new int[] { 1, 1000, -1000, -1 },
ArrayUtils.addAll( new int[] { 1, 1000 }, -1000, -1) ) );
assertTrue( Arrays.equals( new int[] { -1000, -1 },
ArrayUtils.addAll( null, new int[] { -1000, -1 } ) ) );
assertTrue( Arrays.equals( new int[] { 1, 1000 },
ArrayUtils.addAll( new int[] { 1, 1000 }, null ) ) );
// long
assertTrue( Arrays.equals( new long[] { 1L, -1L, 1000L, -1000L },
ArrayUtils.addAll( new long[] { 1L, -1L }, 1000L, -1000L) ) );
assertTrue( Arrays.equals( new long[] { 1000L, -1000L },
ArrayUtils.addAll( null, new long[] { 1000L, -1000L } ) ) );
assertTrue( Arrays.equals( new long[] { 1L, -1L },
ArrayUtils.addAll( new long[] { 1L, -1L }, null ) ) );
// float
assertTrue( Arrays.equals( new float[] { 10.5f, 10.1f, 1.6f, 0.01f },
ArrayUtils.addAll( new float[] { 10.5f, 10.1f }, 1.6f, 0.01f) ) );
assertTrue( Arrays.equals( new float[] { 1.6f, 0.01f },
ArrayUtils.addAll( null, new float[] { 1.6f, 0.01f } ) ) );
assertTrue( Arrays.equals( new float[] { 10.5f, 10.1f },
ArrayUtils.addAll( new float[] { 10.5f, 10.1f }, null ) ) );
// double
assertTrue( Arrays.equals( new double[] { Math.PI, -Math.PI, 0, 9.99 },
ArrayUtils.addAll( new double[] { Math.PI, -Math.PI }, 0, 9.99) ) );
assertTrue( Arrays.equals( new double[] { 0, 9.99 },
ArrayUtils.addAll( null, new double[] { 0, 9.99 } ) ) );
assertTrue( Arrays.equals( new double[] { Math.PI, -Math.PI },
ArrayUtils.addAll( new double[] { Math.PI, -Math.PI }, null ) ) );
}
@SuppressWarnings("deprecation")
@Test
public void testAddObjectAtIndex() {
Object[] newArray;
newArray = ArrayUtils.add((Object[])null, 0, "a");
assertTrue(Arrays.equals(new String[]{"a"}, newArray));
assertTrue(Arrays.equals(new Object[]{"a"}, newArray));
assertEquals(String.class, newArray.getClass().getComponentType());
final String[] stringArray1 = new String[]{"a", "b", "c"};
newArray = ArrayUtils.add(stringArray1, 0, null);
assertTrue(Arrays.equals(new String[]{null, "a", "b", "c"}, newArray));
assertEquals(String.class, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(stringArray1, 1, null);
assertTrue(Arrays.equals(new String[]{"a", null, "b", "c"}, newArray));
assertEquals(String.class, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(stringArray1, 3, null);
assertTrue(Arrays.equals(new String[]{"a", "b", "c", null}, newArray));
assertEquals(String.class, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(stringArray1, 3, "d");
assertTrue(Arrays.equals(new String[]{"a", "b", "c", "d"}, newArray));
assertEquals(String.class, newArray.getClass().getComponentType());
assertEquals(String.class, newArray.getClass().getComponentType());
final Object[] o = new Object[] {"1", "2", "4"};
final Object[] result = ArrayUtils.add(o, 2, "3");
final Object[] result2 = ArrayUtils.add(o, 3, "5");
assertNotNull(result);
assertEquals(4, result.length);
assertEquals("1", result[0]);
assertEquals("2", result[1]);
assertEquals("3", result[2]);
assertEquals("4", result[3]);
assertNotNull(result2);
assertEquals(4, result2.length);
assertEquals("1", result2[0]);
assertEquals("2", result2[1]);
assertEquals("4", result2[2]);
assertEquals("5", result2[3]);
// boolean tests
boolean[] booleanArray = ArrayUtils.add( null, 0, true );
assertTrue( Arrays.equals( new boolean[] { true }, booleanArray ) );
try {
booleanArray = ArrayUtils.add( null, -1, true );
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 0", e.getMessage());
}
booleanArray = ArrayUtils.add( new boolean[] { true }, 0, false);
assertTrue( Arrays.equals( new boolean[] { false, true }, booleanArray ) );
booleanArray = ArrayUtils.add( new boolean[] { false }, 1, true);
assertTrue( Arrays.equals( new boolean[] { false, true }, booleanArray ) );
booleanArray = ArrayUtils.add( new boolean[] { true, false }, 1, true);
assertTrue( Arrays.equals( new boolean[] { true, true, false }, booleanArray ) );
try {
booleanArray = ArrayUtils.add( new boolean[] { true, false }, 4, true);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: 4, Length: 2", e.getMessage());
}
try {
booleanArray = ArrayUtils.add( new boolean[] { true, false }, -1, true);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 2", e.getMessage());
}
// char tests
char[] charArray = ArrayUtils.add( (char[]) null, 0, 'a' );
assertTrue( Arrays.equals( new char[] { 'a' }, charArray ) );
try {
charArray = ArrayUtils.add( (char[]) null, -1, 'a' );
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 0", e.getMessage());
}
charArray = ArrayUtils.add( new char[] { 'a' }, 0, 'b');
assertTrue( Arrays.equals( new char[] { 'b', 'a' }, charArray ) );
charArray = ArrayUtils.add( new char[] { 'a', 'b' }, 0, 'c');
assertTrue( Arrays.equals( new char[] { 'c', 'a', 'b' }, charArray ) );
charArray = ArrayUtils.add( new char[] { 'a', 'b' }, 1, 'k');
assertTrue( Arrays.equals( new char[] { 'a', 'k', 'b' }, charArray ) );
charArray = ArrayUtils.add( new char[] { 'a', 'b', 'c' }, 1, 't');
assertTrue( Arrays.equals( new char[] { 'a', 't', 'b', 'c' }, charArray ) );
try {
charArray = ArrayUtils.add( new char[] { 'a', 'b' }, 4, 'c');
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: 4, Length: 2", e.getMessage());
}
try {
charArray = ArrayUtils.add( new char[] { 'a', 'b' }, -1, 'c');
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 2", e.getMessage());
}
// short tests
short[] shortArray = ArrayUtils.add( new short[] { 1 }, 0, (short) 2);
assertTrue( Arrays.equals( new short[] { 2, 1 }, shortArray ) );
try {
shortArray = ArrayUtils.add( (short[]) null, -1, (short) 2);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 0", e.getMessage());
}
shortArray = ArrayUtils.add( new short[] { 2, 6 }, 2, (short) 10);
assertTrue( Arrays.equals( new short[] { 2, 6, 10 }, shortArray ) );
shortArray = ArrayUtils.add( new short[] { 2, 6 }, 0, (short) -4);
assertTrue( Arrays.equals( new short[] { -4, 2, 6 }, shortArray ) );
shortArray = ArrayUtils.add( new short[] { 2, 6, 3 }, 2, (short) 1);
assertTrue( Arrays.equals( new short[] { 2, 6, 1, 3 }, shortArray ) );
try {
shortArray = ArrayUtils.add( new short[] { 2, 6 }, 4, (short) 10);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: 4, Length: 2", e.getMessage());
}
try {
shortArray = ArrayUtils.add( new short[] { 2, 6 }, -1, (short) 10);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 2", e.getMessage());
}
// byte tests
byte[] byteArray = ArrayUtils.add( new byte[] { 1 }, 0, (byte) 2);
assertTrue( Arrays.equals( new byte[] { 2, 1 }, byteArray ) );
try {
byteArray = ArrayUtils.add( (byte[]) null, -1, (byte) 2);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 0", e.getMessage());
}
byteArray = ArrayUtils.add( new byte[] { 2, 6 }, 2, (byte) 3);
assertTrue( Arrays.equals( new byte[] { 2, 6, 3 }, byteArray ) );
byteArray = ArrayUtils.add( new byte[] { 2, 6 }, 0, (byte) 1);
assertTrue( Arrays.equals( new byte[] { 1, 2, 6 }, byteArray ) );
byteArray = ArrayUtils.add( new byte[] { 2, 6, 3 }, 2, (byte) 1);
assertTrue( Arrays.equals( new byte[] { 2, 6, 1, 3 }, byteArray ) );
try {
byteArray = ArrayUtils.add( new byte[] { 2, 6 }, 4, (byte) 3);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: 4, Length: 2", e.getMessage());
}
try {
byteArray = ArrayUtils.add( new byte[] { 2, 6 }, -1, (byte) 3);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 2", e.getMessage());
}
// int tests
int[] intArray = ArrayUtils.add( new int[] { 1 }, 0, 2);
assertTrue( Arrays.equals( new int[] { 2, 1 }, intArray ) );
try {
intArray = ArrayUtils.add( (int[]) null, -1, 2);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 0", e.getMessage());
}
intArray = ArrayUtils.add( new int[] { 2, 6 }, 2, 10);
assertTrue( Arrays.equals( new int[] { 2, 6, 10 }, intArray ) );
intArray = ArrayUtils.add( new int[] { 2, 6 }, 0, -4);
assertTrue( Arrays.equals( new int[] { -4, 2, 6 }, intArray ) );
intArray = ArrayUtils.add( new int[] { 2, 6, 3 }, 2, 1);
assertTrue( Arrays.equals( new int[] { 2, 6, 1, 3 }, intArray ) );
try {
intArray = ArrayUtils.add( new int[] { 2, 6 }, 4, 10);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: 4, Length: 2", e.getMessage());
}
try {
intArray = ArrayUtils.add( new int[] { 2, 6 }, -1, 10);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 2", e.getMessage());
}
// long tests
long[] longArray = ArrayUtils.add( new long[] { 1L }, 0, 2L);
assertTrue( Arrays.equals( new long[] { 2L, 1L }, longArray ) );
try {
longArray = ArrayUtils.add( (long[]) null, -1, 2L);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 0", e.getMessage());
}
longArray = ArrayUtils.add( new long[] { 2L, 6L }, 2, 10L);
assertTrue( Arrays.equals( new long[] { 2L, 6L, 10L }, longArray ) );
longArray = ArrayUtils.add( new long[] { 2L, 6L }, 0, -4L);
assertTrue( Arrays.equals( new long[] { -4L, 2L, 6L }, longArray ) );
longArray = ArrayUtils.add( new long[] { 2L, 6L, 3L }, 2, 1L);
assertTrue( Arrays.equals( new long[] { 2L, 6L, 1L, 3L }, longArray ) );
try {
longArray = ArrayUtils.add( new long[] { 2L, 6L }, 4, 10L);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: 4, Length: 2", e.getMessage());
}
try {
longArray = ArrayUtils.add( new long[] { 2L, 6L }, -1, 10L);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 2", e.getMessage());
}
// float tests
float[] floatArray = ArrayUtils.add( new float[] { 1.1f }, 0, 2.2f);
assertTrue( Arrays.equals( new float[] { 2.2f, 1.1f }, floatArray ) );
try {
floatArray = ArrayUtils.add( (float[]) null, -1, 2.2f);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 0", e.getMessage());
}
floatArray = ArrayUtils.add( new float[] { 2.3f, 6.4f }, 2, 10.5f);
assertTrue( Arrays.equals( new float[] { 2.3f, 6.4f, 10.5f }, floatArray ) );
floatArray = ArrayUtils.add( new float[] { 2.6f, 6.7f }, 0, -4.8f);
assertTrue( Arrays.equals( new float[] { -4.8f, 2.6f, 6.7f }, floatArray ) );
floatArray = ArrayUtils.add( new float[] { 2.9f, 6.0f, 0.3f }, 2, 1.0f);
assertTrue( Arrays.equals( new float[] { 2.9f, 6.0f, 1.0f, 0.3f }, floatArray ) );
try {
floatArray = ArrayUtils.add( new float[] { 2.3f, 6.4f }, 4, 10.5f);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: 4, Length: 2", e.getMessage());
}
try {
floatArray = ArrayUtils.add( new float[] { 2.3f, 6.4f }, -1, 10.5f);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 2", e.getMessage());
}
// double tests
double[] doubleArray = ArrayUtils.add( new double[] { 1.1 }, 0, 2.2);
assertTrue( Arrays.equals( new double[] { 2.2, 1.1 }, doubleArray ) );
try {
doubleArray = ArrayUtils.add(null, -1, 2.2);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 0", e.getMessage());
}
doubleArray = ArrayUtils.add( new double[] { 2.3, 6.4 }, 2, 10.5);
assertTrue( Arrays.equals( new double[] { 2.3, 6.4, 10.5 }, doubleArray ) );
doubleArray = ArrayUtils.add( new double[] { 2.6, 6.7 }, 0, -4.8);
assertTrue( Arrays.equals( new double[] { -4.8, 2.6, 6.7 }, doubleArray ) );
doubleArray = ArrayUtils.add( new double[] { 2.9, 6.0, 0.3 }, 2, 1.0);
assertTrue( Arrays.equals( new double[] { 2.9, 6.0, 1.0, 0.3 }, doubleArray ) );
try {
doubleArray = ArrayUtils.add( new double[] { 2.3, 6.4 }, 4, 10.5);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: 4, Length: 2", e.getMessage());
}
try {
doubleArray = ArrayUtils.add( new double[] { 2.3, 6.4 }, -1, 10.5);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 2", e.getMessage());
}
}
}
| |
/*
* Copyright 2008 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.common.base.Preconditions;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSTypeExpression;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
/**
* Prepare the AST before we do any checks or optimizations on it.
*
* This pass must run. It should bring the AST into a consistent state,
* and add annotations where necessary. It should not make any transformations
* on the tree that would lose source information, since we need that source
* information for checks.
*
* @author johnlenz@google.com (John Lenz)
*/
class PrepareAst implements CompilerPass {
private final AbstractCompiler compiler;
private final boolean checkOnly;
PrepareAst(AbstractCompiler compiler) {
this(compiler, false);
}
PrepareAst(AbstractCompiler compiler, boolean checkOnly) {
this.compiler = compiler;
this.checkOnly = checkOnly;
}
private void reportChange() {
if (checkOnly) {
Preconditions.checkState(false, "normalizeNodeType constraints violated");
}
}
@Override
public void process(Node externs, Node root) {
if (checkOnly) {
normalizeNodeTypes(root);
} else {
// Don't perform "PrepareAnnotations" when doing checks as
// they currently aren't valid during sanity checks. In particular,
// they DIRECT_EVAL shouldn't be applied after inlining has been
// performed.
if (externs != null) {
NodeTraversal.traverse(
compiler, externs, new PrepareAnnotations(compiler));
}
if (root != null) {
NodeTraversal.traverse(
compiler, root, new PrepareAnnotations(compiler));
}
}
}
/**
* Covert EXPR_VOID to EXPR_RESULT to simplify the rest of the code.
*/
private void normalizeNodeTypes(Node n) {
if (n.getType() == Token.EXPR_VOID) {
n.setType(Token.EXPR_RESULT);
reportChange();
}
// Remove unused properties to minimize differences between ASTs
// produced by the two parsers.
if (n.getType() == Token.FUNCTION) {
Preconditions.checkState(n.getProp(Node.FUNCTION_PROP) == null);
}
normalizeBlocks(n);
for (Node child = n.getFirstChild();
child != null; child = child.getNext()) {
// This pass is run during the CompilerTestCase validation, so this
// parent pointer check serves as a more general check.
Preconditions.checkState(child.getParent() == n);
normalizeNodeTypes(child);
}
}
/**
* Add blocks to IF, WHILE, DO, etc.
*/
private void normalizeBlocks(Node n) {
if (NodeUtil.isControlStructure(n)
&& n.getType() != Token.LABEL
&& n.getType() != Token.SWITCH) {
for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
if (NodeUtil.isControlStructureCodeBlock(n,c) &&
c.getType() != Token.BLOCK) {
Node newBlock = new Node(Token.BLOCK, n.getLineno(), n.getCharno());
newBlock.copyInformationFrom(n);
n.replaceChild(c, newBlock);
if (c.getType() != Token.EMPTY) {
newBlock.addChildrenToFront(c);
} else {
newBlock.setWasEmptyNode(true);
}
c = newBlock;
reportChange();
}
}
}
}
/**
* Normalize where annotations appear on the AST. Copies
* around existing JSDoc annotations as well as internal annotations.
*/
static class PrepareAnnotations
implements NodeTraversal.Callback {
private final CodingConvention convention;
PrepareAnnotations(AbstractCompiler compiler) {
this.convention = compiler.getCodingConvention();
}
@Override
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
if (n.getType() == Token.OBJECTLIT) {
normalizeObjectLiteralAnnotations(n);
}
return true;
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
switch (n.getType()) {
case Token.CALL:
annotateCalls(n);
break;
case Token.FUNCTION:
annotateFunctions(n, parent);
annotateDispatchers(n, parent);
break;
}
}
private void normalizeObjectLiteralAnnotations(Node objlit) {
Preconditions.checkState(objlit.getType() == Token.OBJECTLIT);
for (Node key = objlit.getFirstChild();
key != null; key = key.getNext()) {
Node value = key.getFirstChild();
normalizeObjectLiteralKeyAnnotations(objlit, key, value);
}
}
/**
* There are two types of calls we are interested in calls without explicit
* "this" values (what we are call "free" calls) and direct call to eval.
*/
private void annotateCalls(Node n) {
Preconditions.checkState(n.getType() == Token.CALL);
// Keep track of of the "this" context of a call. A call without an
// explicit "this" is a free call.
Node first = n.getFirstChild();
if (!NodeUtil.isGet(first)) {
n.putBooleanProp(Node.FREE_CALL, true);
}
// Keep track of the context in which eval is called. It is important
// to distinguish between "(0, eval)()" and "eval()".
if (first.getType() == Token.NAME &&
"eval".equals(first.getString())) {
first.putBooleanProp(Node.DIRECT_EVAL, true);
}
}
/**
* Translate dispatcher info into the property expected node.
*/
private void annotateDispatchers(Node n, Node parent) {
Preconditions.checkState(n.getType() == Token.FUNCTION);
if (parent.getJSDocInfo() != null
&& parent.getJSDocInfo().isJavaDispatch()) {
if (parent.getType() == Token.ASSIGN) {
Preconditions.checkState(parent.getLastChild() == n);
n.putBooleanProp(Node.IS_DISPATCHER, true);
}
}
}
/**
* In the AST that Rhino gives us, it needs to make a distinction
* between jsdoc on the object literal node and jsdoc on the object literal
* value. For example,
* <pre>
* var x = {
* / JSDOC /
* a: 'b',
* c: / JSDOC / 'd'
* };
* </pre>
*
* But in few narrow cases (in particular, function literals), it's
* a lot easier for us if the doc is attached to the value.
*/
private void normalizeObjectLiteralKeyAnnotations(
Node objlit, Node key, Node value) {
Preconditions.checkState(objlit.getType() == Token.OBJECTLIT);
if (key.getJSDocInfo() != null &&
value.getType() == Token.FUNCTION) {
value.setJSDocInfo(key.getJSDocInfo());
}
}
/**
* Annotate optional and var_arg function parameters.
*/
private void annotateFunctions(Node n, Node parent) {
JSDocInfo fnInfo = NodeUtil.getFunctionJSDocInfo(n);
// Compute which function parameters are optional and
// which are var_args.
Node args = n.getFirstChild().getNext();
for (Node arg = args.getFirstChild();
arg != null;
arg = arg.getNext()) {
String argName = arg.getString();
JSTypeExpression typeExpr = fnInfo == null ?
null : fnInfo.getParameterType(argName);
if (convention.isOptionalParameter(arg) ||
typeExpr != null && typeExpr.isOptionalArg()) {
arg.putBooleanProp(Node.IS_OPTIONAL_PARAM, true);
}
if (convention.isVarArgsParameter(arg) ||
typeExpr != null && typeExpr.isVarArgs()) {
arg.putBooleanProp(Node.IS_VAR_ARGS_PARAM, true);
}
}
}
}
}
| |
/**
* Copyright 2005-2014 Red Hat, Inc.
*
* Red Hat 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 io.fabric8.core.jmx;
import static io.fabric8.api.MQService.Config.CONFIG_URL;
import static io.fabric8.api.MQService.Config.DATA;
import static io.fabric8.api.MQService.Config.GROUP;
import static io.fabric8.api.MQService.Config.KIND;
import static io.fabric8.api.MQService.Config.MINIMUM_INSTANCES;
import static io.fabric8.api.MQService.Config.NETWORKS;
import static io.fabric8.api.MQService.Config.NETWORK_PASSWORD;
import static io.fabric8.api.MQService.Config.NETWORK_USER_NAME;
import static io.fabric8.api.MQService.Config.PARENT;
import static io.fabric8.api.MQService.Config.REPLICAS;
import static io.fabric8.api.MQService.Config.SSL;
import static io.fabric8.zookeeper.utils.ZooKeeperUtils.getChildrenSafe;
import static io.fabric8.zookeeper.utils.ZooKeeperUtils.getSubstitutedData;
import io.fabric8.api.Container;
import io.fabric8.api.ContainerProvider;
import io.fabric8.api.Containers;
import io.fabric8.api.CreateContainerBasicOptions;
import io.fabric8.api.FabricRequirements;
import io.fabric8.api.FabricService;
import io.fabric8.api.MQService;
import io.fabric8.api.Profile;
import io.fabric8.api.ProfileRequirements;
import io.fabric8.api.ProfileService;
import io.fabric8.api.RuntimeProperties;
import io.fabric8.api.Version;
import io.fabric8.api.jmx.BrokerKind;
import io.fabric8.api.jmx.MQBrokerConfigDTO;
import io.fabric8.api.jmx.MQBrokerStatusDTO;
import io.fabric8.api.jmx.MQManagerMXBean;
import io.fabric8.utils.JMXUtils;
import io.fabric8.utils.Maps;
import io.fabric8.utils.Strings;
import io.fabric8.internal.Objects;
import io.fabric8.service.MQServiceImpl;
import io.fabric8.zookeeper.ZkPath;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.StandardMBean;
import org.apache.curator.framework.CuratorFramework;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.jboss.gravia.utils.IllegalArgumentAssertion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* An MBean for working with the global A-MQ topology configuration inside the Fabric profiles
*/
@Component(label = "Fabric8 MQ Manager JMX MBean", metatype = false)
public class MQManager implements MQManagerMXBean {
private static final transient Logger LOG = LoggerFactory.getLogger(MQManager.class);
private static ObjectName OBJECT_NAME;
static {
try {
OBJECT_NAME = new ObjectName("io.fabric8:type=MQManager");
} catch (MalformedObjectNameException e) {
// ignore
}
}
@Reference(referenceInterface = FabricService.class)
private FabricService fabricService;
@Reference(referenceInterface = MBeanServer.class)
private MBeanServer mbeanServer;
@Reference(referenceInterface = CuratorFramework.class)
private CuratorFramework curator;
@Reference(referenceInterface = RuntimeProperties.class)
private RuntimeProperties runtimeProperties;
private MQService mqService;
@Activate
void activate() throws Exception {
Objects.notNull(fabricService, "fabricService");
mqService = createMQService(fabricService, runtimeProperties);
if (mbeanServer != null) {
StandardMBean mbean = new StandardMBean(this, MQManagerMXBean.class);
JMXUtils.registerMBean(mbean, mbeanServer, OBJECT_NAME);
}
}
@Deactivate
void deactivate() throws Exception {
if (mbeanServer != null) {
JMXUtils.unregisterMBean(mbeanServer, OBJECT_NAME);
}
}
@Override
public List<MQBrokerConfigDTO> loadBrokerConfiguration() {
List<MQBrokerConfigDTO> answer = new ArrayList<MQBrokerConfigDTO>();
Collection<Profile> values = getActiveOrRequiredBrokerProfileMap();
for (Profile profile : values) {
List<MQBrokerConfigDTO> list = createConfigDTOs(mqService, profile);
answer.addAll(list);
}
return answer;
}
@Override
public List<MQBrokerStatusDTO> loadBrokerStatus() throws Exception {
FabricRequirements requirements = fabricService.getRequirements();
List<MQBrokerStatusDTO> answer = new ArrayList<MQBrokerStatusDTO>();
Version defaultVersion = fabricService.getDefaultVersion();
Container[] containers = fabricService.getContainers();
List<Profile> values = getActiveOrRequiredBrokerProfileMap(defaultVersion, requirements);
for (Profile profile : values) {
List<MQBrokerConfigDTO> list = createConfigDTOs(mqService, profile);
for (MQBrokerConfigDTO configDTO : list) {
ProfileRequirements profileRequirements = requirements.findProfileRequirements(profile.getId());
int count = 0;
for (Container container : containers) {
if (Containers.containerHasProfile(container, profile)) {
MQBrokerStatusDTO status = createStatusDTO(profile, configDTO, profileRequirements, container);
count++;
answer.add(status);
}
}
// if there are no containers yet, lets create a record anyway
if (count == 0) {
MQBrokerStatusDTO status = createStatusDTO(profile, configDTO, profileRequirements, null);
answer.add(status);
}
}
}
addMasterSlaveStatus(answer);
return answer;
}
protected void addMasterSlaveStatus(List<MQBrokerStatusDTO> answer) throws Exception {
Map<String, Map<String, MQBrokerStatusDTO>> groupMap = new HashMap<String, Map<String, MQBrokerStatusDTO>>();
for (MQBrokerStatusDTO status : answer) {
String key = status.getGroup();
Map<String, MQBrokerStatusDTO> list = groupMap.get(key);
if (list == null) {
list = new HashMap<String, MQBrokerStatusDTO>();
groupMap.put(key, list);
}
String statusPath = String.format("%s/%s", status.getContainer(), status.getBrokerName());
list.put(statusPath, status);
}
CuratorFramework curator = getCurator();
// now lets check the cluster status for each group
Set<Map.Entry<String, Map<String, MQBrokerStatusDTO>>> entries = groupMap.entrySet();
for (Map.Entry<String, Map<String, MQBrokerStatusDTO>> entry : entries) {
String group = entry.getKey();
Map<String, MQBrokerStatusDTO> containerMap = entry.getValue();
String groupPath = ZkPath.MQ_CLUSTER.getPath(group);
List<String> children = getChildrenSafe(curator, groupPath);
for (String child : children) {
String childPath = groupPath + "/" + child;
byte[] data = curator.getData().forPath(childPath);
if (data != null && data.length > 0) {
String text = new String(data).trim();
if (!text.isEmpty()) {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(data, HashMap.class);
String id = stringValue(map, "id", "container");
if (id != null) {
String container = stringValue(map, "container", "agent");
String statusPath = String.format("%s/%s", container, id);
MQBrokerStatusDTO containerStatus = containerMap.get(statusPath);
if (containerStatus != null) {
Boolean master = null;
List services = listValue(map, "services");
if (services != null) {
if (!services.isEmpty()) {
List<String> serviceTexts = new ArrayList<String>();
for (Object service : services) {
String serviceText = getSubstitutedData(curator, service.toString());
if (Strings.isNotBlank(serviceText)) {
serviceTexts.add(serviceText);
}
containerStatus.setServices(serviceTexts);
}
master = Boolean.TRUE;
} else {
master = Boolean.FALSE;
}
} else {
master = Boolean.FALSE;
}
containerStatus.setMaster(master);
}
}
}
}
}
}
}
protected static String stringValue(Map<String, Object> map, String... keys) {
Object value = value(map, keys);
if (value instanceof String) {
return (String) value;
} else if (value != null) {
return value.toString();
}
return null;
}
protected static List listValue(Map<String, Object> map, String... keys) {
Object value = value(map, keys);
if (value instanceof List) {
return (List) value;
} else if (value instanceof Object[]) {
return Arrays.asList((Object[]) value);
}
return null;
}
protected static Object value(Map<String, Object> map, String... keys) {
for (String key : keys) {
Object value = map.get(key);
if (value != null) {
return value;
}
}
return null;
}
protected MQBrokerStatusDTO createStatusDTO(Profile profile, MQBrokerConfigDTO configDTO, ProfileRequirements profileRequirements, Container container) {
MQBrokerStatusDTO answer = new MQBrokerStatusDTO(configDTO);
if (container != null) {
answer.setContainer(container.getId());
answer.setAlive(container.isAlive());
answer.setProvisionResult(container.getProvisionResult());
answer.setProvisionStatus(container.getProvisionStatus());
answer.setJolokiaUrl(container.getJolokiaUrl());
}
if (profileRequirements != null) {
Integer minimumInstances = profileRequirements.getMinimumInstances();
if (minimumInstances != null) {
answer.setMinimumInstances(minimumInstances);
}
}
return answer;
}
public static List<MQBrokerConfigDTO> createConfigDTOs(MQService mqService, Profile profile) {
List<MQBrokerConfigDTO> answer = new ArrayList<MQBrokerConfigDTO>();
Map<String, Map<String, String>> configurations = profile.getConfigurations();
Set<Map.Entry<String, Map<String, String>>> entries = configurations.entrySet();
for (Map.Entry<String, Map<String, String>> entry : entries) {
String key = entry.getKey();
Map<String, String> configuration = entry.getValue();
if (isBrokerConfigPid(key)) {
String brokerName = getBrokerNameFromPID(key);
String profileId = profile.getId();
MQBrokerConfigDTO dto = new MQBrokerConfigDTO();
dto.setProfile(profileId);
dto.setBrokerName(brokerName);
String version = profile.getVersion();
dto.setVersion(version);
List<String> parentIds = profile.getParentIds();
if (parentIds.size() > 0) {
dto.setParentProfile(parentIds.get(0));
}
if (configuration != null) {
dto.setData(configuration.get(DATA));
dto.setConfigUrl(configuration.get(CONFIG_URL));
dto.setGroup(configuration.get(GROUP));
dto.setKind(BrokerKind.fromValue(configuration.get(KIND)));
dto.setMinimumInstances(Maps.integerValue(configuration, MINIMUM_INSTANCES));
dto.setNetworks(Maps.stringValues(configuration, NETWORKS));
dto.setNetworksUserName(configuration.get(NETWORK_USER_NAME));
dto.setNetworksPassword(configuration.get(NETWORK_PASSWORD));
dto.setReplicas(Maps.integerValue(configuration, REPLICAS));
for (Map.Entry<String, String> configurationEntry : configuration.entrySet()) {
if (configurationEntry.getKey().endsWith("-port")) {
dto.getPorts().put(configurationEntry.getKey().substring(0, configurationEntry.getKey().indexOf("-port")) , configurationEntry.getValue());
}
}
}
answer.add(dto);
}
}
return answer;
}
public List<Profile> getActiveOrRequiredBrokerProfileMap() {
return getActiveOrRequiredBrokerProfileMap(fabricService.getDefaultVersion());
}
public List<Profile> getActiveOrRequiredBrokerProfileMap(Version version) {
return getActiveOrRequiredBrokerProfileMap(version, fabricService.getRequirements());
}
private List<Profile> getActiveOrRequiredBrokerProfileMap(Version version, FabricRequirements requirements) {
IllegalArgumentAssertion.assertNotNull(fabricService, "fabricService");
List<Profile> answer = new ArrayList<Profile>();
if (version != null) {
ProfileService profileService = fabricService.adapt(ProfileService.class);
List<Profile> profiles = version.getProfiles();
for (Profile profile : profiles) {
// ignore if we don't have any requirements or instances as it could be profiles such
// as the out of the box mq-default / mq-amq etc
String versionId = profile.getVersion();
String profileId = profile.getId();
if (requirements.hasMinimumInstances(profileId) || fabricService.getAssociatedContainers(versionId, profileId).length > 0) {
Profile overlay = profileService.getOverlayProfile(profile);
Map<String, Map<String, String>> configurations = overlay.getConfigurations();
Set<Map.Entry<String, Map<String, String>>> entries = configurations.entrySet();
for (Map.Entry<String, Map<String, String>> entry : entries) {
String key = entry.getKey();
if (isBrokerConfigPid(key)) {
answer.add(overlay);
}
}
}
}
}
return answer;
}
protected static String getBrokerNameFromPID(String key) {
return key.substring(MQService.MQ_FABRIC_SERVER_PID_PREFIX.length());
}
protected static boolean isBrokerConfigPid(String key) {
return key.startsWith(MQService.MQ_FABRIC_SERVER_PID_PREFIX);
}
@Override
public void saveBrokerConfigurationJSON(String json) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
List<MQBrokerConfigDTO> dtos = new ArrayList<MQBrokerConfigDTO>();
MappingIterator<Object> iter = mapper.reader(MQBrokerConfigDTO.class).readValues(json);
while (iter.hasNext()) {
Object next = iter.next();
if (next instanceof MQBrokerConfigDTO) {
dtos.add((MQBrokerConfigDTO) next);
} else {
LOG.warn("Expected MQBrokerConfigDTO but parsed invalid DTO " + next);
}
}
saveBrokerConfiguration(dtos);
}
public void saveBrokerConfiguration(List<MQBrokerConfigDTO> dtos) throws IOException {
for (MQBrokerConfigDTO dto : dtos) {
createOrUpdateProfile(dto, fabricService, runtimeProperties);
}
}
/**
* Creates or updates the broker profile for the given DTO and updates the requirements so that the
* minimum number of instances of the profile is updated
*/
public static Profile createOrUpdateProfile(MQBrokerConfigDTO dto, FabricService fabricService, RuntimeProperties runtimeProperties) throws IOException {
FabricRequirements requirements = fabricService.getRequirements();
MQService mqService = createMQService(fabricService, runtimeProperties);
Map<String, String> configuration = new HashMap<String, String>();
List<String> properties = dto.getProperties();
String version = dto.version();
if (properties != null) {
for (String entry : properties) {
String[] parts = entry.split("=", 2);
if (parts.length == 2) {
configuration.put(parts[0], parts[1]);
} else {
configuration.put(parts[0], "");
}
}
}
String data = dto.getData();
String profileName = dto.profile();
String brokerName = dto.getBrokerName();
if (data == null) {
// lets use a relative path so we work on any karaf container
data = "${runtime.data}" + brokerName;
}
configuration.put(DATA, data);
for (Map.Entry<String,String> port: dto.getPorts().entrySet()) {
configuration.put(port.getKey() + "-port", port.getValue());
}
BrokerKind kind = dto.kind();
configuration.put(KIND, kind.toString());
String config = dto.getConfigUrl();
if (config != null) {
configuration.put(CONFIG_URL, mqService.getConfig(version, config));
}
String group = dto.getGroup();
if (group != null) {
configuration.put(GROUP, group);
}
Maps.setStringValues(configuration, NETWORKS, dto.getNetworks());
String networksUserName = dto.getNetworksUserName();
if (networksUserName != null) {
configuration.put(NETWORK_USER_NAME, networksUserName);
}
String networksPassword = dto.getNetworksPassword();
if (networksPassword != null) {
configuration.put(NETWORK_PASSWORD, networksPassword);
}
String parentProfile = dto.getParentProfile();
if (parentProfile != null) {
configuration.put(PARENT, parentProfile);
}
Boolean ssl = dto.getSsl();
if (ssl != null) {
configuration.put(SSL, ssl.toString());
}
Integer replicas = dto.getReplicas();
if (replicas != null) {
configuration.put(REPLICAS, replicas.toString());
}
Integer minInstances = dto.getMinimumInstances();
if (minInstances != null) {
configuration.put(MINIMUM_INSTANCES, minInstances.toString());
}
Profile profile = mqService.createOrUpdateMQProfile(version, profileName, brokerName, configuration, dto.kind().equals(BrokerKind.Replicated));
String profileId = profile.getId();
ProfileRequirements profileRequirement = requirements.getOrCreateProfileRequirement(profileId);
Integer minimumInstances = profileRequirement.getMinimumInstances();
// lets reload the DTO as we may have inherited some values from the parent profile
List<MQBrokerConfigDTO> list = createConfigDTOs(mqService, profile);
// lets assume 2 required instances for master/slave unless folks use
// N+1 or replicated
int requiredInstances = 2;
if (list.size() == 1) {
MQBrokerConfigDTO loadedDTO = list.get(0);
requiredInstances = loadedDTO.requiredInstances();
} else {
// assume N+1 broker as there's more than one broker in the profile; so lets set the required size to N+1
requiredInstances = list.size() + 1;
}
if (minimumInstances == null || minimumInstances.intValue() < requiredInstances) {
profileRequirement.setMinimumInstances(requiredInstances);
fabricService.setRequirements(requirements);
}
String clientProfile = dto.clientProfile();
if (Strings.isNotBlank(clientProfile)) {
String clientParentProfile = dto.getClientParentProfile();
if (Strings.isNullOrBlank(clientParentProfile)) {
clientParentProfile = "mq-client-base";
}
mqService.createOrUpdateMQClientProfile(version, clientProfile, group, clientParentProfile);
}
return profile;
}
protected static MQServiceImpl createMQService(FabricService fabricService, RuntimeProperties runtimeProperties) {
return new MQServiceImpl(fabricService, runtimeProperties);
}
public static void assignProfileToContainers(FabricService fabricService, Profile profile, String[] assignContainers) {
for (String containerName : assignContainers) {
try {
Container container = fabricService.getContainer(containerName);
if (container == null) {
LOG.warn("Failed to assign profile to " + containerName + ": profile doesn't exists");
} else {
Set<Profile> profiles = new HashSet<Profile>(Arrays.asList(container.getProfiles()));
profiles.add(profile);
container.setProfiles(profiles.toArray(new Profile[profiles.size()]));
LOG.info("Profile successfully assigned to " + containerName);
}
} catch (Exception e) {
LOG.warn("Failed to assign profile to " + containerName + ": " + e.getMessage());
}
}
}
/**
* Creates container builders for the given DTO
*/
public static List<CreateContainerBasicOptions.Builder> createContainerBuilders(MQBrokerConfigDTO dto,
FabricService fabricService, String containerProviderScheme,
String profileId, String version,
String[] createContainers) throws IOException {
ContainerProvider containerProvider = fabricService.getProvider(containerProviderScheme);
Objects.notNull(containerProvider, "No ContainerProvider available for scheme: " + containerProviderScheme);
if (!containerProvider.isValidProvider()) {
throw new IllegalArgumentException("ContainerProvider for scheme: " + containerProviderScheme + " is not valid in current environment");
}
List<CreateContainerBasicOptions.Builder> containerBuilders = new ArrayList<CreateContainerBasicOptions.Builder>();
for (String container : createContainers) {
String type = null;
String parent = fabricService.getCurrentContainerName();
String jvmOpts = dto.getJvmOpts();
CreateContainerBasicOptions.Builder builder = containerProvider.newBuilder();
builder = (CreateContainerBasicOptions.Builder) builder
.name(container)
.parent(parent)
.number(dto.requiredInstances())
.ensembleServer(false)
.proxyUri(fabricService.getMavenRepoURI())
.jvmOpts(jvmOpts)
.zookeeperUrl(fabricService.getZookeeperUrl())
.zookeeperPassword(fabricService.getZookeeperPassword())
.profiles(profileId)
.version(version);
containerBuilders.add(builder);
}
return containerBuilders;
}
public CuratorFramework getCurator() {
return curator;
}
}
| |
/*
* 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.amdatu.remote.discovery;
import static org.amdatu.remote.EndpointUtil.computeHash;
import java.util.HashMap;
import java.util.Map;
import org.amdatu.remote.AbstractEndpointPublishingComponent;
import org.osgi.service.remoteserviceadmin.EndpointDescription;
import org.osgi.service.remoteserviceadmin.EndpointEvent;
import org.osgi.service.remoteserviceadmin.EndpointEventListener;
import org.osgi.service.remoteserviceadmin.EndpointListener;
/**
* Base class for a Discovery Service that handles endpoint registration as well as listener tracking
* and invocation.<br/><br/>
*
* @author <a href="mailto:amdatu-developers@amdatu.org">Amdatu Project Team</a>
*/
@SuppressWarnings("deprecation")
public abstract class AbstractDiscovery extends AbstractEndpointPublishingComponent implements EndpointEventListener,
EndpointListener {
private final Map<EndpointDescription, String> m_discoveredEndpoints = new HashMap<EndpointDescription, String>();
public AbstractDiscovery(String name) {
super("discovery", name);
}
@Override
protected void startComponent() throws Exception {
super.startComponent();
}
@Override
protected void stopComponent() throws Exception {
super.stopComponent();
}
@Override
public void endpointChanged(final EndpointEvent event, final String matchedFilter) {
switch (event.getType()) {
case EndpointEvent.ADDED:
executeTask(new Runnable() {
@Override
public void run() {
logInfo("Added local endpoint: %s", event.getEndpoint());
addPublishedEndpoint(event.getEndpoint(), matchedFilter);
}
});
break;
case EndpointEvent.REMOVED:
executeTask(new Runnable() {
@Override
public void run() {
logInfo("Removed local endpoint: %s", event.getEndpoint());
removePublishedEndpoint(event.getEndpoint(), matchedFilter);
}
});
break;
case EndpointEvent.MODIFIED:
executeTask(new Runnable() {
@Override
public void run() {
logInfo("Modified local endpoint: %s", event.getEndpoint());
modifyPublishedEndpoint(event.getEndpoint(), matchedFilter);
}
});
break;
case EndpointEvent.MODIFIED_ENDMATCH:
executeTask(new Runnable() {
@Override
public void run() {
logInfo("Endmatched local endpoint: %s", event.getEndpoint());
removePublishedEndpoint(event.getEndpoint(), matchedFilter);
}
});
break;
default:
throw new IllegalStateException("Recieved event with unknown type " + event.getType());
}
}
@Override
public void endpointAdded(final EndpointDescription endpoint, final String matchedFilter) {
executeTask(new Runnable() {
@Override
public void run() {
logInfo("Added local endpoint: %s", endpoint);
addPublishedEndpoint(endpoint, matchedFilter);
}
});
}
@Override
public void endpointRemoved(final EndpointDescription endpoint, final String matchedFilter) {
executeTask(new Runnable() {
@Override
public void run() {
logInfo("Removed local endpoint: %s", endpoint);
removePublishedEndpoint(endpoint, matchedFilter);
}
});
}
/**
* Register a newly discovered remote service and invoke relevant listeners. Concrete implementations must
* call this method for every applicable remote registration they discover.
*
* @param endpoint The service Endpoint Description
*/
protected final void addDiscoveredEndpoint(final EndpointDescription endpoint) {
executeTask(new Runnable() {
@Override
public void run() {
String newhash = computeHash(endpoint);
String oldhash = m_discoveredEndpoints.get(endpoint);
if (oldhash == null) {
logInfo("Adding remote endpoint: %s", endpoint);
m_discoveredEndpoints.put(endpoint, newhash);
endpointAdded(endpoint);
}
else if (!oldhash.equals(newhash)) {
logInfo("Mofifying remote endpoint: %s", endpoint);
m_discoveredEndpoints.put(endpoint, newhash);
endpointModified(endpoint);
}
}
});
}
/**
* Unregister a previously discovered remote service endPoint and invoke relevant listeners. Concrete
* implementations must call this method for every applicable remote registration that disappears.
*
* @param endpoint The service Endpoint Description
*/
protected final void removeDiscoveredEndpoint(final EndpointDescription endpoint) {
executeTask(new Runnable() {
@Override
public void run() {
logInfo("Removed remote endpoint: %s", endpoint);
m_discoveredEndpoints.remove(endpoint);
endpointRemoved(endpoint);
}
});
}
/**
* Modifies a previously discovered remote service endPoint and invoke relevant listeners. Concrete
* implementations must call this method for every applicable remote registration that disappears.
*
* @param endpoint The service Endpoint Description
*/
protected final void modifyDiscoveredEndpoint(EndpointDescription endpoint) {
addDiscoveredEndpoint(endpoint);
}
/**
* Called when an exported service is published. The concrete implementation is responsible for registering
* the service in its service registry.
*
* @param endpoint The service Endpoint Description
* @param matchedFilter The matched filter
*/
protected abstract void addPublishedEndpoint(EndpointDescription endpoint, String matchedFilter);
/**
* Called when an exported service is depublished. The concrete implementation is responsible for unregistering
* the service in its service registry.
*
* @param endpoint The service Endpoint Description
* @param matchedFilter the matched filter
*/
protected abstract void removePublishedEndpoint(EndpointDescription endpoint, String matchedFilter);
/**
* Called when an exported service is modified. The concrete implementation is responsible for updating
* the service in its service registry.
*
* @param endpoint The service Endpoint Description
* @param matchedFilter The matched filter
*/
protected abstract void modifyPublishedEndpoint(EndpointDescription endpoint, String matchedFilter);
}
| |
package com.compomics.util.gui.utils.user_choice.list_choosers;
import com.compomics.util.experiment.biology.modifications.Modification;
import com.compomics.util.experiment.biology.modifications.ModificationFactory;
import com.compomics.util.gui.utils.user_choice.ListChooser;
import java.util.ArrayList;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import no.uib.jsparklines.renderers.JSparklinesBarChartTableCellRenderer;
import no.uib.jsparklines.renderers.JSparklinesColorTableCellRenderer;
import org.jfree.chart.plot.PlotOrientation;
/**
* Dialog for choosing an item in a list of modifications.
*
* @author Marc Vaudel
*/
public class ModificationChooser extends ListChooser {
/**
* Empty default constructor
*/
public ModificationChooser() {
}
/**
* The modifications factory.
*/
private ModificationFactory modificationsFactory = ModificationFactory.getInstance();
/**
* List of modifications to display.
*/
private ArrayList<String> modificationsList = new ArrayList<>();
/**
* Constructor. Null values will be replaced by default.
*
* @param parent the parent frame
* @param modifications list of the names of the modifications for the user to select
* @param dialogTitle the title to give to the dialog
* @param panelTitle the title to give to the panel containing the table
* @param instructionsLabel the instructions label on top of the table
* @param multipleSelection boolean indicating whether the user should be
* allowed to select multiple items
*/
public ModificationChooser(java.awt.Frame parent, ArrayList<String> modifications, String dialogTitle, String panelTitle, String instructionsLabel, boolean multipleSelection) {
super(parent, modifications, dialogTitle, panelTitle, instructionsLabel, multipleSelection);
this.modificationsList = modifications;
if (modifications == null || modifications.isEmpty()) {
throw new IllegalArgumentException("No item to select.");
}
setUpTable();
setVisible(true);
}
/**
* Constructor. Null values will be replaced by default.
*
* @param parent the parent frame
* @param modifications list of the names of the modifications for the user to select
* @param dialogTitle the title to give to the dialog
* @param panelTitle the title to give to the panel containing the table
* @param instructionsLabel the instructions label on top of the table
* @param multipleSelection boolean indicating whether the user should be
* allowed to select multiple items
*/
public ModificationChooser(javax.swing.JDialog parent, ArrayList<String> modifications, String dialogTitle, String panelTitle, String instructionsLabel, boolean multipleSelection) {
super(parent, modifications, dialogTitle, panelTitle, instructionsLabel, multipleSelection);
this.modificationsList = modifications;
if (modifications == null || modifications.isEmpty()) {
throw new IllegalArgumentException("No item to select.");
}
setUpTable();
setVisible(true);
}
/**
* Constructor with default values.
*
* @param parent the parent frame
* @param modifications list of the names of the modifications for the user to select
* @param multipleSelection boolean indicating whether the user should be
* allowed to select multiple items
*/
public ModificationChooser(java.awt.Frame parent, ArrayList<String> modifications, boolean multipleSelection) {
this(parent, modifications, "Modification Selection", "Searched Modifications", "Please select a modification from the list of possibilities.", multipleSelection);
}
/**
* Constructor with default values.
*
* @param parent the parent frame
* @param modifications list of the names of the modifications for the user to select
* @param multipleSelection boolean indicating whether the user should be
* allowed to select multiple items
*/
public ModificationChooser(javax.swing.JDialog parent, ArrayList<String> modifications, boolean multipleSelection) {
this(parent, modifications, "Modification Selection", "Searched Modifications", "Please select a modification from the list of possibilities.", multipleSelection);
}
@Override
protected void formatTable() {
JTable modificationsJTable = getTable();
modificationsJTable.setModel(new ModificationsTableModel());
double minMass = modificationsList.stream()
.map(modName -> modificationsFactory.getModification(modName))
.mapToDouble(Modification::getMass)
.min()
.orElse(0.0);
double maxMass = modificationsList.stream()
.map(modName -> modificationsFactory.getModification(modName))
.mapToDouble(Modification::getMass)
.max()
.orElse(0.0);
modificationsJTable.getColumn(" ").setCellRenderer(new JSparklinesColorTableCellRenderer());
modificationsJTable.getColumn(" ").setMaxWidth(35);
modificationsJTable.getColumn("Mass").setMaxWidth(100);
modificationsJTable.getColumn("Mass").setCellRenderer(new JSparklinesBarChartTableCellRenderer(PlotOrientation.HORIZONTAL, minMass, maxMass));
((JSparklinesBarChartTableCellRenderer) modificationsJTable.getColumn("Mass").getCellRenderer()).showNumberAndChart(true, 50);
ArrayList<String> modificationTableToolTips = getTableTooltips();
modificationTableToolTips.add(null);
modificationTableToolTips.add("Modification Name");
modificationTableToolTips.add("Modification Mass");
modificationTableToolTips.add("Default Modification");
}
/**
* Table model for the modifications table.
*/
private class ModificationsTableModel extends DefaultTableModel {
@Override
public int getRowCount() {
return modificationsList.size();
}
@Override
public int getColumnCount() {
return 3;
}
@Override
public String getColumnName(int column) {
switch (column) {
case 0:
return " ";
case 1:
return "Name";
case 2:
return "Mass";
default:
return "";
}
}
@Override
public Object getValueAt(int row, int column) {
String modName = modificationsList.get(row);
switch (column) {
case 0:
return modificationsFactory.getColor(modName);
case 1:
return modName;
case 2:
Modification modification = modificationsFactory.getModification(modName);
return modification.getMass();
default:
return "";
}
}
@Override
public Class getColumnClass(int columnIndex) {
for (int i = 0; i < getRowCount(); i++) {
if (getValueAt(i, columnIndex) != null) {
return getValueAt(i, columnIndex).getClass();
}
}
return String.class;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
}
}
| |
/**
* 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.camel.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EventObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelContextAware;
import org.apache.camel.Exchange;
import org.apache.camel.LoggingLevel;
import org.apache.camel.Processor;
import org.apache.camel.RouteNode;
import org.apache.camel.management.event.AbstractExchangeEvent;
import org.apache.camel.management.event.ExchangeCompletedEvent;
import org.apache.camel.management.event.ExchangeCreatedEvent;
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.processor.interceptor.Tracer;
import org.apache.camel.spi.Breakpoint;
import org.apache.camel.spi.Condition;
import org.apache.camel.spi.Debugger;
import org.apache.camel.support.EventNotifierSupport;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The default implementation of the {@link Debugger}.
*
* @version
*/
public class DefaultDebugger implements Debugger, CamelContextAware {
private static final Logger LOG = LoggerFactory.getLogger(DefaultDebugger.class);
private final List<BreakpointConditions> breakpoints = new CopyOnWriteArrayList<BreakpointConditions>();
private final int maxConcurrentSingleSteps = 1;
private final Map<String, Breakpoint> singleSteps = new HashMap<String, Breakpoint>(maxConcurrentSingleSteps);
private CamelContext camelContext;
/**
* Holder class for breakpoint and the associated conditions
*/
private final class BreakpointConditions {
private Breakpoint breakpoint;
private List<Condition> conditions;
private BreakpointConditions(Breakpoint breakpoint) {
this(breakpoint, null);
}
private BreakpointConditions(Breakpoint breakpoint, List<Condition> conditions) {
this.breakpoint = breakpoint;
this.conditions = conditions;
}
public Breakpoint getBreakpoint() {
return breakpoint;
}
public List<Condition> getConditions() {
return conditions;
}
}
public DefaultDebugger() {
}
public DefaultDebugger(CamelContext camelContext) {
this.camelContext = camelContext;
}
public CamelContext getCamelContext() {
return camelContext;
}
public void setCamelContext(CamelContext camelContext) {
this.camelContext = camelContext;
}
public void addBreakpoint(Breakpoint breakpoint) {
breakpoints.add(new BreakpointConditions(breakpoint));
}
public void addBreakpoint(Breakpoint breakpoint, Condition... conditions) {
if (conditions != null && conditions.length > 0) {
breakpoints.add(new BreakpointConditions(breakpoint, Arrays.asList(conditions)));
} else {
breakpoints.add(new BreakpointConditions(breakpoint));
}
}
public void addSingleStepBreakpoint(final Breakpoint breakpoint) {
breakpoints.add(new BreakpointConditions(breakpoint));
}
public void addSingleStepBreakpoint(final Breakpoint breakpoint, Condition... conditions) {
// wrap the breakpoint into single step breakpoint so we can automatic enable/disable the single step mode
Breakpoint singlestep = new Breakpoint() {
public State getState() {
return breakpoint.getState();
}
public void suspend() {
breakpoint.suspend();
}
public void activate() {
breakpoint.activate();
}
public void beforeProcess(Exchange exchange, Processor processor, ProcessorDefinition definition) {
breakpoint.beforeProcess(exchange, processor, definition);
}
public void afterProcess(Exchange exchange, Processor processor, ProcessorDefinition definition, long timeTaken) {
breakpoint.afterProcess(exchange, processor, definition, timeTaken);
}
public void onEvent(Exchange exchange, EventObject event, ProcessorDefinition definition) {
if (event instanceof ExchangeCreatedEvent) {
exchange.getContext().getDebugger().startSingleStepExchange(exchange.getExchangeId(), this);
} else if (event instanceof ExchangeCompletedEvent) {
exchange.getContext().getDebugger().stopSingleStepExchange(exchange.getExchangeId());
}
breakpoint.onEvent(exchange, event, definition);
}
@Override
public String toString() {
return breakpoint.toString();
}
};
addBreakpoint(singlestep, conditions);
}
public void removeBreakpoint(Breakpoint breakpoint) {
for (BreakpointConditions condition : breakpoints) {
if (condition.getBreakpoint().equals(breakpoint)) {
breakpoints.remove(condition);
}
}
}
public void suspendAllBreakpoints() {
for (BreakpointConditions breakpoint : breakpoints) {
breakpoint.getBreakpoint().suspend();
}
}
public void activateAllBreakpoints() {
for (BreakpointConditions breakpoint : breakpoints) {
breakpoint.getBreakpoint().activate();
}
}
public List<Breakpoint> getBreakpoints() {
List<Breakpoint> answer = new ArrayList<Breakpoint>(breakpoints.size());
for (BreakpointConditions e : breakpoints) {
answer.add(e.getBreakpoint());
}
return Collections.unmodifiableList(answer);
}
public boolean startSingleStepExchange(String exchangeId, Breakpoint breakpoint) {
// can we accept single stepping the given exchange?
if (singleSteps.size() >= maxConcurrentSingleSteps) {
return false;
}
singleSteps.put(exchangeId, breakpoint);
return true;
}
public void stopSingleStepExchange(String exchangeId) {
singleSteps.remove(exchangeId);
}
public boolean beforeProcess(Exchange exchange, Processor processor, ProcessorDefinition definition) {
// is the exchange in single step mode?
Breakpoint singleStep = singleSteps.get(exchange.getExchangeId());
if (singleStep != null) {
onBeforeProcess(exchange, processor, definition, singleStep);
return true;
}
// does any of the breakpoints apply?
boolean match = false;
for (BreakpointConditions breakpoint : breakpoints) {
// breakpoint must be active
if (Breakpoint.State.Active.equals(breakpoint.getBreakpoint().getState())) {
if (matchConditions(exchange, processor, definition, breakpoint)) {
match = true;
onBeforeProcess(exchange, processor, definition, breakpoint.getBreakpoint());
}
}
}
return match;
}
public boolean afterProcess(Exchange exchange, Processor processor, ProcessorDefinition definition, long timeTaken) {
// is the exchange in single step mode?
Breakpoint singleStep = singleSteps.get(exchange.getExchangeId());
if (singleStep != null) {
onAfterProcess(exchange, processor, definition, timeTaken, singleStep);
return true;
}
// does any of the breakpoints apply?
boolean match = false;
for (BreakpointConditions breakpoint : breakpoints) {
// breakpoint must be active
if (Breakpoint.State.Active.equals(breakpoint.getBreakpoint().getState())) {
if (matchConditions(exchange, processor, definition, breakpoint)) {
match = true;
onAfterProcess(exchange, processor, definition, timeTaken, breakpoint.getBreakpoint());
}
}
}
return match;
}
public boolean onEvent(Exchange exchange, EventObject event) {
// is the exchange in single step mode?
Breakpoint singleStep = singleSteps.get(exchange.getExchangeId());
if (singleStep != null) {
onEvent(exchange, event, singleStep);
return true;
}
// does any of the breakpoints apply?
boolean match = false;
for (BreakpointConditions breakpoint : breakpoints) {
// breakpoint must be active
if (Breakpoint.State.Active.equals(breakpoint.getBreakpoint().getState())) {
if (matchConditions(exchange, event, breakpoint)) {
match = true;
onEvent(exchange, event, breakpoint.getBreakpoint());
}
}
}
return match;
}
protected void onBeforeProcess(Exchange exchange, Processor processor, ProcessorDefinition definition, Breakpoint breakpoint) {
try {
breakpoint.beforeProcess(exchange, processor, definition);
} catch (Throwable e) {
LOG.warn("Exception occurred in breakpoint: " + breakpoint + ". This exception will be ignored.", e);
}
}
protected void onAfterProcess(Exchange exchange, Processor processor, ProcessorDefinition definition, long timeTaken, Breakpoint breakpoint) {
try {
breakpoint.afterProcess(exchange, processor, definition, timeTaken);
} catch (Throwable e) {
LOG.warn("Exception occurred in breakpoint: " + breakpoint + ". This exception will be ignored.", e);
}
}
protected void onEvent(Exchange exchange, EventObject event, Breakpoint breakpoint) {
ProcessorDefinition definition = null;
// try to get the last known definition
if (exchange.getUnitOfWork() != null && exchange.getUnitOfWork().getTracedRouteNodes() != null) {
RouteNode node = exchange.getUnitOfWork().getTracedRouteNodes().getLastNode();
if (node != null) {
definition = node.getProcessorDefinition();
}
}
try {
breakpoint.onEvent(exchange, event, definition);
} catch (Throwable e) {
LOG.warn("Exception occurred in breakpoint: " + breakpoint + ". This exception will be ignored.", e);
}
}
private boolean matchConditions(Exchange exchange, Processor processor, ProcessorDefinition definition, BreakpointConditions breakpoint) {
if (breakpoint.getConditions() != null && !breakpoint.getConditions().isEmpty()) {
for (Condition condition : breakpoint.getConditions()) {
if (!condition.matchProcess(exchange, processor, definition)) {
return false;
}
}
}
return true;
}
private boolean matchConditions(Exchange exchange, EventObject event, BreakpointConditions breakpoint) {
if (breakpoint.getConditions() != null && !breakpoint.getConditions().isEmpty()) {
for (Condition condition : breakpoint.getConditions()) {
if (!condition.matchEvent(exchange, event)) {
return false;
}
}
}
return true;
}
public void start() throws Exception {
ObjectHelper.notNull(camelContext, "CamelContext", this);
// register our event notifier
camelContext.getManagementStrategy().addEventNotifier(new DebugEventNotifier());
Tracer tracer = Tracer.getTracer(camelContext);
if (tracer == null) {
// tracer is disabled so enable it silently so we can leverage it to trace the Exchanges for us
tracer = Tracer.createTracer(camelContext);
tracer.setLogLevel(LoggingLevel.OFF);
camelContext.addService(tracer);
camelContext.addInterceptStrategy(tracer);
}
// make sure tracer is enabled so the debugger can leverage the tracer for debugging purposes
tracer.setEnabled(true);
}
public void stop() throws Exception {
breakpoints.clear();
singleSteps.clear();
}
@Override
public String toString() {
return "DefaultDebugger";
}
private final class DebugEventNotifier extends EventNotifierSupport {
private DebugEventNotifier() {
setIgnoreCamelContextEvents(true);
setIgnoreServiceEvents(true);
}
public void notify(EventObject event) throws Exception {
AbstractExchangeEvent aee = (AbstractExchangeEvent) event;
Exchange exchange = aee.getExchange();
onEvent(exchange, event);
if (event instanceof ExchangeCompletedEvent) {
// fail safe to ensure we remove single steps when the Exchange is complete
singleSteps.remove(exchange.getExchangeId());
}
}
public boolean isEnabled(EventObject event) {
return event instanceof AbstractExchangeEvent;
}
protected void doStart() throws Exception {
// noop
}
protected void doStop() throws Exception {
// noop
}
}
}
| |
/**
*
* 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.bookkeeper.zookeeper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.util.concurrent.RateLimiter;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.bookkeeper.stats.NullStatsLogger;
import org.apache.bookkeeper.stats.OpStatsLogger;
import org.apache.bookkeeper.stats.StatsLogger;
import org.apache.bookkeeper.zookeeper.ZooWorker.ZooCallable;
import org.apache.zookeeper.AsyncCallback.ACLCallback;
import org.apache.zookeeper.AsyncCallback.Children2Callback;
import org.apache.zookeeper.AsyncCallback.ChildrenCallback;
import org.apache.zookeeper.AsyncCallback.Create2Callback;
import org.apache.zookeeper.AsyncCallback.DataCallback;
import org.apache.zookeeper.AsyncCallback.MultiCallback;
import org.apache.zookeeper.AsyncCallback.StatCallback;
import org.apache.zookeeper.AsyncCallback.StringCallback;
import org.apache.zookeeper.AsyncCallback.VoidCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Op;
import org.apache.zookeeper.OpResult;
import org.apache.zookeeper.Transaction;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provide a zookeeper client to handle session expire.
*/
public class ZooKeeperClient extends ZooKeeper implements Watcher {
private static final Logger logger = LoggerFactory.getLogger(ZooKeeperClient.class);
private static final int DEFAULT_RETRY_EXECUTOR_THREAD_COUNT = 1;
// ZooKeeper client connection variables
private final String connectString;
private final int sessionTimeoutMs;
private final boolean allowReadOnlyMode;
// state for the zookeeper client
private final AtomicReference<ZooKeeper> zk = new AtomicReference<ZooKeeper>();
private final AtomicBoolean closed = new AtomicBoolean(false);
private final ZooKeeperWatcherBase watcherManager;
private final ScheduledExecutorService retryExecutor;
private final ExecutorService connectExecutor;
// rate limiter
private final RateLimiter rateLimiter;
// retry polices
private final RetryPolicy connectRetryPolicy;
private final RetryPolicy operationRetryPolicy;
// Stats Logger
private final OpStatsLogger createStats;
private final OpStatsLogger getStats;
private final OpStatsLogger setStats;
private final OpStatsLogger deleteStats;
private final OpStatsLogger getChildrenStats;
private final OpStatsLogger existsStats;
private final OpStatsLogger multiStats;
private final OpStatsLogger getACLStats;
private final OpStatsLogger setACLStats;
private final OpStatsLogger syncStats;
private final OpStatsLogger createClientStats;
private final Callable<ZooKeeper> clientCreator = new Callable<ZooKeeper>() {
@Override
public ZooKeeper call() throws Exception {
try {
return ZooWorker.syncCallWithRetries(null, new ZooCallable<ZooKeeper>() {
@Override
public ZooKeeper call() throws KeeperException, InterruptedException {
logger.info("Reconnecting zookeeper {}.", connectString);
// close the previous one
closeZkHandle();
ZooKeeper newZk;
try {
newZk = createZooKeeper();
} catch (IOException ie) {
logger.error("Failed to create zookeeper instance to " + connectString, ie);
throw KeeperException.create(KeeperException.Code.CONNECTIONLOSS);
}
waitForConnection();
zk.set(newZk);
logger.info("ZooKeeper session {} is created to {}.",
Long.toHexString(newZk.getSessionId()), connectString);
return newZk;
}
@Override
public String toString() {
return String.format("ZooKeeper Client Creator (%s)", connectString);
}
}, connectRetryPolicy, rateLimiter, createClientStats);
} catch (Exception e) {
logger.error("Gave up reconnecting to ZooKeeper : ", e);
Runtime.getRuntime().exit(-1);
return null;
}
}
};
@VisibleForTesting
static ZooKeeperClient createConnectedZooKeeperClient(
String connectString, int sessionTimeoutMs, Set<Watcher> childWatchers,
RetryPolicy operationRetryPolicy)
throws KeeperException, InterruptedException, IOException {
return ZooKeeperClient.newBuilder()
.connectString(connectString)
.sessionTimeoutMs(sessionTimeoutMs)
.watchers(childWatchers)
.operationRetryPolicy(operationRetryPolicy)
.build();
}
/**
* A builder to build retryable zookeeper client.
*/
public static class Builder {
String connectString = null;
int sessionTimeoutMs = 10000;
Set<Watcher> watchers = null;
RetryPolicy connectRetryPolicy = null;
RetryPolicy operationRetryPolicy = null;
StatsLogger statsLogger = NullStatsLogger.INSTANCE;
int retryExecThreadCount = DEFAULT_RETRY_EXECUTOR_THREAD_COUNT;
double requestRateLimit = 0;
boolean allowReadOnlyMode = false;
private Builder() {}
public Builder connectString(String connectString) {
this.connectString = connectString;
return this;
}
public Builder sessionTimeoutMs(int sessionTimeoutMs) {
this.sessionTimeoutMs = sessionTimeoutMs;
return this;
}
public Builder watchers(Set<Watcher> watchers) {
this.watchers = watchers;
return this;
}
public Builder connectRetryPolicy(RetryPolicy retryPolicy) {
this.connectRetryPolicy = retryPolicy;
return this;
}
public Builder operationRetryPolicy(RetryPolicy retryPolicy) {
this.operationRetryPolicy = retryPolicy;
return this;
}
public Builder statsLogger(StatsLogger statsLogger) {
this.statsLogger = statsLogger;
return this;
}
public Builder requestRateLimit(double requestRateLimit) {
this.requestRateLimit = requestRateLimit;
return this;
}
public Builder retryThreadCount(int numThreads) {
this.retryExecThreadCount = numThreads;
return this;
}
public Builder allowReadOnlyMode(boolean allowReadOnlyMode) {
this.allowReadOnlyMode = allowReadOnlyMode;
return this;
}
public ZooKeeperClient build() throws IOException, KeeperException, InterruptedException {
checkNotNull(connectString);
checkArgument(sessionTimeoutMs > 0);
checkNotNull(statsLogger);
checkArgument(retryExecThreadCount > 0);
if (null == connectRetryPolicy) {
connectRetryPolicy =
new BoundExponentialBackoffRetryPolicy(sessionTimeoutMs, sessionTimeoutMs, Integer.MAX_VALUE);
}
if (null == operationRetryPolicy) {
operationRetryPolicy =
new BoundExponentialBackoffRetryPolicy(sessionTimeoutMs, sessionTimeoutMs, 0);
}
// Create a watcher manager
StatsLogger watcherStatsLogger = statsLogger.scope("watcher");
ZooKeeperWatcherBase watcherManager =
null == watchers ? new ZooKeeperWatcherBase(sessionTimeoutMs, watcherStatsLogger) :
new ZooKeeperWatcherBase(sessionTimeoutMs, watchers, watcherStatsLogger);
ZooKeeperClient client = new ZooKeeperClient(
connectString,
sessionTimeoutMs,
watcherManager,
connectRetryPolicy,
operationRetryPolicy,
statsLogger,
retryExecThreadCount,
requestRateLimit,
allowReadOnlyMode
);
// Wait for connection to be established.
try {
watcherManager.waitForConnection();
} catch (KeeperException ke) {
client.close();
throw ke;
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
client.close();
throw ie;
}
return client;
}
}
public static Builder newBuilder() {
return new Builder();
}
ZooKeeperClient(String connectString,
int sessionTimeoutMs,
ZooKeeperWatcherBase watcherManager,
RetryPolicy connectRetryPolicy,
RetryPolicy operationRetryPolicy,
StatsLogger statsLogger,
int retryExecThreadCount,
double rate,
boolean allowReadOnlyMode) throws IOException {
super(connectString, sessionTimeoutMs, watcherManager, allowReadOnlyMode);
this.connectString = connectString;
this.sessionTimeoutMs = sessionTimeoutMs;
this.allowReadOnlyMode = allowReadOnlyMode;
this.watcherManager = watcherManager;
this.connectRetryPolicy = connectRetryPolicy;
this.operationRetryPolicy = operationRetryPolicy;
this.rateLimiter = rate > 0 ? RateLimiter.create(rate) : null;
this.retryExecutor =
Executors.newScheduledThreadPool(retryExecThreadCount,
new ThreadFactoryBuilder().setNameFormat("ZKC-retry-executor-%d").build());
this.connectExecutor =
Executors.newSingleThreadExecutor(
new ThreadFactoryBuilder().setNameFormat("ZKC-connect-executor-%d").build());
// added itself to the watcher
watcherManager.addChildWatcher(this);
// Stats
StatsLogger scopedStatsLogger = statsLogger.scope("zk");
createClientStats = scopedStatsLogger.getOpStatsLogger("create_client");
createStats = scopedStatsLogger.getOpStatsLogger("create");
getStats = scopedStatsLogger.getOpStatsLogger("get_data");
setStats = scopedStatsLogger.getOpStatsLogger("set_data");
deleteStats = scopedStatsLogger.getOpStatsLogger("delete");
getChildrenStats = scopedStatsLogger.getOpStatsLogger("get_children");
existsStats = scopedStatsLogger.getOpStatsLogger("exists");
multiStats = scopedStatsLogger.getOpStatsLogger("multi");
getACLStats = scopedStatsLogger.getOpStatsLogger("get_acl");
setACLStats = scopedStatsLogger.getOpStatsLogger("set_acl");
syncStats = scopedStatsLogger.getOpStatsLogger("sync");
}
@Override
public void close() throws InterruptedException {
closed.set(true);
connectExecutor.shutdown();
retryExecutor.shutdown();
closeZkHandle();
}
private void closeZkHandle() throws InterruptedException {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
super.close();
} else {
zkHandle.close();
}
}
protected void waitForConnection() throws KeeperException, InterruptedException {
watcherManager.waitForConnection();
}
protected ZooKeeper createZooKeeper() throws IOException {
return new ZooKeeper(connectString, sessionTimeoutMs, watcherManager, allowReadOnlyMode);
}
@Override
public void process(WatchedEvent event) {
if (event.getType() == EventType.None
&& event.getState() == KeeperState.Expired) {
onExpired();
}
}
private void onExpired() {
if (closed.get()) {
// we don't schedule any tries if the client is closed.
return;
}
logger.info("ZooKeeper session {} is expired from {}.",
Long.toHexString(getSessionId()), connectString);
try {
connectExecutor.submit(clientCreator);
} catch (RejectedExecutionException ree) {
if (!closed.get()) {
logger.error("ZooKeeper reconnect task is rejected : ", ree);
}
} catch (Exception t) {
logger.error("Failed to submit zookeeper reconnect task due to runtime exception : ", t);
}
}
/**
* A runnable that retries zookeeper operations.
*/
abstract static class ZkRetryRunnable implements Runnable {
final ZooWorker worker;
final RateLimiter rateLimiter;
final Runnable that;
ZkRetryRunnable(RetryPolicy retryPolicy,
RateLimiter rateLimiter,
OpStatsLogger statsLogger) {
this.worker = new ZooWorker(retryPolicy, statsLogger);
this.rateLimiter = rateLimiter;
that = this;
}
@Override
public void run() {
if (null != rateLimiter) {
rateLimiter.acquire();
}
zkRun();
}
abstract void zkRun();
}
// inherits from ZooKeeper client for all operations
@Override
public long getSessionId() {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
return super.getSessionId();
}
return zkHandle.getSessionId();
}
@Override
public byte[] getSessionPasswd() {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
return super.getSessionPasswd();
}
return zkHandle.getSessionPasswd();
}
@Override
public int getSessionTimeout() {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
return super.getSessionTimeout();
}
return zkHandle.getSessionTimeout();
}
@Override
public void addAuthInfo(String scheme, byte[] auth) {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
super.addAuthInfo(scheme, auth);
return;
}
zkHandle.addAuthInfo(scheme, auth);
}
private void backOffAndRetry(Runnable r, long nextRetryWaitTimeMs) {
try {
retryExecutor.schedule(r, nextRetryWaitTimeMs, TimeUnit.MILLISECONDS);
} catch (RejectedExecutionException ree) {
if (!closed.get()) {
logger.error("ZooKeeper Operation {} is rejected : ", r, ree);
}
}
}
private boolean allowRetry(ZooWorker worker, int rc) {
return worker.allowRetry(rc) && !closed.get();
}
@Override
public synchronized void register(Watcher watcher) {
watcherManager.addChildWatcher(watcher);
}
@Override
public List<OpResult> multi(final Iterable<Op> ops) throws InterruptedException, KeeperException {
return ZooWorker.syncCallWithRetries(this, new ZooCallable<List<OpResult>>() {
@Override
public String toString() {
return "multi";
}
@Override
public List<OpResult> call() throws KeeperException, InterruptedException {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
return ZooKeeperClient.super.multi(ops);
}
return zkHandle.multi(ops);
}
}, operationRetryPolicy, rateLimiter, multiStats);
}
@Override
public void multi(final Iterable<Op> ops,
final MultiCallback cb,
final Object context) {
final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, createStats) {
final MultiCallback multiCb = new MultiCallback() {
@Override
public void processResult(int rc, String path, Object ctx, List<OpResult> results) {
ZooWorker worker = (ZooWorker) ctx;
if (allowRetry(worker, rc)) {
backOffAndRetry(that, worker.nextRetryWaitTime());
} else {
cb.processResult(rc, path, context, results);
}
}
};
@Override
void zkRun() {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
ZooKeeperClient.super.multi(ops, multiCb, worker);
} else {
zkHandle.multi(ops, multiCb, worker);
}
}
@Override
public String toString() {
return "multi";
}
};
// execute it immediately
proc.run();
}
@Override
@Deprecated
public Transaction transaction() {
// since there is no reference about which client that the transaction could use
// so just use ZooKeeper instance directly.
// you'd better to use {@link #multi}.
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
return super.transaction();
}
return zkHandle.transaction();
}
@Override
public List<ACL> getACL(final String path, final Stat stat) throws KeeperException, InterruptedException {
return ZooWorker.syncCallWithRetries(this, new ZooCallable<List<ACL>>() {
@Override
public String toString() {
return String.format("getACL (%s, stat = %s)", path, stat);
}
@Override
public List<ACL> call() throws KeeperException, InterruptedException {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
return ZooKeeperClient.super.getACL(path, stat);
}
return zkHandle.getACL(path, stat);
}
}, operationRetryPolicy, rateLimiter, getACLStats);
}
@Override
public void getACL(final String path, final Stat stat, final ACLCallback cb, final Object context) {
final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getACLStats) {
final ACLCallback aclCb = new ACLCallback() {
@Override
public void processResult(int rc, String path, Object ctx, List<ACL> acl, Stat stat) {
ZooWorker worker = (ZooWorker) ctx;
if (allowRetry(worker, rc)) {
backOffAndRetry(that, worker.nextRetryWaitTime());
} else {
cb.processResult(rc, path, context, acl, stat);
}
}
};
@Override
public String toString() {
return String.format("getACL (%s, stat = %s)", path, stat);
}
@Override
void zkRun() {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
ZooKeeperClient.super.getACL(path, stat, aclCb, worker);
} else {
zkHandle.getACL(path, stat, aclCb, worker);
}
}
};
// execute it immediately
proc.run();
}
@Override
public Stat setACL(final String path, final List<ACL> acl, final int version)
throws KeeperException, InterruptedException {
return ZooWorker.syncCallWithRetries(this, new ZooCallable<Stat>() {
@Override
public String toString() {
return String.format("setACL (%s, acl = %s, version = %d)", path, acl, version);
}
@Override
public Stat call() throws KeeperException, InterruptedException {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
return ZooKeeperClient.super.setACL(path, acl, version);
}
return zkHandle.setACL(path, acl, version);
}
}, operationRetryPolicy, rateLimiter, setACLStats);
}
@Override
public void setACL(final String path, final List<ACL> acl, final int version,
final StatCallback cb, final Object context) {
final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, setACLStats) {
final StatCallback stCb = new StatCallback() {
@Override
public void processResult(int rc, String path, Object ctx, Stat stat) {
ZooWorker worker = (ZooWorker) ctx;
if (allowRetry(worker, rc)) {
backOffAndRetry(that, worker.nextRetryWaitTime());
} else {
cb.processResult(rc, path, context, stat);
}
}
};
@Override
public String toString() {
return String.format("setACL (%s, acl = %s, version = %d)", path, acl, version);
}
@Override
void zkRun() {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
ZooKeeperClient.super.setACL(path, acl, version, stCb, worker);
} else {
zkHandle.setACL(path, acl, version, stCb, worker);
}
}
};
// execute it immediately
proc.run();
}
@Override
public void sync(final String path, final VoidCallback cb, final Object context) {
final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, syncStats) {
final VoidCallback vCb = new VoidCallback() {
@Override
public void processResult(int rc, String path, Object ctx) {
ZooWorker worker = (ZooWorker) ctx;
if (allowRetry(worker, rc)) {
backOffAndRetry(that, worker.nextRetryWaitTime());
} else {
cb.processResult(rc, path, context);
}
}
};
@Override
public String toString() {
return String.format("sync (%s)", path);
}
@Override
void zkRun() {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
ZooKeeperClient.super.sync(path, vCb, worker);
} else {
zkHandle.sync(path, vCb, worker);
}
}
};
// execute it immediately
proc.run();
}
@Override
public States getState() {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
return ZooKeeperClient.super.getState();
} else {
return zkHandle.getState();
}
}
@Override
public String toString() {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
return ZooKeeperClient.super.toString();
} else {
return zkHandle.toString();
}
}
@Override
public String create(final String path, final byte[] data,
final List<ACL> acl, final CreateMode createMode)
throws KeeperException, InterruptedException {
return ZooWorker.syncCallWithRetries(this, new ZooCallable<String>() {
@Override
public String call() throws KeeperException, InterruptedException {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
return ZooKeeperClient.super.create(path, data, acl, createMode);
}
return zkHandle.create(path, data, acl, createMode);
}
@Override
public String toString() {
return String.format("create (%s, acl = %s, mode = %s)", path, acl, createMode);
}
}, operationRetryPolicy, rateLimiter, createStats);
}
@Override
public void create(final String path, final byte[] data, final List<ACL> acl,
final CreateMode createMode, final StringCallback cb, final Object context) {
final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, createStats) {
final StringCallback createCb = new StringCallback() {
@Override
public void processResult(int rc, String path, Object ctx, String name) {
ZooWorker worker = (ZooWorker) ctx;
if (allowRetry(worker, rc)) {
backOffAndRetry(that, worker.nextRetryWaitTime());
} else {
cb.processResult(rc, path, context, name);
}
}
};
@Override
void zkRun() {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
ZooKeeperClient.super.create(path, data, acl, createMode, createCb, worker);
} else {
zkHandle.create(path, data, acl, createMode, createCb, worker);
}
}
@Override
public String toString() {
return String.format("create (%s, acl = %s, mode = %s)", path, acl, createMode);
}
};
// execute it immediately
proc.run();
}
@Override
public String create(final String path,
final byte[] data,
final List<ACL> acl,
final CreateMode createMode,
final Stat stat)
throws KeeperException, InterruptedException {
return ZooWorker.syncCallWithRetries(this, new ZooCallable<String>() {
@Override
public String call() throws KeeperException, InterruptedException {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
return ZooKeeperClient.super.create(path, data, acl, createMode);
}
return zkHandle.create(path, data, acl, createMode);
}
@Override
public String toString() {
return String.format("create (%s, acl = %s, mode = %s)", path, acl, createMode);
}
}, operationRetryPolicy, rateLimiter, createStats);
}
@Override
public void create(final String path,
final byte[] data,
final List<ACL> acl,
final CreateMode createMode,
final Create2Callback cb,
final Object context) {
final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, createStats) {
final Create2Callback createCb = new Create2Callback() {
@Override
public void processResult(int rc, String path, Object ctx, String name, Stat stat) {
ZooWorker worker = (ZooWorker) ctx;
if (allowRetry(worker, rc)) {
backOffAndRetry(that, worker.nextRetryWaitTime());
} else {
cb.processResult(rc, path, context, name, stat);
}
}
};
@Override
void zkRun() {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
ZooKeeperClient.super.create(path, data, acl, createMode, createCb, worker);
} else {
zkHandle.create(path, data, acl, createMode, createCb, worker);
}
}
@Override
public String toString() {
return String.format("create (%s, acl = %s, mode = %s)", path, acl, createMode);
}
};
// execute it immediately
proc.run();
}
@Override
public void delete(final String path, final int version) throws KeeperException, InterruptedException {
ZooWorker.syncCallWithRetries(this, new ZooCallable<Void>() {
@Override
public Void call() throws KeeperException, InterruptedException {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
ZooKeeperClient.super.delete(path, version);
} else {
zkHandle.delete(path, version);
}
return null;
}
@Override
public String toString() {
return String.format("delete (%s, version = %d)", path, version);
}
}, operationRetryPolicy, rateLimiter, deleteStats);
}
@Override
public void delete(final String path, final int version, final VoidCallback cb, final Object context) {
final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, deleteStats) {
final VoidCallback deleteCb = new VoidCallback() {
@Override
public void processResult(int rc, String path, Object ctx) {
ZooWorker worker = (ZooWorker) ctx;
if (allowRetry(worker, rc)) {
backOffAndRetry(that, worker.nextRetryWaitTime());
} else {
cb.processResult(rc, path, context);
}
}
};
@Override
void zkRun() {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
ZooKeeperClient.super.delete(path, version, deleteCb, worker);
} else {
zkHandle.delete(path, version, deleteCb, worker);
}
}
@Override
public String toString() {
return String.format("delete (%s, version = %d)", path, version);
}
};
// execute it immediately
proc.run();
}
@Override
public Stat exists(final String path, final Watcher watcher) throws KeeperException, InterruptedException {
return ZooWorker.syncCallWithRetries(this, new ZooCallable<Stat>() {
@Override
public Stat call() throws KeeperException, InterruptedException {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
return ZooKeeperClient.super.exists(path, watcher);
}
return zkHandle.exists(path, watcher);
}
@Override
public String toString() {
return String.format("exists (%s, watcher = %s)", path, watcher);
}
}, operationRetryPolicy, rateLimiter, existsStats);
}
@Override
public Stat exists(final String path, final boolean watch) throws KeeperException, InterruptedException {
return ZooWorker.syncCallWithRetries(this, new ZooCallable<Stat>() {
@Override
public Stat call() throws KeeperException, InterruptedException {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
return ZooKeeperClient.super.exists(path, watch);
}
return zkHandle.exists(path, watch);
}
@Override
public String toString() {
return String.format("exists (%s, watcher = %s)", path, watch);
}
}, operationRetryPolicy, rateLimiter, existsStats);
}
@Override
public void exists(final String path, final Watcher watcher, final StatCallback cb, final Object context) {
final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, existsStats) {
final StatCallback stCb = new StatCallback() {
@Override
public void processResult(int rc, String path, Object ctx, Stat stat) {
ZooWorker worker = (ZooWorker) ctx;
if (allowRetry(worker, rc)) {
backOffAndRetry(that, worker.nextRetryWaitTime());
} else {
cb.processResult(rc, path, context, stat);
}
}
};
@Override
void zkRun() {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
ZooKeeperClient.super.exists(path, watcher, stCb, worker);
} else {
zkHandle.exists(path, watcher, stCb, worker);
}
}
@Override
public String toString() {
return String.format("exists (%s, watcher = %s)", path, watcher);
}
};
// execute it immediately
proc.run();
}
@Override
public void exists(final String path, final boolean watch, final StatCallback cb, final Object context) {
final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, existsStats) {
final StatCallback stCb = new StatCallback() {
@Override
public void processResult(int rc, String path, Object ctx, Stat stat) {
ZooWorker worker = (ZooWorker) ctx;
if (allowRetry(worker, rc)) {
backOffAndRetry(that, worker.nextRetryWaitTime());
} else {
cb.processResult(rc, path, context, stat);
}
}
};
@Override
void zkRun() {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
ZooKeeperClient.super.exists(path, watch, stCb, worker);
} else {
zkHandle.exists(path, watch, stCb, worker);
}
}
@Override
public String toString() {
return String.format("exists (%s, watcher = %s)", path, watch);
}
};
// execute it immediately
proc.run();
}
@Override
public byte[] getData(final String path, final Watcher watcher, final Stat stat)
throws KeeperException, InterruptedException {
return ZooWorker.syncCallWithRetries(this, new ZooCallable<byte[]>() {
@Override
public byte[] call() throws KeeperException, InterruptedException {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
return ZooKeeperClient.super.getData(path, watcher, stat);
}
return zkHandle.getData(path, watcher, stat);
}
@Override
public String toString() {
return String.format("getData (%s, watcher = %s)", path, watcher);
}
}, operationRetryPolicy, rateLimiter, getStats);
}
@Override
public byte[] getData(final String path, final boolean watch, final Stat stat)
throws KeeperException, InterruptedException {
return ZooWorker.syncCallWithRetries(this, new ZooCallable<byte[]>() {
@Override
public byte[] call() throws KeeperException, InterruptedException {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
return ZooKeeperClient.super.getData(path, watch, stat);
}
return zkHandle.getData(path, watch, stat);
}
@Override
public String toString() {
return String.format("getData (%s, watcher = %s)", path, watch);
}
}, operationRetryPolicy, rateLimiter, getStats);
}
@Override
public void getData(final String path, final Watcher watcher, final DataCallback cb, final Object context) {
final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getStats) {
final DataCallback dataCb = new DataCallback() {
@Override
public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
ZooWorker worker = (ZooWorker) ctx;
if (allowRetry(worker, rc)) {
backOffAndRetry(that, worker.nextRetryWaitTime());
} else {
cb.processResult(rc, path, context, data, stat);
}
}
};
@Override
void zkRun() {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
ZooKeeperClient.super.getData(path, watcher, dataCb, worker);
} else {
zkHandle.getData(path, watcher, dataCb, worker);
}
}
@Override
public String toString() {
return String.format("getData (%s, watcher = %s)", path, watcher);
}
};
// execute it immediately
proc.run();
}
@Override
public void getData(final String path, final boolean watch, final DataCallback cb, final Object context) {
final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getStats) {
final DataCallback dataCb = new DataCallback() {
@Override
public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
ZooWorker worker = (ZooWorker) ctx;
if (allowRetry(worker, rc)) {
backOffAndRetry(that, worker.nextRetryWaitTime());
} else {
cb.processResult(rc, path, context, data, stat);
}
}
};
@Override
void zkRun() {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
ZooKeeperClient.super.getData(path, watch, dataCb, worker);
} else {
zkHandle.getData(path, watch, dataCb, worker);
}
}
@Override
public String toString() {
return String.format("getData (%s, watcher = %s)", path, watch);
}
};
// execute it immediately
proc.run();
}
@Override
public Stat setData(final String path, final byte[] data, final int version)
throws KeeperException, InterruptedException {
return ZooWorker.syncCallWithRetries(this, new ZooCallable<Stat>() {
@Override
public Stat call() throws KeeperException, InterruptedException {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
return ZooKeeperClient.super.setData(path, data, version);
}
return zkHandle.setData(path, data, version);
}
@Override
public String toString() {
return String.format("setData (%s, version = %d)", path, version);
}
}, operationRetryPolicy, rateLimiter, setStats);
}
@Override
public void setData(final String path, final byte[] data, final int version,
final StatCallback cb, final Object context) {
final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, setStats) {
final StatCallback stCb = new StatCallback() {
@Override
public void processResult(int rc, String path, Object ctx, Stat stat) {
ZooWorker worker = (ZooWorker) ctx;
if (allowRetry(worker, rc)) {
backOffAndRetry(that, worker.nextRetryWaitTime());
} else {
cb.processResult(rc, path, context, stat);
}
}
};
@Override
void zkRun() {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
ZooKeeperClient.super.setData(path, data, version, stCb, worker);
} else {
zkHandle.setData(path, data, version, stCb, worker);
}
}
@Override
public String toString() {
return String.format("setData (%s, version = %d)", path, version);
}
};
// execute it immediately
proc.run();
}
@Override
public List<String> getChildren(final String path, final Watcher watcher, final Stat stat)
throws KeeperException, InterruptedException {
return ZooWorker.syncCallWithRetries(this, new ZooCallable<List<String>>() {
@Override
public List<String> call() throws KeeperException, InterruptedException {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
return ZooKeeperClient.super.getChildren(path, watcher, stat);
}
return zkHandle.getChildren(path, watcher, stat);
}
@Override
public String toString() {
return String.format("getChildren (%s, watcher = %s)", path, watcher);
}
}, operationRetryPolicy, rateLimiter, getChildrenStats);
}
@Override
public List<String> getChildren(final String path, final boolean watch, final Stat stat)
throws KeeperException, InterruptedException {
return ZooWorker.syncCallWithRetries(this, new ZooCallable<List<String>>() {
@Override
public List<String> call() throws KeeperException, InterruptedException {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
return ZooKeeperClient.super.getChildren(path, watch, stat);
}
return zkHandle.getChildren(path, watch, stat);
}
@Override
public String toString() {
return String.format("getChildren (%s, watcher = %s)", path, watch);
}
}, operationRetryPolicy, rateLimiter, getChildrenStats);
}
@Override
public void getChildren(final String path, final Watcher watcher,
final Children2Callback cb, final Object context) {
final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getChildrenStats) {
final Children2Callback childCb = new Children2Callback() {
@Override
public void processResult(int rc, String path, Object ctx,
List<String> children, Stat stat) {
ZooWorker worker = (ZooWorker) ctx;
if (allowRetry(worker, rc)) {
backOffAndRetry(that, worker.nextRetryWaitTime());
} else {
cb.processResult(rc, path, context, children, stat);
}
}
};
@Override
void zkRun() {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
ZooKeeperClient.super.getChildren(path, watcher, childCb, worker);
} else {
zkHandle.getChildren(path, watcher, childCb, worker);
}
}
@Override
public String toString() {
return String.format("getChildren (%s, watcher = %s)", path, watcher);
}
};
// execute it immediately
proc.run();
}
@Override
public void getChildren(final String path, final boolean watch, final Children2Callback cb,
final Object context) {
final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getChildrenStats) {
final Children2Callback childCb = new Children2Callback() {
@Override
public void processResult(int rc, String path, Object ctx,
List<String> children, Stat stat) {
ZooWorker worker = (ZooWorker) ctx;
if (allowRetry(worker, rc)) {
backOffAndRetry(that, worker.nextRetryWaitTime());
} else {
cb.processResult(rc, path, context, children, stat);
}
}
};
@Override
void zkRun() {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
ZooKeeperClient.super.getChildren(path, watch, childCb, worker);
} else {
zkHandle.getChildren(path, watch, childCb, worker);
}
}
@Override
public String toString() {
return String.format("getChildren (%s, watcher = %s)", path, watch);
}
};
// execute it immediately
proc.run();
}
@Override
public List<String> getChildren(final String path, final Watcher watcher)
throws KeeperException, InterruptedException {
return ZooWorker.syncCallWithRetries(this, new ZooCallable<List<String>>() {
@Override
public List<String> call() throws KeeperException, InterruptedException {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
return ZooKeeperClient.super.getChildren(path, watcher);
}
return zkHandle.getChildren(path, watcher);
}
@Override
public String toString() {
return String.format("getChildren (%s, watcher = %s)", path, watcher);
}
}, operationRetryPolicy, rateLimiter, getChildrenStats);
}
@Override
public List<String> getChildren(final String path, final boolean watch)
throws KeeperException, InterruptedException {
return ZooWorker.syncCallWithRetries(this, new ZooCallable<List<String>>() {
@Override
public List<String> call() throws KeeperException, InterruptedException {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
return ZooKeeperClient.super.getChildren(path, watch);
}
return zkHandle.getChildren(path, watch);
}
@Override
public String toString() {
return String.format("getChildren (%s, watcher = %s)", path, watch);
}
}, operationRetryPolicy, rateLimiter, getChildrenStats);
}
@Override
public void getChildren(final String path, final Watcher watcher,
final ChildrenCallback cb, final Object context) {
final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getChildrenStats) {
final ChildrenCallback childCb = new ChildrenCallback() {
@Override
public void processResult(int rc, String path, Object ctx,
List<String> children) {
ZooWorker worker = (ZooWorker) ctx;
if (allowRetry(worker, rc)) {
backOffAndRetry(that, worker.nextRetryWaitTime());
} else {
cb.processResult(rc, path, context, children);
}
}
};
@Override
void zkRun() {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
ZooKeeperClient.super.getChildren(path, watcher, childCb, worker);
} else {
zkHandle.getChildren(path, watcher, childCb, worker);
}
}
@Override
public String toString() {
return String.format("getChildren (%s, watcher = %s)", path, watcher);
}
};
// execute it immediately
proc.run();
}
@Override
public void getChildren(final String path, final boolean watch,
final ChildrenCallback cb, final Object context) {
final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getChildrenStats) {
final ChildrenCallback childCb = new ChildrenCallback() {
@Override
public void processResult(int rc, String path, Object ctx,
List<String> children) {
ZooWorker worker = (ZooWorker) ctx;
if (allowRetry(worker, rc)) {
backOffAndRetry(that, worker.nextRetryWaitTime());
} else {
cb.processResult(rc, path, context, children);
}
}
};
@Override
void zkRun() {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
ZooKeeperClient.super.getChildren(path, watch, childCb, worker);
} else {
zkHandle.getChildren(path, watch, childCb, worker);
}
}
@Override
public String toString() {
return String.format("getChildren (%s, watcher = %s)", path, watch);
}
};
// execute it immediately
proc.run();
}
@Override
public void removeWatches(String path, Watcher watcher, WatcherType watcherType, boolean local)
throws InterruptedException, KeeperException {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
ZooKeeperClient.super.removeWatches(path, watcher, watcherType, local);
} else {
zkHandle.removeWatches(path, watcher, watcherType, local);
}
}
@Override
public void removeWatches(String path,
Watcher watcher,
WatcherType watcherType,
boolean local,
VoidCallback cb,
Object ctx) {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
ZooKeeperClient.super.removeWatches(path, watcher, watcherType, local, cb, ctx);
} else {
zkHandle.removeWatches(path, watcher, watcherType, local, cb, ctx);
}
}
@Override
public void removeAllWatches(String path, WatcherType watcherType, boolean local)
throws InterruptedException, KeeperException {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
ZooKeeperClient.super.removeAllWatches(path, watcherType, local);
} else {
zkHandle.removeAllWatches(path, watcherType, local);
}
}
@Override
public void removeAllWatches(String path, WatcherType watcherType, boolean local, VoidCallback cb, Object ctx) {
ZooKeeper zkHandle = zk.get();
if (null == zkHandle) {
ZooKeeperClient.super.removeAllWatches(path, watcherType, local, cb, ctx);
} else {
zkHandle.removeAllWatches(path, watcherType, local, cb, ctx);
}
}
}
| |
/*
* Copyright 2000-2016 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 com.jetbrains.python.codeInsight;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiPolyVariantReference;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.containers.HashSet;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.PyExpressionCodeFragmentImpl;
import com.jetbrains.python.psi.resolve.PyResolveContext;
import com.jetbrains.python.psi.types.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.intellij.util.containers.ContainerUtil.list;
import static com.jetbrains.python.psi.PyUtil.as;
/**
* @author vlan
*/
public class PyTypingTypeProvider extends PyTypeProviderBase {
public static final Pattern TYPE_COMMENT_PATTERN = Pattern.compile("# *type: *(.*)");
private static ImmutableMap<String, String> COLLECTION_CLASSES = ImmutableMap.<String, String>builder()
.put("typing.List", "list")
.put("typing.Dict", "dict")
.put("typing.Set", PyNames.SET)
.put("typing.FrozenSet", "frozenset")
.put("typing.Tuple", PyNames.TUPLE)
.put("typing.Iterable", PyNames.COLLECTIONS + "." + PyNames.ITERABLE)
.put("typing.Iterator", PyNames.COLLECTIONS + "." + PyNames.ITERATOR)
.put("typing.Container", PyNames.COLLECTIONS + "." + PyNames.CONTAINER)
.put("typing.Sequence", PyNames.COLLECTIONS + "." + PyNames.SEQUENCE)
.put("typing.MutableSequence", PyNames.COLLECTIONS + "." + "MutableSequence")
.put("typing.Mapping", PyNames.COLLECTIONS + "." + PyNames.MAPPING)
.put("typing.MutableMapping", PyNames.COLLECTIONS + "." + "MutableMapping")
.put("typing.AbstractSet", PyNames.COLLECTIONS + "." + "Set")
.put("typing.MutableSet", PyNames.COLLECTIONS + "." + "MutableSet")
.build();
public static ImmutableMap<String, String> TYPING_COLLECTION_CLASSES = ImmutableMap.<String, String>builder()
.put("list", "List")
.put("dict", "Dict")
.put("set", "Set")
.put("frozenset", "FrozenSet")
.build();
private static ImmutableSet<String> GENERIC_CLASSES = ImmutableSet.<String>builder()
.add("typing.Generic")
.add("typing.AbstractGeneric")
.add("typing.Protocol")
.build();
@Nullable
public Ref<PyType> getParameterType(@NotNull PyNamedParameter param, @NotNull PyFunction func, @NotNull TypeEvalContext context) {
final PyAnnotation annotation = param.getAnnotation();
if (annotation != null) {
// XXX: Requires switching from stub to AST
final PyExpression value = annotation.getValue();
if (value != null) {
final PyType type = getType(value, new Context(context));
if (type != null) {
final PyType optionalType = getOptionalTypeFromDefaultNone(param, type, context);
return Ref.create(optionalType != null ? optionalType : type);
}
}
}
final String paramComment = param.getTypeCommentAnnotation();
if (paramComment != null) {
return Ref.create(getStringBasedType(paramComment, param, new Context(context)));
}
final String comment = func.getTypeCommentAnnotation();
if (comment != null) {
final PyTypeParser.ParseResult result = PyTypeParser.parsePep484FunctionTypeComment(param, comment);
final PyCallableType functionType = as(result.getType(), PyCallableType.class);
if (functionType != null) {
final List<PyCallableParameter> paramTypes = functionType.getParameters(context);
// Function annotation of kind (...) -> Type
if (paramTypes == null) {
return Ref.create();
}
final PyParameter[] funcParams = func.getParameterList().getParameters();
final int startOffset = omitFirstParamInTypeComment(func) ? 1 : 0;
for (int paramIndex = 0; paramIndex < funcParams.length; paramIndex++) {
if (funcParams[paramIndex] == param) {
final int typeIndex = paramIndex - startOffset;
if (typeIndex >= 0 && typeIndex < paramTypes.size()) {
return Ref.create(paramTypes.get(typeIndex).getType(context));
}
break;
}
}
}
}
return null;
}
private static boolean omitFirstParamInTypeComment(@NotNull PyFunction func) {
return func.getContainingClass() != null && func.getModifier() != PyFunction.Modifier.STATICMETHOD;
}
@Nullable
@Override
public Ref<PyType> getReturnType(@NotNull PyCallable callable, @NotNull TypeEvalContext context) {
if (callable instanceof PyFunction) {
final PyFunction function = (PyFunction)callable;
final PyAnnotation annotation = function.getAnnotation();
if (annotation != null) {
// XXX: Requires switching from stub to AST
final PyExpression value = annotation.getValue();
if (value != null) {
final PyType type = getType(value, new Context(context));
return type != null ? Ref.create(type) : null;
}
}
final PyType constructorType = getGenericConstructorType(function, new Context(context));
if (constructorType != null) {
return Ref.create(constructorType);
}
final String comment = function.getTypeCommentAnnotation();
if (comment != null) {
final PyTypeParser.ParseResult result = PyTypeParser.parsePep484FunctionTypeComment(callable, comment);
final PyCallableType funcType = as(result.getType(), PyCallableType.class);
if (funcType != null) {
return Ref.create(funcType.getReturnType(context));
}
}
}
return null;
}
@Nullable
@Override
public Ref<PyType> getCallType(@NotNull PyFunction function, @Nullable PyCallSiteExpression callSite, @NotNull TypeEvalContext context) {
if ("typing.cast".equals(function.getQualifiedName())) {
return Optional
.ofNullable(as(callSite, PyCallExpression.class))
.map(PyCallExpression::getArguments)
.filter(args -> args.length > 0)
.map(args -> getType(args[0], new Context(context)))
.map(Ref::create)
.orElse(null);
}
return null;
}
@Override
public PyType getReferenceType(@NotNull PsiElement referenceTarget, TypeEvalContext context, @Nullable PsiElement anchor) {
if (referenceTarget instanceof PyTargetExpression) {
final PyTargetExpression target = (PyTargetExpression)referenceTarget;
if (context.maySwitchToAST(target)) {
// XXX: Requires switching from stub to AST
final PyAnnotation annotation = target.getAnnotation();
if (annotation != null) {
final PyExpression value = annotation.getValue();
if (value != null) {
return getType(value, new Context(context));
}
return null;
}
}
final String comment = target.getTypeCommentAnnotation();
if (comment != null) {
final PyType type = getStringBasedType(comment, referenceTarget, new Context(context));
if (type instanceof PyTupleType) {
final PyTupleExpression tupleExpr = PsiTreeUtil.getParentOfType(target, PyTupleExpression.class);
if (tupleExpr != null) {
return PyTypeChecker.getTargetTypeFromTupleAssignment(target, tupleExpr, (PyTupleType)type);
}
}
return type;
}
}
return null;
}
/**
* Checks that text of a comment starts with the "type:" prefix and returns trimmed part afterwards. This trailing part is supposed to
* contain type annotation in PEP 484 compatible format, that can be parsed with either {@link PyTypeParser#parse(PsiElement, String)}
* or {@link PyTypeParser#parsePep484FunctionTypeComment(PsiElement, String)}.
*/
@Nullable
public static String getTypeCommentValue(@NotNull String text) {
final Matcher m = TYPE_COMMENT_PATTERN.matcher(text);
if (m.matches()) {
return m.group(1);
}
return null;
}
private static boolean isAny(@NotNull PyType type) {
return type instanceof PyClassType && "typing.Any".equals(((PyClassType)type).getPyClass().getQualifiedName());
}
@Nullable
private static PyType getOptionalTypeFromDefaultNone(@NotNull PyNamedParameter param,
@NotNull PyType type,
@NotNull TypeEvalContext context) {
final PyExpression defaultValue = param.getDefaultValue();
if (defaultValue != null) {
final PyType defaultType = context.getType(defaultValue);
if (defaultType instanceof PyNoneType) {
return PyUnionType.union(type, defaultType);
}
}
return null;
}
@Nullable
private static PyType getGenericConstructorType(@NotNull PyFunction function, @NotNull Context context) {
if (PyUtil.isInit(function)) {
final PyClass cls = function.getContainingClass();
if (cls != null) {
final List<PyGenericType> genericTypes = collectGenericTypes(cls, context);
final List<PyType> elementTypes = new ArrayList<>(genericTypes);
if (!elementTypes.isEmpty()) {
return new PyCollectionTypeImpl(cls, false, elementTypes);
}
}
}
return null;
}
@NotNull
private static List<PyGenericType> collectGenericTypes(@NotNull PyClass cls, @NotNull Context context) {
boolean isGeneric = false;
for (PyClass ancestor : cls.getAncestorClasses(context.getTypeContext())) {
if (GENERIC_CLASSES.contains(ancestor.getQualifiedName())) {
isGeneric = true;
break;
}
}
if (isGeneric) {
final ArrayList<PyGenericType> results = new ArrayList<>();
// XXX: Requires switching from stub to AST
for (PyExpression expr : cls.getSuperClassExpressions()) {
if (expr instanceof PySubscriptionExpression) {
final PyExpression indexExpr = ((PySubscriptionExpression)expr).getIndexExpression();
if (indexExpr != null) {
for (PsiElement resolved : tryResolving(indexExpr, context.getTypeContext())) {
final PyGenericType genericType = getGenericType(resolved, context);
if (genericType != null) {
results.add(genericType);
}
}
}
}
}
return results;
}
return Collections.emptyList();
}
@Nullable
private static PyType getType(@NotNull PyExpression expression, @NotNull Context context) {
final List<PyType> members = Lists.newArrayList();
for (PsiElement resolved : tryResolving(expression, context.getTypeContext())) {
members.add(getTypeForResolvedElement(resolved, context));
}
return PyUnionType.union(members);
}
@Nullable
private static PyType getTypeForResolvedElement(@NotNull PsiElement resolved, @NotNull Context context) {
if (context.getExpressionCache().contains(resolved)) {
// Recursive types are not yet supported
return null;
}
context.getExpressionCache().add(resolved);
try {
final PyType unionType = getUnionType(resolved, context);
if (unionType != null) {
return unionType;
}
final Ref<PyType> optionalType = getOptionalType(resolved, context);
if (optionalType != null) {
return optionalType.get();
}
final PyType callableType = getCallableType(resolved, context);
if (callableType != null) {
return callableType;
}
final PyType parameterizedType = getParameterizedType(resolved, context);
if (parameterizedType != null) {
return parameterizedType;
}
final PyType builtinCollection = getBuiltinCollection(resolved);
if (builtinCollection != null) {
return builtinCollection;
}
final PyType genericType = getGenericType(resolved, context);
if (genericType != null) {
return genericType;
}
final Ref<PyType> classType = getClassType(resolved, context.getTypeContext());
if (classType != null) {
return classType.get();
}
final PyType stringBasedType = getStringBasedType(resolved, context);
if (stringBasedType != null) {
return stringBasedType;
}
return null;
}
finally {
context.getExpressionCache().remove(resolved);
}
}
@Nullable
public static PyType getType(@NotNull PsiElement resolved, @NotNull List<PyType> elementTypes) {
final String qualifiedName = getQualifiedName(resolved);
final List<Integer> paramListTypePositions = new ArrayList<>();
final List<Integer> ellipsisTypePositions = new ArrayList<>();
for (int i = 0; i < elementTypes.size(); i++) {
final PyType type = elementTypes.get(i);
if (type instanceof PyTypeParser.ParameterListType) {
paramListTypePositions.add(i);
}
else if (type instanceof PyTypeParser.EllipsisType) {
ellipsisTypePositions.add(i);
}
}
if (!paramListTypePositions.isEmpty()) {
if (!("typing.Callable".equals(qualifiedName) && paramListTypePositions.equals(list(0)))) {
return null;
}
}
if (!ellipsisTypePositions.isEmpty()) {
if (!("typing.Callable".equals(qualifiedName) && ellipsisTypePositions.equals(list(0)) ||
"typing.Tuple".equals(qualifiedName) && ellipsisTypePositions.equals(list(1)) && elementTypes.size() == 2)) {
return null;
}
}
if ("typing.Union".equals(qualifiedName)) {
return PyUnionType.union(elementTypes);
}
if ("typing.Optional".equals(qualifiedName) && elementTypes.size() == 1) {
return PyUnionType.union(elementTypes.get(0), PyNoneType.INSTANCE);
}
if ("typing.Callable".equals(qualifiedName) && elementTypes.size() == 2) {
final PyTypeParser.ParameterListType paramList = as(elementTypes.get(0), PyTypeParser.ParameterListType.class);
if (paramList != null) {
return new PyCallableTypeImpl(paramList.getCallableParameters(), elementTypes.get(1));
}
if (elementTypes.get(0) instanceof PyTypeParser.EllipsisType) {
return new PyCallableTypeImpl(null, elementTypes.get(1));
}
}
if ("typing.Tuple".equals(qualifiedName)) {
if (elementTypes.size() > 1 && elementTypes.get(1) instanceof PyTypeParser.EllipsisType) {
return PyTupleType.createHomogeneous(resolved, elementTypes.get(0));
}
return PyTupleType.create(resolved, elementTypes.toArray(new PyType[elementTypes.size()]));
}
final PyType builtinCollection = getBuiltinCollection(resolved);
if (builtinCollection instanceof PyClassType) {
final PyClassType classType = (PyClassType)builtinCollection;
return new PyCollectionTypeImpl(classType.getPyClass(), false, elementTypes);
}
return null;
}
@Nullable
public static PyType getTypeFromTargetExpression(@NotNull PyTargetExpression expression, @NotNull TypeEvalContext context) {
return getTypeFromTargetExpression(expression, new Context(context));
}
@Nullable
private static PyType getTypeFromTargetExpression(@NotNull PyTargetExpression expression,
@NotNull Context context) {
// XXX: Requires switching from stub to AST
final PyExpression assignedValue = expression.findAssignedValue();
return assignedValue != null ? getTypeForResolvedElement(assignedValue, context) : null;
}
@Nullable
private static Ref<PyType> getClassType(@NotNull PsiElement element, @NotNull TypeEvalContext context) {
if (element instanceof PyTypedElement) {
final PyType type = context.getType((PyTypedElement)element);
if (type != null && isAny(type)) {
return Ref.create();
}
if (type instanceof PyClassLikeType) {
final PyClassLikeType classType = (PyClassLikeType)type;
if (classType.isDefinition()) {
final PyType instanceType = classType.toInstance();
return Ref.create(instanceType);
}
}
else if (type instanceof PyNoneType) {
return Ref.create(type);
}
}
return null;
}
@Nullable
private static Ref<PyType> getOptionalType(@NotNull PsiElement element, @NotNull Context context) {
if (element instanceof PySubscriptionExpression) {
final PySubscriptionExpression subscriptionExpr = (PySubscriptionExpression)element;
final PyExpression operand = subscriptionExpr.getOperand();
final Collection<String> operandNames = resolveToQualifiedNames(operand, context.getTypeContext());
if (operandNames.contains("typing.Optional")) {
final PyExpression indexExpr = subscriptionExpr.getIndexExpression();
if (indexExpr != null) {
final PyType type = getType(indexExpr, context);
if (type != null) {
return Ref.create(PyUnionType.union(type, PyNoneType.INSTANCE));
}
}
return Ref.create();
}
}
return null;
}
@Nullable
private static PyType getStringBasedType(@NotNull PsiElement element, @NotNull Context context) {
if (element instanceof PyStringLiteralExpression) {
// XXX: Requires switching from stub to AST
final String contents = ((PyStringLiteralExpression)element).getStringValue();
return getStringBasedType(contents, element, context);
}
return null;
}
@Nullable
private static PyType getStringBasedType(@NotNull String contents, @NotNull PsiElement anchor, @NotNull Context context) {
final Project project = anchor.getProject();
final PyExpressionCodeFragmentImpl codeFragment = new PyExpressionCodeFragmentImpl(project, "dummy.py", contents, false);
codeFragment.setContext(anchor.getContainingFile());
final PsiElement element = codeFragment.getFirstChild();
if (element instanceof PyExpressionStatement) {
final PyExpression expr = ((PyExpressionStatement)element).getExpression();
if (expr instanceof PyTupleExpression) {
final PyTupleExpression tupleExpr = (PyTupleExpression)expr;
final List<PyType> elementTypes = new ArrayList<>();
for (PyExpression elementExpr : tupleExpr.getElements()) {
elementTypes.add(getType(elementExpr, context));
}
return PyTupleType.create(anchor, elementTypes.toArray(new PyType[elementTypes.size()]));
}
return getType(expr, context);
}
return null;
}
@Nullable
private static PyType getCallableType(@NotNull PsiElement resolved, @NotNull Context context) {
if (resolved instanceof PySubscriptionExpression) {
final PySubscriptionExpression subscriptionExpr = (PySubscriptionExpression)resolved;
final PyExpression operand = subscriptionExpr.getOperand();
final Collection<String> operandNames = resolveToQualifiedNames(operand, context.getTypeContext());
if (operandNames.contains("typing.Callable")) {
final PyExpression indexExpr = subscriptionExpr.getIndexExpression();
if (indexExpr instanceof PyTupleExpression) {
final PyTupleExpression tupleExpr = (PyTupleExpression)indexExpr;
final PyExpression[] elements = tupleExpr.getElements();
if (elements.length == 2) {
final PyExpression parametersExpr = elements[0];
final PyExpression returnTypeExpr = elements[1];
if (parametersExpr instanceof PyListLiteralExpression) {
final List<PyCallableParameter> parameters = new ArrayList<>();
final PyListLiteralExpression listExpr = (PyListLiteralExpression)parametersExpr;
for (PyExpression argExpr : listExpr.getElements()) {
parameters.add(new PyCallableParameterImpl(null, getType(argExpr, context)));
}
final PyType returnType = getType(returnTypeExpr, context);
return new PyCallableTypeImpl(parameters, returnType);
}
if (isEllipsis(parametersExpr)) {
return new PyCallableTypeImpl(null, getType(returnTypeExpr, context));
}
}
}
}
}
return null;
}
private static boolean isEllipsis(@NotNull PyExpression parametersExpr) {
return parametersExpr instanceof PyNoneLiteralExpression && ((PyNoneLiteralExpression)parametersExpr).isEllipsis();
}
@Nullable
private static PyType getUnionType(@NotNull PsiElement element, @NotNull Context context) {
if (element instanceof PySubscriptionExpression) {
final PySubscriptionExpression subscriptionExpr = (PySubscriptionExpression)element;
final PyExpression operand = subscriptionExpr.getOperand();
final Collection<String> operandNames = resolveToQualifiedNames(operand, context.getTypeContext());
if (operandNames.contains("typing.Union")) {
return PyUnionType.union(getIndexTypes(subscriptionExpr, context));
}
}
return null;
}
@Nullable
private static PyGenericType getGenericType(@NotNull PsiElement element, @NotNull Context context) {
if (element instanceof PyCallExpression) {
final PyCallExpression assignedCall = (PyCallExpression)element;
final PyExpression callee = assignedCall.getCallee();
if (callee != null) {
final Collection<String> calleeQNames = resolveToQualifiedNames(callee, context.getTypeContext());
if (calleeQNames.contains("typing.TypeVar")) {
final PyExpression[] arguments = assignedCall.getArguments();
if (arguments.length > 0) {
final PyExpression firstArgument = arguments[0];
if (firstArgument instanceof PyStringLiteralExpression) {
final String name = ((PyStringLiteralExpression)firstArgument).getStringValue();
if (name != null) {
return new PyGenericType(name, getGenericTypeBound(arguments, context));
}
}
}
}
}
}
return null;
}
@Nullable
private static PyType getGenericTypeBound(@NotNull PyExpression[] typeVarArguments, @NotNull Context context) {
final List<PyType> types = new ArrayList<>();
for (int i = 1; i < typeVarArguments.length; i++) {
types.add(getType(typeVarArguments[i], context));
}
return PyUnionType.union(types);
}
@NotNull
private static List<PyType> getIndexTypes(@NotNull PySubscriptionExpression expression, @NotNull Context context) {
final List<PyType> types = new ArrayList<>();
final PyExpression indexExpr = expression.getIndexExpression();
if (indexExpr instanceof PyTupleExpression) {
final PyTupleExpression tupleExpr = (PyTupleExpression)indexExpr;
for (PyExpression expr : tupleExpr.getElements()) {
types.add(getType(expr, context));
}
}
else if (indexExpr != null) {
types.add(getType(indexExpr, context));
}
return types;
}
@Nullable
private static PyType getParameterizedType(@NotNull PsiElement element, @NotNull Context context) {
if (element instanceof PySubscriptionExpression) {
final PySubscriptionExpression subscriptionExpr = (PySubscriptionExpression)element;
final PyExpression operand = subscriptionExpr.getOperand();
final PyExpression indexExpr = subscriptionExpr.getIndexExpression();
final PyType operandType = getType(operand, context);
if (operandType instanceof PyClassType) {
final PyClass cls = ((PyClassType)operandType).getPyClass();
final List<PyType> indexTypes = getIndexTypes(subscriptionExpr, context);
if (PyNames.TUPLE.equals(cls.getQualifiedName())) {
if (indexExpr instanceof PyTupleExpression) {
final PyExpression[] elements = ((PyTupleExpression)indexExpr).getElements();
if (elements.length == 2 && isEllipsis(elements[1])) {
return PyTupleType.createHomogeneous(element, indexTypes.get(0));
}
}
return PyTupleType.create(element, indexTypes.toArray(new PyType[indexTypes.size()]));
}
else if (indexExpr != null) {
return new PyCollectionTypeImpl(cls, false, indexTypes);
}
}
}
return null;
}
@Nullable
private static PyType getBuiltinCollection(@NotNull PsiElement element) {
final String collectionName = getQualifiedName(element);
final String builtinName = COLLECTION_CLASSES.get(collectionName);
return builtinName != null ? PyTypeParser.getTypeByName(element, builtinName) : null;
}
@NotNull
private static List<PsiElement> tryResolving(@NotNull PyExpression expression, @NotNull TypeEvalContext context) {
final List<PsiElement> elements = Lists.newArrayList();
if (expression instanceof PyReferenceExpression) {
final PyReferenceExpression referenceExpr = (PyReferenceExpression)expression;
final PyResolveContext resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(context);
final PsiPolyVariantReference reference = referenceExpr.getReference(resolveContext);
final List<PsiElement> resolved = PyUtil.multiResolveTopPriority(reference);
for (PsiElement element : resolved) {
if (element instanceof PyFunction) {
final PyFunction function = (PyFunction)element;
if (PyUtil.isInit(function)) {
final PyClass cls = function.getContainingClass();
if (cls != null) {
elements.add(cls);
continue;
}
}
}
else if (element instanceof PyTargetExpression) {
final PyTargetExpression targetExpr = (PyTargetExpression)element;
// XXX: Requires switching from stub to AST
final PyExpression assignedValue = targetExpr.findAssignedValue();
if (assignedValue != null) {
elements.add(assignedValue);
continue;
}
}
if (element != null) {
elements.add(element);
}
}
}
return !elements.isEmpty() ? elements : Collections.<PsiElement>singletonList(expression);
}
@NotNull
private static Collection<String> resolveToQualifiedNames(@NotNull PyExpression expression, @NotNull TypeEvalContext context) {
final Set<String> names = Sets.newLinkedHashSet();
for (PsiElement resolved : tryResolving(expression, context)) {
final String name = getQualifiedName(resolved);
if (name != null) {
names.add(name);
}
}
return names;
}
@Nullable
private static String getQualifiedName(@NotNull PsiElement element) {
if (element instanceof PyQualifiedNameOwner) {
final PyQualifiedNameOwner qualifiedNameOwner = (PyQualifiedNameOwner)element;
return qualifiedNameOwner.getQualifiedName();
}
return null;
}
private static class Context {
@NotNull private final TypeEvalContext myContext;
@NotNull private final Set<PsiElement> myCache = new HashSet<>();
private Context(@NotNull TypeEvalContext context) {
myContext = context;
}
@NotNull
public TypeEvalContext getTypeContext() {
return myContext;
}
@NotNull
public Set<PsiElement> getExpressionCache() {
return myCache;
}
}
}
| |
/*
* Druid - a distributed column store.
* Copyright 2012 - 2015 Metamarkets Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.druid.query.search;
import com.google.common.collect.ImmutableList;
import io.druid.granularity.QueryGranularity;
import io.druid.query.Result;
import io.druid.query.search.search.LexicographicSearchSortSpec;
import io.druid.query.search.search.SearchHit;
import io.druid.query.search.search.StrlenSearchSortSpec;
import junit.framework.Assert;
import org.joda.time.DateTime;
import org.junit.Test;
import java.util.Iterator;
/**
*/
public class SearchBinaryFnTest
{
private final DateTime currTime = new DateTime();
private void assertSearchMergeResult(Object o1, Object o2)
{
Iterator i1 = ((Iterable) o1).iterator();
Iterator i2 = ((Iterable) o2).iterator();
while (i1.hasNext() && i2.hasNext()) {
Assert.assertEquals(i1.next(), i2.next());
}
Assert.assertTrue(!i1.hasNext() && !i2.hasNext());
}
@Test
public void testMerge()
{
Result<SearchResultValue> r1 = new Result<SearchResultValue>(
currTime,
new SearchResultValue(
ImmutableList.<SearchHit>of(
new SearchHit(
"blah",
"foo"
)
)
)
);
Result<SearchResultValue> r2 = new Result<SearchResultValue>(
currTime,
new SearchResultValue(
ImmutableList.<SearchHit>of(
new SearchHit(
"blah2",
"foo2"
)
)
)
);
Result<SearchResultValue> expected = new Result<SearchResultValue>(
currTime,
new SearchResultValue(
ImmutableList.<SearchHit>of(
new SearchHit(
"blah",
"foo"
),
new SearchHit(
"blah2",
"foo2"
)
)
)
);
Result<SearchResultValue> actual = new SearchBinaryFn(new LexicographicSearchSortSpec(), QueryGranularity.ALL, Integer.MAX_VALUE).apply(r1, r2);
Assert.assertEquals(expected.getTimestamp(), actual.getTimestamp());
assertSearchMergeResult(expected.getValue(), actual.getValue());
}
@Test
public void testMergeDay()
{
Result<SearchResultValue> r1 = new Result<SearchResultValue>(
currTime,
new SearchResultValue(
ImmutableList.<SearchHit>of(
new SearchHit(
"blah",
"foo"
)
)
)
);
Result<SearchResultValue> r2 = new Result<SearchResultValue>(
currTime,
new SearchResultValue(
ImmutableList.<SearchHit>of(
new SearchHit(
"blah2",
"foo2"
)
)
)
);
Result<SearchResultValue> expected = new Result<SearchResultValue>(
new DateTime(QueryGranularity.DAY.truncate(currTime.getMillis())),
new SearchResultValue(
ImmutableList.<SearchHit>of(
new SearchHit(
"blah",
"foo"
),
new SearchHit(
"blah2",
"foo2"
)
)
)
);
Result<SearchResultValue> actual = new SearchBinaryFn(new LexicographicSearchSortSpec(), QueryGranularity.DAY, Integer.MAX_VALUE).apply(r1, r2);
Assert.assertEquals(expected.getTimestamp(), actual.getTimestamp());
assertSearchMergeResult(expected.getValue(), actual.getValue());
}
@Test
public void testMergeOneResultNull()
{
Result<SearchResultValue> r1 = new Result<SearchResultValue>(
currTime,
new SearchResultValue(
ImmutableList.<SearchHit>of(
new SearchHit(
"blah",
"foo"
)
)
)
);
Result<SearchResultValue> r2 = null;
Result<SearchResultValue> expected = r1;
Result<SearchResultValue> actual = new SearchBinaryFn(new LexicographicSearchSortSpec(), QueryGranularity.ALL, Integer.MAX_VALUE).apply(r1, r2);
Assert.assertEquals(expected.getTimestamp(), actual.getTimestamp());
assertSearchMergeResult(expected.getValue(), actual.getValue());
}
@Test
public void testMergeShiftedTimestamp()
{
Result<SearchResultValue> r1 = new Result<SearchResultValue>(
currTime,
new SearchResultValue(
ImmutableList.<SearchHit>of(
new SearchHit(
"blah",
"foo"
)
)
)
);
Result<SearchResultValue> r2 = new Result<SearchResultValue>(
currTime.plusHours(2),
new SearchResultValue(
ImmutableList.<SearchHit>of(
new SearchHit(
"blah2",
"foo2"
)
)
)
);
Result<SearchResultValue> expected = new Result<SearchResultValue>(
currTime,
new SearchResultValue(
ImmutableList.<SearchHit>of(
new SearchHit(
"blah",
"foo"
),
new SearchHit(
"blah2",
"foo2"
)
)
)
);
Result<SearchResultValue> actual = new SearchBinaryFn(new LexicographicSearchSortSpec(), QueryGranularity.ALL, Integer.MAX_VALUE).apply(r1, r2);
Assert.assertEquals(expected.getTimestamp(), actual.getTimestamp());
assertSearchMergeResult(expected.getValue(), actual.getValue());
}
@Test
public void testStrlenMerge()
{
Result<SearchResultValue> r1 = new Result<SearchResultValue>(
currTime,
new SearchResultValue(
ImmutableList.<SearchHit>of(
new SearchHit(
"blah",
"thisislong"
)
)
)
);
Result<SearchResultValue> r2 = new Result<SearchResultValue>(
currTime,
new SearchResultValue(
ImmutableList.<SearchHit>of(
new SearchHit(
"blah",
"short"
)
)
)
);
Result<SearchResultValue> expected = new Result<SearchResultValue>(
currTime,
new SearchResultValue(
ImmutableList.<SearchHit>of(
new SearchHit(
"blah",
"short"
),
new SearchHit(
"blah",
"thisislong"
)
)
)
);
Result<SearchResultValue> actual = new SearchBinaryFn(new StrlenSearchSortSpec(), QueryGranularity.ALL, Integer.MAX_VALUE).apply(r1, r2);
Assert.assertEquals(expected.getTimestamp(), actual.getTimestamp());
assertSearchMergeResult(expected.getValue(), actual.getValue());
}
@Test
public void testMergeUniqueResults()
{
Result<SearchResultValue> r1 = new Result<SearchResultValue>(
currTime,
new SearchResultValue(
ImmutableList.<SearchHit>of(
new SearchHit(
"blah",
"foo"
)
)
)
);
Result<SearchResultValue> r2 = r1;
Result<SearchResultValue> expected = r1;
Result<SearchResultValue> actual = new SearchBinaryFn(new LexicographicSearchSortSpec(), QueryGranularity.ALL, Integer.MAX_VALUE).apply(r1, r2);
Assert.assertEquals(expected.getTimestamp(), actual.getTimestamp());
assertSearchMergeResult(expected.getValue(), actual.getValue());
}
@Test
public void testMergeLimit(){
Result<SearchResultValue> r1 = new Result<SearchResultValue>(
currTime,
new SearchResultValue(
ImmutableList.<SearchHit>of(
new SearchHit(
"blah",
"foo"
)
)
)
);
Result<SearchResultValue> r2 = new Result<SearchResultValue>(
currTime,
new SearchResultValue(
ImmutableList.<SearchHit>of(
new SearchHit(
"blah2",
"foo2"
)
)
)
);
Result<SearchResultValue> expected = r1;
Result<SearchResultValue> actual = new SearchBinaryFn(new LexicographicSearchSortSpec(), QueryGranularity.ALL, 1).apply(r1, r2);
Assert.assertEquals(expected.getTimestamp(), actual.getTimestamp());
assertSearchMergeResult(expected.getValue(), actual.getValue());
}
}
| |
/*
* 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.accumulo.server.master.tableOps;
import java.io.Serializable;
import java.util.Map;
import java.util.Set;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.client.impl.Tables;
import org.apache.accumulo.core.client.impl.thrift.TableOperation;
import org.apache.accumulo.core.client.impl.thrift.ThriftSecurityException;
import org.apache.accumulo.core.master.state.tables.TableState;
import org.apache.accumulo.core.security.TablePermission;
import org.apache.accumulo.fate.Repo;
import org.apache.accumulo.fate.zookeeper.ZooUtil.NodeExistsPolicy;
import org.apache.accumulo.server.client.HdfsZooInstance;
import org.apache.accumulo.server.master.Master;
import org.apache.accumulo.server.master.state.tables.TableManager;
import org.apache.accumulo.server.security.AuditedSecurityOperation;
import org.apache.accumulo.server.security.SecurityConstants;
import org.apache.accumulo.server.util.MetadataTable;
import org.apache.log4j.Logger;
class CloneInfo implements Serializable {
private static final long serialVersionUID = 1L;
String srcTableId;
String tableName;
String tableId;
Map<String,String> propertiesToSet;
Set<String> propertiesToExclude;
public String user;
}
class FinishCloneTable extends MasterRepo {
private static final long serialVersionUID = 1L;
private CloneInfo cloneInfo;
public FinishCloneTable(CloneInfo cloneInfo) {
this.cloneInfo = cloneInfo;
}
@Override
public long isReady(long tid, Master environment) throws Exception {
return 0;
}
@Override
public Repo<Master> call(long tid, Master environment) throws Exception {
// directories are intentionally not created.... this is done because directories should be unique
// because they occupy a different namespace than normal tablet directories... also some clones
// may never create files.. therefore there is no need to consume namenode space w/ directories
// that are not used... tablet will create directories as needed
TableManager.getInstance().transitionTableState(cloneInfo.tableId, TableState.ONLINE);
Utils.unreserveTable(cloneInfo.srcTableId, tid, false);
Utils.unreserveTable(cloneInfo.tableId, tid, true);
environment.getEventCoordinator().event("Cloned table %s from %s", cloneInfo.tableName, cloneInfo.srcTableId);
Logger.getLogger(FinishCloneTable.class).debug("Cloned table " + cloneInfo.srcTableId + " " + cloneInfo.tableId + " " + cloneInfo.tableName);
return null;
}
@Override
public void undo(long tid, Master environment) throws Exception {}
}
class CloneMetadata extends MasterRepo {
private static final long serialVersionUID = 1L;
private CloneInfo cloneInfo;
public CloneMetadata(CloneInfo cloneInfo) {
this.cloneInfo = cloneInfo;
}
@Override
public long isReady(long tid, Master environment) throws Exception {
return 0;
}
@Override
public Repo<Master> call(long tid, Master environment) throws Exception {
Logger.getLogger(CloneMetadata.class).info(
String.format("Cloning %s with tableId %s from srcTableId %s", cloneInfo.tableName, cloneInfo.tableId, cloneInfo.srcTableId));
Instance instance = HdfsZooInstance.getInstance();
// need to clear out any metadata entries for tableId just in case this
// died before and is executing again
MetadataTable.deleteTable(cloneInfo.tableId, false, SecurityConstants.getSystemCredentials(), environment.getMasterLock());
MetadataTable.cloneTable(instance, cloneInfo.srcTableId, cloneInfo.tableId);
return new FinishCloneTable(cloneInfo);
}
@Override
public void undo(long tid, Master environment) throws Exception {
MetadataTable.deleteTable(cloneInfo.tableId, false, SecurityConstants.getSystemCredentials(), environment.getMasterLock());
}
}
class CloneZookeeper extends MasterRepo {
private static final long serialVersionUID = 1L;
private CloneInfo cloneInfo;
public CloneZookeeper(CloneInfo cloneInfo) {
this.cloneInfo = cloneInfo;
}
@Override
public long isReady(long tid, Master environment) throws Exception {
return Utils.reserveTable(cloneInfo.tableId, tid, true, false, TableOperation.CLONE);
}
@Override
public Repo<Master> call(long tid, Master environment) throws Exception {
Utils.tableNameLock.lock();
try {
// write tableName & tableId to zookeeper
Instance instance = HdfsZooInstance.getInstance();
Utils.checkTableDoesNotExist(instance, cloneInfo.tableName, cloneInfo.tableId, TableOperation.CLONE);
TableManager.getInstance().cloneTable(cloneInfo.srcTableId, cloneInfo.tableId, cloneInfo.tableName, cloneInfo.propertiesToSet,
cloneInfo.propertiesToExclude, NodeExistsPolicy.OVERWRITE);
Tables.clearCache(instance);
return new CloneMetadata(cloneInfo);
} finally {
Utils.tableNameLock.unlock();
}
}
@Override
public void undo(long tid, Master environment) throws Exception {
Instance instance = HdfsZooInstance.getInstance();
TableManager.getInstance().removeTable(cloneInfo.tableId);
Utils.unreserveTable(cloneInfo.tableId, tid, true);
Tables.clearCache(instance);
}
}
class ClonePermissions extends MasterRepo {
private static final long serialVersionUID = 1L;
private CloneInfo cloneInfo;
public ClonePermissions(CloneInfo cloneInfo) {
this.cloneInfo = cloneInfo;
}
@Override
public long isReady(long tid, Master environment) throws Exception {
return 0;
}
@Override
public Repo<Master> call(long tid, Master environment) throws Exception {
// give all table permissions to the creator
for (TablePermission permission : TablePermission.values()) {
try {
AuditedSecurityOperation.getInstance().grantTablePermission(SecurityConstants.getSystemCredentials(), cloneInfo.user, cloneInfo.tableId, permission);
} catch (ThriftSecurityException e) {
Logger.getLogger(FinishCloneTable.class).error(e.getMessage(), e);
throw e;
}
}
// setup permissions in zookeeper before table info in zookeeper
// this way concurrent users will not get a spurious pemission denied
// error
return new CloneZookeeper(cloneInfo);
}
@Override
public void undo(long tid, Master environment) throws Exception {
AuditedSecurityOperation.getInstance().deleteTable(SecurityConstants.getSystemCredentials(), cloneInfo.tableId);
}
}
public class CloneTable extends MasterRepo {
private static final long serialVersionUID = 1L;
private CloneInfo cloneInfo;
public CloneTable(String user, String srcTableId, String tableName, Map<String,String> propertiesToSet, Set<String> propertiesToExclude) {
cloneInfo = new CloneInfo();
cloneInfo.user = user;
cloneInfo.srcTableId = srcTableId;
cloneInfo.tableName = tableName;
cloneInfo.propertiesToExclude = propertiesToExclude;
cloneInfo.propertiesToSet = propertiesToSet;
}
@Override
public long isReady(long tid, Master environment) throws Exception {
return Utils.reserveTable(cloneInfo.srcTableId, tid, false, true, TableOperation.CLONE);
}
@Override
public Repo<Master> call(long tid, Master environment) throws Exception {
Utils.idLock.lock();
try {
Instance instance = HdfsZooInstance.getInstance();
cloneInfo.tableId = Utils.getNextTableId(cloneInfo.tableName, instance);
return new ClonePermissions(cloneInfo);
} finally {
Utils.idLock.unlock();
}
}
@Override
public void undo(long tid, Master environment) throws Exception {
Utils.unreserveTable(cloneInfo.srcTableId, tid, false);
}
}
| |
/*
* 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 jef.net.ftpserver.usermanager.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import jef.net.ftpserver.FtpServerConfigurationException;
import jef.net.ftpserver.ftplet.Authentication;
import jef.net.ftpserver.ftplet.AuthenticationFailedException;
import jef.net.ftpserver.ftplet.Authority;
import jef.net.ftpserver.ftplet.FtpException;
import jef.net.ftpserver.ftplet.User;
import jef.net.ftpserver.usermanager.AnonymousAuthentication;
import jef.net.ftpserver.usermanager.PasswordEncryptor;
import jef.net.ftpserver.usermanager.PropertiesUserManagerFactory;
import jef.net.ftpserver.usermanager.UsernamePasswordAuthentication;
import jef.net.ftpserver.util.BaseProperties;
import jef.net.ftpserver.util.IoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <p>Properties file based <code>UserManager</code> implementation. We use
* <code>user.properties</code> file to store user data.</p>
*
* </p>The file will use the following properties for storing users:</p>
* <table>
* <tr>
* <th>Property</th>
* <th>Documentation</th>
* </tr>
* <tr>
* <td>ftpserver.user.{username}.homedirectory</td>
* <td>Path to the home directory for the user, based on the file system implementation used</td>
* </tr>
* <tr>
* <td>ftpserver.user.{username}.userpassword</td>
* <td>The password for the user. Can be in clear text, MD5 hash or salted SHA hash based on the
* configuration on the user manager
* </td>
* </tr>
* <tr>
* <td>ftpserver.user.{username}.enableflag</td>
* <td>true if the user is enabled, false otherwise</td>
* </tr>
* <tr>
* <td>ftpserver.user.{username}.writepermission</td>
* <td>true if the user is allowed to upload files and create directories, false otherwise</td>
* </tr>
* <tr>
* <td>ftpserver.user.{username}.idletime</td>
* <td>The number of seconds the user is allowed to be idle before disconnected.
* 0 disables the idle timeout
* </td>
* </tr>
* <tr>
* <td>ftpserver.user.{username}.maxloginnumber</td>
* <td>The maximum number of concurrent logins by the user. 0 disables the check.</td>
* </tr>
* <tr>
* <td>ftpserver.user.{username}.maxloginperip</td>
* <td>The maximum number of concurrent logins from the same IP address by the user. 0 disables the check.</td>
* </tr>
* <tr>
* <td>ftpserver.user.{username}.uploadrate</td>
* <td>The maximum number of bytes per second the user is allowed to upload files. 0 disables the check.</td>
* </tr>
* <tr>
* <td>ftpserver.user.{username}.downloadrate</td>
* <td>The maximum number of bytes per second the user is allowed to download files. 0 disables the check.</td>
* </tr>
* </table>
*
* <p>Example:</p>
* <pre>
* ftpserver.user.admin.homedirectory=/ftproot
* ftpserver.user.admin.userpassword=admin
* ftpserver.user.admin.enableflag=true
* ftpserver.user.admin.writepermission=true
* ftpserver.user.admin.idletime=0
* ftpserver.user.admin.maxloginnumber=0
* ftpserver.user.admin.maxloginperip=0
* ftpserver.user.admin.uploadrate=0
* ftpserver.user.admin.downloadrate=0
* </pre>
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class PropertiesUserManager extends AbstractUserManager {
private final Logger LOG = LoggerFactory
.getLogger(PropertiesUserManager.class);
private final static String PREFIX = "ftpserver.user.";
private BaseProperties userDataProp;
private File userDataFile;
private URL userUrl;
/**
* Internal constructor, do not use directly. Use {@link PropertiesUserManagerFactory} instead.
*/
public PropertiesUserManager(PasswordEncryptor passwordEncryptor,
File userDataFile, String adminName) {
super(adminName, passwordEncryptor);
loadFromFile(userDataFile);
}
/**
* Internal constructor, do not use directly. Use {@link PropertiesUserManagerFactory} instead.
*/
public PropertiesUserManager(PasswordEncryptor passwordEncryptor,
URL userDataPath, String adminName) {
super(adminName, passwordEncryptor);
loadFromUrl(userDataPath);
}
private void loadFromFile(File userDataFile) {
try {
userDataProp = new BaseProperties();
if (userDataFile != null) {
LOG.debug("File configured, will try loading");
if (userDataFile.exists()) {
this.userDataFile = userDataFile;
LOG.debug("File found on file system");
FileInputStream fis = null;
try {
fis = new FileInputStream(userDataFile);
userDataProp.load(fis);
} finally {
IoUtils.close(fis);
}
} else {
// try loading it from the classpath
LOG
.debug("File not found on file system, try loading from classpath");
InputStream is = getClass().getClassLoader()
.getResourceAsStream(userDataFile.getPath());
if (is != null) {
try {
userDataProp.load(is);
} finally {
IoUtils.close(is);
}
} else {
throw new FtpServerConfigurationException(
"User data file specified but could not be located, "
+ "neither on the file system or in the classpath: "
+ userDataFile.getPath());
}
}
}
} catch (IOException e) {
throw new FtpServerConfigurationException(
"Error loading user data file : " + userDataFile, e);
}
}
private void loadFromUrl(URL userDataPath) {
try {
userDataProp = new BaseProperties();
if (userDataPath != null) {
LOG.debug("URL configured, will try loading");
userUrl = userDataPath;
InputStream is = null;
is = userDataPath.openStream();
try {
userDataProp.load(is);
} finally {
IoUtils.close(is);
}
}
} catch (IOException e) {
throw new FtpServerConfigurationException(
"Error loading user data resource : " + userDataPath, e);
}
}
/**
* Reloads the contents of the user.properties file. This allows any manual modifications to the file to be recognised by the running server.
*/
public void refresh() {
synchronized (userDataProp) {
if (userDataFile != null) {
LOG.debug("Refreshing user manager using file: "
+ userDataFile.getAbsolutePath());
loadFromFile(userDataFile);
} else {
//file is null, must have been created using URL
LOG.debug("Refreshing user manager using URL: "
+ userUrl.toString());
loadFromUrl(userUrl);
}
}
}
/**
* Retrive the file backing this user manager
* @return The file
*/
public File getFile() {
return userDataFile;
}
/**
* Save user data. Store the properties.
*/
public synchronized void save(User usr) throws FtpException {
// null value check
if (usr.getName() == null) {
throw new NullPointerException("User name is null.");
}
String thisPrefix = PREFIX + usr.getName() + '.';
// set other properties
userDataProp.setProperty(thisPrefix + ATTR_PASSWORD, getPassword(usr));
String home = usr.getHomeDirectory();
if (home == null) {
home = "/";
}
userDataProp.setProperty(thisPrefix + ATTR_HOME, home);
userDataProp.setProperty(thisPrefix + ATTR_ENABLE, usr.getEnabled());
userDataProp.setProperty(thisPrefix + ATTR_WRITE_PERM, usr
.authorize(new WriteRequest()) != null);
userDataProp.setProperty(thisPrefix + ATTR_MAX_IDLE_TIME, usr
.getMaxIdleTime());
TransferRateRequest transferRateRequest = new TransferRateRequest();
transferRateRequest = (TransferRateRequest) usr
.authorize(transferRateRequest);
if (transferRateRequest != null) {
userDataProp.setProperty(thisPrefix + ATTR_MAX_UPLOAD_RATE,
transferRateRequest.getMaxUploadRate());
userDataProp.setProperty(thisPrefix + ATTR_MAX_DOWNLOAD_RATE,
transferRateRequest.getMaxDownloadRate());
} else {
userDataProp.remove(thisPrefix + ATTR_MAX_UPLOAD_RATE);
userDataProp.remove(thisPrefix + ATTR_MAX_DOWNLOAD_RATE);
}
// request that always will succeed
ConcurrentLoginRequest concurrentLoginRequest = new ConcurrentLoginRequest(
0, 0);
concurrentLoginRequest = (ConcurrentLoginRequest) usr
.authorize(concurrentLoginRequest);
if (concurrentLoginRequest != null) {
userDataProp.setProperty(thisPrefix + ATTR_MAX_LOGIN_NUMBER,
concurrentLoginRequest.getMaxConcurrentLogins());
userDataProp.setProperty(thisPrefix + ATTR_MAX_LOGIN_PER_IP,
concurrentLoginRequest.getMaxConcurrentLoginsPerIP());
} else {
userDataProp.remove(thisPrefix + ATTR_MAX_LOGIN_NUMBER);
userDataProp.remove(thisPrefix + ATTR_MAX_LOGIN_PER_IP);
}
saveUserData();
}
/**
* @throws FtpException
*/
private void saveUserData() throws FtpException {
if (userDataFile == null) {
return;
}
File dir = userDataFile.getAbsoluteFile().getParentFile();
if (dir != null && !dir.exists() && !dir.mkdirs()) {
String dirName = dir.getAbsolutePath();
throw new FtpServerConfigurationException(
"Cannot create directory for user data file : " + dirName);
}
// save user data
FileOutputStream fos = null;
try {
fos = new FileOutputStream(userDataFile);
userDataProp.store(fos, "Generated file - don't edit (please)");
} catch (IOException ex) {
LOG.error("Failed saving user data", ex);
throw new FtpException("Failed saving user data", ex);
} finally {
IoUtils.close(fos);
}
}
/**
* Delete an user. Removes all this user entries from the properties. After
* removing the corresponding from the properties, save the data.
*/
public void delete(String usrName) throws FtpException {
// remove entries from properties
String thisPrefix = PREFIX + usrName + '.';
Enumeration<?> propNames = userDataProp.propertyNames();
ArrayList<String> remKeys = new ArrayList<String>();
while (propNames.hasMoreElements()) {
String thisKey = propNames.nextElement().toString();
if (thisKey.startsWith(thisPrefix)) {
remKeys.add(thisKey);
}
}
Iterator<String> remKeysIt = remKeys.iterator();
while (remKeysIt.hasNext()) {
userDataProp.remove(remKeysIt.next());
}
saveUserData();
}
/**
* Get user password. Returns the encrypted value.
*
* <pre>
* If the password value is not null
* password = new password
* else
* if user does exist
* password = old password
* else
* password = ""
* </pre>
*/
private String getPassword(User usr) {
String name = usr.getName();
String password = usr.getPassword();
if (password != null) {
password = getPasswordEncryptor().encrypt(password);
} else {
String blankPassword = getPasswordEncryptor().encrypt("");
if (doesExist(name)) {
String key = PREFIX + name + '.' + ATTR_PASSWORD;
password = userDataProp.getProperty(key, blankPassword);
} else {
password = blankPassword;
}
}
return password;
}
/**
* Get all user names.
*/
public String[] getAllUserNames() {
// get all user names
String suffix = '.' + ATTR_HOME;
ArrayList<String> ulst = new ArrayList<String>();
Enumeration<?> allKeys = userDataProp.propertyNames();
int prefixlen = PREFIX.length();
int suffixlen = suffix.length();
while (allKeys.hasMoreElements()) {
String key = (String) allKeys.nextElement();
if (key.endsWith(suffix)) {
String name = key.substring(prefixlen);
int endIndex = name.length() - suffixlen;
name = name.substring(0, endIndex);
ulst.add(name);
}
}
Collections.sort(ulst);
return ulst.toArray(new String[0]);
}
/**
* Load user data.
*/
public User getUserByName(String userName) {
if (!doesExist(userName)) {
return null;
}
String baseKey = PREFIX + userName + '.';
BaseUser user = new BaseUser();
user.setName(userName);
user.setEnabled(userDataProp.getBoolean(baseKey + ATTR_ENABLE, true));
user.setHomeDirectory(userDataProp
.getProperty(baseKey + ATTR_HOME, "/"));
List<Authority> authorities = new ArrayList<Authority>();
if (userDataProp.getBoolean(baseKey + ATTR_WRITE_PERM, false)) {
authorities.add(new WritePermission());
}
int maxLogin = userDataProp.getInteger(baseKey + ATTR_MAX_LOGIN_NUMBER,
0);
int maxLoginPerIP = userDataProp.getInteger(baseKey
+ ATTR_MAX_LOGIN_PER_IP, 0);
authorities.add(new ConcurrentLoginPermission(maxLogin, maxLoginPerIP));
int uploadRate = userDataProp.getInteger(
baseKey + ATTR_MAX_UPLOAD_RATE, 0);
int downloadRate = userDataProp.getInteger(baseKey
+ ATTR_MAX_DOWNLOAD_RATE, 0);
authorities.add(new TransferRatePermission(downloadRate, uploadRate));
user.setAuthorities(authorities);
user.setMaxIdleTime(userDataProp.getInteger(baseKey
+ ATTR_MAX_IDLE_TIME, 0));
return user;
}
/**
* User existance check
*/
public boolean doesExist(String name) {
String key = PREFIX + name + '.' + ATTR_HOME;
return userDataProp.containsKey(key);
}
/**
* User authenticate method
*/
public User authenticate(Authentication authentication)
throws AuthenticationFailedException {
if (authentication instanceof UsernamePasswordAuthentication) {
UsernamePasswordAuthentication upauth = (UsernamePasswordAuthentication) authentication;
String user = upauth.getUsername();
String password = upauth.getPassword();
if (user == null) {
throw new AuthenticationFailedException("Authentication failed");
}
if (password == null) {
password = "";
}
String storedPassword = userDataProp.getProperty(PREFIX + user
+ '.' + ATTR_PASSWORD);
if (storedPassword == null) {
// user does not exist
throw new AuthenticationFailedException("Authentication failed");
}
if (getPasswordEncryptor().matches(password, storedPassword)) {
return getUserByName(user);
} else {
throw new AuthenticationFailedException("Authentication failed");
}
} else if (authentication instanceof AnonymousAuthentication) {
if (doesExist("anonymous")) {
return getUserByName("anonymous");
} else {
throw new AuthenticationFailedException("Authentication failed");
}
} else {
throw new IllegalArgumentException(
"Authentication not supported by this user manager");
}
}
/**
* Close the user manager - remove existing entries.
*/
public synchronized void dispose() {
if (userDataProp != null) {
userDataProp.clear();
userDataProp = null;
}
}
}
| |
/*
* 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.ignite.internal.binary;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.sql.Time;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.ignite.binary.BinaryObjectException;
import org.apache.ignite.configuration.BinaryConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.marshaller.MarshallerContextTestImpl;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Test;
import static org.apache.ignite.internal.binary.GridBinaryMarshaller.TYPE_ID_POS;
import static org.apache.ignite.testframework.GridTestUtils.assertThrows;
/**
*
*/
public class BinaryFieldExtractionSelfTest extends GridCommonAbstractTest {
/**
* Create marshaller.
*
* @return Binary marshaller.
* @throws Exception If failed.
*/
protected BinaryMarshaller createMarshaller() throws Exception {
BinaryContext ctx = new BinaryContext(BinaryCachingMetadataHandler.create(), new IgniteConfiguration(),
log());
BinaryMarshaller marsh = new BinaryMarshaller();
BinaryConfiguration bCfg = new BinaryConfiguration();
IgniteConfiguration iCfg = new IgniteConfiguration();
iCfg.setBinaryConfiguration(bCfg);
marsh.setContext(new MarshallerContextTestImpl(null));
marsh.setBinaryContext(ctx, iCfg);
return marsh;
}
/**
* @throws Exception If failed.
*/
@Test
public void testPrimitiveMarshalling() throws Exception {
BinaryMarshaller marsh = createMarshaller();
ThreadLocalRandom rnd = ThreadLocalRandom.current();
TestObject obj = new TestObject(0);
BinaryObjectImpl binObj = toBinary(obj, marsh);
BinaryFieldEx[] fields = new BinaryFieldEx[] {
(BinaryFieldEx)binObj.type().field("bVal"),
(BinaryFieldEx)binObj.type().field("cVal"),
(BinaryFieldEx)binObj.type().field("sVal"),
(BinaryFieldEx)binObj.type().field("iVal"),
(BinaryFieldEx)binObj.type().field("lVal"),
(BinaryFieldEx)binObj.type().field("fVal"),
(BinaryFieldEx)binObj.type().field("dVal")
};
ByteBuffer buf = ByteBuffer.allocate(1024 * 1024);
for (int i = 0; i < 100; i++) {
TestObject to = new TestObject(rnd.nextLong());
BinaryObjectImpl bObj = toBinary(to, marsh);
for (BinaryFieldEx field : fields)
field.writeField(bObj, buf);
buf.flip();
for (BinaryFieldEx field : fields)
assertEquals((Object)field.value(bObj), field.readField(buf));
buf.flip();
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testTimeMarshalling() throws Exception {
BinaryMarshaller marsh = createMarshaller();
TimeValue obj = new TimeValue(11111L);
BinaryObjectImpl binObj = toBinary(obj, marsh);
BinaryFieldEx field = (BinaryFieldEx)binObj.type().field("time");
ByteBuffer buf = ByteBuffer.allocate(16);
field.writeField(binObj, buf);
buf.flip();
assertEquals(field.value(binObj), field.<Time>readField(buf));
}
/**
* Checking the exception and its text when changing the typeId of a
* BinaryField.
*
* @throws Exception If failed.
*/
@Test
public void testChangeTypeIdOfBinaryField() throws Exception {
BinaryMarshaller marsh = createMarshaller();
TimeValue timeVal = new TimeValue(11111L);
DecimalValue decimalVal = new DecimalValue(BigDecimal.ZERO);
BinaryObjectImpl timeValBinObj = toBinary(timeVal, marsh);
BinaryObjectImpl decimalValBinObj = toBinary(decimalVal, marsh);
BinaryFieldEx timeBinField = (BinaryFieldEx)timeValBinObj.type().field("time");
Field typeIdField = U.findField(timeBinField.getClass(), "typeId");
typeIdField.set(timeBinField, decimalValBinObj.typeId());
String expMsg = exceptionMessageOfDifferentTypeIdBinaryField(
decimalValBinObj.typeId(),
decimalVal.getClass().getName(),
timeValBinObj.typeId(),
timeVal.getClass().getName(),
U.field(timeBinField, "fieldId"),
timeBinField.name(),
null
);
assertThrows(log, () -> timeBinField.value(timeValBinObj), BinaryObjectException.class, expMsg);
}
/**
* Checking the exception and its text when changing the typeId of a
* BinaryField in case of not finding the expected BinaryType.
*
* @throws Exception If failed.
*/
@Test
public void testChangeTypeIdOfBinaryFieldCaseNotFoundExpectedTypeId() throws Exception {
BinaryMarshaller marsh = createMarshaller();
TimeValue timeVal = new TimeValue(11111L);
BinaryObjectImpl timeValBinObj = toBinary(timeVal, marsh);
BinaryFieldEx timeBinField = (BinaryFieldEx)timeValBinObj.type().field("time");
int newTypeId = timeValBinObj.typeId() + 1;
Field typeIdField = U.findField(timeBinField.getClass(), "typeId");
typeIdField.set(timeBinField, newTypeId);
String expMsg = exceptionMessageOfDifferentTypeIdBinaryField(
newTypeId,
null,
timeValBinObj.typeId(),
timeVal.getClass().getName(),
U.field(timeBinField, "fieldId"),
timeBinField.name(),
null
);
assertThrows(log, () -> timeBinField.value(timeValBinObj), BinaryObjectException.class, expMsg);
}
/**
* Check that when changing typeId of BinaryObject, when trying to get the
* field value BinaryObjectException will be thrown with the corresponding
* text.
*
* @throws Exception If failed.
*/
@Test
public void testChangeTypeIdOfBinaryFieldCaseNotFoundActualTypeId() throws Exception {
BinaryMarshaller marsh = createMarshaller();
TimeValue timeVal = new TimeValue(11111L);
BinaryObjectImpl timeValBinObj = toBinary(timeVal, marsh);
BinaryFieldEx timeBinField = (BinaryFieldEx)timeValBinObj.type().field("time");
int beforeTypeId = timeValBinObj.typeId();
String fieldType = binaryContext(marsh).metadata(timeValBinObj.typeId()).fieldTypeName(timeBinField.name());
Field startField = U.findField(timeValBinObj.getClass(), "start");
int start = (int)startField.get(timeValBinObj);
Field arrField = U.findField(timeValBinObj.getClass(), "arr");
byte[] arr = (byte[])arrField.get(timeValBinObj);
arr[start + TYPE_ID_POS] += 1;
String expMsg = exceptionMessageOfDifferentTypeIdBinaryField(
beforeTypeId,
timeVal.getClass().getName(),
timeValBinObj.typeId(),
null,
U.field(timeBinField, "fieldId"),
timeBinField.name(),
fieldType
);
assertThrows(log, () -> timeBinField.value(timeValBinObj), BinaryObjectException.class, expMsg);
}
/**
* @throws Exception If failed.
*/
@Test
public void testDecimalFieldMarshalling() throws Exception {
BinaryMarshaller marsh = createMarshaller();
BigDecimal values[] = new BigDecimal[] { BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.TEN,
new BigDecimal("-100.5"), BigDecimal.valueOf(Long.MAX_VALUE, 0),
BigDecimal.valueOf(Long.MIN_VALUE, 0), BigDecimal.valueOf(Long.MAX_VALUE, 8),
BigDecimal.valueOf(Long.MIN_VALUE, 8)};
DecimalValue decVal = new DecimalValue(values[0]);
BinaryObjectImpl binObj = toBinary(decVal, marsh);
BinaryFieldEx field = (BinaryFieldEx)binObj.type().field("decVal");
ByteBuffer buf = ByteBuffer.allocate(64);
for (BigDecimal value : values) {
decVal = new DecimalValue(value);
binObj = toBinary(decVal, marsh);
field.writeField(binObj, buf);
buf.flip();
assertEquals((Object)field.value(binObj), field.readField(buf));
buf.clear();
}
}
/**
* @param obj Object to transform to a binary object.
* @param marsh Binary marshaller.
* @return Binary object.
*/
protected BinaryObjectImpl toBinary(Object obj, BinaryMarshaller marsh) throws Exception {
byte[] bytes = marsh.marshal(obj);
return new BinaryObjectImpl(binaryContext(marsh), bytes, 0);
}
/**
* Get binary context for the current marshaller.
*
* @param marsh Marshaller.
* @return Binary context.
*/
protected static BinaryContext binaryContext(BinaryMarshaller marsh) {
GridBinaryMarshaller impl = U.field(marsh, "impl");
return impl.context();
}
/**
*
*/
private static class TestObject {
/** */
private byte bVal;
/** */
private char cVal;
/** */
private short sVal;
/** */
private int iVal;
/** */
private long lVal;
/** */
private float fVal;
/** */
private double dVal;
/**
* @param seed Seed.
*/
private TestObject(long seed) {
bVal = (byte)seed;
cVal = (char)seed;
sVal = (short)seed;
iVal = (int)seed;
lVal = seed;
fVal = seed;
dVal = seed;
}
}
/** */
private static class TimeValue {
/** */
private Time time;
/**
* @param time Time.
*/
TimeValue(long time) {
this.time = new Time(time);
}
}
/**
*
*/
private static class DecimalValue {
/** */
private BigDecimal decVal;
/**
*
* @param decVal Value to use
*/
private DecimalValue(BigDecimal decVal) {
this.decVal = decVal;
}
}
/**
* Creates an exception text for the case when the typeId differs in the
* BinaryField and the BinaryObject.
*
* @param expTypeId Expected typeId.
* @param expTypeName Expected typeName.
* @param actualTypeId Actual typeId.
* @param actualTypeName Actual typeName.
* @param fieldId FieldId.
* @param fieldName FieldName.
* @param fieldType FieldType.
* @return Exception message.
*/
private String exceptionMessageOfDifferentTypeIdBinaryField(
int expTypeId,
String expTypeName,
int actualTypeId,
String actualTypeName,
int fieldId,
String fieldName,
String fieldType
) {
return "Failed to get field because type ID of passed object differs from type ID this " +
"BinaryField belongs to [expected=[typeId=" + expTypeId + ", typeName=" + expTypeName +
"], actual=[typeId=" + actualTypeId + ", typeName=" + actualTypeName + "], fieldId=" + fieldId +
", fieldName=" + fieldName + ", fieldType=" + fieldType + "]";
}
}
| |
/*
* 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.nifi.cluster.coordination.heartbeat;
import org.apache.nifi.cluster.coordination.ClusterCoordinator;
import org.apache.nifi.cluster.coordination.node.NodeConnectionState;
import org.apache.nifi.cluster.coordination.node.NodeConnectionStatus;
import org.apache.nifi.cluster.coordination.node.NodeWorkload;
import org.apache.nifi.cluster.protocol.Heartbeat;
import org.apache.nifi.cluster.protocol.HeartbeatPayload;
import org.apache.nifi.cluster.protocol.NodeIdentifier;
import org.apache.nifi.cluster.protocol.ProtocolException;
import org.apache.nifi.cluster.protocol.ProtocolHandler;
import org.apache.nifi.cluster.protocol.ProtocolListener;
import org.apache.nifi.cluster.protocol.message.ClusterWorkloadRequestMessage;
import org.apache.nifi.cluster.protocol.message.ClusterWorkloadResponseMessage;
import org.apache.nifi.cluster.protocol.message.HeartbeatMessage;
import org.apache.nifi.cluster.protocol.message.HeartbeatResponseMessage;
import org.apache.nifi.cluster.protocol.message.ProtocolMessage;
import org.apache.nifi.cluster.protocol.message.ProtocolMessage.MessageType;
import org.apache.nifi.util.NiFiProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Uses Apache ZooKeeper to advertise the address to send heartbeats to, and
* then relies on the NiFi Cluster Protocol to receive heartbeat messages from
* nodes in the cluster.
*/
public class ClusterProtocolHeartbeatMonitor extends AbstractHeartbeatMonitor implements HeartbeatMonitor, ProtocolHandler {
protected static final Logger logger = LoggerFactory.getLogger(ClusterProtocolHeartbeatMonitor.class);
private final String heartbeatAddress;
private final ConcurrentMap<NodeIdentifier, NodeHeartbeat> heartbeatMessages = new ConcurrentHashMap<>();
private volatile long purgeTimestamp = System.currentTimeMillis();
public ClusterProtocolHeartbeatMonitor(final ClusterCoordinator clusterCoordinator, final ProtocolListener protocolListener, final NiFiProperties nifiProperties) {
super(clusterCoordinator, nifiProperties);
protocolListener.addHandler(this);
String hostname = nifiProperties.getProperty(NiFiProperties.CLUSTER_NODE_ADDRESS);
if (hostname == null || hostname.trim().isEmpty()) {
hostname = "localhost";
}
final String port = nifiProperties.getProperty(NiFiProperties.CLUSTER_NODE_PROTOCOL_PORT);
if (port == null || port.trim().isEmpty()) {
throw new RuntimeException("Unable to determine which port Cluster Coordinator Protocol is listening on because the '"
+ NiFiProperties.CLUSTER_NODE_PROTOCOL_PORT + "' property is not set");
}
try {
Integer.parseInt(port);
} catch (final NumberFormatException nfe) {
throw new RuntimeException("Unable to determine which port Cluster Coordinator Protocol is listening on because the '"
+ NiFiProperties.CLUSTER_NODE_PROTOCOL_PORT + "' property is set to '" + port + "', which is not a valid port number.");
}
heartbeatAddress = hostname + ":" + port;
}
@Override
public String getHeartbeatAddress() {
return heartbeatAddress;
}
@Override
public void onStart() {
// We don't know what the heartbeats look like for the nodes, since we were just elected to monitoring
// them. However, the map may be filled with old heartbeats. So we clear the heartbeats and populate the
// map with new heartbeats set to the current time and using the currently known status. We do this so
// that if we go the required amount of time without receiving a heartbeat, we do know to mark the node
// as disconnected.
heartbeatMessages.clear();
for (final NodeIdentifier nodeId : clusterCoordinator.getNodeIdentifiers()) {
final NodeHeartbeat heartbeat = new StandardNodeHeartbeat(nodeId, System.currentTimeMillis(),
clusterCoordinator.getConnectionStatus(nodeId), 0, 0L, 0, System.currentTimeMillis());
heartbeatMessages.put(nodeId, heartbeat);
}
}
@Override
public void onStop() {
}
@Override
protected Map<NodeIdentifier, NodeHeartbeat> getLatestHeartbeats() {
return Collections.unmodifiableMap(heartbeatMessages);
}
@Override
public synchronized void removeHeartbeat(final NodeIdentifier nodeId) {
logger.debug("Deleting heartbeat for node {}", nodeId);
heartbeatMessages.remove(nodeId);
}
@Override
public synchronized void purgeHeartbeats() {
logger.debug("Purging old heartbeats");
heartbeatMessages.clear();
purgeTimestamp = System.currentTimeMillis();
}
@Override
public synchronized long getPurgeTimestamp() {
return purgeTimestamp;
}
@Override
public ProtocolMessage handle(final ProtocolMessage msg, Set<String> nodeIds) throws ProtocolException {
switch (msg.getType()) {
case HEARTBEAT:
return handleHeartbeat((HeartbeatMessage) msg);
case CLUSTER_WORKLOAD_REQUEST:
return handleClusterWorkload((ClusterWorkloadRequestMessage) msg);
default:
throw new ProtocolException("Cannot handle message of type " + msg.getType());
}
}
private ProtocolMessage handleHeartbeat(final HeartbeatMessage msg) {
final HeartbeatMessage heartbeatMsg = msg;
final Heartbeat heartbeat = heartbeatMsg.getHeartbeat();
final NodeIdentifier nodeId = heartbeat.getNodeIdentifier();
final NodeConnectionStatus connectionStatus = heartbeat.getConnectionStatus();
final byte[] payloadBytes = heartbeat.getPayload();
final HeartbeatPayload payload = HeartbeatPayload.unmarshal(payloadBytes);
final int activeThreadCount = payload.getActiveThreadCount();
final int flowFileCount = (int) payload.getTotalFlowFileCount();
final long flowFileBytes = payload.getTotalFlowFileBytes();
final long systemStartTime = payload.getSystemStartTime();
final NodeHeartbeat nodeHeartbeat = new StandardNodeHeartbeat(nodeId, System.currentTimeMillis(),
connectionStatus, flowFileCount, flowFileBytes, activeThreadCount, systemStartTime);
heartbeatMessages.put(heartbeat.getNodeIdentifier(), nodeHeartbeat);
logger.debug("Received new heartbeat from {}", nodeId);
// Formulate a List of differences between our view of the cluster topology and the node's view
// and send that back to the node so that it is in-sync with us
List<NodeConnectionStatus> nodeStatusList = payload.getClusterStatus();
if (nodeStatusList == null) {
nodeStatusList = Collections.emptyList();
}
final List<NodeConnectionStatus> updatedStatuses = getUpdatedStatuses(nodeStatusList);
final HeartbeatResponseMessage responseMessage = new HeartbeatResponseMessage();
responseMessage.setUpdatedNodeStatuses(updatedStatuses);
if (!getClusterCoordinator().isFlowElectionComplete()) {
responseMessage.setFlowElectionMessage(getClusterCoordinator().getFlowElectionStatus());
}
return responseMessage;
}
private ProtocolMessage handleClusterWorkload(final ClusterWorkloadRequestMessage msg) {
final ClusterWorkloadResponseMessage response = new ClusterWorkloadResponseMessage();
final Map<NodeIdentifier, NodeWorkload> workloads = new HashMap<>();
getLatestHeartbeats().values().stream()
.filter(hb -> NodeConnectionState.CONNECTED.equals(hb.getConnectionStatus().getState()))
.forEach(hb -> {
NodeWorkload wl = new NodeWorkload();
wl.setReportedTimestamp(hb.getTimestamp());
wl.setSystemStartTime(hb.getSystemStartTime());
wl.setActiveThreadCount(hb.getActiveThreadCount());
wl.setFlowFileCount(hb.getFlowFileCount());
wl.setFlowFileBytes(hb.getFlowFileBytes());
workloads.put(hb.getNodeIdentifier(), wl);
});
response.setNodeWorkloads(workloads);
return response;
}
private List<NodeConnectionStatus> getUpdatedStatuses(final List<NodeConnectionStatus> nodeStatusList) {
// Map node's statuses by NodeIdentifier for quick & easy lookup
final Map<NodeIdentifier, NodeConnectionStatus> nodeStatusMap = nodeStatusList.stream()
.collect(Collectors.toMap(status -> status.getNodeIdentifier(), Function.identity()));
// Check if our connection status is the same for each Node Identifier and if not, add our version of the status
// to a List of updated statuses.
final List<NodeConnectionStatus> currentStatuses = clusterCoordinator.getConnectionStatuses();
final List<NodeConnectionStatus> updatedStatuses = new ArrayList<>();
for (final NodeConnectionStatus currentStatus : currentStatuses) {
final NodeConnectionStatus nodeStatus = nodeStatusMap.get(currentStatus.getNodeIdentifier());
if (!currentStatus.equals(nodeStatus)) {
updatedStatuses.add(currentStatus);
}
}
// If the node has any statuses that we do not have, add a REMOVED status to the update list
final Set<NodeIdentifier> nodeIds = currentStatuses.stream().map(status -> status.getNodeIdentifier()).collect(Collectors.toSet());
for (final NodeConnectionStatus nodeStatus : nodeStatusList) {
if (!nodeIds.contains(nodeStatus.getNodeIdentifier())) {
updatedStatuses.add(new NodeConnectionStatus(nodeStatus.getNodeIdentifier(), NodeConnectionState.REMOVED, null));
}
}
logger.debug("\n\nCalculated diff between current cluster status and node cluster status as follows:\nNode: {}\nSelf: {}\nDifference: {}\n\n",
nodeStatusList, currentStatuses, updatedStatuses);
return updatedStatuses;
}
@Override
public boolean canHandle(ProtocolMessage msg) {
return msg.getType() == MessageType.HEARTBEAT || msg.getType() == MessageType.CLUSTER_WORKLOAD_REQUEST;
}
}
| |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.ui.FixedSizeButton;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.NlsContexts;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.CharFilter;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.components.JBTextField;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Consumer;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import sun.awt.AWTAccessor;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeListener;
import java.lang.reflect.InvocationTargetException;
public final class GuiUtils {
private static final Insets paddingInsideDialog = JBUI.insets(5);
private static final CharFilter NOT_MNEMONIC_CHAR_FILTER = ch -> ch != '&' && ch != UIUtil.MNEMONIC;
public static JPanel constructFieldWithBrowseButton(JComponent aComponent, ActionListener aActionListener) {
return constructFieldWithBrowseButton(aComponent, aActionListener, 0);
}
public static JPanel constructFieldWithBrowseButton(TextFieldWithHistory aComponent, ActionListener aActionListener) {
return constructFieldWithBrowseButton(aComponent, aActionListener, 0);
}
private static JPanel constructFieldWithBrowseButton(final JComponent aComponent, final ActionListener aActionListener, int delta) {
JPanel result = new JPanel(new GridBagLayout());
result.add(aComponent, new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, JBUI.emptyInsets(), 0, 0));
FixedSizeButton browseButton = new FixedSizeButton(aComponent.getPreferredSize().height - delta);//ignore border in case of browse button
TextFieldWithBrowseButton.MyDoClickAction.addTo(browseButton, aComponent);
result.add(browseButton, new GridBagConstraints(1, 0, 1, 1, 0, 1, GridBagConstraints.CENTER, GridBagConstraints.NONE,
JBUI.emptyInsets(), 0, 0));
browseButton.addActionListener(aActionListener);
return result;
}
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2021.2")
public static JPanel constructDirectoryBrowserField(final JTextField field, final String objectName) {
return constructFieldWithBrowseButton(field, new ActionListener() {
@SuppressWarnings("HardCodedStringLiteral")
@Override
public void actionPerformed(ActionEvent e) {
FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor().withTitle("Select " + objectName);
VirtualFile file = FileChooser.chooseFile(descriptor, field, null, null);
if (file != null) {
field.setText(FileUtil.toSystemDependentName(file.getPath()));
field.postActionEvent();
}
}
});
}
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2021.2")
public static JPanel makeTitledPanel(JComponent aComponent, @NlsContexts.BorderTitle String aTitle) {
JPanel result = makePaddedPanel(aComponent, false, true, false, true);
return wrapWithBorder(result, IdeBorderFactory.createTitledBorder(aTitle));
}
private static JPanel wrapWithBorder(JComponent aPanel, Border aBorder) {
JPanel wrapper = new JPanel(new BorderLayout());
wrapper.add(aPanel, BorderLayout.CENTER);
wrapper.setBorder(aBorder);
return wrapper;
}
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2021.2")
public static BorderLayout createBorderLayout() {
return new BorderLayout(paddingInsideDialog.left, paddingInsideDialog.top);
}
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2021.2")
public static GridLayout createGridLayout(int aRows, int aColumns) {
return new GridLayout(aRows, aColumns, paddingInsideDialog.left, paddingInsideDialog.top);
}
public static Component createVerticalStrut() {
return Box.createRigidArea(new Dimension(0, paddingInsideDialog.top));
}
private static JPanel makePaddedPanel(JComponent aComponent,
boolean aTop,
boolean aLeft,
boolean aBottom,
boolean aRight) {
return wrapWithBorder(aComponent, BorderFactory.createEmptyBorder(
aTop ? paddingInsideDialog.top : 0,
aLeft ? paddingInsideDialog.left : 0,
aBottom ? paddingInsideDialog.bottom : 0,
aRight ? paddingInsideDialog.right : 0));
}
public static String getTextWithoutMnemonicEscaping(String text) {
return StringUtil.strip(text, NOT_MNEMONIC_CHAR_FILTER);
}
public static char getDisplayedMnemonic(String text) {
final int i = getDisplayedMnemonicIndex(text);
return i == -1 ? (char)-1 : text.charAt(i + 1);
}
public static int getDisplayedMnemonicIndex(String text) {
return text.indexOf("&");
}
public static void replaceJSplitPaneWithIDEASplitter(JComponent root) {
replaceJSplitPaneWithIDEASplitter(root, false);
}
public static void replaceJSplitPaneWithIDEASplitter(JComponent root, boolean useOnePixelDivider) {
final Container parent = root.getParent();
if (root instanceof JSplitPane) {
// we can painlessly replace only splitter which is the only child in container
if (parent.getComponents().length != 1 && !(parent instanceof Splitter)) {
return;
}
final JSplitPane pane = (JSplitPane)root;
final Component component1 = pane.getTopComponent();
final Component component2 = pane.getBottomComponent();
final int orientation = pane.getOrientation();
boolean vertical = orientation == JSplitPane.VERTICAL_SPLIT;
final Splitter splitter = useOnePixelDivider ? new OnePixelSplitter(vertical) : new JBSplitter(vertical);
splitter.setFirstComponent((JComponent) component1);
splitter.setSecondComponent((JComponent) component2);
splitter.setShowDividerControls(pane.isOneTouchExpandable());
splitter.setHonorComponentsMinimumSize(true);
if (pane.getDividerLocation() > 0) {
// let the component chance to resize itself
SwingUtilities.invokeLater(() -> {
double proportion;
if (pane.getOrientation() == JSplitPane.VERTICAL_SPLIT) {
proportion = pane.getDividerLocation() / (double)(parent.getHeight() - pane.getDividerSize());
}
else {
proportion = pane.getDividerLocation() / (double)(parent.getWidth() - pane.getDividerSize());
}
if (proportion > 0 && proportion < 1) {
splitter.setProportion((float)proportion);
}
});
}
if (parent instanceof Splitter) {
final Splitter psplitter = (Splitter) parent;
if (psplitter.getFirstComponent() == root)
psplitter.setFirstComponent(splitter);
else
psplitter.setSecondComponent(splitter);
}
else {
parent.remove(0);
parent.setLayout(new BorderLayout());
parent.add(splitter, BorderLayout.CENTER);
}
replaceJSplitPaneWithIDEASplitter((JComponent) component1, useOnePixelDivider);
replaceJSplitPaneWithIDEASplitter((JComponent) component2, useOnePixelDivider);
}
else {
final Component[] components = root.getComponents();
for (Component component : components) {
if (component instanceof JComponent) {
replaceJSplitPaneWithIDEASplitter((JComponent)component, useOnePixelDivider);
}
}
}
}
public static void iterateChildren(Component container, Consumer<? super Component> consumer, JComponent... excludeComponents) {
if (excludeComponents != null && ArrayUtil.find(excludeComponents, container) != -1) return;
consumer.consume(container);
if (container instanceof Container) {
final Component[] components = ((Container)container).getComponents();
for (Component child : components) {
iterateChildren(child, consumer, excludeComponents);
}
}
}
public static void enableChildren(final boolean enabled, Component... components) {
for (final Component component : components) {
enableChildren(component, enabled);
}
}
public static void showComponents(final boolean visible, Component... components) {
for (final Component component : components) {
component.setVisible(visible);
}
}
public static void enableChildren(Component container, final boolean enabled, JComponent... excludeComponents) {
iterateChildren(container, t -> enableComponent(t, enabled), excludeComponents);
}
private static void enableComponent(Component component, boolean enabled) {
if (component.isEnabled() == enabled) return;
component.setEnabled(enabled);
if (component instanceof JPanel) {
final Border border = ((JPanel)component).getBorder();
if (border instanceof TitledBorder) {
Color color = enabled ? component.getForeground() : UIUtil.getInactiveTextColor();
((TitledBorder)border).setTitleColor(color);
}
}
else if (component instanceof JLabel) {
Color color = UIUtil.getInactiveTextColor();
@NonNls String changeColorString = "<font color=#" + colorToHex(color) +">";
final JLabel label = (JLabel)component;
@NonNls String text = label.getText();
if (text != null && text.startsWith("<html>")) {
if (StringUtil.startsWithConcatenation(text, "<html>", changeColorString) && enabled) {
text = "<html>"+text.substring(("<html>"+changeColorString).length());
}
else if (!StringUtil.startsWithConcatenation(text, "<html>", changeColorString) && !enabled) {
text = "<html>"+changeColorString+text.substring("<html>".length());
}
label.setText(text);
}
}
else if (component instanceof JTable) {
TableColumnModel columnModel = ((JTable)component).getColumnModel();
for (int i=0; i<columnModel.getColumnCount();i++) {
TableCellRenderer cellRenderer = columnModel.getColumn(0).getCellRenderer();
if (cellRenderer instanceof Component) {
enableComponent((Component)cellRenderer, enabled);
}
}
}
}
public static String colorToHex(final Color color) {
return to2DigitsHex(color.getRed())
+to2DigitsHex(color.getGreen())
+to2DigitsHex(color.getBlue());
}
private static String to2DigitsHex(int i) {
String s = Integer.toHexString(i);
if (s.length() < 2) s = "0" + s;
return s;
}
/**
* @deprecated Use {@link Application#invokeAndWait}
*/
@SuppressWarnings("RedundantThrows")
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public static void runOrInvokeAndWait(@NotNull Runnable runnable) throws InvocationTargetException, InterruptedException {
ApplicationManager.getApplication().invokeAndWait(runnable);
}
public static void invokeLaterIfNeeded(@NotNull Runnable runnable, @NotNull ModalityState modalityState) {
Application app = ApplicationManager.getApplication();
if (app.isDispatchThread()) {
runnable.run();
}
else {
app.invokeLater(runnable, modalityState);
}
}
public static void invokeLaterIfNeeded(@NotNull Runnable runnable, @NotNull ModalityState modalityState, @NotNull Condition expired) {
Application app = ApplicationManager.getApplication();
if (app.isDispatchThread()) {
runnable.run();
}
else {
app.invokeLater(runnable, modalityState, expired);
}
}
public static JTextField createUndoableTextField() {
return new JBTextField();
}
/**
* Returns dimension with width required to type certain number of chars in provided component
* @param charCount number of chars
* @param comp component
* @return dimension with width enough to insert provided number of chars into component
*/
@NotNull
public static Dimension getSizeByChars(int charCount, @NotNull JComponent comp) {
Dimension size = comp.getPreferredSize();
FontMetrics fontMetrics = comp.getFontMetrics(comp.getFont());
size.width = fontMetrics.charWidth('a') * charCount;
return size;
}
public static void installVisibilityReferent(JComponent owner, JComponent referent) {
referent.addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
toggleVisibility(e);
}
@Override
public void componentHidden(ComponentEvent e) {
toggleVisibility(e);
}
private void toggleVisibility(ComponentEvent e) {
Component component = e.getComponent();
if (component != null) {
owner.setVisible(component.isVisible());
}
}
});
}
/**
* removes all children and parent references, listeners from {@code container} to avoid possible memory leaks
*/
public static void removePotentiallyLeakingReferences(@NotNull Container container) {
assert SwingUtilities.isEventDispatchThread();
AWTAccessor.getComponentAccessor().setParent(container, null);
container.removeAll();
for (ComponentListener c : container.getComponentListeners()) container.removeComponentListener(c);
for (FocusListener c : container.getFocusListeners()) container.removeFocusListener(c);
for (HierarchyListener c : container.getHierarchyListeners()) container.removeHierarchyListener(c);
for (HierarchyBoundsListener c : container.getHierarchyBoundsListeners()) container.removeHierarchyBoundsListener(c);
for (KeyListener c : container.getKeyListeners()) container.removeKeyListener(c);
for (MouseListener c : container.getMouseListeners()) container.removeMouseListener(c);
for (MouseMotionListener c : container.getMouseMotionListeners()) container.removeMouseMotionListener(c);
for (MouseWheelListener c : container.getMouseWheelListeners()) container.removeMouseWheelListener(c);
for (InputMethodListener c : container.getInputMethodListeners()) container.removeInputMethodListener(c);
for (PropertyChangeListener c : container.getPropertyChangeListeners()) container.removePropertyChangeListener(c);
for (ContainerListener c : container.getContainerListeners()) container.removeContainerListener(c);
}
}
| |
/*
* Copyright 2000-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 com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.ExceptionUtil;
import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.generation.surroundWith.SurroundWithUtil;
import com.intellij.codeInsight.intention.impl.BaseIntentionAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.util.RefactoringUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* @author mike
*/
public class AddExceptionToCatchFix extends BaseIntentionAction {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.quickfix.AddExceptionToCatchFix");
private final boolean myUncaughtOnly;
public AddExceptionToCatchFix(boolean uncaughtOnly) {
myUncaughtOnly = uncaughtOnly;
}
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file) {
int offset = editor.getCaretModel().getOffset();
PsiElement element = findElement(file, offset);
if (element == null) return;
PsiTryStatement tryStatement = (PsiTryStatement)element.getParent();
List<PsiClassType> unhandledExceptions = new ArrayList<>(getExceptions(element, null));
if (unhandledExceptions.isEmpty()) return;
ExceptionUtil.sortExceptionsByHierarchy(unhandledExceptions);
IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace();
PsiCodeBlock catchBlockToSelect = null;
try {
if (tryStatement.getFinallyBlock() == null && tryStatement.getCatchBlocks().length == 0) {
for (PsiClassType unhandledException : unhandledExceptions) {
addCatchStatement(tryStatement, unhandledException, file);
}
catchBlockToSelect = tryStatement.getCatchBlocks()[0];
}
else {
for (PsiClassType unhandledException : unhandledExceptions) {
PsiCodeBlock codeBlock = addCatchStatement(tryStatement, unhandledException, file);
if (catchBlockToSelect == null) catchBlockToSelect = codeBlock;
}
}
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
if (catchBlockToSelect != null) {
TextRange range = SurroundWithUtil.getRangeToSelect(catchBlockToSelect);
editor.getCaretModel().moveToOffset(range.getStartOffset());
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
editor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset());
}
}
@NotNull
protected Collection<PsiClassType> getExceptions(PsiElement element, PsiElement topElement) {
Collection<PsiClassType> exceptions = ExceptionUtil.collectUnhandledExceptions(element, topElement);
if(!myUncaughtOnly && exceptions.isEmpty()) {
exceptions = ExceptionUtil.getThrownExceptions(element);
if (exceptions.isEmpty()) {
PsiElementFactory factory = JavaPsiFacade.getElementFactory(element.getProject());
PsiClassType exceptionType = factory.createTypeByFQClassName(CommonClassNames.JAVA_LANG_EXCEPTION, element.getResolveScope());
exceptions = Collections.singleton(exceptionType);
}
}
return exceptions;
}
private static PsiCodeBlock addCatchStatement(PsiTryStatement tryStatement,
PsiClassType exceptionType,
PsiFile file) throws IncorrectOperationException {
PsiElementFactory factory = JavaPsiFacade.getElementFactory(tryStatement.getProject());
if (tryStatement.getTryBlock() == null) {
addTryBlock(tryStatement, factory);
}
JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(tryStatement.getProject());
String name = styleManager.suggestVariableName(VariableKind.PARAMETER, null, null, exceptionType).names[0];
name = styleManager.suggestUniqueVariableName(name, tryStatement, false);
PsiCatchSection catchSection = factory.createCatchSection(exceptionType, name, file);
PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock();
if (finallyBlock == null) {
tryStatement.add(catchSection);
}
else {
tryStatement.addBefore(catchSection, getFinallySectionStart(finallyBlock));
}
PsiParameter[] parameters = tryStatement.getCatchBlockParameters();
PsiTypeElement typeElement = parameters[parameters.length - 1].getTypeElement();
if (typeElement != null) {
JavaCodeStyleManager.getInstance(file.getProject()).shortenClassReferences(typeElement);
}
PsiCodeBlock[] catchBlocks = tryStatement.getCatchBlocks();
return catchBlocks[catchBlocks.length - 1];
}
private static void addTryBlock(PsiTryStatement tryStatement, PsiElementFactory factory) {
PsiCodeBlock tryBlock = factory.createCodeBlock();
PsiElement anchor;
PsiCatchSection[] catchSections = tryStatement.getCatchSections();
if (catchSections.length > 0) {
anchor = catchSections[0];
}
else {
PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock();
anchor = finallyBlock != null ? getFinallySectionStart(finallyBlock) : null;
}
if (anchor != null) {
tryStatement.addBefore(tryBlock, anchor);
}
else {
tryStatement.add(tryBlock);
}
}
private static PsiElement getFinallySectionStart(@NotNull PsiCodeBlock finallyBlock) {
PsiElement finallyElement = finallyBlock;
while (!PsiUtil.isJavaToken(finallyElement, JavaTokenType.FINALLY_KEYWORD) && finallyElement != null) {
finallyElement = finallyElement.getPrevSibling();
}
assert finallyElement != null : finallyBlock.getParent().getText();
return finallyElement;
}
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
if (!(file instanceof PsiJavaFile)) return false;
int offset = editor.getCaretModel().getOffset();
PsiElement element = findElement(file, offset);
if (element == null) return false;
setText(QuickFixBundle.message("add.catch.clause.text"));
return true;
}
@Nullable
private PsiElement findElement(final PsiFile file, final int offset) {
PsiElement element = file.findElementAt(offset);
if (element instanceof PsiWhiteSpace) element = file.findElementAt(offset - 1);
if (element == null) return null;
PsiElement parentStatement = RefactoringUtil.getParentStatement(element, false);
if (parentStatement instanceof PsiDeclarationStatement) {
PsiElement[] declaredElements = ((PsiDeclarationStatement)parentStatement).getDeclaredElements();
if (declaredElements.length > 0 && declaredElements[0] instanceof PsiClass) {
return null;
}
}
final PsiElement parent = PsiTreeUtil.getParentOfType(element, PsiTryStatement.class, PsiMethod.class, PsiFunctionalExpression.class);
if (parent == null || parent instanceof PsiMethod || parent instanceof PsiFunctionalExpression) return null;
final PsiTryStatement statement = (PsiTryStatement) parent;
final PsiCodeBlock tryBlock = statement.getTryBlock();
if (tryBlock != null) {
TextRange range = tryBlock.getTextRange();
if (range.contains(offset) || range.getEndOffset() == offset) {
if (!getExceptions(tryBlock, statement.getParent()).isEmpty()) {
return tryBlock;
}
}
}
final PsiResourceList resourceList = statement.getResourceList();
if (resourceList != null && resourceList.getTextRange().contains(offset)) {
if (!getExceptions(resourceList, statement.getParent()).isEmpty()) {
return resourceList;
}
}
return null;
}
@Override
@NotNull
public String getFamilyName() {
return QuickFixBundle.message("add.catch.clause.family");
}
}
| |
package com.jaselogic.adamsonelearn;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import com.jaselogic.adamsonelearn.SubjectListAdapter.SubjectListItem;
import com.jaselogic.adamsonelearn.TodayListAdapter.TodayListItem;
import com.jaselogic.adamsonelearn.UpdatesListAdapter.UpdatesListItem;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.content.LocalBroadcastManager;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
class HomePageFragment {
//Page fragment class
public static class UpdatesFragment extends ListFragment {
//private String cookie;
private UpdatesListAdapter adapter;
private ArrayList<UpdatesListItem> updateArrayList;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View pageRootView = inflater.inflate(R.layout.fragment_listview,
container, false);
updateArrayList = new ArrayList<UpdatesListItem>();
adapter = new UpdatesListAdapter(getActivity(), updateArrayList);
setListAdapter(adapter);
//get original cookie
//cookie = ((Dashboard)getActivity()).cookie;
return pageRootView;
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
populateUpdatesList();
broadcastUpdatesReady();
}
};
@Override
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(getActivity())
.unregisterReceiver(mBroadcastReceiver);
}
@Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(getActivity())
.registerReceiver(mBroadcastReceiver, new IntentFilter(UpdateIntentService.NOTIFICATION));
}
public void populateUpdatesList() {
DateFormat formatter = new SimpleDateFormat(
"'Date Added : 'MMM dd, yyyy 'at' hh:mm:ss aa");
//open database
SQLiteDatabase eLearnDb = getActivity().openOrCreateDatabase("AdUELearn", Context.MODE_PRIVATE, null);
Cursor c = eLearnDb.rawQuery(
"SELECT SubjTable.ProfName, UpdatesTable.SectionId, " +
"SubjTable.SubjName, UpdatesTable.Title, " +
"UpdatesTable.Body, UpdatesTable.DateAdded, " +
"SubjTable.AvatarSrc " +
"FROM UpdatesTable LEFT JOIN SubjTable ON " +
"UpdatesTable.SectionId=SubjTable.SectionId", null);
while(c.moveToNext()) {
UpdatesListItem tempItem = new UpdatesListItem();
tempItem.name = c.getString(c.getColumnIndex("ProfName"));
StringBuilder sbSubject = new StringBuilder(
c.getString(c.getColumnIndex("SectionId"))
);
sbSubject.append(" : ");
sbSubject.append(c.getString(c.getColumnIndex("SubjName")));
tempItem.subject = sbSubject.toString();
tempItem.title = c.getString(c.getColumnIndex("Title"));
tempItem.body = c.getString(c.getColumnIndex("Body"));
tempItem.dateAdded = formatter.format(new Date(c.getLong(c.getColumnIndex("DateAdded"))));
tempItem.avatarSrc = c.getString(c.getColumnIndex("AvatarSrc"));
updateArrayList.add(tempItem);
}
adapter.notifyDataSetChanged();
//close database
eLearnDb.close();
}
public void broadcastUpdatesReady() {
Intent intent = new Intent("updates-list-ready");
LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
}
}
public static class SubjectsFragment extends ListFragment {
private String cookie;
private SubjectListAdapter adapter;
private ArrayList<SubjectListItem> subjectArrayList;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View pageRootView = inflater.inflate(R.layout.fragment_listview,
container, false);
subjectArrayList = new ArrayList<SubjectListItem>();
adapter = new SubjectListAdapter(getActivity(), subjectArrayList);
setListAdapter(adapter);
//get original cookie
cookie = ((Dashboard)getActivity()).cookie;
Intent intent = new Intent(getActivity(), SubjectIntentService.class);
intent.putExtra(SubjectIntentService.EXTRA_COOKIE, cookie);
getActivity().startService(intent);
return pageRootView;
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
SQLiteDatabase eLearnDb = getActivity().openOrCreateDatabase("AdUELearn", Context.MODE_PRIVATE, null);
displaySubjects(eLearnDb);
eLearnDb.close();
//start updates intent
Intent updatesIntent = new Intent(getActivity(), UpdateIntentService.class);
updatesIntent.putExtra(SubjectIntentService.EXTRA_COOKIE, cookie);
getActivity().startService(updatesIntent);
}
};
@Override
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(getActivity())
.unregisterReceiver(mBroadcastReceiver);
}
@Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(getActivity())
.registerReceiver(mBroadcastReceiver, new IntentFilter(SubjectIntentService.NOTIFICATION));
}
public void broadcastListReady() {
Intent intent = new Intent("subject-list-ready");
LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
}
public void displaySubjects(SQLiteDatabase eLearnDb) {
//issue select
Cursor c = eLearnDb.rawQuery("SELECT * FROM SubjTable", null);
while(c.moveToNext()) {
SubjectListItem subjectItem = new SubjectListItem();
StringBuilder sbSubject = new StringBuilder(
String.format("%05d", c.getInt(c.getColumnIndex("SectionId")))
);
sbSubject.append(" : ");
sbSubject.append(c.getString(c.getColumnIndex("SubjName")));
subjectItem.subject = sbSubject.toString();
subjectItem.teacher = c.getString(c.getColumnIndex("ProfName"));
StringBuilder sbSchedule = new StringBuilder(
ScheduleHelper.convertIntToStringDaySlot(c.getInt(c.getColumnIndex("DaySlot")))
);
sbSchedule.append(" ");
sbSchedule.append(
ScheduleHelper.convertIntToStringSlot(
c.getInt(c.getColumnIndex("TimeStart")),
c.getInt(c.getColumnIndex("TimeEnd")) )
);
sbSchedule.append(" ");
sbSchedule.append(c.getString(c.getColumnIndex("Room")));
subjectItem.schedule = sbSchedule.toString();
subjectItem.avatarSrc = c.getString(c.getColumnIndex("AvatarSrc"));
subjectArrayList.add(subjectItem);
}
adapter.notifyDataSetChanged();
}
}
public static class TodayFragment extends ListFragment {
private TodayListAdapter adapter;
private ArrayList<TodayListItem> todayArrayList;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup pageRootView = (ViewGroup) inflater.inflate(
R.layout.fragment_listview, container, false);
todayArrayList = new ArrayList<TodayListItem>();
adapter = new TodayListAdapter(getActivity(), todayArrayList);
setListAdapter(adapter);
return pageRootView;
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//get current time
Time timeNow = new Time();
timeNow.setToNow();
//open database
SQLiteDatabase eLearnDb = getActivity().openOrCreateDatabase("AdUELearn", Context.MODE_PRIVATE, null);
populateTodayListView(timeNow, eLearnDb);
//close database
eLearnDb.close();
}
};
//listen to subject list ready event
@Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(getActivity())
.registerReceiver(mMessageReceiver, new IntentFilter("updates-list-ready"));
}
@Override
public void onPause() {
LocalBroadcastManager.getInstance(getActivity())
.unregisterReceiver(mMessageReceiver);
super.onPause();
}
/*SUBJECT
eLearnDb.execSQL("CREATE TABLE SubjTable " +
"(SectionId INTEGER, SubjName TEXT, " +
"ProfName TEXT, DaySlot INTEGER, " +
"TimeStart INTEGER, TimeEnd INTEGER, Room TEXT, " +
"AvatarSrc TEXT);");
*/
/*UPDATES
* eLearnDb.execSQL("CREATE TABLE UpdatesTable " +
"(SectionId INTEGER, Title TEXT, " +
"Body TEXT, DateAdded INTEGER);");
*/
/*
* "SELECT s.SubjName, s.TimeStart, " +
"s.TimeEnd, s.Room, " +
"u.Title, u.Body " +
"FROM SubjTable s LEFT OUTER JOIN UpdatesTable u " +
"ON s.SectionId = u.SectionId " +
"INNER JOIN (SELECT SectionId, MAX(DateAdded) AS maxDate FROM UpdatesTable GROUP BY SectionId) uniqTable " +
"ON uniqTable.SectionId = u.SectionId AND uniqTable.maxDate = u.DateAdded " +
"WHERE s.DaySlot & ? > 1 " +
"ORDER BY s.TimeStart",
*/
public void populateTodayListView(Time timeNow, SQLiteDatabase eLearnDb) {
Cursor c = eLearnDb.rawQuery(
"SELECT s.SubjName, s.TimeStart, " +
"s.TimeEnd, s.Room, " +
"v.Title, v.Body " +
"FROM SubjTable s LEFT OUTER JOIN " +
"(SELECT * FROM UpdatesTable u " +
"INNER JOIN (SELECT SectionId, MAX(DateAdded) AS maxDate FROM UpdatesTable GROUP BY SectionId) uniqTable " +
"ON uniqTable.SectionId = u.SectionId AND uniqTable.maxDate = u.DateAdded) v " +
"ON s.SectionId = v.SectionId " +
"WHERE s.DaySlot & ? > 1 " +
"ORDER BY s.TimeStart",
new String[] { String.valueOf(1 << (timeNow.weekDay - 1)) }
);
int timeSlotNow = ScheduleHelper.convertTimeToIntSlot(timeNow);
short indicator = 0; // 1 = NOW, 2 = NEXT
Log.d("CURRI", String.valueOf(c.getCount()));
while(c.moveToNext()) {
int curTimeStart = c.getInt(c.getColumnIndex("TimeStart"));
int curTimeEnd = c.getInt(c.getColumnIndex("TimeEnd"));
TodayListItem tempItem = new TodayListItem();
TodayListItem tempTitle = new TodayListItem();
tempTitle.viewType = TodayListAdapter.ItemType.ITEM_TITLE;
if( timeSlotNow < curTimeStart && (indicator & 2) == 0 ) { //WALANG PANG NOW at NEXT
tempItem.viewType = TodayListAdapter.ItemType.ITEM_NEXT;
tempTitle.mainText = "NEXT:";
todayArrayList.add(tempTitle);
indicator |= 2;
} else if ( timeSlotNow >= curTimeStart && timeSlotNow < curTimeEnd ) { //Now
tempItem.viewType = TodayListAdapter.ItemType.ITEM_NOW;
tempTitle.mainText = "NOW:";
todayArrayList.add(tempTitle);
indicator |= 1;
} else if ( timeSlotNow < curTimeStart ) {
tempTitle.mainText = "LATER:";
tempItem.viewType = TodayListAdapter.ItemType.ITEM_LATER;
if ( indicator < 4 )
todayArrayList.add(tempTitle);
indicator |= 4;
}
//if now bit is unset after first pass, set it
if( (indicator & 1) == 0 && (indicator & 2) == 2 ) {
tempItem.viewType = TodayListAdapter.ItemType.ITEM_NOW;
indicator |= 1;
}
//add to list here.
if(indicator > 0) {
tempItem.mainText = c.getString(c.getColumnIndex("SubjName"));
tempItem.timeText = ScheduleHelper
.convertIntToStringSlot(curTimeStart, curTimeEnd);
tempItem.roomText = c.getString(c.getColumnIndex("Room"));
//build reminder string
String bodyString = c.getString(c.getColumnIndex("Body"));
String titleString = c.getString(c.getColumnIndex("Title"));
if(bodyString != null) {
StringBuilder sbRem = new StringBuilder("<b>");
sbRem.append(titleString);
sbRem.append("</b>. ");
sbRem.append(bodyString);
tempItem.reminderText = sbRem.toString();
} else {
tempItem.reminderText = "None";
}
todayArrayList.add(tempItem);
}
}
adapter.notifyDataSetChanged();
}
}
}
| |
/**
* Copyright (c) 2016-present, RxJava Contributors.
*
* 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 io.reactivex.internal.operators.observable;
import static org.junit.Assert.*;
import java.util.*;
import java.util.concurrent.*;
import org.junit.*;
import io.reactivex.*;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposables;
import io.reactivex.exceptions.TestException;
import io.reactivex.functions.*;
import io.reactivex.internal.functions.Functions;
import io.reactivex.observers.*;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.schedulers.TestScheduler;
import io.reactivex.subjects.*;
public class ObservableWindowWithStartEndObservableTest {
private TestScheduler scheduler;
private Scheduler.Worker innerScheduler;
@Before
public void before() {
scheduler = new TestScheduler();
innerScheduler = scheduler.createWorker();
}
@Test
public void testObservableBasedOpenerAndCloser() {
final List<String> list = new ArrayList<String>();
final List<List<String>> lists = new ArrayList<List<String>>();
Observable<String> source = Observable.unsafeCreate(new ObservableSource<String>() {
@Override
public void subscribe(Observer<? super String> innerObserver) {
innerObserver.onSubscribe(Disposables.empty());
push(innerObserver, "one", 10);
push(innerObserver, "two", 60);
push(innerObserver, "three", 110);
push(innerObserver, "four", 160);
push(innerObserver, "five", 210);
complete(innerObserver, 500);
}
});
Observable<Object> openings = Observable.unsafeCreate(new ObservableSource<Object>() {
@Override
public void subscribe(Observer<? super Object> innerObserver) {
innerObserver.onSubscribe(Disposables.empty());
push(innerObserver, new Object(), 50);
push(innerObserver, new Object(), 200);
complete(innerObserver, 250);
}
});
Function<Object, Observable<Object>> closer = new Function<Object, Observable<Object>>() {
@Override
public Observable<Object> apply(Object opening) {
return Observable.unsafeCreate(new ObservableSource<Object>() {
@Override
public void subscribe(Observer<? super Object> innerObserver) {
innerObserver.onSubscribe(Disposables.empty());
push(innerObserver, new Object(), 100);
complete(innerObserver, 101);
}
});
}
};
Observable<Observable<String>> windowed = source.window(openings, closer);
windowed.subscribe(observeWindow(list, lists));
scheduler.advanceTimeTo(500, TimeUnit.MILLISECONDS);
assertEquals(2, lists.size());
assertEquals(lists.get(0), list("two", "three"));
assertEquals(lists.get(1), list("five"));
}
@Test
public void testObservableBasedCloser() {
final List<String> list = new ArrayList<String>();
final List<List<String>> lists = new ArrayList<List<String>>();
Observable<String> source = Observable.unsafeCreate(new ObservableSource<String>() {
@Override
public void subscribe(Observer<? super String> innerObserver) {
innerObserver.onSubscribe(Disposables.empty());
push(innerObserver, "one", 10);
push(innerObserver, "two", 60);
push(innerObserver, "three", 110);
push(innerObserver, "four", 160);
push(innerObserver, "five", 210);
complete(innerObserver, 250);
}
});
Callable<Observable<Object>> closer = new Callable<Observable<Object>>() {
int calls;
@Override
public Observable<Object> call() {
return Observable.unsafeCreate(new ObservableSource<Object>() {
@Override
public void subscribe(Observer<? super Object> innerObserver) {
innerObserver.onSubscribe(Disposables.empty());
int c = calls++;
if (c == 0) {
push(innerObserver, new Object(), 100);
} else
if (c == 1) {
push(innerObserver, new Object(), 100);
} else {
complete(innerObserver, 101);
}
}
});
}
};
Observable<Observable<String>> windowed = source.window(closer);
windowed.subscribe(observeWindow(list, lists));
scheduler.advanceTimeTo(500, TimeUnit.MILLISECONDS);
assertEquals(3, lists.size());
assertEquals(lists.get(0), list("one", "two"));
assertEquals(lists.get(1), list("three", "four"));
assertEquals(lists.get(2), list("five"));
}
private List<String> list(String... args) {
List<String> list = new ArrayList<String>();
for (String arg : args) {
list.add(arg);
}
return list;
}
private <T> void push(final Observer<T> observer, final T value, int delay) {
innerScheduler.schedule(new Runnable() {
@Override
public void run() {
observer.onNext(value);
}
}, delay, TimeUnit.MILLISECONDS);
}
private void complete(final Observer<?> observer, int delay) {
innerScheduler.schedule(new Runnable() {
@Override
public void run() {
observer.onComplete();
}
}, delay, TimeUnit.MILLISECONDS);
}
private Consumer<Observable<String>> observeWindow(final List<String> list, final List<List<String>> lists) {
return new Consumer<Observable<String>>() {
@Override
public void accept(Observable<String> stringObservable) {
stringObservable.subscribe(new DefaultObserver<String>() {
@Override
public void onComplete() {
lists.add(new ArrayList<String>(list));
list.clear();
}
@Override
public void onError(Throwable e) {
fail(e.getMessage());
}
@Override
public void onNext(String args) {
list.add(args);
}
});
}
};
}
@Test
public void testNoUnsubscribeAndNoLeak() {
PublishSubject<Integer> source = PublishSubject.create();
PublishSubject<Integer> open = PublishSubject.create();
final PublishSubject<Integer> close = PublishSubject.create();
TestObserver<Observable<Integer>> to = new TestObserver<Observable<Integer>>();
source.window(open, new Function<Integer, Observable<Integer>>() {
@Override
public Observable<Integer> apply(Integer t) {
return close;
}
}).subscribe(to);
open.onNext(1);
source.onNext(1);
assertTrue(open.hasObservers());
assertTrue(close.hasObservers());
close.onNext(1);
assertFalse(close.hasObservers());
source.onComplete();
to.assertComplete();
to.assertNoErrors();
to.assertValueCount(1);
// 2.0.2 - not anymore
// assertTrue("Not cancelled!", ts.isCancelled());
assertFalse(open.hasObservers());
assertFalse(close.hasObservers());
}
@Test
public void testUnsubscribeAll() {
PublishSubject<Integer> source = PublishSubject.create();
PublishSubject<Integer> open = PublishSubject.create();
final PublishSubject<Integer> close = PublishSubject.create();
TestObserver<Observable<Integer>> to = new TestObserver<Observable<Integer>>();
source.window(open, new Function<Integer, Observable<Integer>>() {
@Override
public Observable<Integer> apply(Integer t) {
return close;
}
}).subscribe(to);
open.onNext(1);
assertTrue(open.hasObservers());
assertTrue(close.hasObservers());
to.dispose();
// FIXME subject has subscribers because of the open window
assertTrue(open.hasObservers());
// FIXME subject has subscribers because of the open window
assertTrue(close.hasObservers());
}
@Test
public void boundarySelectorNormal() {
PublishSubject<Integer> source = PublishSubject.create();
PublishSubject<Integer> start = PublishSubject.create();
final PublishSubject<Integer> end = PublishSubject.create();
TestObserver<Integer> to = source.window(start, new Function<Integer, ObservableSource<Integer>>() {
@Override
public ObservableSource<Integer> apply(Integer v) throws Exception {
return end;
}
})
.flatMap(Functions.<Observable<Integer>>identity())
.test();
start.onNext(0);
source.onNext(1);
source.onNext(2);
source.onNext(3);
source.onNext(4);
start.onNext(1);
source.onNext(5);
source.onNext(6);
end.onNext(1);
start.onNext(2);
TestHelper.emit(source, 7, 8);
to.assertResult(1, 2, 3, 4, 5, 5, 6, 6, 7, 8);
}
@Test
public void startError() {
PublishSubject<Integer> source = PublishSubject.create();
PublishSubject<Integer> start = PublishSubject.create();
final PublishSubject<Integer> end = PublishSubject.create();
TestObserver<Integer> to = source.window(start, new Function<Integer, ObservableSource<Integer>>() {
@Override
public ObservableSource<Integer> apply(Integer v) throws Exception {
return end;
}
})
.flatMap(Functions.<Observable<Integer>>identity())
.test();
start.onError(new TestException());
to.assertFailure(TestException.class);
assertFalse("Source has observers!", source.hasObservers());
assertFalse("Start has observers!", start.hasObservers());
assertFalse("End has observers!", end.hasObservers());
}
@Test
public void endError() {
PublishSubject<Integer> source = PublishSubject.create();
PublishSubject<Integer> start = PublishSubject.create();
final PublishSubject<Integer> end = PublishSubject.create();
TestObserver<Integer> to = source.window(start, new Function<Integer, ObservableSource<Integer>>() {
@Override
public ObservableSource<Integer> apply(Integer v) throws Exception {
return end;
}
})
.flatMap(Functions.<Observable<Integer>>identity())
.test();
start.onNext(1);
end.onError(new TestException());
to.assertFailure(TestException.class);
assertFalse("Source has observers!", source.hasObservers());
assertFalse("Start has observers!", start.hasObservers());
assertFalse("End has observers!", end.hasObservers());
}
@Test
public void dispose() {
TestHelper.checkDisposed(Observable.just(1).window(Observable.just(2), Functions.justFunction(Observable.never())));
}
@Test
public void reentrant() {
final Subject<Integer> ps = PublishSubject.<Integer>create();
TestObserver<Integer> to = new TestObserver<Integer>() {
@Override
public void onNext(Integer t) {
super.onNext(t);
if (t == 1) {
ps.onNext(2);
ps.onComplete();
}
}
};
ps.window(BehaviorSubject.createDefault(1), Functions.justFunction(Observable.never()))
.flatMap(new Function<Observable<Integer>, ObservableSource<Integer>>() {
@Override
public ObservableSource<Integer> apply(Observable<Integer> v) throws Exception {
return v;
}
})
.subscribe(to);
ps.onNext(1);
to
.awaitDone(1, TimeUnit.SECONDS)
.assertResult(1, 2);
}
@Test
public void badSourceCallable() {
TestHelper.checkBadSourceObservable(new Function<Observable<Object>, Object>() {
@Override
public Object apply(Observable<Object> o) throws Exception {
return o.window(Observable.just(1), Functions.justFunction(Observable.never()));
}
}, false, 1, 1, (Object[])null);
}
@Test
public void windowCloseIngoresCancel() {
List<Throwable> errors = TestHelper.trackPluginErrors();
try {
BehaviorSubject.createDefault(1)
.window(BehaviorSubject.createDefault(1), new Function<Integer, Observable<Integer>>() {
@Override
public Observable<Integer> apply(Integer f) throws Exception {
return new Observable<Integer>() {
@Override
protected void subscribeActual(
Observer<? super Integer> s) {
s.onSubscribe(Disposables.empty());
s.onNext(1);
s.onNext(2);
s.onError(new TestException());
}
};
}
})
.test()
.assertValueCount(1)
.assertNoErrors()
.assertNotComplete();
TestHelper.assertUndeliverable(errors, 0, TestException.class);
} finally {
RxJavaPlugins.reset();
}
}
}
| |
/*
* 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.zookeeper.server;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.jute.BinaryOutputArchive;
import org.apache.jute.Record;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.SessionExpiredException;
import org.apache.zookeeper.KeeperException.SessionMovedException;
import org.apache.zookeeper.MultiOperationRecord;
import org.apache.zookeeper.Op;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooDefs.OpCode;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.proto.CreateRequest;
import org.apache.zookeeper.proto.ReconfigRequest;
import org.apache.zookeeper.proto.RequestHeader;
import org.apache.zookeeper.proto.SetDataRequest;
import org.apache.zookeeper.server.ZooKeeperServer.ChangeRecord;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.quorum.Leader;
import org.apache.zookeeper.server.quorum.LeaderBeanTest;
import org.apache.zookeeper.server.quorum.LeaderZooKeeperServer;
import org.apache.zookeeper.server.quorum.QuorumPeer;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
import org.apache.zookeeper.server.quorum.flexible.QuorumVerifier;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.txn.ErrorTxn;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PrepRequestProcessorTest extends ClientBase {
private static final Logger LOG = LoggerFactory.getLogger(PrepRequestProcessorTest.class);
private static final int CONNECTION_TIMEOUT = 3000;
private static String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
private CountDownLatch pLatch;
private ZooKeeperServer zks;
private ServerCnxnFactory servcnxnf;
private PrepRequestProcessor processor;
private Request outcome;
private boolean isReconfigEnabledPreviously;
private boolean isStandaloneEnabledPreviously;
@BeforeEach
public void setup() throws Exception {
File tmpDir = ClientBase.createTmpDir();
ClientBase.setupTestEnv();
zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
SyncRequestProcessor.setSnapCount(100);
final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
servcnxnf = ServerCnxnFactory.createFactory(PORT, -1);
servcnxnf.startup(zks);
assertTrue(ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT), "waiting for server being up ");
zks.sessionTracker = new MySessionTracker();
isReconfigEnabledPreviously = QuorumPeerConfig.isReconfigEnabled();
isStandaloneEnabledPreviously = QuorumPeerConfig.isStandaloneEnabled();
}
@AfterEach
public void teardown() throws Exception {
if (servcnxnf != null) {
servcnxnf.shutdown();
}
if (zks != null) {
zks.shutdown();
}
// reset the reconfig option
QuorumPeerConfig.setReconfigEnabled(isReconfigEnabledPreviously);
QuorumPeerConfig.setStandaloneEnabled(isStandaloneEnabledPreviously);
}
@Test
public void testPRequest() throws Exception {
pLatch = new CountDownLatch(1);
processor = new PrepRequestProcessor(zks, new MyRequestProcessor());
Request foo = new Request(null, 1L, 1, OpCode.create, ByteBuffer.allocate(3), null);
processor.pRequest(foo);
assertEquals(new ErrorTxn(KeeperException.Code.MARSHALLINGERROR.intValue()), outcome.getTxn(), "Request should have marshalling error");
assertTrue(pLatch.await(5, TimeUnit.SECONDS), "request hasn't been processed in chain");
}
private Request createRequest(Record record, int opCode) throws IOException {
return createRequest(record, opCode, 1L);
}
private Request createRequest(Record record, int opCode, long sessionId) throws IOException {
return createRequest(record, opCode, sessionId, false);
}
private Request createRequest(Record record, int opCode, boolean admin) throws IOException {
return createRequest(record, opCode, 1L, admin);
}
private Request createRequest(Record record, int opCode, long sessionId, boolean admin) throws IOException {
// encoding
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos);
record.serialize(boa, "request");
baos.close();
// Id
List<Id> ids = Arrays.asList(admin ? new Id("super", "super user") : Ids.ANYONE_ID_UNSAFE);
return new Request(null, sessionId, 0, opCode, ByteBuffer.wrap(baos.toByteArray()), ids);
}
private void process(List<Op> ops) throws Exception {
pLatch = new CountDownLatch(1);
processor = new PrepRequestProcessor(zks, new MyRequestProcessor());
Record record = new MultiOperationRecord(ops);
Request req = createRequest(record, OpCode.multi, false);
processor.pRequest(req);
assertTrue(pLatch.await(5, TimeUnit.SECONDS), "request hasn't been processed in chain");
}
/**
* This test checks that a successful multi will change outstanding record
* and failed multi shouldn't change outstanding record.
*/
@Test
public void testMultiOutstandingChange() throws Exception {
zks.getZKDatabase().dataTree.createNode("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, 0, 0, 0, 0);
assertNull(zks.outstandingChangesForPath.get("/foo"));
process(Arrays.asList(Op.setData("/foo", new byte[0], -1)));
ChangeRecord cr = zks.outstandingChangesForPath.get("/foo");
assertNotNull(cr, "Change record wasn't set");
assertEquals(1, cr.zxid, "Record zxid wasn't set correctly");
process(Arrays.asList(Op.delete("/foo", -1)));
cr = zks.outstandingChangesForPath.get("/foo");
assertEquals(2, cr.zxid, "Record zxid wasn't set correctly");
// It should fail and shouldn't change outstanding record.
process(Arrays.asList(Op.delete("/foo", -1)));
cr = zks.outstandingChangesForPath.get("/foo");
// zxid should still be previous result because record's not changed.
assertEquals(2, cr.zxid, "Record zxid wasn't set correctly");
}
@Test
public void testReconfigWithAnotherOutstandingChange() throws Exception {
QuorumPeerConfig.setReconfigEnabled(true);
QuorumPeerConfig.setStandaloneEnabled(false);
QuorumPeer qp = new QuorumPeer();
QuorumVerifier quorumVerifierMock = mock(QuorumVerifier.class);
when(quorumVerifierMock.getAllMembers()).thenReturn(LeaderBeanTest.getMockedPeerViews(qp.getId()));
qp.setQuorumVerifier(quorumVerifierMock, false);
FileTxnSnapLog snapLog = new FileTxnSnapLog(tmpDir, tmpDir);
LeaderZooKeeperServer lzks = new LeaderZooKeeperServer(snapLog, qp, new ZKDatabase(snapLog));
qp.leader = new Leader(qp, lzks);
lzks.sessionTracker = new MySessionTracker();
ZooKeeperServer.setDigestEnabled(true);
processor = new PrepRequestProcessor(lzks, new MyRequestProcessor());
Record record = new CreateRequest("/foo", "data".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT.toFlag());
pLatch = new CountDownLatch(1);
processor.pRequest(createRequest(record, OpCode.create, false));
assertTrue(pLatch.await(5, TimeUnit.SECONDS), "request hasn't been processed in chain");
String newMember = "server.0=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ":participant";
record = new ReconfigRequest(null, null, newMember, 0);
pLatch = new CountDownLatch(1);
processor.pRequest(createRequest(record, OpCode.reconfig, true));
assertTrue(pLatch.await(5, TimeUnit.SECONDS), "request hasn't been processed in chain");
assertEquals(outcome.getHdr().getType(), OpCode.reconfig); // Verifies that there was no error.
}
/**
* ZOOKEEPER-2052:
* This test checks that if a multi operation aborted, and during the multi there is side effect
* that changed outstandingChangesForPath, after aborted the side effect should be removed and
* everything should be restored correctly.
*/
@Test
public void testMultiRollbackNoLastChange() throws Exception {
zks.getZKDatabase().dataTree.createNode("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, 0, 0, 0, 0);
zks.getZKDatabase().dataTree.createNode("/foo/bar", new byte[0], Ids.OPEN_ACL_UNSAFE, 0, 0, 0, 0);
assertNull(zks.outstandingChangesForPath.get("/foo"));
// multi record:
// set "/foo" => succeed, leave a outstanding change
// delete "/foo" => fail, roll back change
process(Arrays.asList(Op.setData("/foo", new byte[0], -1), Op.delete("/foo", -1)));
// aborting multi shouldn't leave any record.
assertNull(zks.outstandingChangesForPath.get("/foo"));
}
/**
* Test ephemerals are deleted when the session is closed with
* the newly added CloseSessionTxn in ZOOKEEPER-3145.
*/
@Test
public void testCloseSessionTxn() throws Exception {
boolean before = ZooKeeperServer.isCloseSessionTxnEnabled();
ZooKeeperServer.setCloseSessionTxnEnabled(true);
try {
// create a few ephemerals
long ephemeralOwner = 1;
DataTree dt = zks.getZKDatabase().dataTree;
dt.createNode("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, ephemeralOwner, 0, 0, 0);
dt.createNode("/bar", new byte[0], Ids.OPEN_ACL_UNSAFE, ephemeralOwner, 0, 0, 0);
// close session
RequestHeader header = new RequestHeader();
header.setType(OpCode.closeSession);
final FinalRequestProcessor frq = new FinalRequestProcessor(zks);
final CountDownLatch latch = new CountDownLatch(1);
processor = new PrepRequestProcessor(zks, new RequestProcessor() {
@Override
public void processRequest(Request request) {
frq.processRequest(request);
latch.countDown();
}
@Override
public void shutdown() {
// TODO Auto-generated method stub
}
});
processor.pRequest(createRequest(header, OpCode.closeSession, ephemeralOwner));
assertTrue(latch.await(3, TimeUnit.SECONDS));
// assert ephemerals are deleted
assertEquals(null, dt.getNode("/foo"));
assertEquals(null, dt.getNode("/bar"));
} finally {
ZooKeeperServer.setCloseSessionTxnEnabled(before);
}
}
/**
* It tests that PrepRequestProcessor will return BadArgument KeeperException
* if the request path (if it exists) is not valid, e.g. empty string.
*/
@Test
public void testInvalidPath() throws Exception {
pLatch = new CountDownLatch(1);
processor = new PrepRequestProcessor(zks, new MyRequestProcessor());
SetDataRequest record = new SetDataRequest("", new byte[0], -1);
Request req = createRequest(record, OpCode.setData, false);
processor.pRequest(req);
pLatch.await();
assertEquals(outcome.getHdr().getType(), OpCode.error);
assertEquals(outcome.getException().code(), KeeperException.Code.BADARGUMENTS);
}
private class MyRequestProcessor implements RequestProcessor {
@Override
public void processRequest(Request request) {
// getting called by PrepRequestProcessor
outcome = request;
pLatch.countDown();
}
@Override
public void shutdown() {
// TODO Auto-generated method stub
}
}
private class MySessionTracker implements SessionTracker {
@Override
public boolean trackSession(long id, int to) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean commitSession(long id, int to) {
// TODO Auto-generated method stub
return false;
}
@Override
public void checkSession(long sessionId, Object owner) throws SessionExpiredException, SessionMovedException {
// TODO Auto-generated method stub
}
@Override
public long createSession(int sessionTimeout) {
// TODO Auto-generated method stub
return 0;
}
@Override
public void dumpSessions(PrintWriter pwriter) {
// TODO Auto-generated method stub
}
@Override
public void removeSession(long sessionId) {
// TODO Auto-generated method stub
}
public int upgradeSession(long sessionId) {
// TODO Auto-generated method stub
return 0;
}
@Override
public void setOwner(long id, Object owner) throws SessionExpiredException {
// TODO Auto-generated method stub
}
@Override
public void shutdown() {
// TODO Auto-generated method stub
}
@Override
public boolean touchSession(long sessionId, int sessionTimeout) {
// TODO Auto-generated method stub
return false;
}
@Override
public void setSessionClosing(long sessionId) {
// TODO Auto-generated method stub
}
@Override
public boolean isTrackingSession(long sessionId) {
// TODO Auto-generated method stub
return false;
}
@Override
public void checkGlobalSession(long sessionId, Object owner) throws SessionExpiredException, SessionMovedException {
// TODO Auto-generated method stub
}
@Override
public Map<Long, Set<Long>> getSessionExpiryMap() {
return new HashMap<Long, Set<Long>>();
}
@Override
public long getLocalSessionCount() {
return 0;
}
@Override
public boolean isLocalSessionsEnabled() {
return false;
}
public Set<Long> globalSessions() {
return Collections.emptySet();
}
public Set<Long> localSessions() {
return Collections.emptySet();
}
}
}
| |
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.extractor.ts;
import static com.google.android.exoplayer2.extractor.ts.TsPayloadReader.FLAG_DATA_ALIGNMENT_INDICATOR;
import static com.google.android.exoplayer2.metadata.id3.Id3Decoder.ID3_HEADER_LENGTH;
import static com.google.android.exoplayer2.metadata.id3.Id3Decoder.ID3_TAG;
import static java.lang.annotation.ElementType.TYPE_USE;
import androidx.annotation.IntDef;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ParserException;
import com.google.android.exoplayer2.PlaybackException;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.extractor.ConstantBitrateSeekMap;
import com.google.android.exoplayer2.extractor.Extractor;
import com.google.android.exoplayer2.extractor.ExtractorInput;
import com.google.android.exoplayer2.extractor.ExtractorOutput;
import com.google.android.exoplayer2.extractor.ExtractorsFactory;
import com.google.android.exoplayer2.extractor.PositionHolder;
import com.google.android.exoplayer2.extractor.SeekMap;
import com.google.android.exoplayer2.extractor.ts.TsPayloadReader.TrackIdGenerator;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.ParsableBitArray;
import com.google.android.exoplayer2.util.ParsableByteArray;
import java.io.EOFException;
import java.io.IOException;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.RequiresNonNull;
/** Extracts data from AAC bit streams with ADTS framing. */
public final class AdtsExtractor implements Extractor {
/** Factory for {@link AdtsExtractor} instances. */
public static final ExtractorsFactory FACTORY = () -> new Extractor[] {new AdtsExtractor()};
/**
* Flags controlling the behavior of the extractor. Possible flag values are {@link
* #FLAG_ENABLE_CONSTANT_BITRATE_SEEKING} and {@link
* #FLAG_ENABLE_CONSTANT_BITRATE_SEEKING_ALWAYS}.
*/
@Documented
@Retention(RetentionPolicy.SOURCE)
@Target(TYPE_USE)
@IntDef(
flag = true,
value = {FLAG_ENABLE_CONSTANT_BITRATE_SEEKING, FLAG_ENABLE_CONSTANT_BITRATE_SEEKING_ALWAYS})
public @interface Flags {}
/**
* Flag to force enable seeking using a constant bitrate assumption in cases where seeking would
* otherwise not be possible.
*
* <p>Note that this approach may result in approximated stream duration and seek position that
* are not precise, especially when the stream bitrate varies a lot.
*/
public static final int FLAG_ENABLE_CONSTANT_BITRATE_SEEKING = 1;
/**
* Like {@link #FLAG_ENABLE_CONSTANT_BITRATE_SEEKING}, except that seeking is also enabled in
* cases where the content length (and hence the duration of the media) is unknown. Application
* code should ensure that requested seek positions are valid when using this flag, or be ready to
* handle playback failures reported through {@link Player.Listener#onPlayerError} with {@link
* PlaybackException#errorCode} set to {@link
* PlaybackException#ERROR_CODE_IO_READ_POSITION_OUT_OF_RANGE}.
*
* <p>If this flag is set, then the behavior enabled by {@link
* #FLAG_ENABLE_CONSTANT_BITRATE_SEEKING} is implicitly enabled as well.
*/
public static final int FLAG_ENABLE_CONSTANT_BITRATE_SEEKING_ALWAYS = 1 << 1;
private static final int MAX_PACKET_SIZE = 2 * 1024;
/**
* The maximum number of bytes to search when sniffing, excluding the header, before giving up.
* Frame sizes are represented by 13-bit fields, so expect a valid frame in the first 8192 bytes.
*/
private static final int MAX_SNIFF_BYTES = 8 * 1024;
/**
* The maximum number of frames to use when calculating the average frame size for constant
* bitrate seeking.
*/
private static final int NUM_FRAMES_FOR_AVERAGE_FRAME_SIZE = 1000;
private final @Flags int flags;
private final AdtsReader reader;
private final ParsableByteArray packetBuffer;
private final ParsableByteArray scratch;
private final ParsableBitArray scratchBits;
private @MonotonicNonNull ExtractorOutput extractorOutput;
private long firstSampleTimestampUs;
private long firstFramePosition;
private int averageFrameSize;
private boolean hasCalculatedAverageFrameSize;
private boolean startedPacket;
private boolean hasOutputSeekMap;
/** Creates a new extractor for ADTS bitstreams. */
public AdtsExtractor() {
this(/* flags= */ 0);
}
/**
* Creates a new extractor for ADTS bitstreams.
*
* @param flags Flags that control the extractor's behavior.
*/
public AdtsExtractor(@Flags int flags) {
if ((flags & FLAG_ENABLE_CONSTANT_BITRATE_SEEKING_ALWAYS) != 0) {
flags |= FLAG_ENABLE_CONSTANT_BITRATE_SEEKING;
}
this.flags = flags;
reader = new AdtsReader(true);
packetBuffer = new ParsableByteArray(MAX_PACKET_SIZE);
averageFrameSize = C.LENGTH_UNSET;
firstFramePosition = C.POSITION_UNSET;
// Allocate scratch space for an ID3 header. The same buffer is also used to read 4 byte values.
scratch = new ParsableByteArray(ID3_HEADER_LENGTH);
scratchBits = new ParsableBitArray(scratch.getData());
}
// Extractor implementation.
@Override
public boolean sniff(ExtractorInput input) throws IOException {
// Skip any ID3 headers.
int startPosition = peekId3Header(input);
// Try to find four or more consecutive AAC audio frames, exceeding the MPEG TS packet size.
int headerPosition = startPosition;
int totalValidFramesSize = 0;
int validFramesCount = 0;
while (true) {
input.peekFully(scratch.getData(), 0, 2);
scratch.setPosition(0);
int syncBytes = scratch.readUnsignedShort();
if (!AdtsReader.isAdtsSyncWord(syncBytes)) {
// We didn't find an ADTS sync word. Start searching again from one byte further into the
// start of the stream.
validFramesCount = 0;
totalValidFramesSize = 0;
headerPosition++;
input.resetPeekPosition();
input.advancePeekPosition(headerPosition);
} else {
if (++validFramesCount >= 4 && totalValidFramesSize > TsExtractor.TS_PACKET_SIZE) {
return true;
}
// Skip the frame.
input.peekFully(scratch.getData(), 0, 4);
scratchBits.setPosition(14);
int frameSize = scratchBits.readBits(13);
if (frameSize <= 6) {
// The size is too small, so we're probably not reading an ADTS frame. Start searching
// again from one byte further into the start of the stream.
validFramesCount = 0;
totalValidFramesSize = 0;
headerPosition++;
input.resetPeekPosition();
input.advancePeekPosition(headerPosition);
} else {
input.advancePeekPosition(frameSize - 6);
totalValidFramesSize += frameSize;
}
}
if (headerPosition - startPosition >= MAX_SNIFF_BYTES) {
return false;
}
}
}
@Override
public void init(ExtractorOutput output) {
this.extractorOutput = output;
reader.createTracks(output, new TrackIdGenerator(0, 1));
output.endTracks();
}
@Override
public void seek(long position, long timeUs) {
startedPacket = false;
reader.seek();
firstSampleTimestampUs = timeUs;
}
@Override
public void release() {
// Do nothing
}
@Override
public int read(ExtractorInput input, PositionHolder seekPosition) throws IOException {
Assertions.checkStateNotNull(extractorOutput); // Asserts that init has been called.
long inputLength = input.getLength();
boolean canUseConstantBitrateSeeking =
(flags & FLAG_ENABLE_CONSTANT_BITRATE_SEEKING_ALWAYS) != 0
|| ((flags & FLAG_ENABLE_CONSTANT_BITRATE_SEEKING) != 0
&& inputLength != C.LENGTH_UNSET);
if (canUseConstantBitrateSeeking) {
calculateAverageFrameSize(input);
}
int bytesRead = input.read(packetBuffer.getData(), 0, MAX_PACKET_SIZE);
boolean readEndOfStream = bytesRead == RESULT_END_OF_INPUT;
maybeOutputSeekMap(inputLength, readEndOfStream);
if (readEndOfStream) {
return RESULT_END_OF_INPUT;
}
// Feed whatever data we have to the reader, regardless of whether the read finished or not.
packetBuffer.setPosition(0);
packetBuffer.setLimit(bytesRead);
if (!startedPacket) {
// Pass data to the reader as though it's contained within a single infinitely long packet.
reader.packetStarted(firstSampleTimestampUs, FLAG_DATA_ALIGNMENT_INDICATOR);
startedPacket = true;
}
// TODO: Make it possible for reader to consume the dataSource directly, so that it becomes
// unnecessary to copy the data through packetBuffer.
reader.consume(packetBuffer);
return RESULT_CONTINUE;
}
private int peekId3Header(ExtractorInput input) throws IOException {
int firstFramePosition = 0;
while (true) {
input.peekFully(scratch.getData(), /* offset= */ 0, ID3_HEADER_LENGTH);
scratch.setPosition(0);
if (scratch.readUnsignedInt24() != ID3_TAG) {
break;
}
scratch.skipBytes(3);
int length = scratch.readSynchSafeInt();
firstFramePosition += ID3_HEADER_LENGTH + length;
input.advancePeekPosition(length);
}
input.resetPeekPosition();
input.advancePeekPosition(firstFramePosition);
if (this.firstFramePosition == C.POSITION_UNSET) {
this.firstFramePosition = firstFramePosition;
}
return firstFramePosition;
}
@RequiresNonNull("extractorOutput")
private void maybeOutputSeekMap(long inputLength, boolean readEndOfStream) {
if (hasOutputSeekMap) {
return;
}
boolean useConstantBitrateSeeking =
(flags & FLAG_ENABLE_CONSTANT_BITRATE_SEEKING) != 0 && averageFrameSize > 0;
if (useConstantBitrateSeeking
&& reader.getSampleDurationUs() == C.TIME_UNSET
&& !readEndOfStream) {
// Wait for the sampleDurationUs to be available, or for the end of the stream to be reached,
// before creating seek map.
return;
}
if (useConstantBitrateSeeking && reader.getSampleDurationUs() != C.TIME_UNSET) {
extractorOutput.seekMap(
getConstantBitrateSeekMap(
inputLength, (flags & FLAG_ENABLE_CONSTANT_BITRATE_SEEKING_ALWAYS) != 0));
} else {
extractorOutput.seekMap(new SeekMap.Unseekable(C.TIME_UNSET));
}
hasOutputSeekMap = true;
}
private void calculateAverageFrameSize(ExtractorInput input) throws IOException {
if (hasCalculatedAverageFrameSize) {
return;
}
averageFrameSize = C.LENGTH_UNSET;
input.resetPeekPosition();
if (input.getPosition() == 0) {
// Skip any ID3 headers.
peekId3Header(input);
}
int numValidFrames = 0;
long totalValidFramesSize = 0;
try {
while (input.peekFully(
scratch.getData(), /* offset= */ 0, /* length= */ 2, /* allowEndOfInput= */ true)) {
scratch.setPosition(0);
int syncBytes = scratch.readUnsignedShort();
if (!AdtsReader.isAdtsSyncWord(syncBytes)) {
// Invalid sync byte pattern.
// Constant bit-rate seeking will probably fail for this stream.
numValidFrames = 0;
break;
} else {
// Read the frame size.
if (!input.peekFully(
scratch.getData(), /* offset= */ 0, /* length= */ 4, /* allowEndOfInput= */ true)) {
break;
}
scratchBits.setPosition(14);
int currentFrameSize = scratchBits.readBits(13);
// Either the stream is malformed OR we're not parsing an ADTS stream.
if (currentFrameSize <= 6) {
hasCalculatedAverageFrameSize = true;
throw ParserException.createForMalformedContainer(
"Malformed ADTS stream", /* cause= */ null);
}
totalValidFramesSize += currentFrameSize;
if (++numValidFrames == NUM_FRAMES_FOR_AVERAGE_FRAME_SIZE) {
break;
}
if (!input.advancePeekPosition(currentFrameSize - 6, /* allowEndOfInput= */ true)) {
break;
}
}
}
} catch (EOFException e) {
// We reached the end of the input during a peekFully() or advancePeekPosition() operation.
// This is OK, it just means the input has an incomplete ADTS frame at the end. Ideally
// ExtractorInput would allow these operations to encounter end-of-input without throwing an
// exception [internal: b/145586657].
}
input.resetPeekPosition();
if (numValidFrames > 0) {
averageFrameSize = (int) (totalValidFramesSize / numValidFrames);
} else {
averageFrameSize = C.LENGTH_UNSET;
}
hasCalculatedAverageFrameSize = true;
}
private SeekMap getConstantBitrateSeekMap(long inputLength, boolean allowSeeksIfLengthUnknown) {
int bitrate = getBitrateFromFrameSize(averageFrameSize, reader.getSampleDurationUs());
return new ConstantBitrateSeekMap(
inputLength, firstFramePosition, bitrate, averageFrameSize, allowSeeksIfLengthUnknown);
}
/**
* Returns the stream bitrate, given a frame size and the duration of that frame in microseconds.
*
* @param frameSize The size of each frame in the stream.
* @param durationUsPerFrame The duration of the given frame in microseconds.
* @return The stream bitrate.
*/
private static int getBitrateFromFrameSize(int frameSize, long durationUsPerFrame) {
return (int) ((frameSize * C.BITS_PER_BYTE * C.MICROS_PER_SECOND) / durationUsPerFrame);
}
}
| |
/*
* Copyright 2010-2012 Ning, Inc.
*
* Ning 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 com.ning.metrics.collector.jaxrs;
import com.ning.metrics.collector.binder.config.CollectorConfig;
import com.ning.metrics.collector.endpoint.ParsedRequest;
import com.ning.metrics.collector.endpoint.extractors.DeserializationType;
import com.ning.metrics.collector.endpoint.extractors.EventDeserializerFactory;
import com.ning.metrics.serialization.event.Event;
import com.ning.metrics.serialization.event.EventDeserializer;
import com.google.inject.Inject;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Meter;
import com.yammer.metrics.core.MetricName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.weakref.jmx.Managed;
import javax.ws.rs.core.CacheControl;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* Event handler for the HTTP API (GET and POST).
*/
public class EventDeserializerRequestHandler
{
private static final Logger log = LoggerFactory.getLogger(EventDeserializerRequestHandler.class);
private static final String METRICS_GROUP = EventDeserializerRequestHandler.class.getPackage().getName();
final EventFilterRequestHandler filterRequestHandler;
final EventDeserializerFactory eventDeserializerFactory;
private final CacheControl cacheControl;
// We keep two meters (success and failure) for each DeserializationType
private final Map<MetricName, Meter> metrics = new HashMap<MetricName, Meter>();
private final Meter rejectedMeter;
private final Meter badRequestMeter;
private volatile boolean collectionEnabled;
@Inject
public EventDeserializerRequestHandler(final CollectorConfig config,
final EventFilterRequestHandler filterRequestHandler,
final EventDeserializerFactory deserializerFactory)
{
this(config.isEventEndpointEnabled(), filterRequestHandler, deserializerFactory);
}
//@VisibleForTesting
public EventDeserializerRequestHandler(final boolean isCollectionEnabled,
final EventFilterRequestHandler filterRequestHandler,
final EventDeserializerFactory deserializerFactory)
{
this.collectionEnabled = isCollectionEnabled;
this.filterRequestHandler = filterRequestHandler;
this.eventDeserializerFactory = deserializerFactory;
rejectedMeter = Metrics.newMeter(new MetricName(METRICS_GROUP, "DeserializationStats", "Rejected"), "events", TimeUnit.SECONDS);
badRequestMeter = Metrics.newMeter(new MetricName(METRICS_GROUP, "DeserializationStats", "BadRequest"), "events", TimeUnit.SECONDS);
// Exposes stats per Event type
for (final DeserializationType deserializationType : DeserializationType.values()) {
final MetricName successMetricName = getSuccessMetricsKey(deserializationType);
final MetricName failureMetricName = getFailureMetricsKey(deserializationType);
metrics.put(successMetricName, Metrics.newMeter(successMetricName, "events", TimeUnit.SECONDS));
metrics.put(failureMetricName, Metrics.newMeter(failureMetricName, "events", TimeUnit.SECONDS));
}
cacheControl = new CacheControl();
cacheControl.setPrivate(true);
cacheControl.setNoCache(true);
cacheControl.setProxyRevalidate(true);
}
public Response handleEventRequest(final ParsedRequest parsedRequest)
{
// If collection is disabled for this collector, ignore
if (!collectionEnabled) {
log.debug("Collection disabled, rejecting request: {}", parsedRequest);
rejectedMeter.mark();
return Response.status(Response.Status.SERVICE_UNAVAILABLE)
.header("Warning", String.format("199 Collection disabled"))
.cacheControl(cacheControl)
.build();
}
// First, create a deserializer from the request
final EventDeserializer extractor;
try {
extractor = eventDeserializerFactory.getEventDeserializer(parsedRequest);
}
// Can occur if the deserializer fails immediately (if the stream/file doesn't begin correctly)
// fail fast and notify the sender that their message is improperly formatted
catch (IOException e) {
return handleDeserializationFailure(parsedRequest, 0, 0, e);
}
// Then, try to deserialize and process the event(s)
int successes = 0;
int failures = 0;
try {
while (extractor.hasNextEvent()) {
final Event event = extractor.getNextEvent();
if (event == null) {
continue;
}
log.debug(String.format("Processing event %s", event));
final DeserializationType deserializationType = parsedRequest.getContentType();
if (filterRequestHandler.processEvent(event, parsedRequest)) {
metrics.get(getSuccessMetricsKey(deserializationType)).mark();
successes++;
}
else {
metrics.get(getFailureMetricsKey(deserializationType)).mark();
failures++;
}
}
}
// Catch IOException (getNextEvent() failed) and RuntimeExceptions
catch (Exception e) {
return handleDeserializationFailure(parsedRequest, successes, failures, e);
}
return buildResponse(parsedRequest, successes, failures);
}
private Response buildResponse(final ParsedRequest parsedRequest, final int successes, final int failures)
{
if (failures == 0) {
return Response.status(Response.Status.ACCEPTED)
.cacheControl(cacheControl)
.build();
}
else {
log.warn("Some events in the request couldn't be processed: {} successes/{} failures [{}]", new Object[]{successes, failures, parsedRequest.toString()});
return Response.status(Response.Status.ACCEPTED)
.header("Warning", String.format("199 [%d successes] [%d failures]", successes, failures))
.cacheControl(cacheControl)
.build();
}
}
public Response handleDeserializationFailure(final ParsedRequest parsedRequest, final int successes, final int failures, final Exception e)
{
log.warn(String.format("Exception while extracting or processing an event. [%s] %s", parsedRequest.toString(), e.toString()));
badRequestMeter.mark();
return Response.status(Response.Status.BAD_REQUEST)
.header("Warning", String.format("199 [%d successes] [%d failures] [%s]", successes, failures, e.toString()))
.cacheControl(cacheControl)
.build();
}
@Managed(description = "enable/disable collection of events")
public void setCollectionEnabled(final boolean value)
{
collectionEnabled = value;
}
@Managed(description = "event collection enabled?")
public boolean getCollectionEnabled()
{
return collectionEnabled;
}
//@VisibleForTesting
MetricName getSuccessMetricsKey(final DeserializationType type)
{
return new MetricName(METRICS_GROUP, "DeserializationStats", type.toString() + "_SUCCESS");
}
//@VisibleForTesting
MetricName getFailureMetricsKey(final DeserializationType type)
{
return new MetricName(METRICS_GROUP, "DeserializationStats", type.toString() + "_FAILURE");
}
//@VisibleForTesting
Map<MetricName, Meter> getMetrics()
{
return metrics;
}
//@VisibleForTesting
Meter getRejectedMeter()
{
return rejectedMeter;
}
//@VisibleForTesting
Meter getBadRequestMeter()
{
return badRequestMeter;
}
}
| |
package com.easygis.map.layer;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Handler;
import android.os.HandlerThread;
import com.easygis.map.Bounds;
import com.easygis.map.EMap;
import com.easygis.map.Layer;
import com.easygis.map.MapInfo;
import com.easygis.map.Tile;
import com.easygis.util.CoordinatorTranslation;
import com.easygis.util.EGISLog;
public class TileLayer extends Layer {
private EMap mMap;
private TileLayerDataLoader mTileLoader;
private List<PixelTile> mCurrentTiles = new ArrayList<PixelTile>();
private Bitmap mBufferedBitmap;
private Bitmap mBackgroundBitmap;
private Bounds mBounds;
private Object mLock = new Object();
private WorkerState mState = WorkerState.NONE;
private CoordinatorTranslation mTranslation;
private HandlerThread mMessageQueue = new HandlerThread(
"TileLayerMessageQueue");
private Handler mMessageHandler;
private Paint paint = new Paint();
public TileLayer(Context context, EMap map) {
super(context);
updateMapInfo(map);
}
public TileLayer(Context context, EMap map,
TileLayerDataLoader mTileLoader) {
super(context);
updateMapInfo(map);
this.mTileLoader = mTileLoader;
}
public void updateMapInfo(EMap map) {
this.mMap = map;
mTranslation = new CoordinatorTranslation(
(int)mMap.getMapInfo().mTileWidth);
startRender();
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
startRender();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
stopRender();
if (mBufferedBitmap != null) {
EGISLog.i(mBufferedBitmap + " is recycled");
mBufferedBitmap.recycle();
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
super.onLayout(changed, left, top, right, bottom);
mMessageHandler.postAtFrontOfQueue(mConfigRunnable);
}
private Matrix m = new Matrix();
float scale = 1.0F;
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int savePoint = canvas.save();
canvas.scale(scale, scale);
if (mBufferedBitmap != null) {
canvas.drawBitmap(mBufferedBitmap, 0, 0, paint);
}
canvas.restoreToCount(savePoint);
}
@Override
public void updateBounds(Bounds bounds) {
this.mBounds = bounds;
if (mMessageHandler != null) {
mMessageHandler.post(mUpdateBoundsRunnable);
}
}
@Override
public void updateBounds(Bounds bounds, int zoom) {
updateBounds(bounds);
}
@Override
protected void scale(float sc) {
scale *= sc;
}
private void drawTile(List<PixelTile> tileList, Bitmap target) {
Canvas c = new Canvas(target);
Paint p = new Paint();
for (PixelTile ptile : tileList) {
c.drawBitmap((Bitmap) ptile.tile.mTileData, ptile.offsetX,
ptile.offsetY, p);
postInvalidate();
}
}
private void startRender() {
if (!mWorker.isAlive()) {
mWorker.start();
}
if (!mMessageQueue.isAlive()) {
mMessageQueue.start();
}
if (mMessageHandler == null) {
mMessageHandler = new Handler(mMessageQueue.getLooper());
}
synchronized (mLock) {
mState = WorkerState.NONE;
mLock.notify();
}
}
private void stopRender() {
mMessageQueue.quit();
mMessageHandler = null;
synchronized (mLock) {
mState = WorkerState.DIED;
mLock.notify();
}
}
private TileDataLoaderCallback mTileDataLoadedCallback = new TileDataLoaderCallback() {
@Override
public void tileLoadedNotification(int row, int col, int zoom, Tile tile) {
}
};
private Thread mWorker = new Thread() {
@Override
public void run() {
while (true) {
synchronized (mLock) {
if (mState == WorkerState.DIED) {
break;
}
if (mState == WorkerState.NONE
|| mState == WorkerState.DONE) {
try {
mLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (mState != WorkerState.RENDER) {
continue;
}
// Until bitmap is not null
while (mBufferedBitmap == null) {
try {
mLock.wait(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
drawTile(mCurrentTiles, mBufferedBitmap);
mState = WorkerState.DONE;
}
}
}
};
private Runnable mUpdateBoundsRunnable = new Runnable() {
@Override
public void run() {
int zoom = mMap.getZoom();
int tileWidth = (int)mMap.getMapInfo().mTileWidth;
int tileHeight = (int) mMap.getMapInfo().mTileHeight;
long start = System.currentTimeMillis();
int[] topLeft = mTranslation.translateMetersToTile(mBounds.left,
mBounds.top, zoom);
int[] bottomRight = mTranslation.translateMetersToTile(
mBounds.right, mBounds.bottom, zoom);
int startRow = topLeft[1];
int endRow = bottomRight[1];
int startCol = topLeft[0];
int endCol = bottomRight[0];
double[] pixels = mTranslation.translateMetersToPixels(
mBounds.left, mBounds.top, zoom);
int offsetX = (int) -(pixels[0] - startCol * tileWidth);
int offsetY = (int) -(pixels[1] - startRow * tileHeight);
EGISLog.i(startRow + "," + startCol + " - " + endRow + "," + endCol
+ " offsetX:" + offsetX + " offsetY:" + offsetY
+ " px:" + pixels[0] + " py:" + pixels[1]);
if (offsetX > 0) {
startCol -= 1;
offsetX -= tileWidth;
} else if (offsetX < 0 && Math.abs(offsetX) > (int)tileWidth) {
startCol += 1;
offsetX += tileWidth;
}
if (offsetY > 0) {
startRow -= 1;
offsetY -= tileHeight;
} else if (offsetY < 0 && Math.abs(offsetY) > (int)tileHeight) {
startRow += 1;
offsetY += tileHeight;
}
long start0 = System.currentTimeMillis();
EGISLog.i("After adjust:" + startRow + "," + startCol + " - "
+ endRow + "," + endCol + " offsetX:" + offsetX
+ " offsetY:" + offsetY);
List<PixelTile> list = new ArrayList<PixelTile>();
int maxRow = mMap.getMapInfo().mSupportedLevels[zoom].mEndRow;
int maxCol = mMap.getMapInfo().mSupportedLevels[zoom].mEndCol;
for (int i = startRow, indexI = 0; i <= endRow; i++, indexI++) {
for (int j = startCol, indexJ = 0; j <= endCol; j++, indexJ++) {
int tileOffsetX = offsetX + indexJ
* (int) tileWidth;
int tileOffsetY = offsetY + indexI
* (int) tileHeight;
if (j <= maxCol && i <= maxRow) {
Tile tile = mTileLoader.getTile(i, j, zoom);
if (tile != null && tile.mTileData != null) {
list.add(new PixelTile(tileOffsetX,
tileOffsetY, tile));
} else {
EGISLog.e("row : " + i + " col:" + j
+ " bitmap is null");
}
}
}
}
long start1 = System.currentTimeMillis();
synchronized (mLock) {
mCurrentTiles.clear();
mCurrentTiles.addAll(list);
mState = WorkerState.RENDER;
mLock.notify();
}
long end = System.currentTimeMillis();
EGISLog.e("updateBounds cost:"+(end - start)+" "+(start1 -start)+" "+(start0 -start));
}
};
private Runnable mConfigRunnable = new Runnable() {
@Override
public void run() {
synchronized (mLock) {
mMessageHandler.removeCallbacks(mConfigRunnable);
mMessageHandler.removeCallbacks(mUpdateBoundsRunnable);
int width = getWidth();
int height = getHeight();
if (mBufferedBitmap == null) {
mBufferedBitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_4444);
} else {
if (mBufferedBitmap.getWidth() != width
|| mBufferedBitmap.getHeight() != height) {
if (android.os.Build.VERSION_CODES.KITKAT >= android.os.Build.VERSION.SDK_INT) {
mBufferedBitmap.reconfigure(width, height,
Bitmap.Config.ARGB_4444);
} else {
mBufferedBitmap.recycle();
mBufferedBitmap = Bitmap.createBitmap(width,
height, Bitmap.Config.ARGB_4444);
}
}
}
EGISLog.i("reconfig bitmap ["+width+","+height+"]......" + mBufferedBitmap);
mState = WorkerState.RENDER;
mLock.notify();
}
}
};
class PixelTile {
int offsetX;
int offsetY;
Tile tile;
public PixelTile(int offsetX, int offsetY, Tile tile) {
super();
this.offsetX = offsetX;
this.offsetY = offsetY;
this.tile = tile;
}
}
enum WorkerState {
NONE, RENDER, DONE, DIED;
}
}
| |
/*
* 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.internal;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.PrefixQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.Version;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.lucene.BytesRefs;
import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.fielddata.FieldDataType;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.Mapper;
import org.elasticsearch.index.mapper.MapperParsingException;
import org.elasticsearch.index.mapper.MergeMappingException;
import org.elasticsearch.index.mapper.MergeResult;
import org.elasticsearch.index.mapper.MetadataFieldMapper;
import org.elasticsearch.index.mapper.ParseContext;
import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.index.query.QueryParseContext;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import static org.elasticsearch.index.mapper.core.TypeParsers.parseField;
/**
*
*/
public class TypeFieldMapper extends MetadataFieldMapper {
public static final String NAME = "_type";
public static final String CONTENT_TYPE = "_type";
public static class Defaults {
public static final String NAME = TypeFieldMapper.NAME;
public static final MappedFieldType FIELD_TYPE = new TypeFieldType();
static {
FIELD_TYPE.setIndexOptions(IndexOptions.DOCS);
FIELD_TYPE.setTokenized(false);
FIELD_TYPE.setStored(false);
FIELD_TYPE.setOmitNorms(true);
FIELD_TYPE.setIndexAnalyzer(Lucene.KEYWORD_ANALYZER);
FIELD_TYPE.setSearchAnalyzer(Lucene.KEYWORD_ANALYZER);
FIELD_TYPE.setNames(new MappedFieldType.Names(NAME));
FIELD_TYPE.freeze();
}
}
public static class Builder extends MetadataFieldMapper.Builder<Builder, TypeFieldMapper> {
public Builder(MappedFieldType existing) {
super(Defaults.NAME, existing == null ? Defaults.FIELD_TYPE : existing);
indexName = Defaults.NAME;
}
@Override
public TypeFieldMapper build(BuilderContext context) {
fieldType.setNames(new MappedFieldType.Names(indexName, indexName, name));
return new TypeFieldMapper(fieldType, context.indexSettings());
}
}
public static class TypeParser implements Mapper.TypeParser {
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
if (parserContext.indexVersionCreated().onOrAfter(Version.V_2_0_0_beta1)) {
throw new MapperParsingException(NAME + " is not configurable");
}
Builder builder = new Builder(parserContext.mapperService().fullName(NAME));
parseField(builder, builder.name, node, parserContext);
return builder;
}
}
static final class TypeFieldType extends MappedFieldType {
public TypeFieldType() {
setFieldDataType(new FieldDataType("string"));
}
protected TypeFieldType(TypeFieldType ref) {
super(ref);
}
@Override
public MappedFieldType clone() {
return new TypeFieldType(this);
}
@Override
public String typeName() {
return CONTENT_TYPE;
}
@Override
public String value(Object value) {
if (value == null) {
return null;
}
return value.toString();
}
@Override
public boolean useTermQueryWithQueryString() {
return true;
}
@Override
public Query termQuery(Object value, @Nullable QueryParseContext context) {
if (indexOptions() == IndexOptions.NONE) {
return new ConstantScoreQuery(new PrefixQuery(new Term(UidFieldMapper.NAME, Uid.typePrefixAsBytes(BytesRefs.toBytesRef(value)))));
}
return new ConstantScoreQuery(new TermQuery(createTerm(value)));
}
}
public TypeFieldMapper(Settings indexSettings, MappedFieldType existing) {
this(existing == null ? Defaults.FIELD_TYPE.clone() : existing.clone(),
indexSettings);
}
public TypeFieldMapper(MappedFieldType fieldType, Settings indexSettings) {
super(NAME, fieldType, Defaults.FIELD_TYPE, indexSettings);
}
@Override
public void preParse(ParseContext context) throws IOException {
super.parse(context);
}
@Override
public void postParse(ParseContext context) throws IOException {
}
@Override
public Mapper parse(ParseContext context) throws IOException {
// we parse in pre parse
return null;
}
@Override
protected void parseCreateField(ParseContext context, List<Field> fields) throws IOException {
if (fieldType().indexOptions() == IndexOptions.NONE && !fieldType().stored()) {
return;
}
fields.add(new Field(fieldType().names().indexName(), context.type(), fieldType()));
if (fieldType().hasDocValues()) {
fields.add(new SortedSetDocValuesField(fieldType().names().indexName(), new BytesRef(context.type())));
}
}
@Override
protected String contentType() {
return CONTENT_TYPE;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
if (indexCreatedBefore2x == false) {
return builder;
}
boolean includeDefaults = params.paramAsBoolean("include_defaults", false);
// if all are defaults, no sense to write it at all
boolean indexed = fieldType().indexOptions() != IndexOptions.NONE;
boolean defaultIndexed = Defaults.FIELD_TYPE.indexOptions() != IndexOptions.NONE;
if (!includeDefaults && fieldType().stored() == Defaults.FIELD_TYPE.stored() && indexed == defaultIndexed) {
return builder;
}
builder.startObject(CONTENT_TYPE);
if (includeDefaults || fieldType().stored() != Defaults.FIELD_TYPE.stored()) {
builder.field("store", fieldType().stored());
}
if (includeDefaults || indexed != defaultIndexed) {
builder.field("index", indexTokenizeOptionToString(indexed, fieldType().tokenized()));
}
builder.endObject();
return builder;
}
@Override
public void merge(Mapper mergeWith, MergeResult mergeResult) throws MergeMappingException {
// do nothing here, no merging, but also no exception
}
}
| |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.connect.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/ListApprovedOrigins" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListApprovedOriginsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The approved origins.
* </p>
*/
private java.util.List<String> origins;
/**
* <p>
* If there are additional results, this is the token for the next set of results.
* </p>
*/
private String nextToken;
/**
* <p>
* The approved origins.
* </p>
*
* @return The approved origins.
*/
public java.util.List<String> getOrigins() {
return origins;
}
/**
* <p>
* The approved origins.
* </p>
*
* @param origins
* The approved origins.
*/
public void setOrigins(java.util.Collection<String> origins) {
if (origins == null) {
this.origins = null;
return;
}
this.origins = new java.util.ArrayList<String>(origins);
}
/**
* <p>
* The approved origins.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setOrigins(java.util.Collection)} or {@link #withOrigins(java.util.Collection)} if you want to override
* the existing values.
* </p>
*
* @param origins
* The approved origins.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListApprovedOriginsResult withOrigins(String... origins) {
if (this.origins == null) {
setOrigins(new java.util.ArrayList<String>(origins.length));
}
for (String ele : origins) {
this.origins.add(ele);
}
return this;
}
/**
* <p>
* The approved origins.
* </p>
*
* @param origins
* The approved origins.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListApprovedOriginsResult withOrigins(java.util.Collection<String> origins) {
setOrigins(origins);
return this;
}
/**
* <p>
* If there are additional results, this is the token for the next set of results.
* </p>
*
* @param nextToken
* If there are additional results, this is the token for the next set of results.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* If there are additional results, this is the token for the next set of results.
* </p>
*
* @return If there are additional results, this is the token for the next set of results.
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* If there are additional results, this is the token for the next set of results.
* </p>
*
* @param nextToken
* If there are additional results, this is the token for the next set of results.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListApprovedOriginsResult withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getOrigins() != null)
sb.append("Origins: ").append(getOrigins()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListApprovedOriginsResult == false)
return false;
ListApprovedOriginsResult other = (ListApprovedOriginsResult) obj;
if (other.getOrigins() == null ^ this.getOrigins() == null)
return false;
if (other.getOrigins() != null && other.getOrigins().equals(this.getOrigins()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getOrigins() == null) ? 0 : getOrigins().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
return hashCode;
}
@Override
public ListApprovedOriginsResult clone() {
try {
return (ListApprovedOriginsResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| |
package org.cobbzilla.util.mq.kestrel;
import org.cobbzilla.util.mq.MqClient;
import org.cobbzilla.util.mq.MqConsumer;
import org.cobbzilla.util.mq.MqProducer;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.command.KestrelCommandFactory;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.rubyeye.xmemcached.utils.AddrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* (c) Copyright 2013 Jonathan Cobb
* This code is available under the Apache License, version 2: http://www.apache.org/licenses/LICENSE-2.0.html
*/
public class KestrelClient implements MqClient {
public static final String KPARAM_OPEN = "/open";
public static final String KPARAM_CLOSE = "/close";
public static final String KPARAM_ABORT = "/abort";
private static final Logger LOG = LoggerFactory.getLogger(KestrelClient.class);
public static final String PROP_KESTREL_HOSTS = "kestrelHosts";
public static final String PROP_RECONNECT_INTERVAL_IN_MINUTES = "kestrelReconnectIntervalInMinutes";
public static final String PROP_KESTREL_CONNECTIONS = "kestrelConnectionPoolSize";
private Properties initProperties;
protected volatile MemcachedClient client;
private KestrelConsumerListener listener = null;
private volatile Thread listenerThread = null;
private long reconnectIntervalMillis = 5 * 60 * 1000; // 5 minutes
/** for debugging */
public void setReconnectIntervalMillis(long reconnectIntervalMillis) {
this.reconnectIntervalMillis = reconnectIntervalMillis;
}
private volatile long lastConnect;
@Override
public synchronized void init(Properties properties) throws IOException {
LOG.debug("init: KestrelClient initializing...");
this.initProperties = properties;
int connectionPoolSize = 1;
try {
connectionPoolSize = Integer.parseInt(properties.getProperty(PROP_KESTREL_CONNECTIONS));
} catch (Exception e) {
LOG.warn(PROP_KESTREL_CONNECTIONS+" undefined, using default of "+connectionPoolSize);
}
final List<InetSocketAddress> memcachedHosts = getMemcachedHosts(properties.getProperty(PROP_KESTREL_HOSTS));
final String hosts = properties.getProperty(PROP_KESTREL_HOSTS);
final MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(hosts));
builder.setCommandFactory(new KestrelCommandFactory());
builder.setConnectionPoolSize(connectionPoolSize);
client = builder.build();
client.setPrimitiveAsString(true);
final String reconnectIntervalString = properties.getProperty(PROP_RECONNECT_INTERVAL_IN_MINUTES);
if (reconnectIntervalString != null) {
reconnectIntervalMillis = 60 * 1000 * Long.parseLong(reconnectIntervalString);
}
lastConnect = System.currentTimeMillis();
LOG.info("init: KestrelClient fully initialized with hosts="+memcachedHosts+", reconnecting every "+(reconnectIntervalMillis/1000/60)+" minutes");
}
private List<InetSocketAddress> getMemcachedHosts(String value) {
List<InetSocketAddress> addresses = new ArrayList<>();
String[] hostPortPairs = value.split(" ");
for (String pair : hostPortPairs) {
final int colonPos = pair.indexOf(":");
final String host = pair.substring(0, colonPos);
final int port = Integer.parseInt(pair.substring(colonPos+1));
addresses.add(new InetSocketAddress(host, port));
}
return addresses;
}
@Override
public MqProducer getProducer(String queueName) {
return new KestrelProducer(this, queueName);
}
private static AtomicInteger threadCount = new AtomicInteger(0);
@Override
public synchronized void registerConsumer(MqConsumer callback, String queueName, String errorQueueName) {
if (listenerThread != null) {
throw new IllegalStateException("No more than one listener per client");
}
listener = new KestrelConsumerListener(this, callback, queueName, errorQueueName);
listenerThread = new Thread(listener);
listenerThread.setDaemon(true);
listenerThread.setName("kestrel-consumer-" + threadCount.getAndIncrement());
listenerThread.start();
}
@Override
public void flushAllQueues() throws InterruptedException, MemcachedException, TimeoutException {
client.flushAll();
}
@Override
public void deleteQueue(String queueName) throws InterruptedException, TimeoutException {
try {
client.delete(queueName);
} catch (MemcachedException e) {
// noop - bug in XMemcached considers "DELETED" response invalid, but it's actually correct.
}
}
@Override
public void shutdown() throws IOException {
// Fair warning...
LOG.debug("shutdown: telling listener threads to stop...");
if (listenerThread != null) {
listener.stop();
listenerThread.interrupt();
}
// finally, stop the client
LOG.debug("shutdown: trying to shutdown the memcache client");
shutdownMemcacheClient();
LOG.debug("shutdown: client successfully and fully shutdown");
}
private synchronized void shutdownMemcacheClient() throws IOException {
if (client != null) {
LOG.debug("shutdownMemcacheClient: trying to shutdown the memcache client");
client.shutdown();
LOG.debug("shutdownMemcacheClient: memcache client stopped");
} else {
LOG.warn("shutdownMemcacheClient: memcache client already stopped");
}
}
public synchronized Object get (String queue, String options, long timeout) throws InterruptedException, TimeoutException, MemcachedException {
checkReconnect();
return get_internal(queue, options, timeout);
}
private synchronized Object get_internal(String queue, String options, long timeout) throws TimeoutException, InterruptedException, MemcachedException {
return client.get(queue + options + "/t=" + timeout, timeout + 100);
}
public synchronized void set (String queueName, Object message) throws InterruptedException, TimeoutException, MemcachedException {
client.set(queueName, 0, message);
}
public synchronized void ack (String queueName, long timeout) {
internal_ack(queueName, KPARAM_CLOSE, timeout);
}
public synchronized void abort (String queueName, long timeout) {
internal_ack(queueName, KPARAM_ABORT, timeout);
}
private void internal_ack (String queueName, String ackType, long timeout) {
long now = System.currentTimeMillis();
int numTries = 0;
int maxTries = 10;
long backoff = 250;
while (numTries < maxTries) {
try {
get_internal(queueName, ackType, timeout);
LOG.debug("internal_ack(" + now + "," + ackType + ","+numTries+"): ack succeeded");
return;
} catch (Exception e) {
String message2 = "internal_ack("+now+","+ackType+","+numTries+"): Couldn't ack an existing open read on queue "+queueName+": "+e;
LOG.error(message2, e);
try {
Thread.sleep(backoff);
} catch (InterruptedException e1) {
final String msg = "Interrupted while trying to ack, bailing out";
LOG.warn(msg);
throw new IllegalStateException(msg, e1);
}
numTries++;
backoff *= 2;
}
}
}
private void checkReconnect() {
final long now = System.currentTimeMillis();
if (isTimeToReconnect(now)) {
lastConnect = now;
LOG.info("checkReconnect: time to reconnect, shutting down and reinitializing...");
try {
synchronized (this) {
shutdownMemcacheClient();
init(initProperties);
}
} catch (IOException e) {
throw new IllegalStateException("Error reconnecting: "+e);
}
}
}
private boolean isTimeToReconnect(long now) {
return now - lastConnect > reconnectIntervalMillis;
}
}
| |
/*
* Copyright 2006-2007 Jeremias Maerki.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.datamatrix.encoder;
import com.google.zxing.Dimension;
import java.util.Arrays;
/**
* DataMatrix ECC 200 data encoder following the algorithm described in ISO/IEC 16022:200(E) in
* annex S.
*/
public final class HighLevelEncoder {
/**
* mode latch to C40 encodation mode
*/
static final char LATCH_TO_C40 = 230;
/**
* mode latch to Base 256 encodation mode
*/
static final char LATCH_TO_BASE256 = 231;
/**
* Upper Shift
*/
static final char UPPER_SHIFT = 235;
/**
* FNC1 Codeword
*/
//private static final char FNC1 = 232;
/**
* Structured Append Codeword
*/
//private static final char STRUCTURED_APPEND = 233;
/**
* Reader Programming
*/
//private static final char READER_PROGRAMMING = 234;
/**
* mode latch to ANSI X.12 encodation mode
*/
static final char LATCH_TO_ANSIX12 = 238;
/**
* mode latch to Text encodation mode
*/
static final char LATCH_TO_TEXT = 239;
/**
* mode latch to EDIFACT encodation mode
*/
static final char LATCH_TO_EDIFACT = 240;
/**
* Unlatch from C40 encodation
*/
static final char C40_UNLATCH = 254;
/**
* Unlatch from X12 encodation
*/
static final char X12_UNLATCH = 254;
static final int ASCII_ENCODATION = 0;
/**
* ECI character (Extended Channel Interpretation)
*/
//private static final char ECI = 241;
static final int C40_ENCODATION = 1;
static final int TEXT_ENCODATION = 2;
static final int X12_ENCODATION = 3;
static final int EDIFACT_ENCODATION = 4;
static final int BASE256_ENCODATION = 5;
/**
* Padding character
*/
private static final char PAD = 129;
/**
* 05 Macro
*/
private static final char MACRO_05 = 236;
/**
* 06 Macro
*/
private static final char MACRO_06 = 237;
/**
* 05 Macro header
*/
private static final String MACRO_05_HEADER = "[)>\u001E05\u001D";
/**
* 06 Macro header
*/
private static final String MACRO_06_HEADER = "[)>\u001E06\u001D";
/**
* Macro trailer
*/
private static final String MACRO_TRAILER = "\u001E\u0004";
private HighLevelEncoder() {
}
/*
* Converts the message to a byte array using the default encoding (cp437) as defined by the
* specification
*
* @param msg the message
* @return the byte array of the message
*/
/*
public static byte[] getBytesForMessage(String msg) {
return msg.getBytes(Charset.forName("cp437")); //See 4.4.3 and annex B of ISO/IEC 15438:2001(E)
}
*/
private static char randomize253State(char ch, int codewordPosition) {
int pseudoRandom = ((149 * codewordPosition) % 253) + 1;
int tempVariable = ch + pseudoRandom;
return tempVariable <= 254 ? (char) tempVariable : (char) (tempVariable - 254);
}
/**
* Performs message encoding of a DataMatrix message using the algorithm described in annex P
* of ISO/IEC 16022:2000(E).
*
* @param msg the message
* @return the encoded message (the char values range from 0 to 255)
*/
public static String encodeHighLevel(String msg) {
return encodeHighLevel(msg, SymbolShapeHint.FORCE_NONE, null, null);
}
/**
* Performs message encoding of a DataMatrix message using the algorithm described in annex P
* of ISO/IEC 16022:2000(E).
*
* @param msg the message
* @param shape requested shape. May be {@code SymbolShapeHint.FORCE_NONE},
* {@code SymbolShapeHint.FORCE_SQUARE} or {@code SymbolShapeHint.FORCE_RECTANGLE}.
* @param minSize the minimum symbol size constraint or null for no constraint
* @param maxSize the maximum symbol size constraint or null for no constraint
* @return the encoded message (the char values range from 0 to 255)
*/
public static String encodeHighLevel(String msg,
SymbolShapeHint shape,
Dimension minSize,
Dimension maxSize) {
//the codewords 0..255 are encoded as Unicode characters
Encoder[] encoders = {
new ASCIIEncoder(), new C40Encoder(), new TextEncoder(),
new X12Encoder(), new EdifactEncoder(), new Base256Encoder()
};
EncoderContext context = new EncoderContext(msg);
context.setSymbolShape(shape);
context.setSizeConstraints(minSize, maxSize);
if (msg.startsWith(MACRO_05_HEADER) && msg.endsWith(MACRO_TRAILER)) {
context.writeCodeword(MACRO_05);
context.setSkipAtEnd(2);
context.pos += MACRO_05_HEADER.length();
} else if (msg.startsWith(MACRO_06_HEADER) && msg.endsWith(MACRO_TRAILER)) {
context.writeCodeword(MACRO_06);
context.setSkipAtEnd(2);
context.pos += MACRO_06_HEADER.length();
}
int encodingMode = ASCII_ENCODATION; //Default mode
while (context.hasMoreCharacters()) {
encoders[encodingMode].encode(context);
if (context.getNewEncoding() >= 0) {
encodingMode = context.getNewEncoding();
context.resetEncoderSignal();
}
}
int len = context.getCodewordCount();
context.updateSymbolInfo();
int capacity = context.getSymbolInfo().getDataCapacity();
if (len < capacity) {
if (encodingMode != ASCII_ENCODATION && encodingMode != BASE256_ENCODATION) {
context.writeCodeword('\u00fe'); //Unlatch (254)
}
}
//Padding
StringBuilder codewords = context.getCodewords();
if (codewords.length() < capacity) {
codewords.append(PAD);
}
while (codewords.length() < capacity) {
codewords.append(randomize253State(PAD, codewords.length() + 1));
}
return context.getCodewords().toString();
}
static int lookAheadTest(CharSequence msg, int startpos, int currentMode) {
if (startpos >= msg.length()) {
return currentMode;
}
float[] charCounts;
//step J
if (currentMode == ASCII_ENCODATION) {
charCounts = new float[]{0, 1, 1, 1, 1, 1.25f};
} else {
charCounts = new float[]{1, 2, 2, 2, 2, 2.25f};
charCounts[currentMode] = 0;
}
int charsProcessed = 0;
while (true) {
//step K
if ((startpos + charsProcessed) == msg.length()) {
int min = Integer.MAX_VALUE;
byte[] mins = new byte[6];
int[] intCharCounts = new int[6];
min = findMinimums(charCounts, intCharCounts, min, mins);
int minCount = getMinimumCount(mins);
if (intCharCounts[ASCII_ENCODATION] == min) {
return ASCII_ENCODATION;
}
if (minCount == 1 && mins[BASE256_ENCODATION] > 0) {
return BASE256_ENCODATION;
}
if (minCount == 1 && mins[EDIFACT_ENCODATION] > 0) {
return EDIFACT_ENCODATION;
}
if (minCount == 1 && mins[TEXT_ENCODATION] > 0) {
return TEXT_ENCODATION;
}
if (minCount == 1 && mins[X12_ENCODATION] > 0) {
return X12_ENCODATION;
}
return C40_ENCODATION;
}
char c = msg.charAt(startpos + charsProcessed);
charsProcessed++;
//step L
if (isDigit(c)) {
charCounts[ASCII_ENCODATION] += 0.5;
} else if (isExtendedASCII(c)) {
charCounts[ASCII_ENCODATION] = (int) Math.ceil(charCounts[ASCII_ENCODATION]);
charCounts[ASCII_ENCODATION] += 2;
} else {
charCounts[ASCII_ENCODATION] = (int) Math.ceil(charCounts[ASCII_ENCODATION]);
charCounts[ASCII_ENCODATION]++;
}
//step M
if (isNativeC40(c)) {
charCounts[C40_ENCODATION] += 2.0f / 3.0f;
} else if (isExtendedASCII(c)) {
charCounts[C40_ENCODATION] += 8.0f / 3.0f;
} else {
charCounts[C40_ENCODATION] += 4.0f / 3.0f;
}
//step N
if (isNativeText(c)) {
charCounts[TEXT_ENCODATION] += 2.0f / 3.0f;
} else if (isExtendedASCII(c)) {
charCounts[TEXT_ENCODATION] += 8.0f / 3.0f;
} else {
charCounts[TEXT_ENCODATION] += 4.0f / 3.0f;
}
//step O
if (isNativeX12(c)) {
charCounts[X12_ENCODATION] += 2.0f / 3.0f;
} else if (isExtendedASCII(c)) {
charCounts[X12_ENCODATION] += 13.0f / 3.0f;
} else {
charCounts[X12_ENCODATION] += 10.0f / 3.0f;
}
//step P
if (isNativeEDIFACT(c)) {
charCounts[EDIFACT_ENCODATION] += 3.0f / 4.0f;
} else if (isExtendedASCII(c)) {
charCounts[EDIFACT_ENCODATION] += 17.0f / 4.0f;
} else {
charCounts[EDIFACT_ENCODATION] += 13.0f / 4.0f;
}
// step Q
if (isSpecialB256(c)) {
charCounts[BASE256_ENCODATION] += 4;
} else {
charCounts[BASE256_ENCODATION]++;
}
//step R
if (charsProcessed >= 4) {
int[] intCharCounts = new int[6];
byte[] mins = new byte[6];
findMinimums(charCounts, intCharCounts, Integer.MAX_VALUE, mins);
int minCount = getMinimumCount(mins);
if (intCharCounts[ASCII_ENCODATION] < intCharCounts[BASE256_ENCODATION]
&& intCharCounts[ASCII_ENCODATION] < intCharCounts[C40_ENCODATION]
&& intCharCounts[ASCII_ENCODATION] < intCharCounts[TEXT_ENCODATION]
&& intCharCounts[ASCII_ENCODATION] < intCharCounts[X12_ENCODATION]
&& intCharCounts[ASCII_ENCODATION] < intCharCounts[EDIFACT_ENCODATION]) {
return ASCII_ENCODATION;
}
if (intCharCounts[BASE256_ENCODATION] < intCharCounts[ASCII_ENCODATION]
|| (mins[C40_ENCODATION] + mins[TEXT_ENCODATION] + mins[X12_ENCODATION] + mins[EDIFACT_ENCODATION]) == 0) {
return BASE256_ENCODATION;
}
if (minCount == 1 && mins[EDIFACT_ENCODATION] > 0) {
return EDIFACT_ENCODATION;
}
if (minCount == 1 && mins[TEXT_ENCODATION] > 0) {
return TEXT_ENCODATION;
}
if (minCount == 1 && mins[X12_ENCODATION] > 0) {
return X12_ENCODATION;
}
if (intCharCounts[C40_ENCODATION] + 1 < intCharCounts[ASCII_ENCODATION]
&& intCharCounts[C40_ENCODATION] + 1 < intCharCounts[BASE256_ENCODATION]
&& intCharCounts[C40_ENCODATION] + 1 < intCharCounts[EDIFACT_ENCODATION]
&& intCharCounts[C40_ENCODATION] + 1 < intCharCounts[TEXT_ENCODATION]) {
if (intCharCounts[C40_ENCODATION] < intCharCounts[X12_ENCODATION]) {
return C40_ENCODATION;
}
if (intCharCounts[C40_ENCODATION] == intCharCounts[X12_ENCODATION]) {
int p = startpos + charsProcessed + 1;
while (p < msg.length()) {
char tc = msg.charAt(p);
if (isX12TermSep(tc)) {
return X12_ENCODATION;
}
if (!isNativeX12(tc)) {
break;
}
p++;
}
return C40_ENCODATION;
}
}
}
}
}
private static int findMinimums(float[] charCounts, int[] intCharCounts, int min, byte[] mins) {
Arrays.fill(mins, (byte) 0);
for (int i = 0; i < 6; i++) {
intCharCounts[i] = (int) Math.ceil(charCounts[i]);
int current = intCharCounts[i];
if (min > current) {
min = current;
Arrays.fill(mins, (byte) 0);
}
if (min == current) {
mins[i]++;
}
}
return min;
}
private static int getMinimumCount(byte[] mins) {
int minCount = 0;
for (int i = 0; i < 6; i++) {
minCount += mins[i];
}
return minCount;
}
static boolean isDigit(char ch) {
return ch >= '0' && ch <= '9';
}
static boolean isExtendedASCII(char ch) {
return ch >= 128 && ch <= 255;
}
private static boolean isNativeC40(char ch) {
return (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z');
}
private static boolean isNativeText(char ch) {
return (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z');
}
private static boolean isNativeX12(char ch) {
return isX12TermSep(ch) || (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z');
}
private static boolean isX12TermSep(char ch) {
return (ch == '\r') //CR
|| (ch == '*')
|| (ch == '>');
}
private static boolean isNativeEDIFACT(char ch) {
return ch >= ' ' && ch <= '^';
}
private static boolean isSpecialB256(char ch) {
return false; //TODO NOT IMPLEMENTED YET!!!
}
/**
* Determines the number of consecutive characters that are encodable using numeric compaction.
*
* @param msg the message
* @param startpos the start position within the message
* @return the requested character count
*/
public static int determineConsecutiveDigitCount(CharSequence msg, int startpos) {
int count = 0;
int len = msg.length();
int idx = startpos;
if (idx < len) {
char ch = msg.charAt(idx);
while (isDigit(ch) && idx < len) {
count++;
idx++;
if (idx < len) {
ch = msg.charAt(idx);
}
}
}
return count;
}
static void illegalCharacter(char c) {
String hex = Integer.toHexString(c);
hex = "0000".substring(0, 4 - hex.length()) + hex;
throw new IllegalArgumentException("Illegal character: " + c + " (0x" + hex + ')');
}
}
| |
package org.apache.cassandra.io.sstable;
/*
*
* 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.
*
*/
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.junit.Test;
import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.Util;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.RowMutation;
import org.apache.cassandra.db.Keyspace;
import org.apache.cassandra.db.marshal.BytesType;
import org.apache.cassandra.db.marshal.CompositeType;
import org.apache.cassandra.db.marshal.IntegerType;
import org.apache.cassandra.utils.ByteBufferUtil;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class SSTableMetadataTest extends SchemaLoader
{
@Test
public void testTrackMaxDeletionTime() throws ExecutionException, InterruptedException
{
Keyspace keyspace = Keyspace.open("Keyspace1");
ColumnFamilyStore store = keyspace.getColumnFamilyStore("Standard1");
long timestamp = System.currentTimeMillis();
for(int i = 0; i < 10; i++)
{
DecoratedKey key = Util.dk(Integer.toString(i));
RowMutation rm = new RowMutation("Keyspace1", key.key);
for (int j = 0; j < 10; j++)
rm.add("Standard1", ByteBufferUtil.bytes(Integer.toString(j)),
ByteBufferUtil.EMPTY_BYTE_BUFFER,
timestamp,
10 + j);
rm.apply();
}
RowMutation rm = new RowMutation("Keyspace1", Util.dk("longttl").key);
rm.add("Standard1", ByteBufferUtil.bytes("col"),
ByteBufferUtil.EMPTY_BYTE_BUFFER,
timestamp,
10000);
rm.apply();
store.forceBlockingFlush();
assertEquals(1, store.getSSTables().size());
int ttltimestamp = (int)(System.currentTimeMillis()/1000);
int firstDelTime = 0;
for(SSTableReader sstable : store.getSSTables())
{
firstDelTime = sstable.getSSTableMetadata().maxLocalDeletionTime;
assertEquals(ttltimestamp + 10000, firstDelTime, 10);
}
rm = new RowMutation("Keyspace1", Util.dk("longttl2").key);
rm.add("Standard1", ByteBufferUtil.bytes("col"),
ByteBufferUtil.EMPTY_BYTE_BUFFER,
timestamp,
20000);
rm.apply();
ttltimestamp = (int) (System.currentTimeMillis()/1000);
store.forceBlockingFlush();
assertEquals(2, store.getSSTables().size());
List<SSTableReader> sstables = new ArrayList<SSTableReader>(store.getSSTables());
if(sstables.get(0).getSSTableMetadata().maxLocalDeletionTime < sstables.get(1).getSSTableMetadata().maxLocalDeletionTime)
{
assertEquals(sstables.get(0).getSSTableMetadata().maxLocalDeletionTime, firstDelTime);
assertEquals(sstables.get(1).getSSTableMetadata().maxLocalDeletionTime, ttltimestamp + 20000, 10);
}
else
{
assertEquals(sstables.get(1).getSSTableMetadata().maxLocalDeletionTime, firstDelTime);
assertEquals(sstables.get(0).getSSTableMetadata().maxLocalDeletionTime, ttltimestamp + 20000, 10);
}
Util.compact(store, store.getSSTables());
assertEquals(1, store.getSSTables().size());
for(SSTableReader sstable : store.getSSTables())
{
assertEquals(sstable.getSSTableMetadata().maxLocalDeletionTime, ttltimestamp + 20000, 10);
}
}
/**
* 1. create a row with columns with ttls, 5x100 and 1x1000
* 2. flush, verify (maxLocalDeletionTime = time+1000)
* 3. delete column with ttl=1000
* 4. flush, verify the new sstable (maxLocalDeletionTime = ~now)
* 5. compact
* 6. verify resulting sstable has maxLocalDeletionTime = time + 100.
*
* @throws ExecutionException
* @throws InterruptedException
*/
@Test
public void testWithDeletes() throws ExecutionException, InterruptedException
{
Keyspace keyspace = Keyspace.open("Keyspace1");
ColumnFamilyStore store = keyspace.getColumnFamilyStore("Standard2");
long timestamp = System.currentTimeMillis();
DecoratedKey key = Util.dk("deletetest");
RowMutation rm = new RowMutation("Keyspace1", key.key);
for (int i = 0; i<5; i++)
rm.add("Standard2", ByteBufferUtil.bytes("deletecolumn"+i),
ByteBufferUtil.EMPTY_BYTE_BUFFER,
timestamp,
100);
rm.add("Standard2", ByteBufferUtil.bytes("todelete"),
ByteBufferUtil.EMPTY_BYTE_BUFFER,
timestamp,
1000);
rm.apply();
store.forceBlockingFlush();
assertEquals(1,store.getSSTables().size());
int ttltimestamp = (int) (System.currentTimeMillis()/1000);
int firstMaxDelTime = 0;
for(SSTableReader sstable : store.getSSTables())
{
firstMaxDelTime = sstable.getSSTableMetadata().maxLocalDeletionTime;
assertEquals(ttltimestamp + 1000, firstMaxDelTime, 10);
}
rm = new RowMutation("Keyspace1", key.key);
rm.delete("Standard2", ByteBufferUtil.bytes("todelete"), timestamp + 1);
rm.apply();
store.forceBlockingFlush();
assertEquals(2,store.getSSTables().size());
boolean foundDelete = false;
for(SSTableReader sstable : store.getSSTables())
{
if(sstable.getSSTableMetadata().maxLocalDeletionTime != firstMaxDelTime)
{
assertEquals(sstable.getSSTableMetadata().maxLocalDeletionTime, ttltimestamp, 10);
foundDelete = true;
}
}
assertTrue(foundDelete);
Util.compact(store, store.getSSTables());
assertEquals(1,store.getSSTables().size());
for(SSTableReader sstable : store.getSSTables())
{
assertEquals(ttltimestamp + 100, sstable.getSSTableMetadata().maxLocalDeletionTime, 10);
}
}
@Test
public void trackMaxMinColNames() throws CharacterCodingException, ExecutionException, InterruptedException
{
Keyspace keyspace = Keyspace.open("Keyspace1");
ColumnFamilyStore store = keyspace.getColumnFamilyStore("Standard3");
store.getCompactionStrategy();
for (int j = 0; j < 8; j++)
{
DecoratedKey key = Util.dk("row"+j);
RowMutation rm = new RowMutation("Keyspace1", key.key);
for (int i = 100; i<150; i++)
{
rm.add("Standard3", ByteBufferUtil.bytes(j+"col"+i),
ByteBufferUtil.EMPTY_BYTE_BUFFER,
System.currentTimeMillis());
}
rm.apply();
}
store.forceBlockingFlush();
assertEquals(1, store.getSSTables().size());
for (SSTableReader sstable : store.getSSTables())
{
assertEquals(ByteBufferUtil.string(sstable.getSSTableMetadata().minColumnNames.get(0)), "0col100");
assertEquals(ByteBufferUtil.string(sstable.getSSTableMetadata().maxColumnNames.get(0)), "7col149");
}
DecoratedKey key = Util.dk("row2");
RowMutation rm = new RowMutation("Keyspace1", key.key);
for (int i = 101; i<299; i++)
{
rm.add("Standard3", ByteBufferUtil.bytes(9+"col"+i),
ByteBufferUtil.EMPTY_BYTE_BUFFER,
System.currentTimeMillis());
}
rm.apply();
store.forceBlockingFlush();
store.forceMajorCompaction();
assertEquals(1, store.getSSTables().size());
for (SSTableReader sstable : store.getSSTables())
{
assertEquals(ByteBufferUtil.string(sstable.getSSTableMetadata().minColumnNames.get(0)), "0col100");
assertEquals(ByteBufferUtil.string(sstable.getSSTableMetadata().maxColumnNames.get(0)), "9col298");
}
}
@Test
public void testMaxMinComposites() throws CharacterCodingException, ExecutionException, InterruptedException
{
/*
creates two sstables, columns like this:
---------------------
k |a0:9|a1:8|..|a9:0
---------------------
and
---------------------
k2 |b0:9|b1:8|..|b9:0
---------------------
meaning max columns are b9 and 9, min is a0 and 0
*/
Keyspace keyspace = Keyspace.open("Keyspace1");
ColumnFamilyStore cfs = keyspace.getColumnFamilyStore("StandardComposite2");
CompositeType ct = CompositeType.getInstance(BytesType.instance, IntegerType.instance);
ByteBuffer key = ByteBufferUtil.bytes("k");
for (int i = 0; i < 10; i++)
{
RowMutation rm = new RowMutation("Keyspace1", key);
ByteBuffer colName = ct.builder().add(ByteBufferUtil.bytes("a"+(9-i))).add(ByteBufferUtil.bytes(i)).build();
rm.add("StandardComposite2", colName, ByteBufferUtil.EMPTY_BYTE_BUFFER, 0);
rm.apply();
}
cfs.forceBlockingFlush();
key = ByteBufferUtil.bytes("k2");
for (int i = 0; i < 10; i++)
{
RowMutation rm = new RowMutation("Keyspace1", key);
ByteBuffer colName = ct.builder().add(ByteBufferUtil.bytes("b"+(9-i))).add(ByteBufferUtil.bytes(i)).build();
rm.add("StandardComposite2", colName, ByteBufferUtil.EMPTY_BYTE_BUFFER, 0);
rm.apply();
}
cfs.forceBlockingFlush();
cfs.forceMajorCompaction();
assertEquals(cfs.getSSTables().size(), 1);
for (SSTableReader sstable : cfs.getSSTables())
{
assertEquals("b9", ByteBufferUtil.string(sstable.getSSTableMetadata().maxColumnNames.get(0)));
assertEquals(9, ByteBufferUtil.toInt(sstable.getSSTableMetadata().maxColumnNames.get(1)));
assertEquals("a0", ByteBufferUtil.string(sstable.getSSTableMetadata().minColumnNames.get(0)));
assertEquals(0, ByteBufferUtil.toInt(sstable.getSSTableMetadata().minColumnNames.get(1)));
}
}
}
| |
//
// Triple Play - utilities for use in PlayN-based games
// Copyright (c) 2011-2014, Three Rings Design, Inc. - All rights reserved.
// http://github.com/threerings/tripleplay/blob/master/LICENSE
package tripleplay.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import playn.core.Graphics;
import playn.core.QuadBatch;
import playn.core.Surface;
import playn.core.TextureSurface;
import playn.core.Tile;
import react.Slot;
/**
* A runtime texture packer.
*/
public class TexturePacker
{
public interface Renderer {
void render (Surface surface, float x, float y, float width, float height);
}
/** Add an image to the packer. */
public TexturePacker add (String id, Tile tile) {
return addItem(new TileItem(id, tile));
}
/** Add a lazily rendered region to the packer.
* The renderer will be used to draw the region each time pack() is called. */
public TexturePacker add (String id, float width, float height, Renderer renderer) {
return addItem(new RenderedItem(id, width, height, renderer));
}
/**
* Pack all images into as few atlases as possible.
* @return A map containing the new images, keyed by the id they were added with.
*/
public Map<String,Tile> pack (Graphics gfx, QuadBatch batch) {
List<Item> unpacked = new ArrayList<Item>(_items.values());
// TODO(bruno): Experiment with different heuristics. Brute force calculate using multiple
// different heuristics and use the best one?
Collections.sort(unpacked, new Comparator<Item>() {
public int compare (Item o1, Item o2) {
// Sort by perimeter (instead of area). It can be harder to fit long skinny
// textures after the large square ones
return (int)(o2.width+o2.height) - (int)(o1.width+o1.height);
}
});
List<Atlas> atlases = new ArrayList<Atlas>();
while (!unpacked.isEmpty()) {
atlases.add(createAtlas());
// Try to pack each item into any atlas
for (Iterator<Item> it = unpacked.iterator(); it.hasNext(); ) {
Item item = it.next();
for (Atlas atlas : atlases) {
if (atlas.place(item)) {
it.remove();
}
}
}
}
final Map<String,Tile> packed = new HashMap<String,Tile>();
for (Atlas atlas : atlases) {
Node root = atlas.root;
final TextureSurface atlasTex = new TextureSurface(gfx, batch, root.width, root.height);
atlasTex.begin();
root.visitItems(new Slot<Node>() { @Override public void onEmit (Node n) {
// Draw the item to the atlas
n.item.draw(atlasTex, n.x, n.y);
// Record its region
packed.put(n.item.id, atlasTex.texture.tile(n.x, n.y, n.width, n.height));
}});
atlasTex.end();
}
return packed;
}
protected Atlas createAtlas () {
// TODO(bruno): Be smarter about sizing
return new Atlas(MAX_SIZE, MAX_SIZE);
}
protected TexturePacker addItem (Item item) {
if (item.width+PADDING > MAX_SIZE || item.height+PADDING > MAX_SIZE) {
throw new RuntimeException("Item is too big to pack " + item);
}
_items.put(item.id, item);
return this;
}
protected static abstract class Item {
public final String id;
public final float width, height;
public Item (String id, float width, float height) {
this.id = id;
this.width = width;
this.height = height;
}
public abstract void draw (Surface surface, float x, float y);
@Override public String toString () {
return "[id=" + id + ", size=" + width + "x" + height + "]";
}
}
protected static class TileItem extends Item {
public final Tile tile;
public TileItem (String id, Tile tile) {
super(id, tile.width(), tile.height());
this.tile = tile;
}
@Override public void draw (Surface surface, float x, float y) {
surface.draw(tile, x, y);
}
}
protected static class RenderedItem extends Item {
public final Renderer renderer;
public RenderedItem (String id, float width, float height, Renderer renderer) {
super(id, width, height);
this.renderer = renderer;
}
@Override public void draw (Surface surface, float x, float y) {
renderer.render(surface, x, y, width, height);
}
}
protected static class Atlas {
public final Node root;
public Atlas (int width, int height) {
root = new Node(0, 0, width, height);
}
public boolean place (Item item) {
Node node = root.search(item.width + PADDING, item.height + PADDING);
if (node == null) return false;
node.item = item;
return true;
}
}
protected static class Node {
/** The bounds of this node (and its children). */
public final float x, y, width, height;
/** This node's two children, if any. */
public Node left, right;
/** The texture that is placed here, if any. Implies that this is a leaf node. */
public Item item;
public Node (float x, float y, float width, float height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/** Find a free node in this tree big enough to fit an area, or null. */
public Node search (float w, float h) {
// There's already an item here, terminate
if (item != null) return null;
// That'll never fit, terminate
if (width < w || height < h) return null;
if (left != null) {
Node descendent = left.search(w, h);
if (descendent == null) descendent = right.search(w, h);
return descendent;
} else {
// This node is a perfect size, no need to subdivide
if (width == w && height == h) return this;
// Split into two children
float dw = width-w, dh = height-h;
if (dw > dh) {
left = new Node(x, y, w, height);
right = new Node(x + w, y, dw, height);
} else {
left = new Node(x, y, width, h);
right = new Node(x, y + h, width, dh);
}
return left.search(w, h);
}
}
/** Iterate over all nodes with items in this tree. */
public void visitItems (Slot<Node> slot) {
if (item != null) slot.onEmit(this);
if (left != null) {
left.visitItems(slot);
right.visitItems(slot);
}
}
}
protected static final int PADDING = 1;
protected static final int MAX_SIZE = 2048;
protected Map<String,Item> _items = new HashMap<String,Item>();
}
| |
package com.huawei.esdk.ivs.professional.local.impl.service;
import java.util.List;
import javax.xml.ws.Holder;
import org.apache.log4j.Logger;
import com.huawei.esdk.ivs.professional.local.bean.IVSSDKResponse;
import com.huawei.esdk.ivs.professional.local.bean.IndexRange;
import com.huawei.esdk.ivs.professional.local.bean.QueryUnifiedFormat;
import com.huawei.esdk.ivs.professional.local.bean.RoleInfos;
import com.huawei.esdk.ivs.professional.local.bean.UserGroupInfos;
import com.huawei.esdk.ivs.professional.local.bean.UserInfo;
import com.huawei.esdk.ivs.professional.local.bean.UserInfos;
import com.huawei.esdk.ivs.professional.local.constant.NativeConstant;
import com.huawei.esdk.ivs.professional.local.impl.autogen.IVSProfessionalUserManager;
import com.huawei.esdk.ivs.professional.local.impl.utils.AES128Utils;
import com.huawei.esdk.ivs.professional.local.impl.utils.Base64Utils;
import com.huawei.esdk.ivs.professional.local.impl.utils.ClientProvider;
import com.huawei.esdk.ivs.professional.local.impl.utils.ExceptionUtils;
import com.huawei.esdk.ivs.professional.local.impl.utils.StringUtils;
import com.huawei.esdk.ivs.professional.local.service.usermanager.UserManagerServiceEx;
import com.huawei.esdk.platform.professional.local.constant.PlatformNativeConstant;
public class UserManagerServiceExImpl implements UserManagerServiceEx
{
private static final Logger LOGGER = Logger
.getLogger(UserManagerServiceExImpl.class);
private IVSProfessionalUserManager ivsProfessionalUserManager =
(IVSProfessionalUserManager)ClientProvider.getClient(IVSProfessionalUserManager.class);
private static UserManagerServiceExImpl instance = null;
public static synchronized UserManagerServiceExImpl getInstance()
{
if (null == instance)
{
instance = new UserManagerServiceExImpl();
}
return instance;
}
public IVSSDKResponse<Integer> addUser(UserInfo userInfo)
{
LOGGER.info("begin to execute addUser method");
IVSSDKResponse<Integer> result = new IVSSDKResponse<Integer>();
Holder<Integer> resultCode = new Holder<Integer>();
Holder<Integer> userId = new Holder<Integer>();
if(null == userInfo)
{
result.setResultCode(NativeConstant.SDK_PARAM_NOT_COMPLETE_ERRORCODE);
return result;
}
if(!StringUtils.isNullOrEmpty(userInfo.getPassword()))
{
String encodePwd = null;
try
{
encodePwd = Base64Utils.encode(AES128Utils.encode(userInfo.getPassword().getBytes("UTF-8")));
if (StringUtils.isNullOrEmpty(encodePwd))
{
result.setResultCode(PlatformNativeConstant.SDK_TP_PASSWORD_ENCODE_ERRORCODE);
return result;
}
}
catch (Exception e)
{
LOGGER.debug("encode password error");
result.setResultCode(PlatformNativeConstant.SDK_TP_PASSWORD_ENCODE_ERRORCODE);
return result;
}
userInfo.setPassword(encodePwd);
}
else
{
result.setResultCode(NativeConstant.PWD_ERRORCODE);
return result;
}
try
{
ivsProfessionalUserManager.addUser(userInfo, resultCode, userId);
}
catch (Exception e)
{
LOGGER.error("addUser method exception happened", e);
result.setResultCode(ExceptionUtils.processSoapException(e));
return result;
}
result.setResult(userId.value);
result.setResultCode(resultCode.value);
LOGGER.info("execute addUser method completed");
return result;
}
public IVSSDKResponse<Integer> getUserId()
{
LOGGER.info("begin to execute getUserId method");
IVSSDKResponse<Integer> result = new IVSSDKResponse<Integer>();
Holder<Integer> resultCode = new Holder<Integer>();
Holder<Integer> userId = new Holder<Integer>();
try
{
ivsProfessionalUserManager.getUserId(resultCode, userId);
}
catch (Exception e)
{
LOGGER.error("getUserId method exception happened", e);
result.setResultCode(ExceptionUtils.processSoapException(e));
return result;
}
result.setResult(userId.value);
result.setResultCode(resultCode.value);
LOGGER.info("execute getUserId method completed");
return result;
}
@Override
public IVSSDKResponse<UserInfo> getUserInfo(String domainCode, Integer userId)
{
LOGGER.info("begin to execute getUserInfo method");
IVSSDKResponse<UserInfo> result = new IVSSDKResponse<UserInfo>();
Holder<Integer> resultCode = new Holder<Integer>();
Holder<UserInfo> userInfo = new Holder<UserInfo>();
try
{
ivsProfessionalUserManager.getUserInfo(domainCode, userId, resultCode, userInfo);
}
catch (Exception e)
{
LOGGER.error("getUserInfo method exception happened", e);
result.setResultCode(ExceptionUtils.processSoapException(e));
return result;
}
UserInfo user = userInfo.value;
if (null != user && !StringUtils.isNullOrEmpty(user.getPassword()))
{
user.setPassword(AES128Utils.decodeFromBase64(user.getPassword()));
}
result.setResult(user);
result.setResultCode(resultCode.value);
LOGGER.info("execute getUserInfo method completed");
return result;
}
@Override
public IVSSDKResponse<UserInfos> getUserList(String domainCode, QueryUnifiedFormat unifiedQuery)
{
LOGGER.info("begin to execute getUserList method");
IVSSDKResponse<UserInfos> result = new IVSSDKResponse<UserInfos>();
Holder<Integer> resultCode = new Holder<Integer>();
Holder<UserInfos> userInfoList = new Holder<UserInfos>();
try
{
ivsProfessionalUserManager.getUserList(domainCode, unifiedQuery, resultCode, userInfoList);
}
catch (Exception e)
{
LOGGER.error("getUserList method exception happened", e);
result.setResultCode(ExceptionUtils.processSoapException(e));
return result;
}
UserInfos users = userInfoList.value;
if (null != users && null != users.getUserInfoList())
{
List<UserInfo> userInfos = users.getUserInfoList().getUserInfo();
if (null != userInfos && !userInfos.isEmpty())
{
for (UserInfo userInfo : userInfos)
{
if (!StringUtils.isNullOrEmpty(userInfo.getPassword()))
{
userInfo.setPassword(AES128Utils.decodeFromBase64(userInfo.getPassword()));
}
}
}
}
result.setResult(users);
result.setResultCode(resultCode.value);
LOGGER.info("execute getUserList method completed");
return result;
}
@Override
public Integer deleteUser(String domainCode, Integer userId)
{
LOGGER.info("begin to execute deleteUser method");
try
{
Integer errorCode = ivsProfessionalUserManager.deleteUser(domainCode, userId);
LOGGER.info("execute deleteUser method completed");
return errorCode;
}
catch (Exception e)
{
LOGGER.error("deleteUser method exception happened", e);
return ExceptionUtils.processSoapException(e);
}
}
@Override
public Integer modifyUser(UserInfo userInfo)
{
LOGGER.info("begin to execute modifyUser method");
if(null == userInfo)
{
return NativeConstant.SDK_PARAM_NOT_COMPLETE_ERRORCODE;
}
if(!StringUtils.isNullOrEmpty(userInfo.getPassword()))
{
String encodePwd = null;
try
{
encodePwd = Base64Utils.encode(AES128Utils.encode(userInfo.getPassword().getBytes("UTF-8")));
if (StringUtils.isNullOrEmpty(encodePwd))
{
return PlatformNativeConstant.SDK_TP_PASSWORD_ENCODE_ERRORCODE;
}
}
catch (Exception e)
{
LOGGER.debug("encode password error");
return PlatformNativeConstant.SDK_TP_PASSWORD_ENCODE_ERRORCODE;
}
userInfo.setPassword(encodePwd);
}
try
{
Integer errorCode = ivsProfessionalUserManager.modifyUser(userInfo);
LOGGER.info("execute modifyUser method completed");
return errorCode;
}
catch (Exception e)
{
LOGGER.error("modifyUser method exception happened", e);
return ExceptionUtils.processSoapException(e);
}
}
@Override
public Integer changePassword(String oldPwd, String newPwd)
{
LOGGER.info("begin to execute changePassword method");
String encodeNewPwd = null;
String encodeOldPwd = null;
if(!StringUtils.isNullOrEmpty(oldPwd) && !StringUtils.isNullOrEmpty(newPwd))
{
try
{
encodeNewPwd = Base64Utils.encode(AES128Utils.encode(newPwd.getBytes("UTF-8")));
if (StringUtils.isNullOrEmpty(encodeNewPwd))
{
return PlatformNativeConstant.SDK_TP_PASSWORD_ENCODE_ERRORCODE;
}
}
catch (Exception e)
{
LOGGER.debug("encode password error");
return PlatformNativeConstant.SDK_TP_PASSWORD_ENCODE_ERRORCODE;
}
try
{
encodeOldPwd = Base64Utils.encode(AES128Utils.encode(oldPwd.getBytes("UTF-8")));
if (StringUtils.isNullOrEmpty(encodeOldPwd))
{
return PlatformNativeConstant.SDK_TP_PASSWORD_ENCODE_ERRORCODE;
}
}
catch (Exception e)
{
LOGGER.debug("encode password error");
return PlatformNativeConstant.SDK_TP_PASSWORD_ENCODE_ERRORCODE;
}
}
else
{
return NativeConstant.SDK_PARAM_NOT_COMPLETE_ERRORCODE;
}
try
{
Integer errorCode = ivsProfessionalUserManager.changePassword(encodeOldPwd, encodeNewPwd);
LOGGER.info("execute changePassword method completed");
return errorCode;
}
catch (Exception e)
{
LOGGER.error("changePassword method exception happened", e);
return ExceptionUtils.processSoapException(e);
}
}
@Override
public IVSSDKResponse<UserGroupInfos> getUserGroupList(String domainCode, IndexRange indexRange)
{
LOGGER.info("begin to execute getUserGroupList method");
IVSSDKResponse<UserGroupInfos> result = new IVSSDKResponse<UserGroupInfos>();
Holder<Integer> resultCode = new Holder<Integer>();
Holder<UserGroupInfos> userGroupInfos = new Holder<UserGroupInfos>();
try
{
ivsProfessionalUserManager.getUserGroupList(domainCode, indexRange, resultCode, userGroupInfos);
}
catch (Exception e)
{
LOGGER.error("getUserGroupList method exception happened", e);
result.setResultCode(ExceptionUtils.processSoapException(e));
return result;
}
result.setResult(userGroupInfos.value);
result.setResultCode(resultCode.value);
LOGGER.info("execute getUserGroupList method completed");
return result;
}
@Override
public IVSSDKResponse<RoleInfos> getRoleList(String domainCode)
{
LOGGER.info("begin to execute getRoleList method");
IVSSDKResponse<RoleInfos> result = new IVSSDKResponse<RoleInfos>();
Holder<Integer> resultCode = new Holder<Integer>();
Holder<RoleInfos> roleInfos = new Holder<RoleInfos>();
try
{
ivsProfessionalUserManager.getRoleList(domainCode, resultCode, roleInfos);
}
catch (Exception e)
{
LOGGER.error("getRoleList method exception happened", e);
result.setResultCode(ExceptionUtils.processSoapException(e));
return result;
}
result.setResult(roleInfos.value);
result.setResultCode(resultCode.value);
LOGGER.info("execute getRoleList method completed");
return result;
}
}
| |
/*
* Copyright 2015-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.d;
import com.facebook.buck.cxx.CxxLink;
import com.facebook.buck.cxx.CxxLinkOptions;
import com.facebook.buck.cxx.CxxLinkableEnhancer;
import com.facebook.buck.cxx.toolchain.CxxBuckConfig;
import com.facebook.buck.cxx.toolchain.CxxPlatform;
import com.facebook.buck.cxx.toolchain.linker.Linker;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkable;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkableInput;
import com.facebook.buck.graph.AbstractBreadthFirstTraversal;
import com.facebook.buck.io.file.MorePaths;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.model.Flavor;
import com.facebook.buck.model.InternalFlavor;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.BuildableSupport;
import com.facebook.buck.rules.CellPathResolver;
import com.facebook.buck.rules.DefaultSourcePathResolver;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.SymlinkTree;
import com.facebook.buck.rules.Tool;
import com.facebook.buck.rules.args.SourcePathArg;
import com.facebook.buck.rules.args.StringArg;
import com.facebook.buck.rules.coercer.SourceList;
import com.facebook.buck.util.MoreMaps;
import com.google.common.base.Preconditions;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
/** Utility functions for use in D Descriptions. */
abstract class DDescriptionUtils {
public static final Flavor SOURCE_LINK_TREE = InternalFlavor.of("source-link-tree");
/**
* Creates a BuildTarget, based on an existing build target, but flavored with a CxxPlatform and
* an additional flavor created by combining a prefix and an output file name.
*
* @param existingTarget the existing target
* @param flavorPrefix prefix to be used for added flavor
* @param fileName filename to be used for added flavor
* @param cxxPlatform the C++ platform to compile for
* @return the new BuildTarget
*/
public static BuildTarget createBuildTargetForFile(
BuildTarget existingTarget, String flavorPrefix, String fileName, CxxPlatform cxxPlatform) {
return existingTarget.withAppendedFlavors(
cxxPlatform.getFlavor(),
InternalFlavor.of(flavorPrefix + Flavor.replaceInvalidCharacters(fileName)));
}
/**
* Creates a new BuildTarget, based on an existing target, for a file to be compiled.
*
* @param existingTarget the existing target
* @param src the source file to be compiled
* @param cxxPlatform the C++ platform to compile the file for
* @return a BuildTarget to compile a D source file to an object file
*/
public static BuildTarget createDCompileBuildTarget(
BuildTarget existingTarget, String src, CxxPlatform cxxPlatform) {
return createBuildTargetForFile(
existingTarget, "compile-", DCompileStep.getObjectNameForSourceName(src), cxxPlatform);
}
/**
* Creates a {@link NativeLinkable} using sources compiled by the D compiler.
*
* @param cellPathResolver
* @param params build parameters for the build target
* @param buildRuleResolver resolver for build rules
* @param cxxPlatform the C++ platform to compile for
* @param dBuckConfig the Buck configuration for D
* @param compilerFlags flags to pass to the compiler
* @param sources source files to compile
* @return the new build rule
*/
public static CxxLink createNativeLinkable(
CellPathResolver cellPathResolver,
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleParams params,
BuildRuleResolver buildRuleResolver,
CxxPlatform cxxPlatform,
DBuckConfig dBuckConfig,
CxxBuckConfig cxxBuckConfig,
ImmutableList<String> compilerFlags,
SourceList sources,
ImmutableList<String> linkerFlags,
DIncludes includes) {
SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(buildRuleResolver);
SourcePathResolver sourcePathResolver = DefaultSourcePathResolver.from(ruleFinder);
ImmutableList<SourcePath> sourcePaths =
sourcePathsForCompiledSources(
buildTarget,
projectFilesystem,
params,
buildRuleResolver,
sourcePathResolver,
ruleFinder,
cxxPlatform,
dBuckConfig,
compilerFlags,
sources,
includes);
// Return a rule to link the .o for the binary together with its
// dependencies.
return CxxLinkableEnhancer.createCxxLinkableBuildRule(
cxxBuckConfig,
cxxPlatform,
projectFilesystem,
buildRuleResolver,
sourcePathResolver,
ruleFinder,
buildTarget,
Linker.LinkType.EXECUTABLE,
Optional.empty(),
BuildTargets.getGenPath(projectFilesystem, buildTarget, "%s/" + buildTarget.getShortName()),
ImmutableList.of(),
Linker.LinkableDepType.STATIC,
CxxLinkOptions.of(),
FluentIterable.from(params.getBuildDeps()).filter(NativeLinkable.class),
/* cxxRuntimeType */ Optional.empty(),
/* bundleLoader */ Optional.empty(),
ImmutableSet.of(),
ImmutableSet.of(),
NativeLinkableInput.builder()
.addAllArgs(StringArg.from(dBuckConfig.getLinkerFlags()))
.addAllArgs(StringArg.from(linkerFlags))
.addAllArgs(SourcePathArg.from(sourcePaths))
.build(),
Optional.empty(),
cellPathResolver);
}
public static BuildTarget getSymlinkTreeTarget(BuildTarget baseTarget) {
return baseTarget.withAppendedFlavors(SOURCE_LINK_TREE);
}
public static SymlinkTree createSourceSymlinkTree(
BuildTarget target,
ProjectFilesystem projectFilesystem,
SourcePathResolver pathResolver,
SourcePathRuleFinder ruleFinder,
SourceList sources) {
Preconditions.checkState(target.getFlavors().contains(SOURCE_LINK_TREE));
return new SymlinkTree(
"d_src",
target,
projectFilesystem,
BuildTargets.getGenPath(projectFilesystem, target, "%s"),
MoreMaps.transformKeys(
sources.toNameMap(target, pathResolver, "srcs"),
MorePaths.toPathFn(projectFilesystem.getRootPath().getFileSystem())),
ImmutableMultimap.of(),
ruleFinder);
}
private static ImmutableMap<BuildTarget, DLibrary> getTransitiveDLibraryRules(
Iterable<? extends BuildRule> inputs) {
ImmutableMap.Builder<BuildTarget, DLibrary> libraries = ImmutableMap.builder();
new AbstractBreadthFirstTraversal<BuildRule>(inputs) {
@Override
public Iterable<BuildRule> visit(BuildRule rule) {
if (rule instanceof DLibrary) {
libraries.put(rule.getBuildTarget(), (DLibrary) rule);
return rule.getBuildDeps();
}
return ImmutableSet.of();
}
}.start();
return libraries.build();
}
/**
* Ensures that a DCompileBuildRule exists for the given target, creating a DCompileBuildRule if
* neccesary.
*
* @param baseParams build parameters for the rule
* @param buildRuleResolver BuildRuleResolver the rule should be in
* @param src the source file to be compiled
* @param compilerFlags flags to pass to the compiler
* @param compileTarget the target the rule should be for
* @param dBuckConfig the Buck configuration for D
* @return the build rule
*/
public static DCompileBuildRule requireBuildRule(
BuildTarget compileTarget,
BuildTarget baseBuildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleParams baseParams,
BuildRuleResolver buildRuleResolver,
SourcePathRuleFinder ruleFinder,
DBuckConfig dBuckConfig,
ImmutableList<String> compilerFlags,
String name,
SourcePath src,
DIncludes includes) {
return (DCompileBuildRule)
buildRuleResolver.computeIfAbsent(
compileTarget,
ignored -> {
Tool compiler = dBuckConfig.getDCompiler();
Map<BuildTarget, DIncludes> transitiveIncludes = new TreeMap<>();
transitiveIncludes.put(baseBuildTarget, includes);
for (Map.Entry<BuildTarget, DLibrary> library :
getTransitiveDLibraryRules(baseParams.getBuildDeps()).entrySet()) {
transitiveIncludes.put(library.getKey(), library.getValue().getIncludes());
}
ImmutableSortedSet.Builder<BuildRule> depsBuilder = ImmutableSortedSet.naturalOrder();
depsBuilder.addAll(BuildableSupport.getDepsCollection(compiler, ruleFinder));
depsBuilder.addAll(ruleFinder.filterBuildRuleInputs(src));
for (DIncludes dIncludes : transitiveIncludes.values()) {
depsBuilder.addAll(dIncludes.getDeps(ruleFinder));
}
ImmutableSortedSet<BuildRule> deps = depsBuilder.build();
return new DCompileBuildRule(
compileTarget,
projectFilesystem,
baseParams.withDeclaredDeps(deps).withoutExtraDeps(),
compiler,
ImmutableList.<String>builder()
.addAll(dBuckConfig.getBaseCompilerFlags())
.addAll(compilerFlags)
.build(),
name,
ImmutableSortedSet.of(src),
ImmutableList.copyOf(transitiveIncludes.values()));
});
}
/**
* Generates BuildTargets and BuildRules to compile D sources to object files, and returns a list
* of SourcePaths referring to the generated object files.
*
* @param sources source files to compile
* @param compilerFlags flags to pass to the compiler
* @param baseParams build parameters for the compilation
* @param buildRuleResolver resolver for build rules
* @param sourcePathResolver resolver for source paths
* @param cxxPlatform the C++ platform to compile for
* @param dBuckConfig the Buck configuration for D
* @return SourcePaths of the generated object files
*/
public static ImmutableList<SourcePath> sourcePathsForCompiledSources(
BuildTarget baseBuildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleParams baseParams,
BuildRuleResolver buildRuleResolver,
SourcePathResolver sourcePathResolver,
SourcePathRuleFinder ruleFinder,
CxxPlatform cxxPlatform,
DBuckConfig dBuckConfig,
ImmutableList<String> compilerFlags,
SourceList sources,
DIncludes includes) {
ImmutableList.Builder<SourcePath> sourcePaths = ImmutableList.builder();
for (Map.Entry<String, SourcePath> source :
sources.toNameMap(baseBuildTarget, sourcePathResolver, "srcs").entrySet()) {
BuildTarget compileTarget =
createDCompileBuildTarget(baseBuildTarget, source.getKey(), cxxPlatform);
BuildRule rule =
requireBuildRule(
compileTarget,
baseBuildTarget,
projectFilesystem,
baseParams,
buildRuleResolver,
ruleFinder,
dBuckConfig,
compilerFlags,
source.getKey(),
source.getValue(),
includes);
sourcePaths.add(rule.getSourcePathToOutput());
}
return sourcePaths.build();
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.NavigableMap;
import java.util.TreeMap;
import org.apache.hadoop.hbase.testclassification.MiscTests;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mockito.Mockito;
@Category({MiscTests.class, SmallTests.class})
public class TestCellUtil {
@ClassRule
public static final HBaseClassTestRule CLASS_RULE =
HBaseClassTestRule.forClass(TestCellUtil.class);
/**
* CellScannable used in test. Returns a {@link TestCellScanner}
*/
private static class TestCellScannable implements CellScannable {
private final int cellsCount;
TestCellScannable(final int cellsCount) {
this.cellsCount = cellsCount;
}
@Override
public CellScanner cellScanner() {
return new TestCellScanner(this.cellsCount);
}
}
/**
* CellScanner used in test.
*/
private static class TestCellScanner implements CellScanner {
private int count = 0;
private Cell current = null;
private final int cellsCount;
TestCellScanner(final int cellsCount) {
this.cellsCount = cellsCount;
}
@Override
public Cell current() {
return this.current;
}
@Override
public boolean advance() throws IOException {
if (this.count < cellsCount) {
this.current = new TestCell(this.count);
this.count++;
return true;
}
return false;
}
}
/**
* Cell used in test. Has row only.
*/
private static class TestCell implements Cell {
private final byte [] row;
TestCell(final int i) {
this.row = Bytes.toBytes(i);
}
@Override
public byte[] getRowArray() {
return this.row;
}
@Override
public int getRowOffset() {
return 0;
}
@Override
public short getRowLength() {
return (short)this.row.length;
}
@Override
public byte[] getFamilyArray() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getFamilyOffset() {
// TODO Auto-generated method stub
return 0;
}
@Override
public byte getFamilyLength() {
// TODO Auto-generated method stub
return 0;
}
@Override
public byte[] getQualifierArray() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getQualifierOffset() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getQualifierLength() {
// TODO Auto-generated method stub
return 0;
}
@Override
public long getTimestamp() {
// TODO Auto-generated method stub
return 0;
}
@Override
public byte getTypeByte() {
// TODO Auto-generated method stub
return 0;
}
@Override
public byte[] getValueArray() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getValueOffset() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getValueLength() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getSerializedSize() {
return 0;
}
@Override
public byte[] getTagsArray() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getTagsOffset() {
// TODO Auto-generated method stub
return 0;
}
@Override
public long getSequenceId() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getTagsLength() {
// TODO Auto-generated method stub
return 0;
}
@Override
public long heapSize() {
return 0;
}
}
/**
* Was overflowing if 100k or so lists of cellscanners to return.
*/
@Test
public void testCreateCellScannerOverflow() throws IOException {
consume(doCreateCellScanner(1, 1), 1 * 1);
consume(doCreateCellScanner(3, 0), 3 * 0);
consume(doCreateCellScanner(3, 3), 3 * 3);
consume(doCreateCellScanner(0, 1), 0 * 1);
// Do big number. See HBASE-11813 for why.
final int hundredK = 100000;
consume(doCreateCellScanner(hundredK, 0), hundredK * 0);
consume(doCreateCellArray(1), 1);
consume(doCreateCellArray(0), 0);
consume(doCreateCellArray(3), 3);
List<CellScannable> cells = new ArrayList<>(hundredK);
for (int i = 0; i < hundredK; i++) {
cells.add(new TestCellScannable(1));
}
consume(CellUtil.createCellScanner(cells), hundredK * 1);
NavigableMap<byte [], List<Cell>> m = new TreeMap<>(Bytes.BYTES_COMPARATOR);
List<Cell> cellArray = new ArrayList<>(hundredK);
for (int i = 0; i < hundredK; i++) {
cellArray.add(new TestCell(i));
}
m.put(new byte [] {'f'}, cellArray);
consume(CellUtil.createCellScanner(m), hundredK * 1);
}
private CellScanner doCreateCellArray(final int itemsPerList) {
Cell [] cells = new Cell [itemsPerList];
for (int i = 0; i < itemsPerList; i++) {
cells[i] = new TestCell(i);
}
return CellUtil.createCellScanner(cells);
}
private CellScanner doCreateCellScanner(final int listsCount, final int itemsPerList)
throws IOException {
List<CellScannable> cells = new ArrayList<>(listsCount);
for (int i = 0; i < listsCount; i++) {
CellScannable cs = new CellScannable() {
@Override
public CellScanner cellScanner() {
return new TestCellScanner(itemsPerList);
}
};
cells.add(cs);
}
return CellUtil.createCellScanner(cells);
}
private void consume(final CellScanner scanner, final int expected) throws IOException {
int count = 0;
while (scanner.advance()) {
count++;
}
Assert.assertEquals(expected, count);
}
@Test
public void testOverlappingKeys() {
byte[] empty = HConstants.EMPTY_BYTE_ARRAY;
byte[] a = Bytes.toBytes("a");
byte[] b = Bytes.toBytes("b");
byte[] c = Bytes.toBytes("c");
byte[] d = Bytes.toBytes("d");
// overlaps
Assert.assertTrue(PrivateCellUtil.overlappingKeys(a, b, a, b));
Assert.assertTrue(PrivateCellUtil.overlappingKeys(a, c, a, b));
Assert.assertTrue(PrivateCellUtil.overlappingKeys(a, b, a, c));
Assert.assertTrue(PrivateCellUtil.overlappingKeys(b, c, a, c));
Assert.assertTrue(PrivateCellUtil.overlappingKeys(a, c, b, c));
Assert.assertTrue(PrivateCellUtil.overlappingKeys(a, d, b, c));
Assert.assertTrue(PrivateCellUtil.overlappingKeys(b, c, a, d));
Assert.assertTrue(PrivateCellUtil.overlappingKeys(empty, b, a, b));
Assert.assertTrue(PrivateCellUtil.overlappingKeys(empty, b, a, c));
Assert.assertTrue(PrivateCellUtil.overlappingKeys(a, b, empty, b));
Assert.assertTrue(PrivateCellUtil.overlappingKeys(a, b, empty, c));
Assert.assertTrue(PrivateCellUtil.overlappingKeys(a, empty, a, b));
Assert.assertTrue(PrivateCellUtil.overlappingKeys(a, empty, a, c));
Assert.assertTrue(PrivateCellUtil.overlappingKeys(a, b, empty, empty));
Assert.assertTrue(PrivateCellUtil.overlappingKeys(empty, empty, a, b));
// non overlaps
Assert.assertFalse(PrivateCellUtil.overlappingKeys(a, b, c, d));
Assert.assertFalse(PrivateCellUtil.overlappingKeys(c, d, a, b));
Assert.assertFalse(PrivateCellUtil.overlappingKeys(b, c, c, d));
Assert.assertFalse(PrivateCellUtil.overlappingKeys(b, c, c, empty));
Assert.assertFalse(PrivateCellUtil.overlappingKeys(b, c, d, empty));
Assert.assertFalse(PrivateCellUtil.overlappingKeys(c, d, b, c));
Assert.assertFalse(PrivateCellUtil.overlappingKeys(c, empty, b, c));
Assert.assertFalse(PrivateCellUtil.overlappingKeys(d, empty, b, c));
Assert.assertFalse(PrivateCellUtil.overlappingKeys(b, c, a, b));
Assert.assertFalse(PrivateCellUtil.overlappingKeys(b, c, empty, b));
Assert.assertFalse(PrivateCellUtil.overlappingKeys(b, c, empty, a));
Assert.assertFalse(PrivateCellUtil.overlappingKeys(a,b, b, c));
Assert.assertFalse(PrivateCellUtil.overlappingKeys(empty, b, b, c));
Assert.assertFalse(PrivateCellUtil.overlappingKeys(empty, a, b, c));
}
@Test
public void testFindCommonPrefixInFlatKey() {
// The whole key matching case
KeyValue kv1 = new KeyValue(Bytes.toBytes("r1"), Bytes.toBytes("f1"),
Bytes.toBytes("q1"), null);
Assert.assertEquals(kv1.getKeyLength(),
PrivateCellUtil.findCommonPrefixInFlatKey(kv1, kv1, true, true));
Assert.assertEquals(kv1.getKeyLength(),
PrivateCellUtil.findCommonPrefixInFlatKey(kv1, kv1, false, true));
Assert.assertEquals(kv1.getKeyLength() - KeyValue.TIMESTAMP_TYPE_SIZE,
PrivateCellUtil.findCommonPrefixInFlatKey(kv1, kv1, true, false));
// The rk length itself mismatch
KeyValue kv2 = new KeyValue(Bytes.toBytes("r12"), Bytes.toBytes("f1"),
Bytes.toBytes("q1"), null);
Assert.assertEquals(1, PrivateCellUtil.findCommonPrefixInFlatKey(kv1, kv2, true, true));
// part of rk is same
KeyValue kv3 = new KeyValue(Bytes.toBytes("r14"), Bytes.toBytes("f1"),
Bytes.toBytes("q1"), null);
Assert.assertEquals(KeyValue.ROW_LENGTH_SIZE + Bytes.toBytes("r1").length,
PrivateCellUtil.findCommonPrefixInFlatKey(kv2, kv3, true, true));
// entire rk is same but different cf name
KeyValue kv4 = new KeyValue(Bytes.toBytes("r14"), Bytes.toBytes("f2"),
Bytes.toBytes("q1"), null);
Assert.assertEquals(KeyValue.ROW_LENGTH_SIZE + kv3.getRowLength() + KeyValue.FAMILY_LENGTH_SIZE
+ Bytes.toBytes("f").length,
PrivateCellUtil.findCommonPrefixInFlatKey(kv3, kv4, false, true));
// rk and family are same and part of qualifier
KeyValue kv5 = new KeyValue(Bytes.toBytes("r14"), Bytes.toBytes("f2"),
Bytes.toBytes("q123"), null);
Assert.assertEquals(KeyValue.ROW_LENGTH_SIZE + kv3.getRowLength() + KeyValue.FAMILY_LENGTH_SIZE
+ kv4.getFamilyLength() + kv4.getQualifierLength(),
PrivateCellUtil.findCommonPrefixInFlatKey(kv4, kv5, true, true));
// rk, cf and q are same. ts differs
KeyValue kv6 = new KeyValue(Bytes.toBytes("rk"), 1234L);
KeyValue kv7 = new KeyValue(Bytes.toBytes("rk"), 1235L);
// only last byte out of 8 ts bytes in ts part differs
Assert.assertEquals(KeyValue.ROW_LENGTH_SIZE + kv6.getRowLength() + KeyValue.FAMILY_LENGTH_SIZE
+ kv6.getFamilyLength() + kv6.getQualifierLength() + 7,
PrivateCellUtil.findCommonPrefixInFlatKey(kv6, kv7, true, true));
// rk, cf, q and ts are same. Only type differs
KeyValue kv8 = new KeyValue(Bytes.toBytes("rk"), 1234L, KeyValue.Type.Delete);
Assert.assertEquals(KeyValue.ROW_LENGTH_SIZE + kv6.getRowLength() + KeyValue.FAMILY_LENGTH_SIZE
+ kv6.getFamilyLength() + kv6.getQualifierLength() + KeyValue.TIMESTAMP_SIZE,
PrivateCellUtil.findCommonPrefixInFlatKey(kv6, kv8, true, true));
// With out TS_TYPE check
Assert.assertEquals(KeyValue.ROW_LENGTH_SIZE + kv6.getRowLength() + KeyValue.FAMILY_LENGTH_SIZE
+ kv6.getFamilyLength() + kv6.getQualifierLength(),
PrivateCellUtil.findCommonPrefixInFlatKey(kv6, kv8, true, false));
}
/**
* Assert CellUtil makes Cell toStrings same way we do KeyValue toStrings.
*/
@Test
public void testToString() {
byte [] row = Bytes.toBytes("row");
long ts = 123L;
// Make a KeyValue and a Cell and see if same toString result.
KeyValue kv = new KeyValue(row, HConstants.EMPTY_BYTE_ARRAY, HConstants.EMPTY_BYTE_ARRAY,
ts, KeyValue.Type.Minimum, HConstants.EMPTY_BYTE_ARRAY);
Cell cell = CellUtil.createCell(row, HConstants.EMPTY_BYTE_ARRAY, HConstants.EMPTY_BYTE_ARRAY,
ts, KeyValue.Type.Minimum.getCode(), HConstants.EMPTY_BYTE_ARRAY);
String cellToString = CellUtil.getCellKeyAsString(cell);
assertEquals(kv.toString(), cellToString);
// Do another w/ non-null family.
byte [] f = new byte [] {'f'};
byte [] q = new byte [] {'q'};
kv = new KeyValue(row, f, q, ts, KeyValue.Type.Minimum, HConstants.EMPTY_BYTE_ARRAY);
cell = CellUtil.createCell(row, f, q, ts, KeyValue.Type.Minimum.getCode(),
HConstants.EMPTY_BYTE_ARRAY);
cellToString = CellUtil.getCellKeyAsString(cell);
assertEquals(kv.toString(), cellToString);
}
@Test
public void testToString1() {
String row = "test.row";
String family = "test.family";
String qualifier = "test.qualifier";
long timestamp = 42;
KeyValue.Type type = KeyValue.Type.Put;
String value = "test.value";
long seqId = 1042;
Cell cell = CellUtil.createCell(Bytes.toBytes(row), Bytes.toBytes(family),
Bytes.toBytes(qualifier), timestamp, type.getCode(), Bytes.toBytes(value), seqId);
String nonVerbose = CellUtil.toString(cell, false);
String verbose = CellUtil.toString(cell, true);
System.out.println("nonVerbose=" + nonVerbose);
System.out.println("verbose=" + verbose);
Assert.assertEquals(
String.format("%s/%s:%s/%d/%s/vlen=%s/seqid=%s",
row, family, qualifier, timestamp, type.toString(),
Bytes.toBytes(value).length, seqId),
nonVerbose);
Assert.assertEquals(
String.format("%s/%s:%s/%d/%s/vlen=%s/seqid=%s/%s",
row, family, qualifier, timestamp, type.toString(), Bytes.toBytes(value).length,
seqId, value),
verbose);
// TODO: test with tags
}
@Test
public void testCloneCellFieldsFromByteBufferedCell() {
byte[] r = Bytes.toBytes("row1");
byte[] f = Bytes.toBytes("cf1");
byte[] q = Bytes.toBytes("qual1");
byte[] v = Bytes.toBytes("val1");
byte[] tags = Bytes.toBytes("tag1");
KeyValue kv =
new KeyValue(r, f, q, 0, q.length, 1234L, KeyValue.Type.Put, v, 0, v.length, tags);
ByteBuffer buffer = ByteBuffer.wrap(kv.getBuffer());
Cell bbCell = new ByteBufferKeyValue(buffer, 0, buffer.remaining());
byte[] rDest = CellUtil.cloneRow(bbCell);
assertTrue(Bytes.equals(r, rDest));
byte[] fDest = CellUtil.cloneFamily(bbCell);
assertTrue(Bytes.equals(f, fDest));
byte[] qDest = CellUtil.cloneQualifier(bbCell);
assertTrue(Bytes.equals(q, qDest));
byte[] vDest = CellUtil.cloneValue(bbCell);
assertTrue(Bytes.equals(v, vDest));
byte[] tDest = new byte[tags.length];
PrivateCellUtil.copyTagsTo(bbCell, tDest, 0);
assertTrue(Bytes.equals(tags, tDest));
}
@Test
public void testMatchingCellFieldsFromByteBufferedCell() {
byte[] r = Bytes.toBytes("row1");
byte[] f = Bytes.toBytes("cf1");
byte[] q1 = Bytes.toBytes("qual1");
byte[] q2 = Bytes.toBytes("qual2");
byte[] v = Bytes.toBytes("val1");
byte[] tags = Bytes.toBytes("tag1");
KeyValue kv =
new KeyValue(r, f, q1, 0, q1.length, 1234L, KeyValue.Type.Put, v, 0, v.length, tags);
ByteBuffer buffer = ByteBuffer.wrap(kv.getBuffer());
Cell bbCell1 = new ByteBufferKeyValue(buffer, 0, buffer.remaining());
kv = new KeyValue(r, f, q2, 0, q2.length, 1234L, KeyValue.Type.Put, v, 0, v.length, tags);
buffer = ByteBuffer.wrap(kv.getBuffer());
Cell bbCell2 = new ByteBufferKeyValue(buffer, 0, buffer.remaining());
assertTrue(CellUtil.matchingRows(bbCell1, bbCell2));
assertTrue(CellUtil.matchingRows(kv, bbCell2));
assertTrue(CellUtil.matchingRows(bbCell1, r));
assertTrue(CellUtil.matchingFamily(bbCell1, bbCell2));
assertTrue(CellUtil.matchingFamily(kv, bbCell2));
assertTrue(CellUtil.matchingFamily(bbCell1, f));
assertFalse(CellUtil.matchingQualifier(bbCell1, bbCell2));
assertTrue(CellUtil.matchingQualifier(kv, bbCell2));
assertTrue(CellUtil.matchingQualifier(bbCell1, q1));
assertTrue(CellUtil.matchingQualifier(bbCell2, q2));
assertTrue(CellUtil.matchingValue(bbCell1, bbCell2));
assertTrue(CellUtil.matchingValue(kv, bbCell2));
assertTrue(CellUtil.matchingValue(bbCell1, v));
assertFalse(CellUtil.matchingColumn(bbCell1, bbCell2));
assertTrue(CellUtil.matchingColumn(kv, bbCell2));
assertTrue(CellUtil.matchingColumn(bbCell1, f, q1));
assertTrue(CellUtil.matchingColumn(bbCell2, f, q2));
}
@Test
public void testCellFieldsAsPrimitiveTypesFromByteBufferedCell() {
int ri = 123;
byte[] r = Bytes.toBytes(ri);
byte[] f = Bytes.toBytes("cf1");
byte[] q = Bytes.toBytes("qual1");
long vl = 10981L;
byte[] v = Bytes.toBytes(vl);
KeyValue kv = new KeyValue(r, f, q, v);
ByteBuffer buffer = ByteBuffer.wrap(kv.getBuffer());
Cell bbCell = new ByteBufferKeyValue(buffer, 0, buffer.remaining());
assertEquals(ri, PrivateCellUtil.getRowAsInt(bbCell));
assertEquals(vl, PrivateCellUtil.getValueAsLong(bbCell));
double vd = 3005.5;
v = Bytes.toBytes(vd);
kv = new KeyValue(r, f, q, v);
buffer = ByteBuffer.wrap(kv.getBuffer());
bbCell = new ByteBufferKeyValue(buffer, 0, buffer.remaining());
assertEquals(vd, PrivateCellUtil.getValueAsDouble(bbCell), 0.0);
BigDecimal bd = new BigDecimal(9999);
v = Bytes.toBytes(bd);
kv = new KeyValue(r, f, q, v);
buffer = ByteBuffer.wrap(kv.getBuffer());
bbCell = new ByteBufferKeyValue(buffer, 0, buffer.remaining());
assertEquals(bd, PrivateCellUtil.getValueAsBigDecimal(bbCell));
}
@Test
public void testWriteCell() throws IOException {
byte[] r = Bytes.toBytes("row1");
byte[] f = Bytes.toBytes("cf1");
byte[] q1 = Bytes.toBytes("qual1");
byte[] q2 = Bytes.toBytes("qual2");
byte[] v = Bytes.toBytes("val1");
byte[] tags = Bytes.toBytes("tag1");
KeyValue kv =
new KeyValue(r, f, q1, 0, q1.length, 1234L, KeyValue.Type.Put, v, 0, v.length, tags);
NonExtendedCell nonExtCell = new NonExtendedCell(kv);
ByteArrayOutputStream os = new ByteArrayOutputStream();
int writeCell = PrivateCellUtil.writeCell(nonExtCell, os, true);
byte[] byteArray = os.toByteArray();
KeyValue res = new KeyValue(byteArray);
assertTrue(CellUtil.equals(kv, res));
}
@Test
public void testGetType() throws IOException {
Cell c = Mockito.mock(Cell.class);
Mockito.when(c.getType()).thenCallRealMethod();
for (Cell.Type type : Cell.Type.values()) {
Mockito.when(c.getTypeByte()).thenReturn(type.getCode());
assertEquals(type, c.getType());
}
try {
Mockito.when(c.getTypeByte()).thenReturn(KeyValue.Type.Maximum.getCode());
c.getType();
fail("The code of Maximum can't be handled by Cell.Type");
} catch(UnsupportedOperationException e) {
}
try {
Mockito.when(c.getTypeByte()).thenReturn(KeyValue.Type.Minimum.getCode());
c.getType();
fail("The code of Maximum can't be handled by Cell.Type");
} catch(UnsupportedOperationException e) {
}
}
private static class NonExtendedCell implements Cell {
private KeyValue kv;
public NonExtendedCell(KeyValue kv) {
this.kv = kv;
}
@Override
public byte[] getRowArray() {
return this.kv.getRowArray();
}
@Override
public int getRowOffset() {
return this.kv.getRowOffset();
}
@Override
public short getRowLength() {
return this.kv.getRowLength();
}
@Override
public byte[] getFamilyArray() {
return this.kv.getFamilyArray();
}
@Override
public int getFamilyOffset() {
return this.kv.getFamilyOffset();
}
@Override
public byte getFamilyLength() {
return this.kv.getFamilyLength();
}
@Override
public byte[] getQualifierArray() {
return this.kv.getQualifierArray();
}
@Override
public int getQualifierOffset() {
return this.kv.getQualifierOffset();
}
@Override
public int getQualifierLength() {
return this.kv.getQualifierLength();
}
@Override
public long getTimestamp() {
return this.kv.getTimestamp();
}
@Override
public byte getTypeByte() {
return this.kv.getTypeByte();
}
@Override
public long getSequenceId() {
return this.kv.getSequenceId();
}
@Override
public byte[] getValueArray() {
return this.kv.getValueArray();
}
@Override
public int getValueOffset() {
return this.kv.getValueOffset();
}
@Override
public int getValueLength() {
return this.kv.getValueLength();
}
@Override
public int getSerializedSize() {
return this.kv.getSerializedSize();
}
@Override
public byte[] getTagsArray() {
return this.kv.getTagsArray();
}
@Override
public int getTagsOffset() {
return this.kv.getTagsOffset();
}
@Override
public int getTagsLength() {
return this.kv.getTagsLength();
}
@Override
public long heapSize() {
return this.kv.heapSize();
}
}
}
| |
/**
* This file is part of the XP-Framework
*
* XP-Framework Maven plugin
* Copyright (c) 2011, XP-Framework Team
*/
package net.xp_forge.maven.plugins.xp;
import java.io.File;
import java.util.Map;
import java.util.Set;
import java.util.List;
import java.util.HashMap;
import java.util.HashSet;
import java.util.ArrayList;
import org.apache.maven.model.Dependency;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.shared.filtering.MavenResourcesFiltering;
/**
* Base class for all MOJO's
*
*/
public abstract class AbstractXpMojo extends AbstractMojo {
public static final String LINE_SEPARATOR= "------------------------------------------------------------------------";
public static final String CREATED_BY_NOTICE= "This file was automatically created by xp-maven-plugin";
public static final String XP_FRAMEWORK_GROUP_ID = "net.xp-framework";
public static final String CORE_ARTIFACT_ID = "core";
public static final String TOOLS_ARTIFACT_ID = "tools";
public static final String COMPILER_ARTIFACT_ID = "compiler";
// Application directories mapping (input => output)
public static final Map<String, String> APP_DIRECTORIES_MAP;
static {
APP_DIRECTORIES_MAP= new HashMap<String, String>();
APP_DIRECTORIES_MAP.put("webapp", "doc_root");
APP_DIRECTORIES_MAP.put("doc_root", "doc_root");
APP_DIRECTORIES_MAP.put("config", "etc");
APP_DIRECTORIES_MAP.put("etc", "etc");
APP_DIRECTORIES_MAP.put("xsl", "xsl");
APP_DIRECTORIES_MAP.put("deploy", "conf");
}
/**
* The Maven project
*
* @parameter default-value="${project}"
* @required
* @readonly
*/
protected MavenProject project;
/**
* The parallel Maven project that was forked
*
* @parameter default-value="${executedProject}"
* @required
* @readonly
*/
protected MavenProject executedProject;
/**
* The projects in the reactor
*
* @parameter expression="${reactorProjects}"
* @readonly
*/
protected List<MavenProject> reactorProjects;
/**
* The Maven session
*
* @parameter default-value="${session}"
* @readonly
* @required
*/
protected MavenSession session;
/**
* Maven project helper
*
* @component
*/
protected MavenProjectHelper projectHelper;
/**
* Maven resource filtering
*
* @component role="org.apache.maven.shared.filtering.MavenResourcesFiltering" role-hint="default"
* @required
*/
protected MavenResourcesFiltering mavenResourcesFiltering;
/**
* Project base directory
*
* @parameter expression="${basedir}" default-value="${basedir}"
* @required
* @readonly
*/
protected File basedir;
/**
* Directory containing the generated XAR
*
* @parameter expression="${project.build.directory}"
* @required
* @readonly
*/
protected File outputDirectory;
/**
* The directory containing generated classes of the project being tested
* This will be included after the test classes in the test classpath
*
* @parameter expression="${project.build.outputDirectory}"
* @required
* @readonly
*/
protected File classesDirectory;
/**
* The directory containing generated test classes of the project being tested
* This will be included at the beginning of the test classpath
*
* @parameter expression="${project.build.testOutputDirectory}"
* @required
* @readonly
*/
protected File testClassesDirectory;
/**
* The directory containing generated integration test classes of the project being tested
* This will be included at the beginning of the test classpath
*
* @parameter expression="${project.build.itOutputDirectory}" default-value="${project.build.directory}/it-classes"
*/
protected File itClassesDirectory;
/**
* Vendor libraries directory (dependencies that are cannot be found by Maven in any repository)
*
* @parameter expression="${xp.vendorLibDirectory}" default-value="${basedir}/lib"
*/
protected File vendorLibDir;
/**
* Classifier to add to the generated artifact
*
* @parameter expression="${project.classifier}"
*/
protected String classifier;
/**
* @parameter default-value="${project.packaging}"
* @required
* @readonly
*/
protected String packaging;
/**
* Whether to use local XP-Framework install or to use bootstrap in [/target]. Default [false].
*
* @parameter expression="${xp.runtime.local}"
*/
protected boolean local;
/**
* USE_XP
*
* @parameter expression="${xp.runtime.use_xp}"
*/
protected String use_xp;
/**
* Directory where XP-Runners are located. If not set, runners will be
* extracted from resources to "${project.build.directory}/.runtime/runners"
*
* @parameter expression="${xp.runtime.runners}"
*/
protected File runnersDirectory;
/**
* Bootstrap timezone. If not set will use system default
*
* @parameter expression="${xp.runtime.timezone}"
*/
protected String timezone;
/**
* Location of the PHP executable. If not set will search for it in PATH
*
* @parameter expression="${xp.runtime.php}"
*/
protected File php;
/**
* PHP extensions to load
*
* @parameter
*/
protected List<String> extensions;
/**
* Returns executed project
*
* @return org.apache.maven.project.MavenProject
*/
protected MavenProject getExecutedProject() {
return (null == this.executedProject ? this.project : this.executedProject);
}
/**
* Helper function to find a project dependency
*
* @param java.lang.String groupId
* @param java.lang.String artifactId
* @return org.apache.maven.model.Dependency null if the specified dependency cannot be found
*/
@SuppressWarnings("unchecked")
protected Dependency findDependency(String groupId, String artifactId) {
for (Dependency dependency : (Iterable<Dependency>)this.project.getDependencies()) {
if (dependency.getGroupId().equals(groupId) && dependency.getArtifactId().equals(artifactId)) {
return dependency;
}
}
// Specified dependency not found
return null;
}
/**
* Helper function to find a project artifact
*
* @param java.lang.String groupId
* @param java.lang.String artifactId
* @return org.apache.maven.artifact.Artifact null if the specified artifact cannot be found
*/
@SuppressWarnings("unchecked")
protected Artifact findArtifact(String groupId, String artifactId) {
for (Artifact artifact : (Iterable<Artifact>)this.project.getArtifacts()) {
if (artifact.getGroupId().equals(groupId) && artifact.getArtifactId().equals(artifactId)) {
return artifact;
}
}
// Specified artifact not found
return null;
}
/**
* Helper function to find a project artifact - only direct dependencies considered.
*
* @param java.lang.String groupId
* @param java.lang.String artifactId
* @return org.apache.maven.artifact.Artifact null if the specified artifact cannot be found
*/
@SuppressWarnings("unchecked")
protected Artifact findDependencyArtifact(String groupId, String artifactId) {
for (Artifact artifact : (Iterable<Artifact>)this.project.getDependencyArtifacts()) {
if (artifact.getGroupId().equals(groupId) && artifact.getArtifactId().equals(artifactId)) {
return artifact;
}
}
// Specified artifact not found
return null;
}
/**
* Helper function to return all project artifacts
*
*
* @param boolean includeXpArtifacts
* @return java.util.Set<org.apache.maven.artifact.Artifact> null if the specified artifact cannot be found
*/
@SuppressWarnings("unchecked")
protected Set<Artifact> getArtifacts(boolean includeXpArtifacts) {
// Short-circut
if (includeXpArtifacts) {
return this.project.getArtifacts();
}
// Return all non XP-artifacts
Set<Artifact> retVal= new HashSet<Artifact>();
for (Artifact artifact : (Iterable<Artifact>)this.project.getArtifacts()) {
if (
artifact.getGroupId().equals(XP_FRAMEWORK_GROUP_ID) &&
null == artifact.getClassifier() && // Some projects may require core-tests artifact as dependency
(
artifact.getArtifactId().equals(CORE_ARTIFACT_ID) ||
artifact.getArtifactId().equals(TOOLS_ARTIFACT_ID) ||
artifact.getArtifactId().equals(COMPILER_ARTIFACT_ID)
)
) continue;
retVal.add(artifact);
}
return retVal;
}
/**
* Get the main artifact that was attached to this project during the "package" phase
*
* @return org.apache.maven.artifact.Artifact null if no artifact was attached to this project
*/
protected Artifact getMainArtifact() {
Artifact retVal= null;
// Get project
MavenProject project= this.getExecutedProject();
// If project has no classifier, return main artifact
if (null == this.classifier || this.classifier.isEmpty()) {
retVal= project.getArtifact();
// Get attached artifact with the specified classifier
} else {
List<Artifact> attachedArtifacts= project.getAttachedArtifacts();
for (Artifact artifact : attachedArtifacts) {
if (null != artifact.getClassifier() && artifact.getClassifier().equals(this.classifier)) {
retVal= artifact;
}
}
}
// Main artifact found
if (null != retVal && null != retVal.getFile()) {
return retVal;
}
// Main artifact not found
getLog().warn("The packaging for this project did not assign a file to the build artifact");
return null;
}
}
| |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.mturk.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/mturk-requester-2017-01-17/ListBonusPayments" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListBonusPaymentsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The ID of the HIT associated with the bonus payments to retrieve. If not specified, all bonus payments for all
* assignments for the given HIT are returned. Either the HITId parameter or the AssignmentId parameter must be
* specified
* </p>
*/
private String hITId;
/**
* <p>
* The ID of the assignment associated with the bonus payments to retrieve. If specified, only bonus payments for
* the given assignment are returned. Either the HITId parameter or the AssignmentId parameter must be specified
* </p>
*/
private String assignmentId;
/**
* <p>
* Pagination token
* </p>
*/
private String nextToken;
private Integer maxResults;
/**
* <p>
* The ID of the HIT associated with the bonus payments to retrieve. If not specified, all bonus payments for all
* assignments for the given HIT are returned. Either the HITId parameter or the AssignmentId parameter must be
* specified
* </p>
*
* @param hITId
* The ID of the HIT associated with the bonus payments to retrieve. If not specified, all bonus payments for
* all assignments for the given HIT are returned. Either the HITId parameter or the AssignmentId parameter
* must be specified
*/
public void setHITId(String hITId) {
this.hITId = hITId;
}
/**
* <p>
* The ID of the HIT associated with the bonus payments to retrieve. If not specified, all bonus payments for all
* assignments for the given HIT are returned. Either the HITId parameter or the AssignmentId parameter must be
* specified
* </p>
*
* @return The ID of the HIT associated with the bonus payments to retrieve. If not specified, all bonus payments
* for all assignments for the given HIT are returned. Either the HITId parameter or the AssignmentId
* parameter must be specified
*/
public String getHITId() {
return this.hITId;
}
/**
* <p>
* The ID of the HIT associated with the bonus payments to retrieve. If not specified, all bonus payments for all
* assignments for the given HIT are returned. Either the HITId parameter or the AssignmentId parameter must be
* specified
* </p>
*
* @param hITId
* The ID of the HIT associated with the bonus payments to retrieve. If not specified, all bonus payments for
* all assignments for the given HIT are returned. Either the HITId parameter or the AssignmentId parameter
* must be specified
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListBonusPaymentsRequest withHITId(String hITId) {
setHITId(hITId);
return this;
}
/**
* <p>
* The ID of the assignment associated with the bonus payments to retrieve. If specified, only bonus payments for
* the given assignment are returned. Either the HITId parameter or the AssignmentId parameter must be specified
* </p>
*
* @param assignmentId
* The ID of the assignment associated with the bonus payments to retrieve. If specified, only bonus payments
* for the given assignment are returned. Either the HITId parameter or the AssignmentId parameter must be
* specified
*/
public void setAssignmentId(String assignmentId) {
this.assignmentId = assignmentId;
}
/**
* <p>
* The ID of the assignment associated with the bonus payments to retrieve. If specified, only bonus payments for
* the given assignment are returned. Either the HITId parameter or the AssignmentId parameter must be specified
* </p>
*
* @return The ID of the assignment associated with the bonus payments to retrieve. If specified, only bonus
* payments for the given assignment are returned. Either the HITId parameter or the AssignmentId parameter
* must be specified
*/
public String getAssignmentId() {
return this.assignmentId;
}
/**
* <p>
* The ID of the assignment associated with the bonus payments to retrieve. If specified, only bonus payments for
* the given assignment are returned. Either the HITId parameter or the AssignmentId parameter must be specified
* </p>
*
* @param assignmentId
* The ID of the assignment associated with the bonus payments to retrieve. If specified, only bonus payments
* for the given assignment are returned. Either the HITId parameter or the AssignmentId parameter must be
* specified
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListBonusPaymentsRequest withAssignmentId(String assignmentId) {
setAssignmentId(assignmentId);
return this;
}
/**
* <p>
* Pagination token
* </p>
*
* @param nextToken
* Pagination token
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* Pagination token
* </p>
*
* @return Pagination token
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* Pagination token
* </p>
*
* @param nextToken
* Pagination token
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListBonusPaymentsRequest withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* @param maxResults
*/
public void setMaxResults(Integer maxResults) {
this.maxResults = maxResults;
}
/**
* @return
*/
public Integer getMaxResults() {
return this.maxResults;
}
/**
* @param maxResults
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListBonusPaymentsRequest withMaxResults(Integer maxResults) {
setMaxResults(maxResults);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getHITId() != null)
sb.append("HITId: ").append(getHITId()).append(",");
if (getAssignmentId() != null)
sb.append("AssignmentId: ").append(getAssignmentId()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken()).append(",");
if (getMaxResults() != null)
sb.append("MaxResults: ").append(getMaxResults());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListBonusPaymentsRequest == false)
return false;
ListBonusPaymentsRequest other = (ListBonusPaymentsRequest) obj;
if (other.getHITId() == null ^ this.getHITId() == null)
return false;
if (other.getHITId() != null && other.getHITId().equals(this.getHITId()) == false)
return false;
if (other.getAssignmentId() == null ^ this.getAssignmentId() == null)
return false;
if (other.getAssignmentId() != null && other.getAssignmentId().equals(this.getAssignmentId()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
if (other.getMaxResults() == null ^ this.getMaxResults() == null)
return false;
if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getHITId() == null) ? 0 : getHITId().hashCode());
hashCode = prime * hashCode + ((getAssignmentId() == null) ? 0 : getAssignmentId().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
return hashCode;
}
@Override
public ListBonusPaymentsRequest clone() {
return (ListBonusPaymentsRequest) super.clone();
}
}
| |
/*
* Copyright 2014 OpenMarket Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector;
import android.app.Activity;
import android.app.Application;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import org.matrix.androidsdk.MXSession;
import im.vector.activity.VectorCallViewActivity;
import im.vector.activity.CommonActivityUtils;
import im.vector.contacts.ContactsManager;
import im.vector.contacts.PIDsRetriever;
import im.vector.ga.GAHelper;
import im.vector.gcm.GcmRegistrationManager;
import im.vector.services.EventStreamService;
import im.vector.util.LogUtilities;
import im.vector.util.RageShake;
import java.io.File;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
/**
* The main application injection point
*/
public class VectorApp extends Application {
private static final String LOG_TAG = "VectorApp";
/**
* The current instance.
*/
private static VectorApp instance = null;
/**
* Rage shake detection to send a bug report.
*/
private static final RageShake mRageShake = new RageShake();
/**
* Delay to detect if the application is in background.
* If there is no active activity during the elapsed time, it means that the application is in background.
*/
private static final long MAX_ACTIVITY_TRANSITION_TIME_MS = 2000;
/**
* The current active activity
*/
private static Activity mCurrentActivity = null;
/**
* Background application detection
*/
private Timer mActivityTransitionTimer;
private TimerTask mActivityTransitionTimerTask;
private boolean mIsInBackground = true;
/**
* Google analytics information.
*/
public static int VERSION_BUILD = -1;
public static String VECTOR_VERSION_STRING = "";
public static String SDK_VERSION_STRING = "";
/**
* Tells if there a pending call whereas the application is backgrounded.
*/
private boolean mIsCallingInBackground = false;
/**
* Monitor the created activities to detect memory leaks.
*/
private final ArrayList<String> mCreatedActivities = new ArrayList<>();
/**
* @return the current instance
*/
public static VectorApp getInstance() {
return instance;
}
@Override
public void onCreate() {
Log.d(LOG_TAG, "onCreate");
super.onCreate();
instance = this;
mActivityTransitionTimer = null;
mActivityTransitionTimerTask = null;
try {
PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
VERSION_BUILD = packageInfo.versionCode;
}
catch (PackageManager.NameNotFoundException e) {
Log.e(LOG_TAG, "fails to retrieve the package info " + e.getMessage());
}
VECTOR_VERSION_STRING = Matrix.getInstance(this).getVersion(true);
// not the first launch
if (null != Matrix.getInstance(this).getDefaultSession()) {
SDK_VERSION_STRING = Matrix.getInstance(this).getDefaultSession().getVersion(true);
} else {
SDK_VERSION_STRING = "";
}
LogUtilities.setLogDirectory(new File(getCacheDir().getAbsolutePath() + "/logs"));
LogUtilities.storeLogcat();
GAHelper.initGoogleAnalytics(getApplicationContext());
mRageShake.start(this);
this.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
mCreatedActivities.add(activity.toString());
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
setCurrentActivity(activity);
}
@Override
public void onActivityPaused(Activity activity) {
setCurrentActivity(null);
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
mCreatedActivities.remove(activity.toString());
if (mCreatedActivities.size() > 1) {
Log.d(LOG_TAG, "onActivityDestroyed : \n" + mCreatedActivities);
}
}
});
}
/**
* Suspend background threads.
*/
private void suspendApp() {
GcmRegistrationManager gcmRegistrationManager = Matrix.getInstance(VectorApp.this).getSharedGCMRegistrationManager();
// suspend the events thread if the client uses GCM
if (!gcmRegistrationManager.isBackgroundSyncAllowed() || (gcmRegistrationManager.useGCM() && gcmRegistrationManager.hasRegistrationToken())) {
Log.d(LOG_TAG, "suspendApp ; pause the event stream");
CommonActivityUtils.pauseEventStream(VectorApp.this);
} else {
Log.d(LOG_TAG, "suspendApp ; the event stream is not paused because GCM is disabled.");
}
// the sessions are not anymore seen as "online"
ArrayList<MXSession> sessions = Matrix.getInstance(this).getSessions();
for(MXSession session : sessions) {
if (session.isAlive()) {
session.setIsOnline(false);
session.setSyncDelay(gcmRegistrationManager.getBackgroundSyncDelay());
session.setSyncTimeout(gcmRegistrationManager.getBackgroundSyncTimeOut());
}
}
PIDsRetriever.getIntance().onAppBackgrounded();
MyPresenceManager.advertiseAllUnavailable();
}
/**
* Test if application is put in background.
* i.e wait 2s before assuming that the application is put in background.
*/
private void startActivityTransitionTimer() {
mActivityTransitionTimer = new Timer();
mActivityTransitionTimerTask = new TimerTask() {
@Override
public void run() {
if (mActivityTransitionTimerTask != null) {
mActivityTransitionTimerTask.cancel();
mActivityTransitionTimerTask = null;
}
if (mActivityTransitionTimer != null) {
mActivityTransitionTimer.cancel();
mActivityTransitionTimer = null;
}
VectorApp.this.mIsInBackground = true;
mIsCallingInBackground = (null != VectorCallViewActivity.getActiveCall());
// if there is a pending call
// the application is not suspended
if (!mIsCallingInBackground) {
Log.d(LOG_TAG, "Suspend the application because there was no resumed activity within 2 seconds");
suspendApp();
} else {
Log.d(LOG_TAG, "App not suspended due to call in progress");
}
}
};
mActivityTransitionTimer.schedule(mActivityTransitionTimerTask, MAX_ACTIVITY_TRANSITION_TIME_MS);
}
/**
* Stop the background detection.
*/
private void stopActivityTransitionTimer() {
if (mActivityTransitionTimerTask != null) {
mActivityTransitionTimerTask.cancel();
mActivityTransitionTimerTask = null;
}
if (mActivityTransitionTimer != null) {
mActivityTransitionTimer.cancel();
mActivityTransitionTimer = null;
}
if (isAppInBackground() && !mIsCallingInBackground) {
// the event stream service has been killed
if (null == EventStreamService.getInstance()) {
CommonActivityUtils.startEventStreamService(VectorApp.this);
} else {
CommonActivityUtils.resumeEventStream(VectorApp.this);
// try to perform a GCM registration if it failed
// or if the GCM server generated a new push key
GcmRegistrationManager gcmRegistrationManager = Matrix.getInstance(this).getSharedGCMRegistrationManager();
if (null != gcmRegistrationManager) {
gcmRegistrationManager.checkRegistrations();
}
}
// get the contact update at application launch
ContactsManager.refreshLocalContactsSnapshot(this);
ArrayList<MXSession> sessions = Matrix.getInstance(this).getSessions();
for(MXSession session : sessions) {
session.getMyUser().refreshUserInfos(null);
session.setIsOnline(true);
session.setSyncDelay(0);
session.setSyncTimeout(0);
}
}
MyPresenceManager.advertiseAllOnline();
mIsCallingInBackground = false;
mIsInBackground = false;
}
/**
* Update the current active activity.
* It manages the application background / foreground when it is required.
* @param activity the current activity, null if there is no more one.
*/
private void setCurrentActivity(Activity activity) {
if (VectorApp.isAppInBackground() && (null != activity)) {
Matrix matrixInstance = Matrix.getInstance(activity.getApplicationContext());
// sanity check
if (null != matrixInstance) {
matrixInstance.refreshPushRules();
}
Log.d(LOG_TAG, "The application is resumed");
// display the memory usage when the application is put iun foreground..
CommonActivityUtils.displayMemoryInformation(activity);
}
// wait 2s to check that the application is put in background
if (null != getInstance()) {
if (null == activity) {
getInstance().startActivityTransitionTimer();
} else {
getInstance().stopActivityTransitionTimer();
}
}
mCurrentActivity = activity;
}
/**
* @return the current active activity
*/
public static Activity getCurrentActivity() { return mCurrentActivity; }
/**
* Return true if the application is in background.
*/
public static boolean isAppInBackground() {
return (null == mCurrentActivity) && (null != getInstance()) && getInstance().mIsInBackground;
}
//==============================================================================================================
// Calls management.
//==============================================================================================================
/**
* The application is warned that a call is ended.
*/
public void onCallEnd() {
if (isAppInBackground() && mIsCallingInBackground) {
Log.d(LOG_TAG, "onCallEnd : Suspend the events thread because the call was ended whereas the application was in background");
suspendApp();
}
mIsCallingInBackground = false;
}
//==============================================================================================================
// cert management : store the active activities.
//==============================================================================================================
private final EventEmitter<Activity> mOnActivityDestroyedListener = new EventEmitter<>();
/**
* @return the EventEmitter list.
*/
public EventEmitter<Activity> getOnActivityDestroyedListener() {
return mOnActivityDestroyedListener;
}
//==============================================================================================================
// Media pickers : image backup
//==============================================================================================================
private static Bitmap mSavedPickerImagePreview = null;
/**
* The image taken from the medias picker is stored in a static variable because
* saving it would take too much time.
* @return the saved image from medias picker
*/
public static Bitmap getSavedPickerImagePreview(){
return mSavedPickerImagePreview;
}
/**
* Save the image taken in the medias picker
* @param aSavedCameraImagePreview the bitmap.
*/
public static void setSavedCameraImagePreview(Bitmap aSavedCameraImagePreview){
if (aSavedCameraImagePreview != mSavedPickerImagePreview) {
// force to release memory
// reported by GA
// it seems that the medias picker might be refreshed
// while leaving the activity
// recycle the bitmap trigger a rendering issue
// Canvas: trying to use a recycled bitmap...
/*if (null != mSavedPickerImagePreview) {
mSavedPickerImagePreview.recycle();
mSavedPickerImagePreview = null;
System.gc();
}*/
mSavedPickerImagePreview = aSavedCameraImagePreview;
}
}
}
| |
/*
* Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
*
* This class includes a proxy server that processes HTTP CONNECT requests,
* and tunnels the data from the client to the server, once the CONNECT
* is accepted.
* It is used by the regression test for the bug fixes: 4323990, 4413069
*/
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
import javax.net.ServerSocketFactory;
import sun.net.www.*;
public class ProxyTunnelServer extends Thread {
private static ServerSocket ss = null;
/*
* holds the registered user's username and password
* only one such entry is maintained
*/
private String userPlusPass;
// client requesting for a tunnel
private Socket clientSocket = null;
/*
* Origin server's address and port that the client
* wants to establish the tunnel for communication.
*/
private InetAddress serverInetAddr;
private int serverPort;
/*
* denote whether the proxy needs to authorize
* CONNECT requests.
*/
static boolean needAuth = false;
public ProxyTunnelServer() throws IOException {
if (ss == null) {
ss = (ServerSocket) ServerSocketFactory.getDefault().
createServerSocket(0);
}
}
public void needUserAuth(boolean auth) {
needAuth = auth;
}
/*
* register users with the proxy, by providing username and
* password. The username and password are used for authorizing the
* user when a CONNECT request is made and needAuth is set to true.
*/
public void setUserAuth(String uname, String passwd) {
userPlusPass = uname + ":" + passwd;
}
public void run() {
try {
clientSocket = ss.accept();
processRequests();
} catch (Exception e) {
System.out.println("Proxy Failed: " + e);
e.printStackTrace();
try {
ss.close();
}
catch (IOException excep) {
System.out.println("ProxyServer close error: " + excep);
excep.printStackTrace();
}
}
}
/*
* Processes the CONNECT requests, if needAuth is set to true, then
* the name and password are extracted from the Proxy-Authorization header
* of the request. They are checked against the one that is registered,
* if there is a match, connection is set in tunneling mode. If
* needAuth is set to false, Proxy-Authorization checks are not made
*/
private void processRequests() throws Exception {
InputStream in = clientSocket.getInputStream();
MessageHeader mheader = new MessageHeader(in);
String statusLine = mheader.getValue(0);
if (statusLine.startsWith("CONNECT")) {
// retrieve the host and port info from the status-line
retrieveConnectInfo(statusLine);
if (needAuth) {
String authInfo;
if ((authInfo = mheader.findValue("Proxy-Authorization"))
!= null) {
if (authenticate(authInfo)) {
needAuth = false;
System.out.println(
"Proxy: client authentication successful");
}
}
}
respondForConnect(needAuth);
// connection set to the tunneling mode
if (!needAuth) {
doTunnel();
/*
* done with tunneling, we process only one successful
* tunneling request
*/
ss.close();
} else {
// we may get another request with Proxy-Authorization set
in.close();
clientSocket.close();
restart();
}
} else {
System.out.println("proxy server: processes only "
+ "CONNECT method requests, recieved: "
+ statusLine);
}
}
private void respondForConnect(boolean needAuth) throws Exception {
OutputStream out = clientSocket.getOutputStream();
PrintWriter pout = new PrintWriter(out);
if (needAuth) {
pout.println("HTTP/1.1 407 Proxy Auth Required");
pout.println("Proxy-Authenticate: Basic realm=\"WallyWorld\"");
pout.println();
pout.flush();
out.close();
} else {
pout.println("HTTP/1.1 200 OK");
pout.println();
pout.flush();
}
}
private void restart() throws IOException {
(new Thread(this)).start();
}
/*
* note: Tunneling has to be provided in both directions, i.e
* from client->server and server->client, even if the application
* data may be unidirectional, SSL handshaking data flows in either
* direction.
*/
private void doTunnel() throws Exception {
Socket serverSocket = new Socket(serverInetAddr, serverPort);
ProxyTunnel clientToServer = new ProxyTunnel(
clientSocket, serverSocket);
ProxyTunnel serverToClient = new ProxyTunnel(
serverSocket, clientSocket);
clientToServer.start();
serverToClient.start();
System.out.println("Proxy: Started tunneling.......");
clientToServer.join();
serverToClient.join();
System.out.println("Proxy: Finished tunneling........");
clientToServer.close();
serverToClient.close();
}
/*
* This inner class provides unidirectional data flow through the sockets
* by continuously copying bytes from the input socket onto the output
* socket, until both sockets are open and EOF has not been received.
*/
class ProxyTunnel extends Thread {
Socket sockIn;
Socket sockOut;
InputStream input;
OutputStream output;
public ProxyTunnel(Socket sockIn, Socket sockOut)
throws Exception {
this.sockIn = sockIn;
this.sockOut = sockOut;
input = sockIn.getInputStream();
output = sockOut.getOutputStream();
}
public void run() {
int BUFFER_SIZE = 400;
byte[] buf = new byte[BUFFER_SIZE];
int bytesRead = 0;
int count = 0; // keep track of the amount of data transfer
try {
while ((bytesRead = input.read(buf)) >= 0) {
output.write(buf, 0, bytesRead);
output.flush();
count += bytesRead;
}
} catch (IOException e) {
/*
* The peer end has closed the connection
* we will close the tunnel
*/
close();
}
}
public void close() {
try {
if (!sockIn.isClosed())
sockIn.close();
if (!sockOut.isClosed())
sockOut.close();
} catch (IOException ignored) { }
}
}
/*
***************************************************************
* helper methods follow
***************************************************************
*/
/*
* This method retrieves the hostname and port of the destination
* that the connect request wants to establish a tunnel for
* communication.
* The input, connectStr is of the form:
* CONNECT server-name:server-port HTTP/1.x
*/
private void retrieveConnectInfo(String connectStr) throws Exception {
int starti;
int endi;
String connectInfo;
String serverName = null;
try {
starti = connectStr.indexOf(' ');
endi = connectStr.lastIndexOf(' ');
connectInfo = connectStr.substring(starti+1, endi).trim();
// retrieve server name and port
endi = connectInfo.indexOf(':');
serverName = connectInfo.substring(0, endi);
serverPort = Integer.parseInt(connectInfo.substring(endi+1));
} catch (Exception e) {
throw new IOException("Proxy recieved a request: "
+ connectStr);
}
serverInetAddr = InetAddress.getByName(serverName);
}
public int getPort() {
return ss.getLocalPort();
}
/*
* do "basic" authentication, authInfo is of the form:
* Basic <encoded username":"password>
* reference RFC 2617
*/
private boolean authenticate(String authInfo) throws IOException {
boolean matched = false;
try {
authInfo.trim();
int ind = authInfo.indexOf(' ');
String recvdUserPlusPass = authInfo.substring(ind + 1).trim();
// extract encoded (username:passwd
if (userPlusPass.equals(
new String(
(new sun.misc.BASE64Decoder()).
decodeBuffer(recvdUserPlusPass)
))) {
matched = true;
}
} catch (Exception e) {
throw new IOException(
"Proxy received invalid Proxy-Authorization value: "
+ authInfo);
}
return matched;
}
}
| |
package gov.nist.registry.ws;
import gov.nist.registry.common2.MetadataTypes;
import gov.nist.registry.common2.exception.MetadataException;
import gov.nist.registry.common2.exception.MetadataValidationException;
import gov.nist.registry.common2.exception.SchemaValidationException;
import gov.nist.registry.common2.exception.XDSRegistryOutOfResourcesException;
import gov.nist.registry.common2.exception.XMLParserException;
import gov.nist.registry.common2.exception.XdsException;
import gov.nist.registry.common2.exception.XdsFormatException;
import gov.nist.registry.common2.exception.XdsInternalException;
import gov.nist.registry.common2.exception.XdsResultNotSinglePatientException;
import gov.nist.registry.common2.exception.XdsValidationException;
import gov.nist.registry.common2.registry.AdhocQueryResponse;
import gov.nist.registry.common2.registry.BackendRegistry;
import gov.nist.registry.common2.registry.BasicQuery;
import gov.nist.registry.common2.registry.Metadata;
import gov.nist.registry.common2.registry.MetadataParser;
import gov.nist.registry.common2.registry.MetadataSupport;
import gov.nist.registry.common2.registry.RegistryUtility;
import gov.nist.registry.common2.registry.Response;
import gov.nist.registry.common2.registry.XdsCommon;
import gov.nist.registry.common2.registry.storedquery.ParamParser;
import gov.nist.registry.common2.registry.storedquery.SqParams;
import gov.nist.registry.ws.config.Registry;
import gov.nist.registry.ws.sq.StoredQuery;
import gov.nist.registry.ws.sq.StoredQueryFactory;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openhealthtools.common.ihe.IheActor;
import org.openhealthtools.common.ws.server.IheHTTPServer;
import org.openhealthtools.openexchange.actorconfig.net.IConnectionDescription;
import org.openhealthtools.openexchange.audit.ActiveParticipant;
import org.openhealthtools.openexchange.audit.IheAuditTrail;
import org.openhealthtools.openexchange.audit.ParticipantObject;
import org.openhealthtools.openexchange.config.PropertyFacade;
import org.openhealthtools.openxds.log.LogMessage;
import org.openhealthtools.openxds.log.LoggerException;
import org.openhealthtools.openxua.api.XuaException;
public class AdhocQueryRequest extends XdsCommon {
MessageContext messageContext;
String service_name = "";
boolean is_secure;
IConnectionDescription connection = null;
/* The IHE Audit Trail for this actor. */
private IheAuditTrail auditLog = null;
private final static Log logger = LogFactory.getLog(AdhocQueryRequest.class);
public AdhocQueryRequest(LogMessage log_message, MessageContext messageContext, boolean is_secure, short xds_version) {
this.log_message = log_message;
this.messageContext = messageContext;
this.is_secure = is_secure;
this.xds_version = xds_version;
IheHTTPServer httpServer = (IheHTTPServer)messageContext.getTransportIn().getReceiver();
try {
IheActor actor = httpServer.getIheActor();
if (actor == null) {
throw new XdsInternalException("Cannot find XdsRepository actor configuration.");
}
connection = actor.getConnection();
if (connection == null) {
throw new XdsInternalException("Cannot find Server connection configuration.");
}
auditLog = actor.getAuditTrail();
} catch (XdsInternalException e) {
logger.fatal("Internal Error " + e.getMessage());
}
}
public void setServiceName(String service_name) {
this.service_name = service_name;
}
public OMElement adhocQueryRequest(OMElement ahqr) {
if (logger.isDebugEnabled()) {
logger.debug("Request from the XDS Consumer:");
logger.debug(ahqr.toString());
}
ahqr.build();
OMNamespace ns = ahqr.getNamespace();
String ns_uri = ns.getNamespaceURI();
transaction_type = SQ_transaction;
try {
if (ns_uri.equals(MetadataSupport.ebQns3.getNamespaceURI())) {
init(new AdhocQueryResponse(Response.version_3), xds_version, messageContext);
} else if (ns_uri.equals(MetadataSupport.ebQns2.getNamespaceURI())) {
init(new AdhocQueryResponse(Response.version_2), xds_version, messageContext);
} else {
init(new AdhocQueryResponse(Response.version_3), xds_version, messageContext);
response.add_error("XDSRegistryError", "Invalid XML namespace on AdhocQueryRequest: " + ns_uri, "AdhocQueryRequest.java", log_message);
return response.getResponse();
}
} catch (XdsInternalException e) {
logger.fatal("Internal Error initializing AdhocQueryRequest transaction: " + e.getMessage());
return null;
}
// Call X-Service Provider Actor to validate X-User Assertion with X-Assertion Provider
try {
boolean validateUserAssertion = PropertyFacade.getBoolean("validate.userassertion");
if(validateUserAssertion){
SoapHeader header = new SoapHeader(messageContext);
boolean status = validateAssertion(header);
if (!status)
throw new XdsException("Invalid Identity Assertion");
}
AdhocQueryRequestInternal(ahqr);
}
catch (XdsResultNotSinglePatientException e) {
response.add_error("XDSResultNotSinglePatient", e.getMessage(), RegistryUtility.exception_trace(e), log_message);
}
catch (XdsValidationException e) {
response.add_error("XDSRegistryError", "Validation Error: " + e.getMessage(), RegistryUtility.exception_trace(e), log_message);
}
catch (XdsFormatException e) {
response.add_error("XDSRegistryError", "SOAP Format Error: " + e.getMessage(), RegistryUtility.exception_trace(e), log_message);
}
catch (XDSRegistryOutOfResourcesException e) {
// query return limitation
response.add_error("XDSRegistryOutOfResources", e.getMessage(), RegistryUtility.exception_trace(e), log_message);
}
catch (SchemaValidationException e) {
response.add_error("XDSRegistryMetadataError", "SchemaValidationException: " + e.getMessage(), RegistryUtility.exception_trace(e), log_message);
}
catch (XdsInternalException e) {
response.add_error("XDSRegistryError", "Internal Error: " + e.getMessage(), RegistryUtility.exception_trace(e), log_message);
logger.fatal(logger_exception_details(e));
}
catch (MetadataValidationException e) {
response.add_error("XDSRegistryError", "Metadata Error: " + e.getMessage(), RegistryUtility.exception_trace(e), log_message);
}
catch (SqlRepairException e) {
response.add_error("XDSRegistryError", "Could not decode SQL: " + e.getMessage(), RegistryUtility.exception_trace(e), log_message);
logger.warn(logger_exception_details(e));
}
catch (MetadataException e) {
response.add_error("XDSRegistryError", "Metadata error: " + e.getMessage(), RegistryUtility.exception_trace(e), log_message);
}
catch (LoggerException e) {
response.add_error("XDSRegistryError", "Logger error: " + e.getMessage(), RegistryUtility.exception_trace(e), log_message);
logger.fatal(logger_exception_details(e));
}
catch (SQLException e) {
response.add_error("XDSRegistryError", "SQL error: " + e.getMessage(), RegistryUtility.exception_trace(e), log_message);
logger.fatal(logger_exception_details(e));
}
catch (XdsException e) {
response.add_error("XDSRegistryError", "XDS Error: " + e.getMessage(), RegistryUtility.exception_trace(e), log_message);
logger.warn(logger_exception_details(e));
}
catch (XuaException e) {
response.add_error("XDSRegistryError", "XUA Error" + e.getMessage(), RegistryUtility.exception_details(e), log_message);
}
catch (Exception e) {
response.add_error("General Exception", "Internal Error: " + e.getMessage(), RegistryUtility.exception_trace(e), log_message);
logger.fatal(logger_exception_details(e));
}
this.log_response();
OMElement res = null;
try {
res = response.getResponse();
if (logger.isDebugEnabled()) {
logger.debug("Response from the Registry");
logger.debug(res.toString());
}
} catch (XdsInternalException e) {
}
return res;
}
public boolean isStoredQuery(OMElement ahqr) {
for (Iterator it=ahqr.getChildElements(); it.hasNext(); ) {
OMElement ele = (OMElement) it.next();
String ele_name = ele.getLocalName();
if (ele_name.equals("AdhocQuery"))
return true;
}
return false;
}
void AdhocQueryRequestInternal(OMElement ahqr)
throws SQLException, XdsException, LoggerException, XDSRegistryOutOfResourcesException, AxisFault,
SqlRepairException, XdsValidationException {
boolean found_query = false;
for (Iterator it=ahqr.getChildElements(); it.hasNext(); ) {
OMElement ele = (OMElement) it.next();
String ele_name = ele.getLocalName();
if (ele_name.equals("SQLQuery")) {
log_message.setTestMessage("SQL");
RegistryUtility.schema_validate_local(ahqr, MetadataTypes.METADATA_TYPE_Q);
found_query=true;
OMElement result = sql_query(ahqr);
// move result elements to response
if (result != null) {
Metadata m = new Metadata(result, false /* parse */, true /* find_wrapper */);
OMElement sqr = m.getWrapper();
if (sqr != null) {
for (Iterator it2=sqr.getChildElements(); it2.hasNext(); ) {
OMElement e = (OMElement) it2.next();
((AdhocQueryResponse)response).addQueryResults(e);
}
}
}
} else if (ele_name.equals("AdhocQuery")) {
log_message.setTestMessage(service_name);
RegistryUtility.schema_validate_local(ahqr, MetadataTypes.METADATA_TYPE_SQ);
found_query = true;
Metadata results = stored_query(ahqr);
//response.query_results = results;
if (results != null)
((AdhocQueryResponse)response).addQueryResults(results.getAllObjects());
}
}
if (!found_query)
response.add_error("XDSRegistryError", "Only SQLQuery and AdhocQuery accepted", "AdhocQueryRequest.java", log_message);
this.log_response();
}
public String getStoredQueryId(OMElement ahqr) {
OMElement adhoc_query = MetadataSupport.firstChildWithLocalName(ahqr, "AdhocQuery") ;
if (adhoc_query == null) return null;
return adhoc_query.getAttributeValue(MetadataSupport.id_qname);
}
public String getHome(OMElement ahqr) throws XdsInternalException, MetadataException, XdsException, LoggerException {
OMElement adhocQuery = MetadataSupport.firstChildWithLocalName(ahqr, "AdhocQuery");
return adhocQuery.getAttributeValue(MetadataSupport.home_qname);
// return (String) new StoredQueryFactory(ahqr).getParm("$homeCommunityId");
// OMElement ahquery = MetadataSupport.firstChildWithLocalName(ahqr, "AdhocQuery");
// if (ahquery == null) return null;
// return ahquery.getAttributeValue(MetadataSupport.id_qname);
}
// Initiating Gateway shall specify the homeCommunityId attribute in all Cross-Community
// Queries which do not contain a patient identifier.
public boolean requiresHomeInXGQ(OMElement ahqr) {
boolean requires = true;
String query_id = getStoredQueryId(ahqr);
if (query_id == null) requires = false;
if (query_id.equals(MetadataSupport.SQ_FindDocuments)) requires = false;
if (query_id.equals(MetadataSupport.SQ_FindFolders)) requires = false;
if (query_id.equals(MetadataSupport.SQ_FindSubmissionSets)) requires = false;
if (query_id.equals(MetadataSupport.SQ_GetAll)) requires = false;
logger.info("query " + query_id + " requires home = " + requires);
return requires;
}
public boolean isMPQ(OMElement ahqr) {
String query_id = getStoredQueryId(ahqr);
if (query_id == null) return false;
if ("urn:uuid:3d1bdb10-39a2-11de-89c2-2f44d94eaa9f".equals(query_id)) return true;
if ("urn:uuid:50d3f5ac-39a2-11de-a1ca-b366239e58df".equals(query_id)) return true;
return false;
}
@SuppressWarnings("unchecked")
Metadata stored_query(OMElement ahqr)
throws XdsException, LoggerException, XDSRegistryOutOfResourcesException, XdsValidationException {
boolean isMPQ = true;
boolean isSQ = false;
// new StoredQueryRequestSoapValidator(xds_version, messageContext).runWithException();
//try {
// Registry holds the configuration for this implementation and selected
// the correct Stored Query implementation by returning a factory object
StoredQueryFactory fact = Registry.getStoredQueryFactory(ahqr, response, log_message);
fact.setServiceName(service_name);
fact.setIsSecure(is_secure);
StoredQuery sq = fact.getImpl();
Metadata m = sq.run();
//Filter metadata
boolean filteringMetadataEnabled = PropertyFacade.getBoolean("filter.metadata");
if(filteringMetadataEnabled){
SoapHeader header = new SoapHeader(messageContext);
try {
m = filter(m, header);
} catch (Exception e) {
throw new XdsException("Exception while filtering metadata", e);
}
}
if (!isMPQ(ahqr)) {
isMPQ = false;
isSQ = true;
if ( !m.isPatientIdConsistent() )
throw new XdsResultNotSinglePatientException("More than one Patient ID in Stored Query result");
}
auditLog(ahqr, isSQ, fact.getQueryId(), isMPQ, m);
return m;
// }
// catch (Exception e) {
// response.add_error("XDSRegistryError", ExceptionUtil.exception_details(e), "StoredQueryFactory.java", log_message);
// return null;
//
// }
}
private OMElement sql_query(OMElement ahqr)
throws XdsInternalException, SchemaValidationException, LoggerException, SqlRepairException, MetadataException, MetadataValidationException, XMLParserException {
// validate against schema - throws exception on error
RegistryUtility.schema_validate_local(ahqr, MetadataTypes.METADATA_TYPE_Q);
logger.debug("sql_query");
// check and repair SQL
boolean isleafClass = false;
SqlRepair sr = new SqlRepair();
String return_type = sr.returnType(ahqr);
if (return_type.equals("LeafClass"))
isleafClass = true;
try {
sr.repair(ahqr);
} catch (SqlRepairException e) {
response.add_error("XDSSqlError", e.getMessage(), RegistryUtility.exception_details(e), log_message);
return null;
} catch (XdsInternalException e) {
response.add_error("XDSRegistryError", e.getMessage(), RegistryUtility.exception_details(e), log_message);
return null;
}
if (log_message != null)
log_message.addOtherParam("SQL", sr.get_query_text(ahqr));
if (logger.isDebugEnabled()) {
logger.debug("SQLQuery:\n" + sr.get_query_text(ahqr));
}
//return backend_query(ahqr);
BackendRegistry br = new BackendRegistry(response, log_message);
OMElement results = br.query(ahqr.toString(), isleafClass);
Metadata metadata = MetadataParser.parseNonSubmission(results);
auditLog(ahqr, false, null, false, null);
if (is_secure) {
BasicQuery bq = new BasicQuery();
bq.secure_URI(metadata);
}
// Problem here - ebxmlrr returns wrong namespaces. The following fixes
results = metadata.fixSQLQueryResponse(return_type);
return results;
}
/**
* Audit Logging of Document Query messages.
* @throws XdsInternalException, MetadataException
*
*/
private void auditLog(OMElement aqr, boolean isStoredQuery, String id, boolean isMPQ, Metadata m) throws XdsInternalException, XdsInternalException, MetadataException {
if (auditLog == null)
return;
String replyto = getMessageContext().getReplyTo().getAddress();
String remoteIP = (String)getMessageContext().getProperty(MessageContext.REMOTE_ADDR);
String localIP = (String)getMessageContext().getProperty(MessageContext.TRANSPORT_ADDR);
ActiveParticipant source = new ActiveParticipant();
source.setUserId(replyto);
source.setAccessPointId(remoteIP);
//TODO: Needs to be improved
String userid = "http://"+connection.getHostname()+":"+connection.getPort()+"/axis2/services/xdsregistryb";
ActiveParticipant dest = new ActiveParticipant();
dest.setUserId(userid);
dest.setAccessPointId(localIP);
//Patient Info
List<ParticipantObject> patientObjs = new ArrayList<ParticipantObject>();
ParticipantObject patientObj = null;
//Query Info
if (isStoredQuery) {
ParamParser parser = new ParamParser();
SqParams params = parser.parse(aqr);
String patientId = params.getStringParm("$XDSDocumentEntryPatientId");
if(patientId != null) patientObj = new ParticipantObject("PatientIdentifier", patientId);
patientObjs.add(patientObj);
}
if(isMPQ){
List<String> patientIds = m.getPatientIds();
for(String patientId :patientIds){
patientObj = new ParticipantObject("PatientIdentifier", patientId);
patientObjs.add(patientObj);
}
}
ParticipantObject queryObj = new ParticipantObject();
queryObj.setQuery(aqr.toString());
if(isStoredQuery || isMPQ)
queryObj.setId(id);
//Finally Log it.
auditLog.logRegistryQuery(source, dest, patientObjs, queryObj, isStoredQuery, isMPQ);
}
}
| |
package com.google.android.vending.expansion.downloader;
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.google.android.vending.expansion.downloader.impl.DownloaderService;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
/**
* This class binds the service API to your application client. It contains the IDownloaderClient proxy,
* which is used to call functions in your client as well as the Stub, which is used to call functions
* in the client implementation of IDownloaderClient.
*
* <p>The IPC is implemented using an Android Messenger and a service Binder. The connect method
* should be called whenever the client wants to bind to the service. It opens up a service connection
* that ends up calling the onServiceConnected client API that passes the service messenger
* in. If the client wants to be notified by the service, it is responsible for then passing its
* messenger to the service in a separate call.
*
* <p>Critical methods are {@link #startDownloadServiceIfRequired} and {@link #CreateStub}.
*
* <p>When your application first starts, you should first check whether your app's expansion files are
* already on the device. If not, you should then call {@link #startDownloadServiceIfRequired}, which
* starts your {@link impl.DownloaderService} to download the expansion files if necessary. The method
* returns a value indicating whether download is required or not.
*
* <p>If a download is required, {@link #startDownloadServiceIfRequired} begins the download through
* the specified service and you should then call {@link #CreateStub} to instantiate a member {@link
* IStub} object that you need in order to receive calls through your {@link IDownloaderClient}
* interface.
*/
public class DownloaderClientMarshaller {
public static final int MSG_ONDOWNLOADSTATE_CHANGED = 10;
public static final int MSG_ONDOWNLOADPROGRESS = 11;
public static final int MSG_ONSERVICECONNECTED = 12;
public static final String PARAM_NEW_STATE = "newState";
public static final String PARAM_PROGRESS = "progress";
public static final String PARAM_MESSENGER = DownloaderService.EXTRA_MESSAGE_HANDLER;
public static final int NO_DOWNLOAD_REQUIRED = DownloaderService.NO_DOWNLOAD_REQUIRED;
public static final int LVL_CHECK_REQUIRED = DownloaderService.LVL_CHECK_REQUIRED;
public static final int DOWNLOAD_REQUIRED = DownloaderService.DOWNLOAD_REQUIRED;
private static class Proxy implements IDownloaderClient {
private Messenger mServiceMessenger;
@Override
public void onDownloadStateChanged(int newState) {
Bundle params = new Bundle(1);
params.putInt(PARAM_NEW_STATE, newState);
send(MSG_ONDOWNLOADSTATE_CHANGED, params);
}
@Override
public void onDownloadProgress(DownloadProgressInfo progress) {
Bundle params = new Bundle(1);
params.putParcelable(PARAM_PROGRESS, progress);
send(MSG_ONDOWNLOADPROGRESS, params);
}
private void send(int method, Bundle params) {
Message m = Message.obtain(null, method);
m.setData(params);
try {
mServiceMessenger.send(m);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public Proxy(Messenger msg) {
mServiceMessenger = msg;
}
@Override
public void onServiceConnected(Messenger m) {
/**
* This is never called through the proxy.
*/
}
}
private static class Stub implements IStub {
private IDownloaderClient mItf = null;
private Class<?> mDownloaderServiceClass;
private boolean mBound;
private Messenger mServiceMessenger;
private Context mContext;
/**
* Target we publish for clients to send messages to IncomingHandler.
*/
final Messenger mMessenger = new Messenger(new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_ONDOWNLOADPROGRESS:
Bundle bun = msg.getData();
if ( null != mContext ) {
bun.setClassLoader(mContext.getClassLoader());
DownloadProgressInfo dpi = (DownloadProgressInfo) msg.getData()
.getParcelable(PARAM_PROGRESS);
mItf.onDownloadProgress(dpi);
}
break;
case MSG_ONDOWNLOADSTATE_CHANGED:
mItf.onDownloadStateChanged(msg.getData().getInt(PARAM_NEW_STATE));
break;
case MSG_ONSERVICECONNECTED:
mItf.onServiceConnected(
(Messenger) msg.getData().getParcelable(PARAM_MESSENGER));
break;
}
}
});
public Stub(IDownloaderClient itf, Class<?> downloaderService) {
mItf = itf;
mDownloaderServiceClass = downloaderService;
}
/**
* Class for interacting with the main interface of the service.
*/
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the object we can use to
// interact with the service. We are communicating with the
// service using a Messenger, so here we get a client-side
// representation of that from the raw IBinder object.
mServiceMessenger = new Messenger(service);
mItf.onServiceConnected(
mServiceMessenger);
mBound = true;
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
mServiceMessenger = null;
mBound = false;
}
};
@Override
public void connect(Context c) {
mContext = c;
Intent bindIntent = new Intent(c, mDownloaderServiceClass);
bindIntent.putExtra(PARAM_MESSENGER, mMessenger);
if ( !c.bindService(bindIntent, mConnection, Context.BIND_DEBUG_UNBIND) ) {
if ( Constants.LOGVV ) {
Log.d(Constants.TAG, "Service Unbound");
}
}
}
@Override
public void disconnect(Context c) {
if (mBound) {
c.unbindService(mConnection);
mBound = false;
}
mContext = null;
}
@Override
public Messenger getMessenger() {
return mMessenger;
}
}
/**
* Returns a proxy that will marshal calls to IDownloaderClient methods
*
* @param msg
* @return
*/
public static IDownloaderClient CreateProxy(Messenger msg) {
return new Proxy(msg);
}
/**
* Returns a stub object that, when connected, will listen for marshaled
* {@link IDownloaderClient} methods and translate them into calls to the supplied
* interface.
*
* @param itf An implementation of IDownloaderClient that will be called
* when remote method calls are unmarshaled.
* @param downloaderService The class for your implementation of {@link
* impl.DownloaderService}.
* @return The {@link IStub} that allows you to connect to the service such that
* your {@link IDownloaderClient} receives status updates.
*/
public static IStub CreateStub(IDownloaderClient itf, Class<?> downloaderService) {
return new Stub(itf, downloaderService);
}
/**
* Starts the download if necessary. This function starts a flow that does `
* many things. 1) Checks to see if the APK version has been checked and
* the metadata database updated 2) If the APK version does not match,
* checks the new LVL status to see if a new download is required 3) If the
* APK version does match, then checks to see if the download(s) have been
* completed 4) If the downloads have been completed, returns
* NO_DOWNLOAD_REQUIRED The idea is that this can be called during the
* startup of an application to quickly ascertain if the application needs
* to wait to hear about any updated APK expansion files. Note that this does
* mean that the application MUST be run for the first time with a network
* connection, even if Market delivers all of the files.
*
* @param context Your application Context.
* @param notificationClient A PendingIntent to start the Activity in your application
* that shows the download progress and which will also start the application when download
* completes.
* @param serviceClass the class of your {@link imp.DownloaderService} implementation
* @return whether the service was started and the reason for starting the service.
* Either {@link #NO_DOWNLOAD_REQUIRED}, {@link #LVL_CHECK_REQUIRED}, or {@link
* #DOWNLOAD_REQUIRED}.
* @throws NameNotFoundException
*/
public static int startDownloadServiceIfRequired(Context context, PendingIntent notificationClient,
Class<?> serviceClass)
throws NameNotFoundException {
return DownloaderService.startDownloadServiceIfRequired(context, notificationClient,
serviceClass);
}
/**
* This version assumes that the intent contains the pending intent as a parameter. This
* is used for responding to alarms.
* <p>The pending intent must be in an extra with the key {@link
* impl.DownloaderService#EXTRA_PENDING_INTENT}.
*
* @param context
* @param notificationClient
* @param serviceClass the class of the service to start
* @return
* @throws NameNotFoundException
*/
public static int startDownloadServiceIfRequired(Context context, Intent notificationClient,
Class<?> serviceClass)
throws NameNotFoundException {
return DownloaderService.startDownloadServiceIfRequired(context, notificationClient,
serviceClass);
}
}
| |
/*
* 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.catalina.ant;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import org.apache.tomcat.util.codec.binary.Base64;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
/**
* Abstract base class for Ant tasks that interact with the
* <em>Manager</em> web application for dynamically deploying and
* undeploying applications. These tasks require Ant 1.4 or later.
*
* @author Craig R. McClanahan
* @since 4.1
*/
public abstract class AbstractCatalinaTask extends BaseRedirectorHelperTask {
// ----------------------------------------------------- Instance Variables
/**
* manager webapp's encoding.
*/
private static final String CHARSET = "utf-8";
// ------------------------------------------------------------- Properties
/**
* The charset used during URL encoding.
*/
protected String charset = "ISO-8859-1";
public String getCharset() {
return (this.charset);
}
public void setCharset(String charset) {
this.charset = charset;
}
/**
* The login password for the <code>Manager</code> application.
*/
protected String password = null;
public String getPassword() {
return (this.password);
}
public void setPassword(String password) {
this.password = password;
}
/**
* The URL of the <code>Manager</code> application to be used.
*/
protected String url = "http://localhost:8080/manager/text";
public String getUrl() {
return (this.url);
}
public void setUrl(String url) {
this.url = url;
}
/**
* The login username for the <code>Manager</code> application.
*/
protected String username = null;
public String getUsername() {
return (this.username);
}
public void setUsername(String username) {
this.username = username;
}
/**
* If set to true - ignore the constraint of the first line of the response
* message that must be "OK -".
* <p>
* When this attribute is set to {@code false} (the default), the first line
* of server response is expected to start with "OK -". If it does not
* then the task is considered as failed and the first line is treated
* as an error message.
* <p>
* When this attribute is set to {@code true}, the first line of the
* response is treated like any other, regardless of its text.
*/
protected boolean ignoreResponseConstraint = false;
public boolean isIgnoreResponseConstraint() {
return ignoreResponseConstraint;
}
public void setIgnoreResponseConstraint(boolean ignoreResponseConstraint) {
this.ignoreResponseConstraint = ignoreResponseConstraint;
}
// --------------------------------------------------------- Public Methods
/**
* Execute the specified command. This logic only performs the common
* attribute validation required by all subclasses; it does not perform
* any functional logic directly.
*
* @exception BuildException if a validation error occurs
*/
@Override
public void execute() throws BuildException {
if ((username == null) || (password == null) || (url == null)) {
throw new BuildException
("Must specify all of 'username', 'password', and 'url'");
}
}
// ------------------------------------------------------ Protected Methods
/**
* Execute the specified command, based on the configured properties.
*
* @param command Command to be executed
*
* @exception BuildException if an error occurs
*/
public void execute(String command) throws BuildException {
execute(command, null, null, -1);
}
/**
* Execute the specified command, based on the configured properties.
* The input stream will be closed upon completion of this task, whether
* it was executed successfully or not.
*
* @param command Command to be executed
* @param istream InputStream to include in an HTTP PUT, if any
* @param contentType Content type to specify for the input, if any
* @param contentLength Content length to specify for the input, if any
*
* @exception BuildException if an error occurs
*/
public void execute(String command, InputStream istream,
String contentType, int contentLength)
throws BuildException {
URLConnection conn = null;
InputStreamReader reader = null;
try {
// Create a connection for this command
conn = (new URL(url + command)).openConnection();
HttpURLConnection hconn = (HttpURLConnection) conn;
// Set up standard connection characteristics
hconn.setAllowUserInteraction(false);
hconn.setDoInput(true);
hconn.setUseCaches(false);
if (istream != null) {
hconn.setDoOutput(true);
hconn.setRequestMethod("PUT");
if (contentType != null) {
hconn.setRequestProperty("Content-Type", contentType);
}
if (contentLength >= 0) {
hconn.setRequestProperty("Content-Length",
"" + contentLength);
hconn.setFixedLengthStreamingMode(contentLength);
}
} else {
hconn.setDoOutput(false);
hconn.setRequestMethod("GET");
}
hconn.setRequestProperty("User-Agent",
"Catalina-Ant-Task/1.0");
// Set up an authorization header with our credentials
String input = username + ":" + password;
String output = Base64.encodeBase64String(
input.getBytes(StandardCharsets.ISO_8859_1));
hconn.setRequestProperty("Authorization",
"Basic " + output);
// Establish the connection with the server
hconn.connect();
// Send the request data (if any)
if (istream != null) {
BufferedOutputStream ostream =
new BufferedOutputStream(hconn.getOutputStream(), 1024);
byte buffer[] = new byte[1024];
while (true) {
int n = istream.read(buffer);
if (n < 0) {
break;
}
ostream.write(buffer, 0, n);
}
ostream.flush();
ostream.close();
istream.close();
}
// Process the response message
reader = new InputStreamReader(hconn.getInputStream(), CHARSET);
StringBuilder buff = new StringBuilder();
String error = null;
int msgPriority = Project.MSG_INFO;
boolean first = true;
while (true) {
int ch = reader.read();
if (ch < 0) {
break;
} else if ((ch == '\r') || (ch == '\n')) {
// in Win \r\n would cause handleOutput() to be called
// twice, the second time with an empty string,
// producing blank lines
if (buff.length() > 0) {
String line = buff.toString();
buff.setLength(0);
if (!ignoreResponseConstraint && first) {
if (!line.startsWith("OK -")) {
error = line;
msgPriority = Project.MSG_ERR;
}
first = false;
}
handleOutput(line, msgPriority);
}
} else {
buff.append((char) ch);
}
}
if (buff.length() > 0) {
handleOutput(buff.toString(), msgPriority);
}
if (error != null && isFailOnError()) {
// exception should be thrown only if failOnError == true
// or error line will be logged twice
throw new BuildException(error);
}
} catch (Exception e) {
if (isFailOnError()) {
throw new BuildException(e);
} else {
handleErrorOutput(e.getMessage());
}
} finally {
closeRedirector();
if (reader != null) {
try {
reader.close();
} catch (IOException ioe) {
// Ignore
}
reader = null;
}
if (istream != null) {
try {
istream.close();
} catch (IOException ioe) {
// Ignore
}
}
}
}
}
| |
/*
* $Id$
*
Copyright (c) 2000-2007 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.mail;
import java.io.*;
import java.net.*;
import org.lockss.app.*;
import org.lockss.util.*;
import org.lockss.util.PriorityQueue;
import org.lockss.config.Configuration;
import org.lockss.daemon.*;
/** SmtpMailService is a MailService that sends mail directly over an smtp
* connection, queuing them in memory and retrying each until it is
* successfully sent */
public class SmtpMailService
extends BaseLockssManager implements MailService, ConfigurableManager {
protected static Logger log = Logger.getLogger("Mail");
static final String PRIORITY_PARAM_MAILQ = "MailQueue";
static final int PRIORITY_DEFAULT_MAILQ = Thread.NORM_PRIORITY /*+ 1*/;
/** Outgoing SMTP relay */
public static final String PARAM_SMTPHOST = PREFIX + "smtphost";
public static final String PARAM_SMTPPORT = PREFIX + "smtpport";
public static final int DEFAULT_SMTPPORT = 25;
/** Interval at which to retry sending messages after retryable error */
public static final String PARAM_RETRY_INTERVAL = PREFIX + "retryInterval";
public static final long DEFAULT_RETRY_INTERVAL = Constants.HOUR;
/** Max times to retry a message before giving up */
public static final String PARAM_MAX_RETRIES = PREFIX + "maxRetries";
public static final int DEFAULT_MAX_RETRIES = 3;
/** Max length of message queue; no new messages accepted if exceeded */
public static final String PARAM_MAX_QUEUELEN = PREFIX + "maxQueueLen";
public static final int DEFAULT_MAX_QUEUELEN = 1000;
/** Max rate at which to send mail; messages remain in queue longer if
* exceeded */
public static final String PARAM_MAX_MAIL_RATE = PREFIX + "maxMailRate";
public static final String DEFAULT_MAX_MAIL_RATE = "10/1h";
private boolean enabled = DEFAULT_ENABLED;
private String smtpHost = null;
private int smtpPort = DEFAULT_SMTPPORT;
private String localHostName;
protected PriorityQueue queue = new PriorityQueue();
private MailThread mailThread;
private RateLimiter rateLimiter;
private long retryInterval;
private int maxRetries;
private int maxQueuelen = DEFAULT_MAX_QUEUELEN;
public void startService() {
super.startService();
}
public synchronized void stopService() {
stopThread();
super.stopService();
}
public synchronized void setConfig(Configuration config,
Configuration prevConfig,
Configuration.Differences changedKeys) {
// Unconditional: not under PREFIX
localHostName = PlatformUtil.getLocalHostname();
// Don't rely on change to enable by default
boolean doEnable = config.getBoolean(PARAM_ENABLED, DEFAULT_ENABLED);
if (changedKeys.contains(PREFIX)) {
maxRetries = config.getInt(PARAM_MAX_RETRIES, DEFAULT_MAX_RETRIES);
maxQueuelen = config.getInt(PARAM_MAX_QUEUELEN, DEFAULT_MAX_QUEUELEN);
retryInterval = config.getTimeInterval(PARAM_RETRY_INTERVAL,
DEFAULT_RETRY_INTERVAL);
rateLimiter =
RateLimiter.getConfiguredRateLimiter(config, rateLimiter,
PARAM_MAX_MAIL_RATE,
DEFAULT_MAX_MAIL_RATE);
smtpHost = config.get(PARAM_SMTPHOST);
smtpPort = config.getInt(PARAM_SMTPPORT, DEFAULT_SMTPPORT);
}
if (doEnable != enabled) {
if (doEnable) {
if (smtpHost==null) {
String parameter = PARAM_SMTPHOST;
log.error("Couldn't determine "+parameter+
" from Configuration. Disabling emails");
enabled = false;
return;
}
if (!queue.isEmpty()) {
ensureThreadRunning();
}
enabled = doEnable;
}
}
}
public boolean sendMail(String sender, String recipient, MailMessage msg) {
if (queue.size() >= maxQueuelen) {
log.warning("Mail queue full, discarding message.");
return false;
}
queue.put(new Req(sender, recipient, msg));
ensureThreadRunning();
return true;
}
void processReq(Req req) {
boolean ok = true;
int res = sendReq(req);
log.debug2("Sent: " + res);
switch (res) {
case SmtpClient.RESULT_RETRY:
if (++req.retryCount > maxRetries) {
log.warning("Req deleted due to too many retries: " +
req.retryCount);
queue.remove(req);
} else {
if (log.isDebug3()) {
log.debug3("Requeueing " + req);
}
req.nextRetry.expireIn(retryInterval);
queue.sort();
}
break;
case SmtpClient.RESULT_FAIL:
// XXX need better log here - client should record smtp
// transaction
log.warning("Send failed");
// fall through
default:
ok = false;
case SmtpClient.RESULT_OK:
req.msg.delete(ok);
queue.remove(req);
}
}
int sendReq(Req req) {
try {
SmtpClient client = makeClient();
int res = client.sendMsg(req.sender, req.recipient, req.msg);
if (log.isDebug3()) {
log.debug3("Client returned " + res);
}
return res;
} catch (Exception e) {
log.error("Client threw", e);
return SmtpClient.RESULT_RETRY;
}
}
SmtpClient makeClient() throws IOException {
log.debug3("makeClient(" + smtpHost + ", " + smtpPort + ")");
return new SmtpClient(smtpHost, smtpPort);
}
static class Req implements Comparable {
String recipient;
String sender;
MailMessage msg;
Deadline nextRetry;
int retryCount = 0;
Req(String sender, String recipient, MailMessage msg) {
this.recipient = recipient;
this.sender = sender;
this.msg = msg;
nextRetry = Deadline.in(0);
}
public int compareTo(Object o) {
return nextRetry.compareTo(((Req)o).nextRetry);
}
}
// Queue runner
BinarySemaphore threadWait = new BinarySemaphore();
synchronized void ensureThreadRunning() {
if (mailThread == null) {
log.info("Starting thread");
mailThread = new MailThread("MailQ");
mailThread.start();
mailThread.waitRunning();
} else {
threadWait.give();
}
}
public void stopThread() {
if (mailThread != null) {
log.info("Stopping thread");
mailThread.stopMail();
mailThread = null;
}
}
private class MailThread extends LockssThread {
private volatile boolean goOn = true;
private MailThread(String name) {
super(name);
}
public void lockssRun() {
triggerWDogOnExit(true);
setPriority(PRIORITY_PARAM_MAILQ, PRIORITY_DEFAULT_MAILQ);
nowRunning();
while (goOn) {
try {
Req req = (Req)queue.peekWait(Deadline.in(10 * Constants.MINUTE));
if (req != null) {
Deadline when = req.nextRetry;
if (!when.expired()) {
threadWait.take(when);
}
if (when.expired()) {
if (!rateLimiter.isEventOk()) {
Deadline whenOk = Deadline.in(rateLimiter.timeUntilEventOk());
log.info("Rate limited until " + whenOk);
whenOk.sleep();
}
rateLimiter.event();
processReq(req);
}
}
} catch (InterruptedException e) {
// no action - expected when stopping or when queue reordered
} catch (Exception e) {
log.error("Unexpected exception caught in MailQueue thread", e);
}
}
}
private void stopMail() {
triggerWDogOnExit(false);
goOn = false;
this.interrupt();
}
}
}
| |
/**
* Copyright (c) 2017 MapR, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ojai.util;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import org.ojai.DocumentReader;
import org.ojai.annotation.API;
import org.ojai.annotation.API.NonNullable;
import org.ojai.types.ODate;
import org.ojai.types.OInterval;
import org.ojai.types.OTime;
import org.ojai.types.OTimestamp;
import com.google.common.base.Preconditions;
/**
* An implementation of {@link DocumentReader} interface which can be used to project
* a sub-set of fields
*/
@API.Public
public class DocumentReaderWithProjection implements DocumentReader {
private final DocumentReader reader;
private final FieldProjector projector;
public DocumentReaderWithProjection(
@NonNullable final DocumentReader reader, @NonNullable final FieldProjector projection) {
this.reader = Preconditions.checkNotNull(reader);
this.projector = Preconditions.checkNotNull(projection).reset(reader);
}
@Override
public EventType next() {
do {
EventType event = reader.next();
if (event == null) {
return null; // end of document
} else if (event == EventType.START_MAP
&& reader.inMap()
&& reader.getFieldName() == null) {
return event; // beginning of the document
}
// move the projection tree to this event
projector.moveTo(event);
if (projector.shouldEmitEvent()) {
// if projection allows, emit the current event
return event;
} else {
// otherwise, skip the entire sub-tree
reader.skipChildren();
}
} while (true);
}
@Override
public DocumentReader skipChildren() {
reader.skipChildren();
return this;
}
@Override
public boolean inMap() {
return reader.inMap();
}
@Override
public String getFieldName() {
return reader.getFieldName();
}
@Override
public int getArrayIndex() {
return reader.getArrayIndex();
}
@Override
public byte getByte() {
return reader.getByte();
}
@Override
public short getShort() {
return reader.getShort();
}
@Override
public int getInt() {
return reader.getInt();
}
@Override
public long getLong() {
return reader.getLong();
}
@Override
public float getFloat() {
return reader.getFloat();
}
@Override
public double getDouble() {
return reader.getDouble();
}
@Override
public BigDecimal getDecimal() {
return reader.getDecimal();
}
@Override
public int getDecimalPrecision() {
return reader.getDecimalPrecision();
}
@Override
public int getDecimalScale() {
return reader.getDecimalScale();
}
@Override
public int getDecimalValueAsInt() {
return reader.getDecimalValueAsInt();
}
@Override
public long getDecimalValueAsLong() {
return reader.getDecimalValueAsLong();
}
@Override
public ByteBuffer getDecimalValueAsBytes() {
return reader.getDecimalValueAsBytes();
}
@Override
public boolean getBoolean() {
return reader.getBoolean();
}
@Override
public String getString() {
return reader.getString();
}
@Override
public long getTimestampLong() {
return reader.getTimestampLong();
}
@Override
public OTimestamp getTimestamp() {
return reader.getTimestamp();
}
@Override
public int getDateInt() {
return reader.getDateInt();
}
@Override
public ODate getDate() {
return reader.getDate();
}
@Override
public int getTimeInt() {
return reader.getTimeInt();
}
@Override
public OTime getTime() {
return reader.getTime();
}
@Override
public OInterval getInterval() {
return reader.getInterval();
}
@Override
public int getIntervalDays() {
return reader.getIntervalDays();
}
@Override
public long getIntervalMillis() {
return reader.getIntervalMillis();
}
@Override
public ByteBuffer getBinary() {
return reader.getBinary();
}
@Override
public EventType getCurrentEvent() {
return reader.getCurrentEvent();
}
}
| |
////////////////////////////////////////////////////////////////////////
//
// DataElement.java
//
// This file was generated by MapForce 2017sp2.
//
// YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE
// OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION.
//
// Refer to the MapForce Documentation for further details.
// http://www.altova.com/mapforce
//
////////////////////////////////////////////////////////////////////////
package com.altova.text.edi;
import com.altova.text.ITextNode;
import com.altova.text.edi.Scanner.State;
import java.io.IOException;
public class DataElement extends StructureItem {
DataTypeValidator mValidator;
public DataElement (String name, DataTypeValidator validator) {
super(name, ITextNode.DataElement);
mValidator = validator;
}
public boolean read (Parser.Context context) {
State beforeState = context.getScanner().getCurrentState();
if ( context.getParser().getEDIKind() == EDISettings.EDIStandard.EDIFixed )
{
Scanner scanner = context.getScanner();
StringBuffer sBuffer = new StringBuffer();
while( sBuffer.length() < mValidator.getMaxLength() && !scanner.isAtEnd() &&
scanner.getCurrentChar() != scanner.mServiceChars.getSegmentTerminator() )
{
char c = scanner.rawConsumeChar();
if( scanner.getCurrentChar() == '\n' )
{
if( c != '\r' )
sBuffer.append( c );
}
else
sBuffer.append( c );
}
mValidator.makeValidOnRead( sBuffer, context, beforeState);
if ( sBuffer.length() == 0)
return false; //data element is absent
context.getGenerator().insertElement (context.getParticle().getName(), sBuffer.toString(), mNodeClass);
return true;
}
//MSH-2 in HL7 MODE also needs special treatment
if( context.getParser().getEDIKind() == EDISettings.EDIStandard.EDIHL7
&& isHL7SpecialField(context.getParticle().getName(), "-2"))
{
Scanner scanner = context.getScanner();
String s = new String();
char c = scanner.rawConsumeChar();
scanner.mServiceChars.setComponentSeparator( c);
s += c;
s += c = scanner.rawConsumeChar();
scanner.mServiceChars.setRepetitionSeparator( c);
if( scanner.getCurrentChar() != scanner.mServiceChars.getDataElementSeparator())
{
s += c = scanner.rawConsumeChar();
scanner.mServiceChars.setReleaseCharacter( c);
}
if( scanner.getCurrentChar() != scanner.mServiceChars.getDataElementSeparator())
{
s += c = scanner.rawConsumeChar();
scanner.mServiceChars.setSubComponentSeparator( c);
}
while( scanner.getCurrentChar() != scanner.mServiceChars.getDataElementSeparator())
{
s += c = scanner.rawConsumeChar();
}
context.getGenerator().insertElement (context.getParticle().getName(), s, mNodeClass);
return true;
}
StringBuffer s = context.getScanner().consumeString(ServiceChars.ComponentSeparator, true);
if ( s.length() == 0 )
return false; // data element is absent
mValidator.makeValidOnRead(s, context, beforeState);
if( context.getParser().getEDIKind() == EDISettings.EDIStandard.EDIX12 )
{
if( context.getParticle().getName().equals( "F447") && context.getCurrentSegmentName().equals("LS") )
context.getParser().setF447( new String( s) );
}
// codelist validate
if (!mValidator.hasValue(s.toString()))
{
if (!mValidator.isIncomplete())
context.handleError(
Parser.ErrorType.CodeListValueWrong,
ErrorMessages.GetInvalidCodeListValueMessage(s.toString(), mValidator.getCodeListValues()),
new ErrorPosition( beforeState ),
s.toString()
);
else
context.handleWarning(
ErrorMessages.GetIncompleteCodeListValueMessage(s.toString(), mValidator.getCodeListValues()),
new ErrorPosition( beforeState ),
s.toString()
);
}
// embedded codelist validate
if (!embeddedCodeListValidate(s.toString(), context.getParticle()))
context.handleError(
Parser.ErrorType.CodeListValueWrong,
ErrorMessages.GetInvalidCodeListValueMessage(s.toString(), embeddedCodeListValueList(context.getParticle())),
new ErrorPosition( beforeState ),
s.toString()
);
// edi validate
String sError = context.getValidator().validate( context.getParticle().getName(), s.toString());
if( sError.length() > 0)
context.handleError(
Parser.ErrorType.SemanticWrong,
sError,
new ErrorPosition( beforeState ),
s.toString()
);
context.getGenerator().insertElement (context.getParticle().getName(), s.toString(), mNodeClass);
return true;
}
public void write (Writer writer, ITextNode node, Particle particle) throws IOException {
StringBuffer sbvalue = new StringBuffer();
String nodeName = new String();
if (node != null)
{
sbvalue.append(node.getValue());
nodeName = node.getName();
}
if (writer.getEDIKind() == EDISettings.EDIStandard.EDIFixed)
{
mValidator.makeValidOnWrite( sbvalue, node, writer, false);
writer.write( sbvalue.toString() );
return;
}
boolean escapeString = true;
if (writer.getEDIKind() == EDISettings.EDIStandard.EDIHL7
&& isHL7SpecialField(nodeName, "-2"))
{
sbvalue = new StringBuffer();
sbvalue.append( writer.getServiceChars().getComponentSeparator());
sbvalue.append( writer.getServiceChars().getRepetitionSeparator());
if( writer.getServiceChars().getReleaseCharacter() != 0 )
{
sbvalue.append( writer.getServiceChars().getReleaseCharacter());
if( writer.getServiceChars().getSubComponentSeparator() != 0 )
sbvalue.append( writer.getServiceChars().getSubComponentSeparator());
}
//don't escape separators
escapeString = false;
}
if (!mValidator.makeValidOnWrite (sbvalue, node, writer, escapeString))
return;
//codelist validate
String sValue = sbvalue.toString();
if (!mValidator.hasValue( sValue))
{
if (!mValidator.isIncomplete())
writer.handleError( node, Parser.ErrorType.CodeListValueWrong, ErrorMessages.GetInvalidCodeListValueMessage(sValue, mValidator.getCodeListValues()) );
else
writer.handleWarning( node, ErrorMessages.GetIncompleteCodeListValueMessage(sValue, mValidator.getCodeListValues()) );
}
// embedded codelist validate
if (!embeddedCodeListValidate(sValue, particle))
writer.handleError(
node,
Parser.ErrorType.CodeListValueWrong,
ErrorMessages.GetInvalidCodeListValueMessage(sValue, embeddedCodeListValueList(particle))
);
//edi validate
String sError = writer.getValidator().validate( nodeName, sValue);
if( sError.length() > 0)
writer.handleError( node, Parser.ErrorType.SemanticWrong, sError);
writer.write (sValue);
}
private boolean embeddedCodeListValidate(String value, Particle particle)
{
if (particle.getCodeValues().length == 0)
return true;
for(String s : particle.getCodeValues())
if (s.equals( value ))
return true;
return false;
}
private String embeddedCodeListValueList(Particle particle)
{
StringBuffer validList = new StringBuffer();
for(String s : particle.getCodeValues())
validList.append(", '" + s + "'");
return validList.toString().substring(2);
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.oncrpc;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.oncrpc.RpcAcceptedReply.AcceptState;
import org.apache.hadoop.oncrpc.security.Verifier;
import org.apache.hadoop.oncrpc.security.VerifierNone;
import org.apache.hadoop.portmap.PortmapMapping;
import org.apache.hadoop.portmap.PortmapRequest;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
/**
* Class for writing RPC server programs based on RFC 1050. Extend this class
* and implement {@link #handleInternal} to handle the requests received.
*/
public abstract class RpcProgram extends SimpleChannelUpstreamHandler {
static final Log LOG = LogFactory.getLog(RpcProgram.class);
public static final int RPCB_PORT = 111;
private final String program;
private final String host;
private int port; // Ephemeral port is chosen later
private final int progNumber;
private final int lowProgVersion;
private final int highProgVersion;
protected final boolean allowInsecurePorts;
/**
* If not null, this will be used as the socket to use to connect to the
* system portmap daemon when registering this RPC server program.
*/
private final DatagramSocket registrationSocket;
/**
* Constructor
*
* @param program program name
* @param host host where the Rpc server program is started
* @param port port where the Rpc server program is listening to
* @param progNumber program number as defined in RFC 1050
* @param lowProgVersion lowest version of the specification supported
* @param highProgVersion highest version of the specification supported
* @param registrationSocket if not null, use this socket to register
* with portmap daemon
* @param allowInsecurePorts true to allow client connections from
* unprivileged ports, false otherwise
*/
protected RpcProgram(String program, String host, int port, int progNumber,
int lowProgVersion, int highProgVersion,
DatagramSocket registrationSocket, boolean allowInsecurePorts) {
this.program = program;
this.host = host;
this.port = port;
this.progNumber = progNumber;
this.lowProgVersion = lowProgVersion;
this.highProgVersion = highProgVersion;
this.registrationSocket = registrationSocket;
this.allowInsecurePorts = allowInsecurePorts;
LOG.info("Will " + (allowInsecurePorts ? "" : "not ") + "accept client "
+ "connections from unprivileged ports");
}
/**
* Register this program with the local portmapper.
*/
public void register(int transport, int boundPort) {
if (boundPort != port) {
LOG.info("The bound port is " + boundPort
+ ", different with configured port " + port);
port = boundPort;
}
// Register all the program versions with portmapper for a given transport
for (int vers = lowProgVersion; vers <= highProgVersion; vers++) {
PortmapMapping mapEntry = new PortmapMapping(progNumber, vers, transport,
port);
register(mapEntry, true);
}
}
/**
* Unregister this program with the local portmapper.
*/
public void unregister(int transport, int boundPort) {
if (boundPort != port) {
LOG.info("The bound port is " + boundPort
+ ", different with configured port " + port);
port = boundPort;
}
// Unregister all the program versions with portmapper for a given transport
for (int vers = lowProgVersion; vers <= highProgVersion; vers++) {
PortmapMapping mapEntry = new PortmapMapping(progNumber, vers, transport,
port);
register(mapEntry, false);
}
}
/**
* Register the program with Portmap or Rpcbind
*/
protected void register(PortmapMapping mapEntry, boolean set) {
XDR mappingRequest = PortmapRequest.create(mapEntry, set);
SimpleUdpClient registrationClient = new SimpleUdpClient(host, RPCB_PORT,
mappingRequest, registrationSocket);
try {
registrationClient.run();
} catch (IOException e) {
String request = set ? "Registration" : "Unregistration";
LOG.error(request + " failure with " + host + ":" + port
+ ", portmap entry: " + mapEntry);
throw new RuntimeException(request + " failure", e);
}
}
// Start extra daemons or services
public void startDaemons() {}
public void stopDaemons() {}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
throws Exception {
RpcInfo info = (RpcInfo) e.getMessage();
RpcCall call = (RpcCall) info.header();
SocketAddress remoteAddress = info.remoteAddress();
if (LOG.isTraceEnabled()) {
LOG.trace(program + " procedure #" + call.getProcedure());
}
if (this.progNumber != call.getProgram()) {
LOG.warn("Invalid RPC call program " + call.getProgram());
sendAcceptedReply(call, remoteAddress, AcceptState.PROG_UNAVAIL, ctx);
return;
}
int ver = call.getVersion();
if (ver < lowProgVersion || ver > highProgVersion) {
LOG.warn("Invalid RPC call version " + ver);
sendAcceptedReply(call, remoteAddress, AcceptState.PROG_MISMATCH, ctx);
return;
}
handleInternal(ctx, info);
}
public boolean doPortMonitoring(SocketAddress remoteAddress) {
if (!allowInsecurePorts) {
if (LOG.isTraceEnabled()) {
LOG.trace("Will not allow connections from unprivileged ports. "
+ "Checking for valid client port...");
}
if (remoteAddress instanceof InetSocketAddress) {
InetSocketAddress inetRemoteAddress = (InetSocketAddress) remoteAddress;
if (inetRemoteAddress.getPort() > 1023) {
LOG.warn("Connection attempted from '" + inetRemoteAddress + "' "
+ "which is an unprivileged port. Rejecting connection.");
return false;
}
} else {
LOG.warn("Could not determine remote port of socket address '"
+ remoteAddress + "'. Rejecting connection.");
return false;
}
}
return true;
}
private void sendAcceptedReply(RpcCall call, SocketAddress remoteAddress,
AcceptState acceptState, ChannelHandlerContext ctx) {
RpcAcceptedReply reply = RpcAcceptedReply.getInstance(call.getXid(),
acceptState, Verifier.VERIFIER_NONE);
XDR out = new XDR();
reply.write(out);
if (acceptState == AcceptState.PROG_MISMATCH) {
out.writeInt(lowProgVersion);
out.writeInt(highProgVersion);
}
ChannelBuffer b = ChannelBuffers.wrappedBuffer(out.asReadOnlyWrap()
.buffer());
RpcResponse rsp = new RpcResponse(b, remoteAddress);
RpcUtil.sendRpcResponse(ctx, rsp);
}
protected static void sendRejectedReply(RpcCall call,
SocketAddress remoteAddress, ChannelHandlerContext ctx) {
XDR out = new XDR();
RpcDeniedReply reply = new RpcDeniedReply(call.getXid(),
RpcReply.ReplyState.MSG_DENIED,
RpcDeniedReply.RejectState.AUTH_ERROR, new VerifierNone());
reply.write(out);
ChannelBuffer buf = ChannelBuffers.wrappedBuffer(out.asReadOnlyWrap()
.buffer());
RpcResponse rsp = new RpcResponse(buf, remoteAddress);
RpcUtil.sendRpcResponse(ctx, rsp);
}
protected abstract void handleInternal(ChannelHandlerContext ctx, RpcInfo info);
@Override
public String toString() {
return "Rpc program: " + program + " at " + host + ":" + port;
}
protected abstract boolean isIdempotent(RpcCall call);
public int getPort() {
return port;
}
}
| |
package mx.bigdata.sat.contabilidad_electronica;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.util.JAXBSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import mx.bigdata.sat.ce_catalogo_cuentas.schema.Catalogo;
import mx.bigdata.sat.common.NamespacePrefixMapperImpl;
import mx.bigdata.sat.common.URIResolverImpl;
import mx.bigdata.sat.security.KeyLoaderEnumeration;
import mx.bigdata.sat.security.factory.KeyLoaderFactory;
import org.apache.commons.codec.binary.Base64;
import org.w3c.dom.Document;
import org.xml.sax.ErrorHandler;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public final class CuentasContablesv11 {
private static final String XSLT = "/xslt/ce_catalogo_cuentas/CatalogoCuentas_1_1.xslt";
private static final String[] XSD = new String[] {
"/xsd/ce_catalogo_cuentas/CatalogoCuentas_1_1.xsd"
};
private static final String XML_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
private static final String BASE_CONTEXT = "mx.bigdata.sat.ce_catalogo_cuentas.schema";
private final static Joiner JOINER = Joiner.on(':');
private final JAXBContext context ;
public static final ImmutableMap<String, String> PREFIXES =
ImmutableMap.of("http://www.sat.gob.mx/esquemas/ContabilidadE/1_1/CatalogoCuentas", "catalogocuentas",
"http://www.w3.org/2001/XMLSchema-instance","xsi");
// ,"http://www.sat.gob.mx/esquemas/ContabilidadE/1_1/CatalogoCuentas", "catalogocuentas"
private final Map<String, String> localPrefixes = Maps.newHashMap(PREFIXES);
/*************************************************************************************************************/
/*************************************************************************************************************/
private TransformerFactory tf;
// final Comprobante document;
final Catalogo document;
public CuentasContablesv11(InputStream in, String... contexts) throws Exception {
this.context = getContext(contexts);
this.document = load(in);
}
public CuentasContablesv11(Catalogo catalogo, String... contexts) throws Exception {
this.context = getContext(contexts);
this.document = copy(catalogo);
}
public void addNamespace(String uri, String prefix) {
localPrefixes.put(uri, prefix);
}
public void setTransformerFactory(TransformerFactory tf) {
this.tf = tf;
tf.setURIResolver(new URIResolverImpl());
}
public Catalogo sellarComprobante(PrivateKey key, X509Certificate cert) throws Exception {
sellar(key, cert);
return doGetCatalogo();
}
public void validar() throws Exception {
validar(null);
}
public void sellar(PrivateKey key, X509Certificate cert) throws Exception {
cert.checkValidity();
String signature = getSignature(key);
document.setSello(signature);
byte[] bytes = cert.getEncoded();
Base64 b64 = new Base64(-1);
String certStr = b64.encodeToString(bytes);
document.setCertificado(certStr);
BigInteger bi = cert.getSerialNumber();
document.setNoCertificado(new String(bi.toByteArray()));
}
public void validar(ErrorHandler handler) throws Exception {
SchemaFactory sf =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source[] schemas = new Source[XSD.length];
for (int i = 0; i < XSD.length; i++) {
schemas[i] = new StreamSource(getClass().getResourceAsStream(XSD[i]));
}
Schema schema = sf.newSchema(schemas);
Validator validator = schema.newValidator();
if (handler != null) {
validator.setErrorHandler(handler);
}
validator.validate(new JAXBSource(context, document));
}
public void verificar() throws Exception {
String certStr = document.getCertificado();
Base64 b64 = new Base64();
byte[] cbs = b64.decode(certStr);
X509Certificate cert = KeyLoaderFactory.createInstance(KeyLoaderEnumeration.PUBLIC_KEY_LOADER,new ByteArrayInputStream(cbs)).getKey();
String sigStr = document.getSello();
byte[] signature = b64.decode(sigStr);
byte[] bytes = getOriginalBytes();
Signature sig = Signature.getInstance("SHA1withRSA");
sig.initVerify(cert);
sig.update(bytes);
boolean bool = sig.verify(signature);
if (!bool) {
throw new Exception("Invalid signature");
}
}
public void guardar(OutputStream out) throws Exception {
Marshaller m = context.createMarshaller();
m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapperImpl(localPrefixes));
m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "www.sat.gob.mx/esquemas/ContabilidadE/1_1/CatalogoCuentas " + "http://www.sat.gob.mx/esquemas/ContabilidadE/1_1/CatalogoCuentas/CatalogoCuentas_1_1.xsd");
byte[] xmlHeaderBytes = XML_HEADER.getBytes("UTF8");
out.write(xmlHeaderBytes);
m.marshal(document, out);
}
public String getCadenaOriginal() throws Exception {
byte[] bytes = getOriginalBytes();
return new String(bytes, "UTF8");
}
public static Catalogo newComprobante(InputStream in) throws Exception {
return load(in);
}
// public ComprobanteBase getComprobante() throws Exception {
// return new CFDv32ComprobanteBase(doGetCatalogo());
// }
Catalogo doGetCatalogo() throws Exception {
return copy(document);
}
byte[] getOriginalBytes() throws Exception {
JAXBSource in = new JAXBSource(context, document);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Result out = new StreamResult(baos);
TransformerFactory factory = tf;
if (factory == null) {
factory = TransformerFactory.newInstance();
factory.setURIResolver(new URIResolverImpl());
}
Transformer transformer = factory.newTransformer(new StreamSource(getClass().getResourceAsStream(XSLT)));
transformer.transform(in, out);
return baos.toByteArray();
}
String getSignature(PrivateKey key) throws Exception {
byte[] bytes = getOriginalBytes();
Signature sig = Signature.getInstance("SHA1withRSA");
sig.initSign(key);
sig.update(bytes);
byte[] signed = sig.sign();
Base64 b64 = new Base64(-1);
return b64.encodeToString(signed);
}
// FUNCIONES AUXILIARES
private static JAXBContext getContext(String[] contexts) throws Exception {
List<String> ctx = Lists.asList(BASE_CONTEXT, contexts);
return JAXBContext.newInstance(JOINER.join(ctx));
}
private static Catalogo load(InputStream source, String... contexts)
throws Exception {
JAXBContext context = getContext(contexts);
try {
Unmarshaller u = context.createUnmarshaller();
return (Catalogo) u.unmarshal(source);
} finally {
source.close();
}
}
// Defensive deep-copy
private Catalogo copy(Catalogo catalogo) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
Marshaller m = context.createMarshaller();
m.marshal(catalogo, doc);
Unmarshaller u = context.createUnmarshaller();
return (Catalogo) u.unmarshal(doc);
}
}
| |
/*
* 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.
*/
/**
* @author Dmitry A. Durnev, Michael Danilov
*/
package com.google.code.appengine.awt;
import java.util.EventListener;
import java.util.EventObject;
import java.util.Hashtable;
import com.google.code.appengine.awt.event.ActionEvent;
import com.google.code.appengine.awt.event.ActionListener;
import com.google.code.appengine.awt.event.AdjustmentEvent;
import com.google.code.appengine.awt.event.AdjustmentListener;
import com.google.code.appengine.awt.event.TextEvent;
import com.google.code.appengine.awt.event.TextListener;
public abstract class AWTEvent extends EventObject {
private static final long serialVersionUID = -1825314779160409405L;
public static final long COMPONENT_EVENT_MASK = 1;
public static final long CONTAINER_EVENT_MASK = 2;
public static final long FOCUS_EVENT_MASK = 4;
public static final long KEY_EVENT_MASK = 8;
public static final long MOUSE_EVENT_MASK = 16;
public static final long MOUSE_MOTION_EVENT_MASK = 32;
public static final long WINDOW_EVENT_MASK = 64;
public static final long ACTION_EVENT_MASK = 128;
public static final long ADJUSTMENT_EVENT_MASK = 256;
public static final long ITEM_EVENT_MASK = 512;
public static final long TEXT_EVENT_MASK = 1024;
public static final long INPUT_METHOD_EVENT_MASK = 2048;
public static final long PAINT_EVENT_MASK = 8192;
public static final long INVOCATION_EVENT_MASK = 16384;
public static final long HIERARCHY_EVENT_MASK = 32768;
public static final long HIERARCHY_BOUNDS_EVENT_MASK = 65536;
public static final long MOUSE_WHEEL_EVENT_MASK = 131072;
public static final long WINDOW_STATE_EVENT_MASK = 262144;
public static final long WINDOW_FOCUS_EVENT_MASK = 524288;
public static final int RESERVED_ID_MAX = 1999;
private static final Hashtable<Integer, EventDescriptor> eventsMap = new Hashtable<Integer, EventDescriptor>();
private static EventConverter converter;
protected int id;
protected boolean consumed;
boolean dispatchedByKFM;
transient boolean isPosted;
static {
// eventsMap.put(new Integer(KeyEvent.KEY_TYPED),
// new EventDescriptor(KEY_EVENT_MASK, KeyListener.class));
// eventsMap.put(new Integer(KeyEvent.KEY_PRESSED),
// new EventDescriptor(KEY_EVENT_MASK, KeyListener.class));
// eventsMap.put(new Integer(KeyEvent.KEY_RELEASED),
// new EventDescriptor(KEY_EVENT_MASK, KeyListener.class));
// eventsMap.put(new Integer(MouseEvent.MOUSE_CLICKED),
// new EventDescriptor(MOUSE_EVENT_MASK, MouseListener.class));
// eventsMap.put(new Integer(MouseEvent.MOUSE_PRESSED),
// new EventDescriptor(MOUSE_EVENT_MASK, MouseListener.class));
// eventsMap.put(new Integer(MouseEvent.MOUSE_RELEASED),
// new EventDescriptor(MOUSE_EVENT_MASK, MouseListener.class));
// eventsMap.put(new Integer(MouseEvent.MOUSE_MOVED),
// new EventDescriptor(MOUSE_MOTION_EVENT_MASK, MouseMotionListener.class));
// eventsMap.put(new Integer(MouseEvent.MOUSE_ENTERED),
// new EventDescriptor(MOUSE_EVENT_MASK, MouseListener.class));
// eventsMap.put(new Integer(MouseEvent.MOUSE_EXITED),
// new EventDescriptor(MOUSE_EVENT_MASK, MouseListener.class));
// eventsMap.put(new Integer(MouseEvent.MOUSE_DRAGGED),
// new EventDescriptor(MOUSE_MOTION_EVENT_MASK, MouseMotionListener.class));
// eventsMap.put(new Integer(MouseEvent.MOUSE_WHEEL),
// new EventDescriptor(MOUSE_WHEEL_EVENT_MASK, MouseWheelListener.class));
// eventsMap.put(new Integer(ComponentEvent.COMPONENT_MOVED),
// new EventDescriptor(COMPONENT_EVENT_MASK, ComponentListener.class));
// eventsMap.put(new Integer(ComponentEvent.COMPONENT_RESIZED),
// new EventDescriptor(COMPONENT_EVENT_MASK, ComponentListener.class));
// eventsMap.put(new Integer(ComponentEvent.COMPONENT_SHOWN),
// new EventDescriptor(COMPONENT_EVENT_MASK, ComponentListener.class));
// eventsMap.put(new Integer(ComponentEvent.COMPONENT_HIDDEN),
// new EventDescriptor(COMPONENT_EVENT_MASK, ComponentListener.class));
// eventsMap.put(new Integer(FocusEvent.FOCUS_GAINED),
// new EventDescriptor(FOCUS_EVENT_MASK, FocusListener.class));
// eventsMap.put(new Integer(FocusEvent.FOCUS_LOST),
// new EventDescriptor(FOCUS_EVENT_MASK, FocusListener.class));
// eventsMap.put(new Integer(PaintEvent.PAINT),
// new EventDescriptor(PAINT_EVENT_MASK, null));
// eventsMap.put(new Integer(PaintEvent.UPDATE),
// new EventDescriptor(PAINT_EVENT_MASK, null));
// eventsMap.put(new Integer(WindowEvent.WINDOW_OPENED),
// new EventDescriptor(WINDOW_EVENT_MASK, WindowListener.class));
// eventsMap.put(new Integer(WindowEvent.WINDOW_CLOSING),
// new EventDescriptor(WINDOW_EVENT_MASK, WindowListener.class));
// eventsMap.put(new Integer(WindowEvent.WINDOW_CLOSED),
// new EventDescriptor(WINDOW_EVENT_MASK, WindowListener.class));
// eventsMap.put(new Integer(WindowEvent.WINDOW_DEICONIFIED),
// new EventDescriptor(WINDOW_EVENT_MASK, WindowListener.class));
// eventsMap.put(new Integer(WindowEvent.WINDOW_ICONIFIED),
// new EventDescriptor(WINDOW_EVENT_MASK, WindowListener.class));
// eventsMap.put(new Integer(WindowEvent.WINDOW_STATE_CHANGED),
// new EventDescriptor(WINDOW_STATE_EVENT_MASK, WindowStateListener.class));
// eventsMap.put(new Integer(WindowEvent.WINDOW_LOST_FOCUS),
// new EventDescriptor(WINDOW_FOCUS_EVENT_MASK, WindowFocusListener.class));
// eventsMap.put(new Integer(WindowEvent.WINDOW_GAINED_FOCUS),
// new EventDescriptor(WINDOW_FOCUS_EVENT_MASK, WindowFocusListener.class));
// eventsMap.put(new Integer(WindowEvent.WINDOW_DEACTIVATED),
// new EventDescriptor(WINDOW_EVENT_MASK, WindowListener.class));
// eventsMap.put(new Integer(WindowEvent.WINDOW_ACTIVATED),
// new EventDescriptor(WINDOW_EVENT_MASK, WindowListener.class));
// eventsMap.put(new Integer(HierarchyEvent.HIERARCHY_CHANGED),
// new EventDescriptor(HIERARCHY_EVENT_MASK, HierarchyListener.class));
// eventsMap.put(new Integer(HierarchyEvent.ANCESTOR_MOVED),
// new EventDescriptor(HIERARCHY_BOUNDS_EVENT_MASK, HierarchyBoundsListener.class));
// eventsMap.put(new Integer(HierarchyEvent.ANCESTOR_RESIZED),
// new EventDescriptor(HIERARCHY_BOUNDS_EVENT_MASK, HierarchyBoundsListener.class));
// eventsMap.put(new Integer(ContainerEvent.COMPONENT_ADDED),
// new EventDescriptor(CONTAINER_EVENT_MASK, ContainerListener.class));
// eventsMap.put(new Integer(ContainerEvent.COMPONENT_REMOVED),
// new EventDescriptor(CONTAINER_EVENT_MASK, ContainerListener.class));
// eventsMap.put(new Integer(InputMethodEvent.INPUT_METHOD_TEXT_CHANGED),
// new EventDescriptor(INPUT_METHOD_EVENT_MASK, InputMethodListener.class));
// eventsMap.put(new Integer(InputMethodEvent.CARET_POSITION_CHANGED),
// new EventDescriptor(INPUT_METHOD_EVENT_MASK, InputMethodListener.class));
// eventsMap.put(new Integer(InvocationEvent.INVOCATION_DEFAULT),
// new EventDescriptor(INVOCATION_EVENT_MASK, null));
// eventsMap.put(new Integer(ItemEvent.ITEM_STATE_CHANGED),
// new EventDescriptor(ITEM_EVENT_MASK, ItemListener.class));
eventsMap.put(new Integer(TextEvent.TEXT_VALUE_CHANGED),
new EventDescriptor(TEXT_EVENT_MASK, TextListener.class));
eventsMap.put(new Integer(ActionEvent.ACTION_PERFORMED),
new EventDescriptor(ACTION_EVENT_MASK, ActionListener.class));
eventsMap.put(new Integer(AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED),
new EventDescriptor(ADJUSTMENT_EVENT_MASK, AdjustmentListener.class));
converter = new EventConverter();
}
public AWTEvent(Event event) {
this(event.target, event.id);
}
public AWTEvent(Object source, int id) {
super(source);
this.id = id;
consumed = false;
}
public int getID() {
return id;
}
public void setSource(Object newSource) {
source = newSource;
}
@Override
public String toString() {
/* The format is based on 1.5 release behavior
* which can be revealed by the following code:
*
* AWTEvent event = new AWTEvent(new Component(){}, 1){};
* System.out.println(event);
*/
String name = ""; //$NON-NLS-1$
// if (source instanceof Component && (source != null)) {
// Component comp = (Component) getSource();
// name = comp.getName();
// if (name == null) {
// name = ""; //$NON-NLS-1$
// }
// }
return (getClass().getName() + "[" + paramString() + "]" //$NON-NLS-1$ //$NON-NLS-2$
+ " on " + (name.length() > 0 ? name : source)); //$NON-NLS-1$
}
public String paramString() {
//nothing to implement: all event types must override this method
return ""; //$NON-NLS-1$
}
protected boolean isConsumed() {
return consumed;
}
protected void consume() {
consumed = true;
}
/**
* Convert AWTEvent object to deprecated Event object
*
* @return new Event object which is a converted AWTEvent object or null
* if the conversion is not possible
*/
Event getEvent() {
throw new UnsupportedOperationException();
// if (id == ActionEvent.ACTION_PERFORMED) {
// ActionEvent ae = (ActionEvent) this;
// return converter.convertActionEvent(ae);
//
// } else if (id == AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED) {
// AdjustmentEvent ae = (AdjustmentEvent) this;
// return converter.convertAdjustmentEvent(ae);
//
// } else if (id == ComponentEvent.COMPONENT_MOVED
// && source instanceof Window) {
// //the only type of Component events is COMPONENT_MOVED on window
// ComponentEvent ce = (ComponentEvent) this;
// return converter.convertComponentEvent(ce);
//
// } else if (id >= FocusEvent.FOCUS_FIRST && id <= FocusEvent.FOCUS_LAST) {
// //nothing to convert
// } else if (id == ItemEvent.ITEM_STATE_CHANGED) {
// ItemEvent ie = (ItemEvent) this;
// return converter.convertItemEvent(ie);
//
// } else if (id == KeyEvent.KEY_PRESSED || id == KeyEvent.KEY_RELEASED) {
// KeyEvent ke = (KeyEvent) this;
// return converter.convertKeyEvent(ke);
// } else if (id >= MouseEvent.MOUSE_FIRST && id <= MouseEvent.MOUSE_LAST) {
// MouseEvent me = (MouseEvent) this;
// return converter.convertMouseEvent(me);
// } else if (id == WindowEvent.WINDOW_CLOSING
// || id == WindowEvent.WINDOW_ICONIFIED
// || id == WindowEvent.WINDOW_DEICONIFIED) {
// //nothing to convert
// } else {
// return null;
// }
//
// return new Event(source, id, null);
}
static final class EventDescriptor {
final long eventMask;
final Class<? extends EventListener> listenerType;
EventDescriptor(long eventMask, Class<? extends EventListener> listenerType) {
this.eventMask = eventMask;
this.listenerType = listenerType;
}
}
static final class EventTypeLookup {
private AWTEvent lastEvent = null;
private EventDescriptor lastEventDescriptor = null;
EventDescriptor getEventDescriptor(AWTEvent event) {
synchronized (this) {
if (event != lastEvent) {
lastEvent = event;
lastEventDescriptor = eventsMap.get(new Integer(event.id));
}
return lastEventDescriptor;
}
}
long getEventMask(AWTEvent event) {
final EventDescriptor ed = getEventDescriptor(event);
return ed == null ? -1 : ed.eventMask;
}
}
static final class EventConverter {
static final int OLD_MOD_MASK = Event.ALT_MASK | Event.CTRL_MASK
| Event.META_MASK | Event.SHIFT_MASK;
Event convertActionEvent(ActionEvent ae) {
Event evt = new Event(ae.getSource(), ae.getID(), ae.getActionCommand());
evt.when = ae.getWhen();
evt.modifiers = ae.getModifiers() & OLD_MOD_MASK;
/* if (source instanceof Button) {
arg = ((Button) source).getLabel();
} else if (source instanceof Checkbox) {
arg = new Boolean(((Checkbox) source).getState());
} else if (source instanceof CheckboxMenuItem) {
arg = ((CheckboxMenuItem) source).getLabel();
} else if (source instanceof Choice) {
arg = ((Choice) source).getSelectedItem();
} else if (source instanceof List) {
arg = ((List) source).getSelectedItem();
} else if (source instanceof MenuItem) {
arg = ((MenuItem) source).getLabel();
} else if (source instanceof TextField) {
arg = ((TextField) source).getText();
}
*/
return evt;
}
Event convertAdjustmentEvent(AdjustmentEvent ae) {
//TODO: Event.SCROLL_BEGIN/SCROLL_END
return new Event(ae.source, ae.id + ae.getAdjustmentType() - 1,
new Integer(ae.getValue()));
}
// Event convertComponentEvent(ComponentEvent ce) {
// Component comp = ce.getComponent();
// Event evt = new Event(comp, Event.WINDOW_MOVED, null);
// evt.x = comp.getX();
// evt.y = comp.getY();
// return evt;
}
// Event convertItemEvent(ItemEvent ie) {
// int oldId = ie.id + ie.getStateChange() - 1;
// Object source = ie.source;
// int idx = -1;
// if (source instanceof List) {
// List list = (List) source;
// idx = list.getSelectedIndex();
// }
// else if (source instanceof Choice) {
// Choice choice = (Choice) source;
// idx = choice.getSelectedIndex();
// }
// Object arg = idx >= 0 ? new Integer(idx) : null;
// return new Event(source, oldId, arg);
// }
// Event convertKeyEvent(KeyEvent ke) {
// int oldId = ke.id;
// //leave only old Event's modifiers
//
// int mod = ke.getModifiers() & OLD_MOD_MASK;
// Component comp = ke.getComponent();
// char keyChar = ke.getKeyChar();
// int keyCode = ke.getKeyCode();
// int key = convertKey(keyChar, keyCode);
// if (key >= Event.HOME && key <= Event.INSERT) {
// oldId += 2; //non-ASCII key -> action key
// }
// return new Event(comp, ke.getWhen(), oldId, 0, 0, key, mod);
// }
// Event convertMouseEvent(MouseEvent me) {
// int id = me.id;
// if (id != MouseEvent.MOUSE_CLICKED) {
// Event evt = new Event(me.source, id, null);
// evt.x = me.getX();
// evt.y = me.getY();
// int mod = me.getModifiers();
// //in Event modifiers mean button number for mouse events:
// evt.modifiers = mod & (Event.ALT_MASK | Event.META_MASK);
// if (id == MouseEvent.MOUSE_PRESSED) {
// evt.clickCount = me.getClickCount();
// }
// return evt;
// }
// return null;
// }
int convertKey(char keyChar, int keyCode) {
throw new UnsupportedOperationException();
// int key;
// //F1 - F12
// if (keyCode >= KeyEvent.VK_F1 && keyCode <= KeyEvent.VK_F12) {
// key = Event.F1 + keyCode - KeyEvent.VK_F1;
// } else {
// switch (keyCode) {
// default: //non-action key
// key = keyChar;
// break;
// //action keys:
// case KeyEvent.VK_HOME:
// key = Event.HOME;
// break;
// case KeyEvent.VK_END:
// key = Event.END;
// break;
// case KeyEvent.VK_PAGE_UP:
// key = Event.PGUP;
// break;
// case KeyEvent.VK_PAGE_DOWN:
// key = Event.PGDN;
// break;
// case KeyEvent.VK_UP:
// key = Event.UP;
// break;
// case KeyEvent.VK_DOWN:
// key = Event.DOWN;
// break;
// case KeyEvent.VK_LEFT:
// key = Event.LEFT;
// break;
// case KeyEvent.VK_RIGHT:
// key = Event.RIGHT;
// break;
// case KeyEvent.VK_PRINTSCREEN:
// key = Event.PRINT_SCREEN;
// break;
// case KeyEvent.VK_SCROLL_LOCK:
// key = Event.SCROLL_LOCK;
// break;
// case KeyEvent.VK_CAPS_LOCK:
// key = Event.CAPS_LOCK;
// break;
// case KeyEvent.VK_NUM_LOCK:
// key = Event.NUM_LOCK;
// break;
// case KeyEvent.VK_PAUSE:
// key = Event.PAUSE;
// break;
// case KeyEvent.VK_INSERT:
// key = Event.INSERT;
// break;
// }
// }
// return key;
// }
}
}
| |
/*
* 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.ignite.yardstick.cache.failover;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.cache.processor.EntryProcessorException;
import javax.cache.processor.MutableEntry;
import org.apache.ignite.cache.CacheEntryProcessor;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.yardstickframework.BenchmarkConfiguration;
import static org.yardstickframework.BenchmarkUtils.println;
/**
* Invoke retry failover benchmark. <p> Each client maintains a local map that it updates together with cache. Client
* invokes an increment closure for all generated keys and atomically increments value for corresponding keys in the
* local map. To validate cache contents, all writes from the client are stopped, values in the local map are compared
* to the values in the cache.
*/
public class IgniteAtomicInvokeRetryBenchmark extends IgniteFailoverAbstractBenchmark<String, Set> {
/** */
private final ConcurrentMap<String, AtomicLong> nextValMap = new ConcurrentHashMap<>();
/** */
private final ReadWriteLock rwl = new ReentrantReadWriteLock(true);
/** */
private volatile Exception ex;
/** {@inheritDoc} */
@Override public void setUp(final BenchmarkConfiguration cfg) throws Exception {
super.setUp(cfg);
Thread thread = new Thread(new Runnable() {
@Override public void run() {
try {
final int timeout = args.cacheOperationTimeoutMillis();
final int range = args.range();
while (!Thread.currentThread().isInterrupted()) {
Thread.sleep(args.cacheConsistencyCheckingPeriod() * 1000);
rwl.writeLock().lock();
try {
println("Start cache validation.");
long startTime = U.currentTimeMillis();
Map<String, Set> badCacheEntries = new HashMap<>();
for (Map.Entry<String, AtomicLong> e : nextValMap.entrySet()) {
String key = e.getKey();
asyncCache.get(key);
Set set = asyncCache.<Set>future().get(timeout);
if (set == null || e.getValue() == null || !Objects.equals(e.getValue().get(), (long)set.size()))
badCacheEntries.put(key, set);
}
if (!badCacheEntries.isEmpty()) {
// Print all usefull information and finish.
for (Map.Entry<String, Set> e : badCacheEntries.entrySet()) {
String key = e.getKey();
println("Got unexpected set size [key='" + key + "', expSize=" + nextValMap.get(key)
+ ", cacheVal=" + e.getValue() + "]");
}
println("Next values map contant:");
for (Map.Entry<String, AtomicLong> e : nextValMap.entrySet())
println("Map Entry [key=" + e.getKey() + ", val=" + e.getValue() + "]");
println("Cache content:");
for (int k2 = 0; k2 < range; k2++) {
String key2 = "key-" + k2;
asyncCache.get(key2);
Object val = asyncCache.future().get(timeout);
if (val != null)
println("Cache Entry [key=" + key2 + ", val=" + val + "]");
}
throw new IgniteConsistencyException("Cache and local map are in inconsistent state " +
"[badKeys=" + badCacheEntries.keySet() + ']');
}
println("Clearing all data.");
asyncCache.removeAll();
asyncCache.future().get(timeout);
nextValMap.clear();
println("Cache validation successfully finished in "
+ (U.currentTimeMillis() - startTime) / 1000 + " sec.");
}
finally {
rwl.writeLock().unlock();
}
}
}
catch (Throwable e) {
ex = new Exception(e);
println("Got exception: " + e);
e.printStackTrace();
if (e instanceof Error)
throw (Error)e;
}
}
}, "cache-" + cacheName() + "-validator");
thread.setDaemon(true);
thread.start();
}
/** {@inheritDoc} */
@Override public boolean test(Map<Object, Object> ctx) throws Exception {
final int k = nextRandom(args.range());
String key = "key-" + k;
rwl.readLock().lock();
try {
if (ex != null)
throw ex;
AtomicLong nextAtomicVal = nextValMap.putIfAbsent(key, new AtomicLong(1));
Long nextVal = 1L;
if (nextAtomicVal != null)
nextVal = nextAtomicVal.incrementAndGet();
asyncCache.invoke(key, new AddInSetEntryProcessor(), nextVal);
asyncCache.future().get(args.cacheOperationTimeoutMillis());
}
finally {
rwl.readLock().unlock();
}
if (ex != null)
throw ex;
return true;
}
/** {@inheritDoc} */
@Override protected String cacheName() {
return "atomic-invoke-retry";
}
/**
*/
private static class AddInSetEntryProcessor implements CacheEntryProcessor<String, Set, Object> {
/** */
private static final long serialVersionUID = 0;
/** {@inheritDoc} */
@Override public Object process(MutableEntry<String, Set> entry,
Object... arguments) throws EntryProcessorException {
assert !F.isEmpty(arguments);
Object val = arguments[0];
Set set;
if (!entry.exists())
set = new HashSet<>();
else
set = entry.getValue();
set.add(val);
entry.setValue(set);
return null;
}
}
}
| |
/*
* 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.rounding;
import org.elasticsearch.ElasticsearchIllegalArgumentException;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.unit.TimeValue;
import org.joda.time.DateTimeField;
import org.joda.time.DateTimeZone;
import org.joda.time.DurationField;
import java.io.IOException;
/**
*/
public abstract class TimeZoneRounding extends Rounding {
public static Builder builder(DateTimeUnit unit) {
return new Builder(unit);
}
public static Builder builder(TimeValue interval) {
return new Builder(interval);
}
public static class Builder {
private DateTimeUnit unit;
private long interval = -1;
private DateTimeZone timeZone = DateTimeZone.UTC;
private float factor = 1.0f;
private long offset;
public Builder(DateTimeUnit unit) {
this.unit = unit;
this.interval = -1;
}
public Builder(TimeValue interval) {
this.unit = null;
if (interval.millis() < 1)
throw new ElasticsearchIllegalArgumentException("Zero or negative time interval not supported");
this.interval = interval.millis();
}
public Builder timeZone(DateTimeZone timeZone) {
this.timeZone = timeZone;
return this;
}
public Builder offset(long offset) {
this.offset = offset;
return this;
}
public Builder factor(float factor) {
this.factor = factor;
return this;
}
public Rounding build() {
Rounding timeZoneRounding;
if (unit != null) {
timeZoneRounding = new TimeUnitRounding(unit, timeZone);
} else {
timeZoneRounding = new TimeIntervalRounding(interval, timeZone);
}
if (offset != 0) {
timeZoneRounding = new OffsetRounding(timeZoneRounding, offset);
}
if (factor != 1.0f) {
timeZoneRounding = new FactorRounding(timeZoneRounding, factor);
}
return timeZoneRounding;
}
}
static class TimeUnitRounding extends TimeZoneRounding {
static final byte ID = 1;
private DateTimeUnit unit;
private DateTimeField field;
private DurationField durationField;
private DateTimeZone timeZone;
TimeUnitRounding() { // for serialization
}
TimeUnitRounding(DateTimeUnit unit, DateTimeZone timeZone) {
this.unit = unit;
this.field = unit.field();
this.durationField = field.getDurationField();
this.timeZone = timeZone;
}
@Override
public byte id() {
return ID;
}
@Override
public long roundKey(long utcMillis) {
long timeLocal = utcMillis;
timeLocal = timeZone.convertUTCToLocal(utcMillis);
long rounded = field.roundFloor(timeLocal);
return timeZone.convertLocalToUTC(rounded, true, utcMillis);
}
@Override
public long valueForKey(long time) {
assert roundKey(time) == time;
return time;
}
@Override
public long nextRoundingValue(long time) {
long timeLocal = time;
timeLocal = timeZone.convertUTCToLocal(time);
long nextInLocalTime = durationField.add(timeLocal, 1);
return timeZone.convertLocalToUTC(nextInLocalTime, true);
}
@Override
public void readFrom(StreamInput in) throws IOException {
unit = DateTimeUnit.resolve(in.readByte());
field = unit.field();
durationField = field.getDurationField();
timeZone = DateTimeZone.forID(in.readString());
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeByte(unit.id());
out.writeString(timeZone.getID());
}
}
static class TimeIntervalRounding extends TimeZoneRounding {
final static byte ID = 2;
private long interval;
private DateTimeZone timeZone;
TimeIntervalRounding() { // for serialization
}
TimeIntervalRounding(long interval, DateTimeZone timeZone) {
if (interval < 1)
throw new ElasticsearchIllegalArgumentException("Zero or negative time interval not supported");
this.interval = interval;
this.timeZone = timeZone;
}
@Override
public byte id() {
return ID;
}
@Override
public long roundKey(long utcMillis) {
long timeLocal = utcMillis;
timeLocal = timeZone.convertUTCToLocal(utcMillis);
long rounded = Rounding.Interval.roundValue(Rounding.Interval.roundKey(timeLocal, interval), interval);
return timeZone.convertLocalToUTC(rounded, true);
}
@Override
public long valueForKey(long time) {
assert roundKey(time) == time;
return time;
}
@Override
public long nextRoundingValue(long time) {
long timeLocal = time;
timeLocal = timeZone.convertUTCToLocal(time);
long next = timeLocal + interval;
return timeZone.convertLocalToUTC(next, true);
}
@Override
public void readFrom(StreamInput in) throws IOException {
interval = in.readVLong();
timeZone = DateTimeZone.forID(in.readString());
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVLong(interval);
out.writeString(timeZone.getID());
}
}
}
| |
package fr.tvbarthel.lib.blurdialogfragment;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.Toolbar;
import android.view.WindowManager;
/**
* Encapsulate dialog behavior with blur effect for
* app using {@link android.support.v4.app.DialogFragment}.
* <p/>
* All the screen behind the dialog will be blurred except the action bar.
*/
public abstract class SupportBlurDialogFragment extends DialogFragment {
/**
* Engine used to blur.
*/
private BlurDialogEngine mBlurEngine;
/**
* Allow to set a Toolbar which isn't set as actionbar.
*/
private Toolbar mToolbar;
/**
* Dimming policy.
*/
private boolean mDimmingEffect;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (mBlurEngine != null) {
mBlurEngine.onAttach(activity); // re attached
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBlurEngine = new BlurDialogEngine(getActivity());
if (mToolbar != null) {
mBlurEngine.setToolbar(mToolbar);
}
int radius = getBlurRadius();
if (radius <= 0) {
throw new IllegalArgumentException("Blur radius must be strictly positive. Found : " + radius);
}
mBlurEngine.setBlurRadius(radius);
float factor = getDownScaleFactor();
if (factor <= 1.0) {
throw new IllegalArgumentException("Down scale must be strictly greater than 1.0. Found : " + factor);
}
mBlurEngine.setDownScaleFactor(factor);
mBlurEngine.setUseRenderScript(isRenderScriptEnable());
mBlurEngine.debug(isDebugEnable());
mBlurEngine.setBlurActionBar(isActionBarBlurred());
mDimmingEffect = isDimmingEnable();
}
@Override
public void onStart() {
Dialog dialog = getDialog();
if (dialog != null) {
// enable or disable dimming effect.
if (!mDimmingEffect) {
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
}
// add default fade to the dialog if no window animation has been set.
int currentAnimation = dialog.getWindow().getAttributes().windowAnimations;
if (currentAnimation == 0) {
dialog.getWindow().getAttributes().windowAnimations
= R.style.BlurDialogFragment_Default_Animation;
}
}
super.onStart();
}
@Override
public void onResume() {
super.onResume();
mBlurEngine.onResume(getRetainInstance());
}
@Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
mBlurEngine.onDismiss();
}
@Override
public void onDetach() {
super.onDetach();
mBlurEngine.onDetach();
}
@Override
public void onDestroyView() {
if (getDialog() != null) {
getDialog().setDismissMessage(null);
}
super.onDestroyView();
}
/**
* Allow to set a Toolbar which isn't set as ActionBar.
* <p/>
* Must be called before onCreate.
*
* @param toolBar toolBar
*/
public void setToolbar(Toolbar toolBar) {
mToolbar = toolBar;
if (mBlurEngine != null) {
mBlurEngine.setToolbar(toolBar);
}
}
/**
* For inheritance purpose.
* <p/>
* Enable or disable debug mode.
*
* @return true if debug mode should be enabled.
*/
protected boolean isDebugEnable() {
return BlurDialogEngine.DEFAULT_DEBUG_POLICY;
}
/**
* For inheritance purpose.
* <p/>
* Allow to customize the down scale factor.
* <p/>
* The factor down scaled factor used to reduce the size of the source image.
* Range : ]1.0,infinity)
*
* @return customized down scaled factor.
*/
protected float getDownScaleFactor() {
return BlurDialogEngine.DEFAULT_BLUR_DOWN_SCALE_FACTOR;
}
/**
* For inheritance purpose.
* <p/>
* Allow to customize the blur radius factor.
* <p/>
* radius down scaled factor used to reduce the size of the source image.
* Range : [1,infinity)
*
* @return customized blur radius.
*/
protected int getBlurRadius() {
return BlurDialogEngine.DEFAULT_BLUR_RADIUS;
}
/**
* For inheritance purpose.
* <p/>
* Enable or disable the dimming effect.
* <p/>
* Disabled by default.
*
* @return enable true to enable the dimming effect.
*/
protected boolean isDimmingEnable() {
return BlurDialogEngine.DEFAULT_DIMMING_POLICY;
}
/**
* For inheritance purpose.
* <p/>
* Enable or disable the blur effect on the action bar.
* <p/>
* Disable by default.
*
* @return true to enable the blur effect on the action bar.
*/
protected boolean isActionBarBlurred() {
return BlurDialogEngine.DEFAULT_ACTION_BAR_BLUR;
}
/**
* For inheritance purpose.
* <p/>
* Enable or disable RenderScript.
* <p/>
* Disable by default.
* <p/>
* Don't forget to add those lines to your build.gradle if your are using Renderscript
* <pre>
* defaultConfig {
* ...
* renderscriptTargetApi 22
* renderscriptSupportModeEnabled true
* ...
* }
* </pre>
*
* @return true to enable RenderScript.
*/
protected boolean isRenderScriptEnable() {
return BlurDialogEngine.DEFAULT_USE_RENDERSCRIPT;
}
}
| |
/**
* Copyright 2007-2016, Kaazing Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaazing.nuklei.reaktor.internal;
import static java.lang.String.format;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.sort;
import static java.util.Collections.unmodifiableMap;
import static java.util.concurrent.TimeUnit.MICROSECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static org.agrona.IoUtil.tmpDirName;
import static org.agrona.LangUtil.rethrowUnchecked;
import static org.apache.commons.cli.Option.builder;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.function.Predicate;
import org.agrona.ErrorHandler;
import org.agrona.collections.ArrayUtil;
import org.agrona.concurrent.Agent;
import org.agrona.concurrent.AgentRunner;
import org.agrona.concurrent.BackoffIdleStrategy;
import org.agrona.concurrent.IdleStrategy;
import org.agrona.concurrent.SigIntBarrier;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.kaazing.nuklei.Configuration;
import org.kaazing.nuklei.Controller;
import org.kaazing.nuklei.ControllerFactory;
import org.kaazing.nuklei.Nukleus;
import org.kaazing.nuklei.NukleusFactory;
public final class Reaktor implements AutoCloseable
{
private final AgentRunner runner;
private final Map<Class<? extends Controller>, Controller> controllersByKind;
private Reaktor(
Configuration config,
Predicate<String> nukleusIncludes,
Predicate<Class<? extends Controller>> controllerIncludes)
{
NukleusFactory nukleusFactory = NukleusFactory.instantiate();
Nukleus[] nuklei = new Nukleus[0];
for (String name : nukleusFactory.names())
{
if (nukleusIncludes.test(name))
{
Nukleus nukleus = nukleusFactory.create(name, config);
nuklei = ArrayUtil.add(nuklei, nukleus);
}
}
ControllerFactory controllerFactory = ControllerFactory.instantiate();
Controller[] controllers = new Controller[0];
Map<Class<? extends Controller>, Controller> controllersByKind = new HashMap<>();
for (Class<? extends Controller> kind : controllerFactory.kinds())
{
if (controllerIncludes.test(kind))
{
Controller controller = controllerFactory.create(kind, config);
controllersByKind.put(kind, controller);
controllers = ArrayUtil.add(controllers, controller);
}
}
this.controllersByKind = unmodifiableMap(controllersByKind);
final Nukleus[] nuklei0 = nuklei;
final Controller[] controllers0 = controllers;
IdleStrategy idleStrategy = new BackoffIdleStrategy(64, 64, NANOSECONDS.toNanos(64L), MICROSECONDS.toNanos(64L));
ErrorHandler errorHandler = throwable -> throwable.printStackTrace(System.err);
Agent agent = new Agent()
{
@Override
public String roleName()
{
return "reaktor";
}
@Override
public int doWork() throws Exception
{
int work = 0;
for (int i=0; i < nuklei0.length; i++)
{
work += nuklei0[i].process();
}
for (int i=0; i < controllers0.length; i++)
{
work += controllers0[i].process();
}
return work;
}
};
this.runner = new AgentRunner(idleStrategy, errorHandler, null, agent);
}
public <T extends Controller> T controller(
Class<T> kind)
{
return kind.cast(controllersByKind.get(kind));
}
public Reaktor start()
{
new Thread(runner).start();
return this;
}
@Override
public void close() throws Exception
{
try
{
runner.close();
}
catch (final Exception ex)
{
rethrowUnchecked(ex);
}
}
public static Reaktor launch(
Configuration config,
Predicate<String> includes)
{
return launch(config, includes, k -> false);
}
public static Reaktor init(
Configuration config,
Predicate<String> nuklei,
Predicate<Class<? extends Controller>> controllers)
{
return new Reaktor(config, nuklei, controllers);
}
public static Reaktor launch(
Configuration config,
Predicate<String> nuklei,
Predicate<Class<? extends Controller>> controllers)
{
Reaktor reaktor = init(config, nuklei, controllers);
reaktor.start();
return reaktor;
}
public static void main(final String[] args) throws Exception
{
CommandLineParser parser = new DefaultParser();
Options options = new Options();
options.addOption(builder("d").longOpt("directory").hasArg().desc("configuration directory").build());
options.addOption(builder("h").longOpt("help").desc("print this message").build());
options.addOption(builder("n").longOpt("nukleus").hasArgs().desc("nukleus name").build());
CommandLine cmdline = parser.parse(options, args);
if (cmdline.hasOption("help"))
{
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("reaktor", options);
}
else
{
String directory = cmdline.getOptionValue("directory", format("%s/org.kaazing.nuklei.reaktor", tmpDirName()));
String[] nuklei = cmdline.getOptionValues("nukleus");
Properties properties = new Properties();
properties.setProperty(Configuration.DIRECTORY_PROPERTY_NAME, directory);
Configuration config = new Configuration(properties);
Predicate<String> includes = name -> true;
if (nuklei != null)
{
Comparator<String> comparator = (o1, o2) -> o1.compareTo(o2);
sort(nuklei, comparator);
includes = name -> binarySearch(nuklei, name, comparator) >= 0;
}
try (Reaktor reaktor = Reaktor.launch(config, includes))
{
System.out.println("Started in " + directory);
new SigIntBarrier().await();
}
}
}
}
| |
package quickfix.fix44;
import quickfix.FieldNotFound;
public class BusinessMessageReject extends Message
{
static final long serialVersionUID = 20050617;
public static final String MSGTYPE = "j";
public BusinessMessageReject()
{
super();
getHeader().setField(new quickfix.field.MsgType(MSGTYPE));
}
public BusinessMessageReject(quickfix.field.RefMsgType refMsgType, quickfix.field.BusinessRejectReason businessRejectReason) {
this();
setField(refMsgType);
setField(businessRejectReason);
}
public void set(quickfix.field.RefSeqNum value)
{
setField(value);
}
public quickfix.field.RefSeqNum get(quickfix.field.RefSeqNum value) throws FieldNotFound
{
getField(value);
return value;
}
public quickfix.field.RefSeqNum getRefSeqNum() throws FieldNotFound
{
quickfix.field.RefSeqNum value = new quickfix.field.RefSeqNum();
getField(value);
return value;
}
public boolean isSet(quickfix.field.RefSeqNum field)
{
return isSetField(field);
}
public boolean isSetRefSeqNum()
{
return isSetField(45);
}
public void set(quickfix.field.RefMsgType value)
{
setField(value);
}
public quickfix.field.RefMsgType get(quickfix.field.RefMsgType value) throws FieldNotFound
{
getField(value);
return value;
}
public quickfix.field.RefMsgType getRefMsgType() throws FieldNotFound
{
quickfix.field.RefMsgType value = new quickfix.field.RefMsgType();
getField(value);
return value;
}
public boolean isSet(quickfix.field.RefMsgType field)
{
return isSetField(field);
}
public boolean isSetRefMsgType()
{
return isSetField(372);
}
public void set(quickfix.field.BusinessRejectRefID value)
{
setField(value);
}
public quickfix.field.BusinessRejectRefID get(quickfix.field.BusinessRejectRefID value) throws FieldNotFound
{
getField(value);
return value;
}
public quickfix.field.BusinessRejectRefID getBusinessRejectRefID() throws FieldNotFound
{
quickfix.field.BusinessRejectRefID value = new quickfix.field.BusinessRejectRefID();
getField(value);
return value;
}
public boolean isSet(quickfix.field.BusinessRejectRefID field)
{
return isSetField(field);
}
public boolean isSetBusinessRejectRefID()
{
return isSetField(379);
}
public void set(quickfix.field.BusinessRejectReason value)
{
setField(value);
}
public quickfix.field.BusinessRejectReason get(quickfix.field.BusinessRejectReason value) throws FieldNotFound
{
getField(value);
return value;
}
public quickfix.field.BusinessRejectReason getBusinessRejectReason() throws FieldNotFound
{
quickfix.field.BusinessRejectReason value = new quickfix.field.BusinessRejectReason();
getField(value);
return value;
}
public boolean isSet(quickfix.field.BusinessRejectReason field)
{
return isSetField(field);
}
public boolean isSetBusinessRejectReason()
{
return isSetField(380);
}
public void set(quickfix.field.Text value)
{
setField(value);
}
public quickfix.field.Text get(quickfix.field.Text value) throws FieldNotFound
{
getField(value);
return value;
}
public quickfix.field.Text getText() throws FieldNotFound
{
quickfix.field.Text value = new quickfix.field.Text();
getField(value);
return value;
}
public boolean isSet(quickfix.field.Text field)
{
return isSetField(field);
}
public boolean isSetText()
{
return isSetField(58);
}
public void set(quickfix.field.EncodedTextLen value)
{
setField(value);
}
public quickfix.field.EncodedTextLen get(quickfix.field.EncodedTextLen value) throws FieldNotFound
{
getField(value);
return value;
}
public quickfix.field.EncodedTextLen getEncodedTextLen() throws FieldNotFound
{
quickfix.field.EncodedTextLen value = new quickfix.field.EncodedTextLen();
getField(value);
return value;
}
public boolean isSet(quickfix.field.EncodedTextLen field)
{
return isSetField(field);
}
public boolean isSetEncodedTextLen()
{
return isSetField(354);
}
public void set(quickfix.field.EncodedText value)
{
setField(value);
}
public quickfix.field.EncodedText get(quickfix.field.EncodedText value) throws FieldNotFound
{
getField(value);
return value;
}
public quickfix.field.EncodedText getEncodedText() throws FieldNotFound
{
quickfix.field.EncodedText value = new quickfix.field.EncodedText();
getField(value);
return value;
}
public boolean isSet(quickfix.field.EncodedText field)
{
return isSetField(field);
}
public boolean isSetEncodedText()
{
return isSetField(355);
}
}
| |
/*
*
* * Copyright 2010-2016 OrientDB LTD (info(-at-)orientdb.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.etl.loader;
import static org.assertj.core.api.Assertions.assertThat;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.exception.OConfigurationException;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.index.OIndexManagerAbstract;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.orientechnologies.orient.etl.OETLBaseTest;
import java.util.List;
import org.junit.Test;
/** Created by frank on 9/14/15. */
public class OETLOrientDBLoaderTest extends OETLBaseTest {
@Test(expected = OConfigurationException.class)
public void shouldFailToManageRemoteServer() throws Exception {
configure(
"{source: { content: { value: 'name,surname\nJay,Miner' } }, extractor : { csv: {} }, loader: { orientdb: {\n"
+ " dbURL: \"remote:sadserver/OETLBaseTest\",\n"
+ " dbUser: \"admin\",\n"
+ " dbPassword: \"admin\",\n"
+ " serverUser: \"admin\",\n"
+ " serverPassword: \"admin\",\n"
+ " dbAutoCreate: true,\n"
+ " tx: false,\n"
+ " batchCommit: 1000,\n"
+ " wal : true,\n"
+ " dbType: \"graph\",\n"
+ " classes: [\n"
+ " {name:\"Person\", extends: \"V\" },\n"
+ " ],\n"
+ " indexes: [{class:\"V\" , fields:[\"surname:String\"], \"type\":\"NOTUNIQUE\", \"metadata\": { \"ignoreNullValues\" : \"false\"}} ] } } }");
proc.execute();
}
@Test
public void testAddMetadataToIndex() {
configure(
"{source: { content: { value: 'name,surname\nJay,Miner' } }, extractor : { csv: {} }, loader: { orientdb: {\n"
+ " dbURL: 'memory:"
+ name.getMethodName()
+ "',\n"
+ " dbUser: \"admin\",\n"
+ " dbPassword: \"admin\",\n"
+ " dbAutoCreate: true,\n"
+ " tx: false,\n"
+ " batchCommit: 1000,\n"
+ " wal : true,\n"
+ " dbType: \"graph\",\n"
+ " classes: [\n"
+ " {name:\"Person\", extends: \"V\" },\n"
+ " ],\n"
+ " indexes: [{class:\"V\" , fields:[\"surname:String\"], \"type\":\"NOTUNIQUE\", \"metadata\": { \"ignoreNullValues\" : \"false\"}} ] } } }");
proc.execute();
ODatabaseDocumentInternal db = (ODatabaseDocumentInternal) proc.getLoader().getPool().acquire();
final OIndexManagerAbstract indexManager = db.getMetadata().getIndexManagerInternal();
assertThat(indexManager.existsIndex("V.surname")).isTrue();
final ODocument indexMetadata = indexManager.getIndex(db, "V.surname").getMetadata();
assertThat(indexMetadata.containsField("ignoreNullValues")).isTrue();
assertThat(indexMetadata.<String>field("ignoreNullValues")).isEqualTo("false");
}
@Test
public void testCreateLuceneIndex() {
configure(
"{source: { content: { value: 'name,surname\nJay,Miner' } }, extractor : { csv: {} }, "
+ "\"transformers\": [\n"
+ " {\n"
+ " \"vertex\": {\n"
+ " \"class\": \"Person\",\n"
+ " \"skipDuplicates\": true\n"
+ " }\n"
+ " }],"
+ "loader: { orientdb: {\n"
+ " dbURL: 'memory:"
+ name.getMethodName()
+ "',\n"
+ " dbUser: \"admin\",\n"
+ " dbPassword: \"admin\",\n"
+ " dbAutoCreate: true,\n"
+ " tx: false,\n"
+ " batchCommit: 1000,\n"
+ " wal : true,\n"
+ " dbType: \"graph\",\n"
+ " classes: [\n"
+ " {name:\"Person\", extends: \"V\" },\n"
+ " ],\n"
+ " indexes: [{class:\"Person\" , fields:[\"surname:String\"], \"type\":\"FULLTEXT\", \"algorithm\":\"LUCENE\", \"metadata\": { \"ignoreNullValues\" : \"false\"}} ] } } }");
proc.execute();
ODatabaseDocumentInternal db = (ODatabaseDocumentInternal) proc.getLoader().getPool().acquire();
final OIndexManagerAbstract indexManager = db.getMetadata().getIndexManagerInternal();
assertThat(indexManager.existsIndex("Person.surname")).isTrue();
final OIndex index = indexManager.getIndex(db, "Person.surname");
final ODocument indexMetadata = index.getMetadata();
assertThat(index.getAlgorithm()).isEqualTo("LUCENE");
assertThat(indexMetadata.containsField("ignoreNullValues")).isTrue();
assertThat(indexMetadata.<String>field("ignoreNullValues")).isEqualTo("false");
final OResultSet resultSet = db.query("select from Person where search_class('mi*')=true");
assertThat(resultSet).hasSize(1);
resultSet.close();
}
@Test
public void shouldSaveDocumentsOnGivenCluster() {
configure(
"{source: { content: { value: 'name,surname\nJay,Miner' } }, extractor : { csv: {} }, loader: { orientdb: {\n"
+ " dbURL: \"memory:"
+ name.getMethodName()
+ "\",\n"
+ " dbUser: \"admin\",\n"
+ " dbPassword: \"admin\",\n"
+ " dbAutoCreate: true,\n"
+ " cluster : \"myCluster\",\n"
+ " tx: false,\n"
+ " batchCommit: 1000,\n"
+ " wal : true,\n"
+ " dbType: \"graph\",\n"
+ " classes: [\n"
+ " {name:\"Person\", extends: \"V\" },\n"
+ " ],\n"
+ " indexes: [{class:\"V\" , fields:[\"surname:String\"], \"type\":\"NOTUNIQUE\", \"metadata\": { \"ignoreNullValues\" : \"false\"}} ] } } }");
proc.execute();
ODatabaseDocument db = proc.getLoader().getPool().acquire();
int idByName = db.getClusterIdByName("myCluster");
OResultSet resultSet = db.query("SELECT from V");
resultSet
.vertexStream()
.forEach(v -> assertThat((v.getIdentity()).getClusterId()).isEqualTo(idByName));
resultSet.close();
db.close();
}
@Test
public void shouldSaveDocuments() {
configure(
"{source: { content: { value: 'name,surname,@class\nJay,Miner,Person' } }, extractor : { csv: {} }, loader: { orientdb: {\n"
+ " dbURL: 'memory:"
+ name.getMethodName()
+ "',\n"
+ " dbUser: \"admin\",\n"
+ " dbPassword: \"admin\",\n"
+ " dbAutoCreate: true,\n tx: false,\n"
+ " batchCommit: 1000,\n"
+ " wal : false,\n"
+ " dbType: \"document\" , \"classes\": [\n"
+ " {\n"
+ " \"name\": \"Person\"\n"
+ " },\n"
+ " {\n"
+ " \"name\": \"UpdateDetails\"\n"
+ " }\n"
+ " ] } } }");
proc.execute();
ODatabaseDocument db = proc.getLoader().getPool().acquire();
List<?> res = db.query(new OSQLSynchQuery<ODocument>("SELECT FROM Person"));
assertThat(res.size()).isEqualTo(1);
db.close();
}
@Test
public void shouldSaveDocumentsWithPredefinedSchema() {
// configure
configure(
"{source: { content: { value: 'name,surname,married,birthday\nJay,Miner,false,1970-01-01 05:30:00' } }, "
+ "extractor : { csv: {columns:['name:string','surname:string','married:boolean','birthday:datetime'], dateFormat :'yyyy-MM-dd HH:mm:ss'} }, loader: { orientdb: {\n"
+ " dbURL: 'memory:"
+ name.getMethodName()
+ "', class:'Person', dbUser: \"admin\",\n"
+ " dbPassword: \"admin\",\n"
+ " dbAutoCreate: false,\n tx: false,\n"
+ " batchCommit: 1000,\n"
+ " wal : false,\n"
+ " dbType: \"document\" } } }");
// create class
ODatabaseDocument db = proc.getLoader().getPool().acquire();
db.command("CREATE Class Person");
db.command("CREATE property Person.name STRING");
db.command("CREATE property Person.surname STRING");
db.command("CREATE property Person.married BOOLEAN");
db.command("CREATE property Person.birthday DATETIME");
db.close();
// import data
proc.execute();
db = proc.getLoader().getPool().acquire();
OResultSet res = db.query("SELECT FROM Person");
assertThat(res).hasSize(1);
res.close();
db.close();
}
}
| |
/*
* 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.sling.discovery.impl.common.heartbeat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.jcr.Property;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.sling.api.resource.ModifiableValueMap;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.commons.testing.junit.categories.Slow;
import org.apache.sling.discovery.TopologyEvent;
import org.apache.sling.discovery.TopologyEventListener;
import org.apache.sling.discovery.TopologyView;
import org.apache.sling.discovery.base.its.setup.VirtualInstance;
import org.apache.sling.discovery.impl.DiscoveryServiceImpl;
import org.apache.sling.discovery.impl.cluster.voting.VotingHelper;
import org.apache.sling.discovery.impl.cluster.voting.VotingView;
import org.apache.sling.discovery.impl.setup.FullJR2VirtualInstance;
import org.apache.sling.discovery.impl.setup.FullJR2VirtualInstanceBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import junitx.util.PrivateAccessor;
public class HeartbeatTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
class SimpleTopologyEventListener implements TopologyEventListener {
private List<TopologyEvent> events = new LinkedList<TopologyEvent>();
private TopologyEvent lastEvent;
private int eventCount;
private final String name;
public SimpleTopologyEventListener(String name) {
this.name = name;
}
@Override
public void handleTopologyEvent(TopologyEvent event) {
events.add(event);
String msg = event.toString();
TopologyView newView = event.getNewView();
switch(event.getType()) {
case PROPERTIES_CHANGED: {
msg = String.valueOf(TopologyEvent.Type.PROPERTIES_CHANGED);
break;
}
case TOPOLOGY_CHANGED: {
msg = TopologyEvent.Type.TOPOLOGY_CHANGED + ", newView contains "+newView.getInstances().size()+", newView.isCurrent="+newView.isCurrent();
break;
}
case TOPOLOGY_CHANGING: {
msg = TopologyEvent.Type.TOPOLOGY_CHANGING + ", oldView contained "+event.getOldView().getInstances().size()+", oldView.isCurrent="+event.getOldView().isCurrent();
break;
}
case TOPOLOGY_INIT: {
if (newView==null) {
msg = TopologyEvent.Type.TOPOLOGY_INIT + ", newView contains null: "+newView;
} else if (newView.getInstances()==null) {
msg = TopologyEvent.Type.TOPOLOGY_INIT + ", newView contains no instances:"+newView+", newView.isCurrent="+newView.isCurrent();
} else {
msg = TopologyEvent.Type.TOPOLOGY_INIT + ", newView contains "+newView.getInstances().size()+", newView.isCurrent="+newView.isCurrent();
}
break;
}
}
LoggerFactory.getLogger(this.getClass()).info("handleTopologyEvent["+name+"]: "+msg);
lastEvent = event;
eventCount++;
}
public int getEventCount() {
return eventCount;
}
public TopologyEvent getLastEvent() {
return lastEvent;
}
}
Set<VirtualInstance> instances = new HashSet<VirtualInstance>();
private Level logLevel;
@Before
public void setup() throws Exception {
final org.apache.log4j.Logger discoveryLogger = LogManager.getRootLogger().getLogger("org.apache.sling.discovery");
logLevel = discoveryLogger.getLevel();
discoveryLogger.setLevel(Level.TRACE);
}
@After
public void tearDown() throws Exception {
final org.apache.log4j.Logger discoveryLogger = LogManager.getRootLogger().getLogger("org.apache.sling.discovery");
discoveryLogger.setLevel(logLevel);
Iterator<VirtualInstance> it = instances.iterator();
while(it.hasNext()) {
VirtualInstance i = it.next();
i.stop();
}
}
@Category(Slow.class) //TODO: takes env 40sec
@Test
public void testPartitioning() throws Throwable {
doTestPartitioning(true);
}
@Category(Slow.class) //TODO: takes env 35sec
@Test
public void testPartitioningWithFailingScheduler() throws Throwable {
doTestPartitioning(false);
}
public FullJR2VirtualInstanceBuilder newBuilder() {
return new FullJR2VirtualInstanceBuilder();
}
public void doTestPartitioning(boolean scheduler) throws Throwable {
logger.info("doTestPartitioning: creating slowMachine...");
FullJR2VirtualInstanceBuilder builder = newBuilder();
builder.setDebugName("slow")
.newRepository("/var/discovery/impl/", true)
.setConnectorPingTimeout(10 /* 10 sec timeout */)
.setConnectorPingInterval(999 /* 999 sec interval: to disable it */)
.setMinEventDelay(0)
.withFailingScheduler(!scheduler);
FullJR2VirtualInstance slowMachine = builder.fullBuild();
assertEquals(1, slowMachine.getDiscoveryService().getTopology().getInstances().size());
assertEquals(slowMachine.getSlingId(), slowMachine.getDiscoveryService().getTopology().getInstances().iterator().next().getSlingId());
instances.add(slowMachine);
Thread.sleep(10); // wait 10ms to ensure 'slowMachine' has the lowerst leaderElectionId (to become leader)
SimpleTopologyEventListener slowListener = new SimpleTopologyEventListener("slow");
slowMachine.bindTopologyEventListener(slowListener);
logger.info("doTestPartitioning: creating fastMachine1...");
FullJR2VirtualInstanceBuilder fastBuilder1 = newBuilder();
fastBuilder1.setDebugName("fast1")
.useRepositoryOf(slowMachine)
.setConnectorPingTimeout(10)
.setConnectorPingInterval(1)
.setMinEventDelay(0)
.withFailingScheduler(!scheduler);
FullJR2VirtualInstance fastMachine1 = fastBuilder1.fullBuild();
assertEquals(1, fastMachine1.getDiscoveryService().getTopology().getInstances().size());
assertEquals(fastMachine1.getSlingId(), fastMachine1.getDiscoveryService().getTopology().getInstances().iterator().next().getSlingId());
instances.add(fastMachine1);
Thread.sleep(10); // wait 10ms to ensure 'fastMachine1' has the 2nd lowerst leaderElectionId (to become leader during partitioning)
SimpleTopologyEventListener fastListener1 = new SimpleTopologyEventListener("fast1");
fastMachine1.bindTopologyEventListener(fastListener1);
logger.info("doTestPartitioning: creating fastMachine2...");
FullJR2VirtualInstanceBuilder fullBuilder2 = newBuilder();
fullBuilder2.setDebugName("fast2")
.useRepositoryOf(slowMachine)
.setConnectorPingTimeout(10)
.setConnectorPingInterval(1)
.setMinEventDelay(0)
.withFailingScheduler(!scheduler);
FullJR2VirtualInstance fastMachine2 = fullBuilder2.fullBuild();
assertEquals(1, fastMachine2.getDiscoveryService().getTopology().getInstances().size());
assertEquals(fastMachine2.getSlingId(), fastMachine2.getDiscoveryService().getTopology().getInstances().iterator().next().getSlingId());
instances.add(fastMachine2);
SimpleTopologyEventListener fastListener2 = new SimpleTopologyEventListener("fast2");
fastMachine2.bindTopologyEventListener(fastListener2);
logger.info("doTestPartitioning: creating fastMachine3...");
FullJR2VirtualInstanceBuilder fullBuilder3 = newBuilder();
fullBuilder3.setDebugName("fast3")
.useRepositoryOf(slowMachine)
.setConnectorPingTimeout(10)
.setConnectorPingInterval(1)
.setMinEventDelay(0)
.withFailingScheduler(!scheduler);
FullJR2VirtualInstance fastMachine3 = fullBuilder3.fullBuild();
assertEquals(1, fastMachine3.getDiscoveryService().getTopology().getInstances().size());
assertEquals(fastMachine3.getSlingId(), fastMachine3.getDiscoveryService().getTopology().getInstances().iterator().next().getSlingId());
instances.add(fastMachine3);
SimpleTopologyEventListener fastListener3 = new SimpleTopologyEventListener("fast3");
fastMachine3.bindTopologyEventListener(fastListener3);
logger.info("doTestPartitioning: creating fastMachine4...");
FullJR2VirtualInstanceBuilder fullBuilder4 = newBuilder();
fullBuilder4.setDebugName("fast4")
.useRepositoryOf(slowMachine)
.setConnectorPingTimeout(10)
.setConnectorPingInterval(1)
.setMinEventDelay(0)
.withFailingScheduler(!scheduler);
FullJR2VirtualInstance fastMachine4 = fullBuilder4.fullBuild();
assertEquals(1, fastMachine4.getDiscoveryService().getTopology().getInstances().size());
assertEquals(fastMachine4.getSlingId(), fastMachine4.getDiscoveryService().getTopology().getInstances().iterator().next().getSlingId());
instances.add(fastMachine4);
SimpleTopologyEventListener fastListener4 = new SimpleTopologyEventListener("fast4");
fastMachine4.bindTopologyEventListener(fastListener4);
logger.info("doTestPartitioning: --------------------------------");
logger.info("doTestPartitioning: letting heartbeats be sent by all instances for a few loops...");
logger.info("doTestPartitioning: --------------------------------");
HeartbeatHandler hhSlow = slowMachine.getHeartbeatHandler();
for(int i=0; i<5; i++) {
logger.info("doTestPartitioning: --------------------------------");
logger.info("doTestPartitioning: doing pinging with hhSlow now...");
logger.info("doTestPartitioning: --------------------------------");
synchronized(lock(hhSlow)) {
hhSlow.issueHeartbeat();
hhSlow.doCheckView();
}
if (!scheduler) {
logger.info("doTestPartitioning: --------------------------------");
logger.info("doTestPartitioning: doing pinging with fastMachine1 now...");
logger.info("doTestPartitioning: --------------------------------");
synchronized(lock(fastMachine1.getHeartbeatHandler())) {
fastMachine1.getHeartbeatHandler().issueHeartbeat();
fastMachine1.getHeartbeatHandler().doCheckView();
}
logger.info("doTestPartitioning: --------------------------------");
logger.info("doTestPartitioning: doing pinging with fastMachine2 now...");
logger.info("doTestPartitioning: --------------------------------");
synchronized(lock(fastMachine2.getHeartbeatHandler())) {
fastMachine2.getHeartbeatHandler().issueHeartbeat();
fastMachine2.getHeartbeatHandler().doCheckView();
}
logger.info("doTestPartitioning: --------------------------------");
logger.info("doTestPartitioning: doing pinging with fastMachine3 now...");
logger.info("doTestPartitioning: --------------------------------");
synchronized(lock(fastMachine3.getHeartbeatHandler())) {
fastMachine3.getHeartbeatHandler().issueHeartbeat();
fastMachine3.getHeartbeatHandler().doCheckView();
}
logger.info("doTestPartitioning: --------------------------------");
logger.info("doTestPartitioning: doing pinging with fastMachine4 now...");
logger.info("doTestPartitioning: --------------------------------");
synchronized(lock(fastMachine4.getHeartbeatHandler())) {
fastMachine4.getHeartbeatHandler().issueHeartbeat();
fastMachine4.getHeartbeatHandler().doCheckView();
}
}
Thread.sleep(1000);
}
// at this stage the 4 fast plus the slow instance should all see each other
logger.info("doTestPartitioning: all 4 instances should have agreed on seeing each other");
assertNotNull(fastListener1.getLastEvent());
assertEquals(TopologyEvent.Type.TOPOLOGY_INIT, fastListener1.getLastEvent().getType());
assertEquals(5, fastListener1.getLastEvent().getNewView().getInstances().size());
assertFalse(fastListener1.getLastEvent().getNewView().getLocalInstance().isLeader());
assertNotNull(fastListener2.getLastEvent());
assertEquals(TopologyEvent.Type.TOPOLOGY_INIT, fastListener2.getLastEvent().getType());
assertEquals(5, fastListener2.getLastEvent().getNewView().getInstances().size());
assertFalse(fastListener2.getLastEvent().getNewView().getLocalInstance().isLeader());
assertNotNull(fastListener3.getLastEvent());
assertEquals(TopologyEvent.Type.TOPOLOGY_INIT, fastListener3.getLastEvent().getType());
assertEquals(5, fastListener3.getLastEvent().getNewView().getInstances().size());
assertFalse(fastListener3.getLastEvent().getNewView().getLocalInstance().isLeader());
assertNotNull(fastListener4.getLastEvent());
assertEquals(TopologyEvent.Type.TOPOLOGY_INIT, fastListener4.getLastEvent().getType());
assertEquals(5, fastListener4.getLastEvent().getNewView().getInstances().size());
assertFalse(fastListener4.getLastEvent().getNewView().getLocalInstance().isLeader());
assertNotNull(slowListener.getLastEvent());
assertEquals(TopologyEvent.Type.TOPOLOGY_INIT, slowListener.getLastEvent().getType());
assertEquals(5, slowListener.getLastEvent().getNewView().getInstances().size());
assertTrue(slowListener.getLastEvent().getNewView().getLocalInstance().isLeader());
// after 12sec the slow instance' heartbeat should have timed out
logger.info("doTestPartitioning: letting slowMachine NOT send any heartbeats for 12sec, only the fast ones do...");
for(int i=0; i<12; i++) {
if (!scheduler) {
synchronized(lock(fastMachine1.getHeartbeatHandler())) {
fastMachine1.getHeartbeatHandler().issueHeartbeat();
fastMachine1.getHeartbeatHandler().doCheckView();
}
synchronized(lock(fastMachine2.getHeartbeatHandler())) {
fastMachine2.getHeartbeatHandler().issueHeartbeat();
fastMachine2.getHeartbeatHandler().doCheckView();
}
synchronized(lock(fastMachine3.getHeartbeatHandler())) {
fastMachine3.getHeartbeatHandler().issueHeartbeat();
fastMachine3.getHeartbeatHandler().doCheckView();
}
synchronized(lock(fastMachine4.getHeartbeatHandler())) {
fastMachine4.getHeartbeatHandler().issueHeartbeat();
fastMachine4.getHeartbeatHandler().doCheckView();
}
}
Thread.sleep(1000);
}
logger.info("doTestPartitioning: this should now have decoupled slowMachine from the other 4...");
// so the fast listeners should only see 4 instances remaining
for(int i=0; i<7; i++) {
logger.info("doTestPartitioning: sleeping 2sec...");
Thread.sleep(2000);
logger.info("doTestPartitioning: the 4 fast machines should all just see themselves...");
assertEquals(TopologyEvent.Type.TOPOLOGY_CHANGED, fastListener1.getLastEvent().getType());
assertEquals(4, fastListener1.getLastEvent().getNewView().getInstances().size());
assertEquals(TopologyEvent.Type.TOPOLOGY_CHANGED, fastListener2.getLastEvent().getType());
assertEquals(4, fastListener2.getLastEvent().getNewView().getInstances().size());
assertEquals(TopologyEvent.Type.TOPOLOGY_CHANGED, fastListener3.getLastEvent().getType());
assertEquals(4, fastListener3.getLastEvent().getNewView().getInstances().size());
assertEquals(TopologyEvent.Type.TOPOLOGY_CHANGED, fastListener4.getLastEvent().getType());
assertEquals(4, fastListener4.getLastEvent().getNewView().getInstances().size());
assertTrue(fastListener1.getLastEvent().getNewView().getLocalInstance().isLeader());
assertFalse(fastListener2.getLastEvent().getNewView().getLocalInstance().isLeader());
assertFalse(fastListener3.getLastEvent().getNewView().getLocalInstance().isLeader());
assertFalse(fastListener4.getLastEvent().getNewView().getLocalInstance().isLeader());
// and the slow instance should be isolated
assertFalse(slowMachine.getDiscoveryService().getTopology().isCurrent());
// however we can't really make any assertions on how many instances a non-current topology contains...
// assertEquals(5, slowMachine.getDiscoveryService().getTopology().getInstances().size());
if (i==0) {
assertEquals(TopologyEvent.Type.TOPOLOGY_INIT, slowListener.getLastEvent().getType());
} else {
assertEquals(TopologyEvent.Type.TOPOLOGY_CHANGING, slowListener.getLastEvent().getType());
}
//TODO but only after 'handlePotentialTopologyChange' is called
// which either happens via handleTopologyChanged (via the TopologyChangeHandler)
// or via updateProperties
DiscoveryServiceImpl slowDisco = (DiscoveryServiceImpl) slowMachine.getDiscoveryService();
slowDisco.updateProperties();
// that should have triggered an async event - which takes a little moment
Thread.sleep(500);
assertEquals(TopologyEvent.Type.TOPOLOGY_CHANGING, slowListener.getLastEvent().getType());
assertEquals(2, slowListener.getEventCount());
TopologyView slowTopo = slowMachine.getDiscoveryService().getTopology();
assertNotNull(slowTopo);
assertFalse(slowTopo.isCurrent());
// again, can't make any assertion on how many instances the slow non-current view contains...
//assertEquals(5, slowTopo.getInstances().size());
if (!scheduler) {
synchronized(lock(fastMachine1.getHeartbeatHandler())) {
fastMachine1.getHeartbeatHandler().issueHeartbeat();
fastMachine1.getHeartbeatHandler().doCheckView();
}
synchronized(lock(fastMachine2.getHeartbeatHandler())) {
fastMachine2.getHeartbeatHandler().issueHeartbeat();
fastMachine2.getHeartbeatHandler().doCheckView();
}
synchronized(lock(fastMachine3.getHeartbeatHandler())) {
fastMachine3.getHeartbeatHandler().issueHeartbeat();
fastMachine3.getHeartbeatHandler().doCheckView();
}
synchronized(lock(fastMachine4.getHeartbeatHandler())) {
fastMachine4.getHeartbeatHandler().issueHeartbeat();
fastMachine4.getHeartbeatHandler().doCheckView();
}
}
}
for(int i=0; i<4; i++) {
hhSlow.issueHeartbeat();
hhSlow.doCheckView();
if (!scheduler) {
synchronized(lock(fastMachine1.getHeartbeatHandler())) {
fastMachine1.getHeartbeatHandler().issueHeartbeat();
fastMachine1.getHeartbeatHandler().doCheckView();
}
synchronized(lock(fastMachine2.getHeartbeatHandler())) {
fastMachine2.getHeartbeatHandler().issueHeartbeat();
fastMachine2.getHeartbeatHandler().doCheckView();
}
synchronized(lock(fastMachine3.getHeartbeatHandler())) {
fastMachine3.getHeartbeatHandler().issueHeartbeat();
fastMachine3.getHeartbeatHandler().doCheckView();
}
synchronized(lock(fastMachine4.getHeartbeatHandler())) {
fastMachine4.getHeartbeatHandler().issueHeartbeat();
fastMachine4.getHeartbeatHandler().doCheckView();
}
}
Thread.sleep(1000);
}
// now all should be in one cluster again
assertEquals(TopologyEvent.Type.TOPOLOGY_CHANGED, fastListener1.getLastEvent().getType());
assertEquals(5, fastListener1.getLastEvent().getNewView().getInstances().size());
assertEquals(TopologyEvent.Type.TOPOLOGY_CHANGED, fastListener2.getLastEvent().getType());
assertEquals(5, fastListener2.getLastEvent().getNewView().getInstances().size());
assertEquals(TopologyEvent.Type.TOPOLOGY_CHANGED, fastListener3.getLastEvent().getType());
assertEquals(5, fastListener3.getLastEvent().getNewView().getInstances().size());
assertEquals(TopologyEvent.Type.TOPOLOGY_CHANGED, fastListener4.getLastEvent().getType());
assertEquals(5, fastListener4.getLastEvent().getNewView().getInstances().size());
assertEquals(TopologyEvent.Type.TOPOLOGY_CHANGED, slowListener.getLastEvent().getType());
assertEquals(5, slowListener.getLastEvent().getNewView().getInstances().size());
// SLING-5030 part 2 : after rejoin-after-partitioning the slowMachine1 should again be leader
slowMachine.dumpRepo();
assertFalse(slowListener.getLastEvent().getNewView().getLocalInstance().isLeader());
assertTrue(fastListener1.getLastEvent().getNewView().getLocalInstance().isLeader());
assertFalse(fastListener2.getLastEvent().getNewView().getLocalInstance().isLeader());
assertFalse(fastListener3.getLastEvent().getNewView().getLocalInstance().isLeader());
assertFalse(fastListener4.getLastEvent().getNewView().getLocalInstance().isLeader());
}
/**
* This tests the case where one machine is slow with sending heartbeats
* and should thus trigger the second, fast machine to kick it out of the topology.
* But the slow one should also get a TOPOLOGY_CHANGING but just not get a
* TOPOLOGY_CHANGED until it finally sends heartbeats again and the voting can
* happen again.
*/
@Category(Slow.class) //TODO: takes env 25sec
@Test
public void testSlowAndFastMachine() throws Throwable {
doTestSlowAndFastMachine(false);
}
@Category(Slow.class) //TODO: takes env 25sec
@Test
public void testSlowAndFastMachineWithFailingScheduler() throws Throwable {
doTestSlowAndFastMachine(true);
}
public void doTestSlowAndFastMachine(boolean withFailingScheduler) throws Throwable {
logger.info("doTestSlowAndFastMachine: creating slowMachine... (w/o heartbeat runner)");
FullJR2VirtualInstanceBuilder slowBuilder = newBuilder();
slowBuilder.setDebugName("slow")
.newRepository("/var/discovery/impl/", true)
.setConnectorPingTimeout(5 /*5 sec timeout */)
.setConnectorPingInterval(999 /* 999sec interval: to disable it */)
.setMinEventDelay(0)
.withFailingScheduler(withFailingScheduler);
FullJR2VirtualInstance slowMachine = slowBuilder.fullBuild();
instances.add(slowMachine);
SimpleTopologyEventListener slowListener = new SimpleTopologyEventListener("slow");
slowMachine.bindTopologyEventListener(slowListener);
logger.info("doTestSlowAndFastMachine: creating fastMachine... (w/o heartbeat runner)");
FullJR2VirtualInstanceBuilder fastBuilder = newBuilder();
fastBuilder.setDebugName("fast")
.useRepositoryOf(slowMachine)
.setConnectorPingTimeout(5)
.setConnectorPingInterval(999)
.setMinEventDelay(0)
.withFailingScheduler(withFailingScheduler);
FullJR2VirtualInstance fastMachine = fastBuilder.fullBuild();
instances.add(fastMachine);
SimpleTopologyEventListener fastListener = new SimpleTopologyEventListener("fast");
fastMachine.bindTopologyEventListener(fastListener);
HeartbeatHandler hhSlow = slowMachine.getHeartbeatHandler();
HeartbeatHandler hhFast = fastMachine.getHeartbeatHandler();
Thread.sleep(1000);
logger.info("doTestSlowAndFastMachine: no event should have been triggered yet");
assertFalse(fastMachine.getDiscoveryService().getTopology().isCurrent());
assertFalse(slowMachine.getDiscoveryService().getTopology().isCurrent());
assertNull(fastListener.getLastEvent());
assertNull(slowListener.getLastEvent());
// make few rounds of heartbeats so that the two instances see each other
logger.info("doTestSlowAndFastMachine: send a couple of heartbeats to connect the two..");
for(int i=0; i<5; i++) {
synchronized(lock(hhSlow)) {
hhSlow.issueHeartbeat();
hhSlow.doCheckView();
}
synchronized(lock(hhFast)) {
hhFast.issueHeartbeat();
hhFast.doCheckView();
}
Thread.sleep(100);
}
logger.info("doTestSlowAndFastMachine: now the two instances should be connected.");
slowMachine.dumpRepo();
assertEquals(2, slowMachine.getDiscoveryService().getTopology().getInstances().size());
assertEquals(2, fastMachine.getDiscoveryService().getTopology().getInstances().size());
assertEquals(TopologyEvent.Type.TOPOLOGY_INIT, fastListener.getLastEvent().getType());
assertEquals(1, fastListener.getEventCount());
assertEquals(TopologyEvent.Type.TOPOLOGY_INIT, slowListener.getLastEvent().getType());
assertEquals(1, slowListener.getEventCount());
// now let the slow machine be slow while the fast one updates as expected
logger.info("doTestSlowAndFastMachine: last heartbeat of slowMachine.");
synchronized(lock(hhSlow)) {
hhSlow.issueHeartbeat();
}
logger.info("doTestSlowAndFastMachine: while the fastMachine still sends heartbeats...");
for(int i=0; i<6; i++) {
Thread.sleep(1500);
synchronized(lock(hhFast)) {
hhFast.issueHeartbeat();
hhFast.doCheckView();
}
}
logger.info("doTestSlowAndFastMachine: now the fastMachine should have decoupled the slow one");
fastMachine.dumpRepo();
hhFast.doCheckView(); // one more for the start of the vote
fastMachine.dumpRepo();
hhFast.doCheckView(); // and one for the promotion
// after 9 sec hhSlow's heartbeat will have timed out, so hhFast will not see hhSlow anymore
fastMachine.dumpRepo();
assertEquals(TopologyEvent.Type.TOPOLOGY_CHANGED, fastListener.getLastEvent().getType());
assertEquals(3, fastListener.getEventCount());
assertEquals(1, fastMachine.getDiscoveryService().getTopology().getInstances().size());
TopologyView topo = slowMachine.getDiscoveryService().getTopology();
assertFalse(topo.isCurrent());
// after those 6 sec, hhSlow does the check (6sec between heartbeat and check)
logger.info("doTestSlowAndFastMachine: slowMachine is going to do a checkView next - and will detect being decoupled");
hhSlow.doCheckView();
slowMachine.dumpRepo();
logger.info("doTestSlowAndFastMachine: slowMachine is going to also do a heartbeat next");
synchronized(lock(hhSlow)) {
hhSlow.issueHeartbeat();
}
assertEquals(TopologyEvent.Type.TOPOLOGY_CHANGED, fastListener.getLastEvent().getType());
assertEquals(3, fastListener.getEventCount());
assertEquals(TopologyEvent.Type.TOPOLOGY_CHANGING, slowListener.getLastEvent().getType());
assertEquals(2, slowListener.getEventCount());
Thread.sleep(8000);
// even after 8 sec the slow lsitener did not send a TOPOLOGY_CHANGED yet
logger.info("doTestSlowAndFastMachine: after another 8 sec of silence from slowMachine, it should still remain in CHANGING state");
assertEquals(TopologyEvent.Type.TOPOLOGY_CHANGING, slowListener.getLastEvent().getType());
assertFalse(slowMachine.getDiscoveryService().getTopology().isCurrent());
assertEquals(2, slowListener.getEventCount());
assertEquals(TopologyEvent.Type.TOPOLOGY_CHANGED, fastListener.getLastEvent().getType());
assertEquals(1, fastMachine.getDiscoveryService().getTopology().getInstances().size());
assertEquals(3, fastListener.getEventCount());
// make few rounds of heartbeats so that the two instances see each other again
logger.info("doTestSlowAndFastMachine: now let both fast and slow issue heartbeats...");
for(int i=0; i<4; i++) {
synchronized(lock(hhFast)) {
hhFast.issueHeartbeat();
hhFast.doCheckView();
}
synchronized(lock(hhSlow)) {
hhSlow.issueHeartbeat();
hhSlow.doCheckView();
}
Thread.sleep(1000);
}
logger.info("doTestSlowAndFastMachine: by now the two should have joined");
// this should have put the two together again
// even after 8 sec the slow lsitener did not send a TOPOLOGY_CHANGED yet
assertEquals(TopologyEvent.Type.TOPOLOGY_CHANGED, fastListener.getLastEvent().getType());
assertTrue(fastMachine.getDiscoveryService().getTopology().isCurrent());
assertEquals(2, fastMachine.getDiscoveryService().getTopology().getInstances().size());
assertEquals(5, fastListener.getEventCount());
assertEquals(TopologyEvent.Type.TOPOLOGY_CHANGED, slowListener.getLastEvent().getType());
assertTrue(slowMachine.getDiscoveryService().getTopology().isCurrent());
assertEquals(2, slowMachine.getDiscoveryService().getTopology().getInstances().size());
assertEquals(3, slowListener.getEventCount());
}
private Object lock(HeartbeatHandler heartbeatHandler) throws NoSuchFieldException {
//TODO: refactor HeartbeatHandler to provide such a synchronized method
// rather having the test rely on this
return PrivateAccessor.getField(heartbeatHandler, "lock");
}
/**
* SLING-5027 : test to reproduce the voting loop
* (and verify that it's fixed)
*/
@Test
public void testVotingLoop() throws Throwable {
logger.info("testVotingLoop: creating slowMachine1...");
FullJR2VirtualInstanceBuilder slowBuilder1 = newBuilder();
slowBuilder1.setDebugName("slow1")
.newRepository("/var/discovery/impl/", true)
.setConnectorPingTimeout(600 /* 600 sec timeout */)
.setConnectorPingInterval(999 /* 999 sec interval: to disable it */)
.setMinEventDelay(0);
FullJR2VirtualInstance slowMachine1 = slowBuilder1.fullBuild();
instances.add(slowMachine1);
SimpleTopologyEventListener slowListener1 = new SimpleTopologyEventListener("slow1");
slowMachine1.bindTopologyEventListener(slowListener1);
logger.info("testVotingLoop: creating slowMachine2...");
FullJR2VirtualInstanceBuilder slowBuilder2 = newBuilder();
slowBuilder2.setDebugName("slow2")
.useRepositoryOf(slowMachine1)
.setConnectorPingTimeout(600 /* 600 sec timeout */)
.setConnectorPingInterval(999 /* 999 sec interval: to disable it */)
.setMinEventDelay(0);
FullJR2VirtualInstance slowMachine2 = slowBuilder2.fullBuild();
instances.add(slowMachine2);
SimpleTopologyEventListener slowListener2 = new SimpleTopologyEventListener("slow2");
slowMachine2.bindTopologyEventListener(slowListener2);
logger.info("testVotingLoop: creating fastMachine...");
FullJR2VirtualInstanceBuilder fastBuilder = newBuilder();
fastBuilder.setDebugName("fast")
.useRepositoryOf(slowMachine1)
.setConnectorPingTimeout(600 /* 600 sec timeout */)
.setConnectorPingInterval(999 /* 999 sec interval: to disable it */)
.setMinEventDelay(0);
FullJR2VirtualInstance fastMachine = fastBuilder.fullBuild();
instances.add(fastMachine);
SimpleTopologyEventListener fastListener = new SimpleTopologyEventListener("fast");
fastMachine.bindTopologyEventListener(fastListener);
HeartbeatHandler hhSlow1 = slowMachine1.getHeartbeatHandler();
HeartbeatHandler hhSlow2 = slowMachine2.getHeartbeatHandler();
HeartbeatHandler hhFast = fastMachine.getHeartbeatHandler();
Thread.sleep(1000);
logger.info("testVotingLoop: after some initial 1sec sleep no event should yet have been sent");
assertFalse(fastMachine.getDiscoveryService().getTopology().isCurrent());
assertFalse(slowMachine1.getDiscoveryService().getTopology().isCurrent());
assertFalse(slowMachine2.getDiscoveryService().getTopology().isCurrent());
assertNull(fastListener.getLastEvent());
assertNull(slowListener1.getLastEvent());
assertNull(slowListener2.getLastEvent());
// prevent the slow machine from voting
logger.info("testVotingLoop: stopping voting of slowMachine1...");
slowMachine1.stopVoting();
// now let all issue a heartbeat
logger.info("testVotingLoop: letting slow1, slow2 and fast all issue 1 heartbeat");
hhSlow1.issueHeartbeat();
hhSlow2.issueHeartbeat();
hhFast.issueHeartbeat();
// now let the fast one start a new voting, to which
// only the fast one will vote, the slow one doesn't.
// that will cause a voting loop
logger.info("testVotingLoop: let the fast one do a checkView, thus initiate a voting");
hhFast.doCheckView();
Calendar previousVotedAt = null;
for(int i=0; i<5; i++) {
logger.info("testVotingLoop: sleeping 1sec...");
Thread.sleep(1000);
logger.info("testVotingLoop: check to see that there is no voting loop...");
// now check the ongoing votings
ResourceResolverFactory factory = fastMachine.getResourceResolverFactory();
ResourceResolver resourceResolver = factory
.getAdministrativeResourceResolver(null);
try{
List<VotingView> ongoingVotings =
VotingHelper.listOpenNonWinningVotings(resourceResolver, fastMachine.getFullConfig());
assertNotNull(ongoingVotings);
assertEquals(1, ongoingVotings.size());
VotingView ongoingVote = ongoingVotings.get(0);
assertFalse(ongoingVote.isWinning());
assertFalse(ongoingVote.hasVotedYes(slowMachine1.getSlingId()));
assertTrue(ongoingVote.hasVotedYes(slowMachine2.getSlingId()));
final Resource memberResource = ongoingVote.getResource().getChild("members").getChild(slowMachine2.getSlingId());
final ModifiableValueMap memberMap = memberResource.adaptTo(ModifiableValueMap.class);
Property vote = (Property) memberMap.get("vote");
assertEquals(Boolean.TRUE, vote.getBoolean());
Property votedAt = (Property) memberMap.get("votedAt");
if (previousVotedAt==null) {
previousVotedAt = votedAt.getDate();
} else {
assertEquals(previousVotedAt, votedAt.getDate());
}
} catch(Exception e) {
resourceResolver.close();
fail("Exception: "+e);
}
}
}
}
| |
package com.netflix.ndbench.plugin.es;
import com.google.common.collect.ImmutableList;
import com.netflix.ndbench.core.config.IConfiguration;
import com.netflix.ndbench.core.discovery.IClusterDiscovery;
import javax.annotation.Nullable;
import java.util.List;
/**
* Enables integration tests to run such that Docker container initialization can be short circuited in favor
* of running a full Elasticsearch distribution locally, where such distribution is listening on standard ports
* (9200 for REST and 9300 for transport.)
* <p>
* To suppress start up of Elasticsearch in Docker, set the environment variable ES_NDBENCH_NO_DOCKER.
* The main reason you would want to do this is because the current Docker configuration has some issues with
* being run so that requests can be routed through an HTTP traffic proxy -- which is useful for debugging.
*/
public class AbstractPluginTest {
static class MockServiceDiscoverer implements IClusterDiscovery {
int port;
MockServiceDiscoverer(int port) {
this.port = port;
}
@Override
public List<String> getApps() {
return ImmutableList.of();
}
@Override
public List<String> getEndpoints(String appName, int defaultPort) {
return ImmutableList.of("localhost:" + port);
}
}
protected static IEsConfig getConfig(final int portNum,
@Nullable final String forcedHostName,
final String indexName,
final boolean isBulkWrite,
final float maxAcceptableWriteFailures,
final int indexRollsPerHour) {
return new IEsConfig() {
@Override
public String getCluster() {
return "elasticsearch";
}
@Override
public String getHostName() {
return forcedHostName;
}
@Override
public Boolean isHttps() {
return false;
}
@Override
public String getIndexName() {
return indexName;
}
@Override
public Integer getRestClientPort() {
return portNum;
}
@Override
public Integer getBulkWriteBatchSize() {
return 5;
}
@Override
public Boolean isRandomizeStrings() {
return true;
}
@Override
public Integer getIndexRollsPerDay() {
return indexRollsPerHour;
}
@Override
public Integer getConnectTimeoutSeconds() {
return 120;
}
@Override
public Integer getConnectionRequestTimeoutSeconds() {
return 120;
}
@Override
public Integer getSocketTimeoutSeconds() {
return 120;
}
@Override
public Integer getMaxRetryTimeoutSeconds() {
return 120;
}
};
}
protected static IConfiguration getCoreConfig(final int writeRateLimit,
final boolean isAutoTuneEnabled,
final int autoTuneRampPeriodMillisecs,
final int autoTuneIncremenetIntervalMillisecs,
final int autoTuneFinalRate,
float maxAcceptableWriteFailures) {
return new IConfiguration() {
@Override
public void initialize() {
}
@Override
public int getNumKeys() {
return 0;
}
@Override
public int getNumValues() {
return 0;
}
@Override
public int getDataSize() {
return 0;
}
@Override
public boolean isPreloadKeys() {
return false;
}
@Override
public double getZipfExponent() {
return 0.5;
}
@Override
public int getBackfillKeySlots()
{
return 1;
}
@Override
public boolean isWriteEnabled() {
return false;
}
@Override
public boolean isReadEnabled() {
return false;
}
@Override
public int getStatsUpdateFreqSeconds() {
return 0;
}
@Override
public int getStatsResetFreqSeconds() {
return 0;
}
@Override
public boolean isUseVariableDataSize() {
return false;
}
@Override
public int getDataSizeLowerBound() {
return 0;
}
@Override
public int getDataSizeUpperBound() {
return 0;
}
@Override
public boolean isGenerateChecksum() { return false; }
@Override
public boolean isValidateChecksum() { return false; }
@Override
public int getReadRateLimit() {
return 0;
}
@Override
public int getWriteRateLimit() {
return writeRateLimit;
}
@Override
public boolean isAutoTuneEnabled() {
return isAutoTuneEnabled;
}
@Override
public Integer getAutoTuneRampPeriodMillisecs() {
return autoTuneRampPeriodMillisecs;
}
@Override
public Integer getAutoTuneIncrementIntervalMillisecs() {
return autoTuneIncremenetIntervalMillisecs;
}
@Override
public Integer getAutoTuneFinalWriteRate() {
return autoTuneFinalRate;
}
@Override
public Float getAutoTuneWriteFailureRatioThreshold() {
return maxAcceptableWriteFailures;
}
};
}
}
| |
/*
Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.binnavi.yfileswrap.zygraph;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.security.zynamics.binnavi.CUtilityFunctions;
import com.google.security.zynamics.binnavi.Database.Exceptions.CouldntSaveDataException;
import com.google.security.zynamics.binnavi.Gui.GraphWindows.Loader.CViewSettingsGenerator;
import com.google.security.zynamics.binnavi.ZyGraph.INaviGraphListener;
import com.google.security.zynamics.binnavi.ZyGraph.IZyGraphInternals;
import com.google.security.zynamics.binnavi.ZyGraph.ZyGraphViewSettings;
import com.google.security.zynamics.binnavi.ZyGraph.Implementations.CEdgeDrawingFunctions;
import com.google.security.zynamics.binnavi.ZyGraph.Settings.IZyGraphLayoutSettingsListener;
import com.google.security.zynamics.binnavi.ZyGraph.Settings.ZyGraphDisplaySettingsListenerAdapter;
import com.google.security.zynamics.binnavi.ZyGraph.Settings.ZyGraphEdgeSettingsListenerAdapter;
import com.google.security.zynamics.binnavi.ZyGraph.Updaters.CEdgeUpdater;
import com.google.security.zynamics.binnavi.debug.debugger.interfaces.IDebugger;
import com.google.security.zynamics.binnavi.disassembly.INaviEdge;
import com.google.security.zynamics.binnavi.disassembly.INaviFunctionNode;
import com.google.security.zynamics.binnavi.disassembly.INaviViewNode;
import com.google.security.zynamics.binnavi.disassembly.algorithms.CViewInserter;
import com.google.security.zynamics.binnavi.disassembly.views.INaviView;
import com.google.security.zynamics.binnavi.disassembly.views.IViewContainer;
import com.google.security.zynamics.binnavi.yfileswrap.zygraph.Implementations.CLayoutFunctions;
import com.google.security.zynamics.binnavi.yfileswrap.zygraph.Implementations.CSettingsFunctions;
import com.google.security.zynamics.binnavi.yfileswrap.zygraph.Synchronizers.CViewGraphSynchronizer;
import com.google.security.zynamics.zylib.disassembly.ViewType;
import com.google.security.zynamics.zylib.general.ListenerProvider;
import com.google.security.zynamics.zylib.gui.zygraph.helpers.GraphConverters;
import com.google.security.zynamics.zylib.gui.zygraph.helpers.GraphHelpers;
import com.google.security.zynamics.zylib.gui.zygraph.helpers.IEdgeCallback;
import com.google.security.zynamics.zylib.gui.zygraph.helpers.INodeCallback;
import com.google.security.zynamics.zylib.gui.zygraph.proximity.MultiEdgeHider;
import com.google.security.zynamics.zylib.gui.zygraph.realizers.IRealizerUpdater;
import com.google.security.zynamics.zylib.gui.zygraph.realizers.IZyNodeRealizerListener;
import com.google.security.zynamics.zylib.gui.zygraph.wrappers.ViewableGraph;
import com.google.security.zynamics.zylib.types.common.CollectionHelpers;
import com.google.security.zynamics.zylib.types.common.ICollectionFilter;
import com.google.security.zynamics.zylib.types.common.IterationMode;
import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.AbstractZyGraph;
import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.ZyGraph2DView;
import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.realizers.ZyEdgeRealizer;
import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.realizers.ZyNodeRealizer;
import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.realizers.ZyProximityNodeRealizer;
import y.base.Edge;
import y.base.Node;
import y.base.NodeList;
import y.view.Graph2D;
import java.awt.Component;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
/**
* The ZyGraph is used to connect views with yfiles graph objects.
*/
public class ZyGraph extends AbstractZyGraph<NaviNode, NaviEdge> {
/**
* Raw view that provides the data for the visible graph.
*/
private INaviView m_rawView;
/**
* Defines the layout and behavior of the graph.
*/
private final ZyGraphViewSettings m_settings;
/**
* Listens on the graph display settings and updates the graph if necessary.
*/
private final InternalDisplaySettingsListener m_settingsListener =
new InternalDisplaySettingsListener();
/**
* Listens on the graph edge settings and updates the graph if necessary.
*/
private final InternalEdgeSettingsListener m_edgeSettingsListener =
new InternalEdgeSettingsListener();
/**
* Listens on the graph layout settings and updates the graph if necessary.
*/
private final InternalLayoutSettingsListener m_layoutSettingsListener =
new InternalLayoutSettingsListener();
/**
* Synchronizes the visible graph with the underlying raw view.
*/
private final CViewGraphSynchronizer m_synchronizer;
/**
* Listeners that are notified about changes in the graph.
*/
private final ListenerProvider<INaviGraphListener> m_listeners =
new ListenerProvider<INaviGraphListener>();
/**
* Flag used to suppress layouting while going through multiple internal states which should be
* presented as one state change to the user.
*/
private boolean m_disableLayoutingInternally = false;
/**
* Creates a new graph for a given view.
*
* @param view The view that provides the raw data of the graph.
* @param nodeMap A map that maps between ynodes and ZyNodes of the graph.
* @param edgeMap A map that maps between yedges and ZyEdges of the graph.
* @param settings Defines the layout and behavior of the graph.
* @param g2dview The yFiles view that displays the graph.
*/
public ZyGraph(final INaviView view, final LinkedHashMap<Node, NaviNode> nodeMap,
final LinkedHashMap<Edge, NaviEdge> edgeMap, final ZyGraphViewSettings settings,
final ZyGraph2DView g2dview) {
super(g2dview, nodeMap, edgeMap, settings);
m_rawView = Preconditions.checkNotNull(view, "IE00869: Argument view can't be null");
m_settings = Preconditions.checkNotNull(settings, "IE00870: Settings argument can't be null");
m_synchronizer = new CViewGraphSynchronizer(this, new GraphInternals(), getMappings());
hideInvisibleElements();
CLayoutFunctions.updateBackground(this);
CEdgeDrawingFunctions.initializeEdgeDrawingMode(this);
initializeListeners();
initializeProximityBrowser();
if ((m_rawView.getType() == ViewType.Native)
&& (getGraph().nodeCount() >= m_settings.getProximitySettings()
.getProximityBrowsingActivationThreshold())) {
m_settings.getProximitySettings().setProximityBrowsing(true);
}
updateMultipleEdgeState();
}
/**
* When a graph is initially shown, the logically invisible elements have to be removed explicitly
* from the yFiles graph.
*/
private void hideInvisibleElements() {
final Graph2D graph = getGraph();
for (final INaviEdge edge : m_rawView.getGraph().getEdges()) {
if (!edge.isVisible()) {
graph.removeEdge(getYEdge(edge));
}
}
for (final INaviViewNode node : m_rawView.getGraph()) {
if (!node.isVisible()) {
graph.removeNode(getYNode(node));
}
}
}
/**
* Sets up all necessary listeners to keep the graph up to date.
*/
private void initializeListeners() {
m_settings.getDisplaySettings().addListener(m_settingsListener);
m_settings.getEdgeSettings().addListener(m_edgeSettingsListener);
m_settings.getLayoutSettings().addListener(m_layoutSettingsListener);
}
/**
* Initializes the proximity browser when the graph is first created.
*/
private void initializeProximityBrowser() {
if ((m_rawView.getType() == ViewType.Native)
&& (m_rawView.getNodeCount() >= m_settings.getProximitySettings()
.getProximityBrowsingActivationThreshold())) {
initializeProximityBrowserNative();
} else if ((m_rawView.getType() == ViewType.NonNative)
&& m_settings.getProximitySettings().getProximityBrowsing()) {
initializeProximityBrowserNonNative();
}
if ((m_rawView.getType() == ViewType.Native)
&& (visibleNodeCount() >= m_settings.getLayoutSettings()
.getAutolayoutDeactivationThreshold())) {
m_settings.getLayoutSettings().setAutomaticLayouting(false);
}
if (m_settings.getLayoutSettings().getAutomaticLayouting()) {
doLayout();
}
}
/**
* Initializes the proximity browser for a native view node.
*/
private void initializeProximityBrowserNative() {
final List<NaviNode> allNodes = GraphHelpers.getNodes(this);
if (!allNodes.isEmpty()) {
// ATTENTION: Do not use allNodes.get(0) because the order of allNodes is not deterministic
final NaviNode firstNode = getMappings().getNode(getRawView().getGraph().getNodes().get(0));
allNodes.remove(firstNode);
showNodes(Lists.newArrayList(firstNode), allNodes);
}
}
/**
* Initializes the proximity browser for a non-native view node.
*/
private void initializeProximityBrowserNonNative() {
// Make sure not to auto-layout non-native views when they are first loaded.
// m_disableLayoutingInternally disables re-layouting in this class, but to
// disable re-layouting in the proximity browser, the layouting setting must
// be changed too.
m_disableLayoutingInternally = true;
final boolean previousSetting = m_settings.getLayoutSettings().getAutomaticLayouting();
m_settings.getLayoutSettings().setAutomaticLayouting(false);
// Small trick to make sure to show the proximity nodes for this graph.
// Use a temporary variable to work around OpenJDK build problem. Original code is:
// showNodes(GraphHelpers.getVisibleNodes(ViewableGraph.wrap(this)), false);
final Collection<NaviNode> nodes = GraphHelpers.getVisibleNodes(ViewableGraph.wrap(this));
showNodes(nodes, false);
m_settings.getLayoutSettings().setAutomaticLayouting(previousSetting);
m_disableLayoutingInternally = false;
if (m_rawView.getConfiguration().getId() == -1) {
// This is a pure performance thing; became necessary after
// having combined call graphs where all nodes would occupy
// the same space otherwise, leading to a huge slowdown.
doLayout();
}
}
/**
* Removes all listeners the graph object created.
*/
private void removeListeners() {
m_settings.getDisplaySettings().removeListener(m_settingsListener);
m_settings.getEdgeSettings().removeListener(m_edgeSettingsListener);
m_settings.getLayoutSettings().removeListener(m_layoutSettingsListener);
}
/**
* Updates the visibility of the edges depending on whether multiple edges are hidden or not.
*/
private void updateMultipleEdgeState() {
if (m_settings.getEdgeSettings().getDisplayMultipleEdgesAsOne()) {
MultiEdgeHider.hideMultipleEdgesInternal(this);
} else {
MultiEdgeHider.unhideMultipleEdgesInternal(this);
}
}
/**
* Adds a listener object that is notified about changes in the graph.
*
* @param listener The listener object to add.
*/
public void addListener(final INaviGraphListener listener) {
super.addListener(listener);
m_listeners.addListener(listener);
m_synchronizer.addListener(listener);
}
/**
* Adds a modifier to each node in the graph.
*
* @param modifier The modifier to be added.
*/
public void addNodeModifier(final IZyNodeRealizerListener<NaviNode> modifier) {
iterate(new INodeCallback<NaviNode>() {
@Override
public IterationMode next(final NaviNode node) {
node.addNodeModifier(modifier);
return IterationMode.CONTINUE;
}
});
}
/**
* This is the preferred way to delete nodes from open graphs.
*
* The reason for this is that node deletion throws selection events and proximity browsing
* re-layouts after each selection event, making the deletion of multiple nodes without pre/post
* events tediously slow.
*
* @param nodes The nodes to delete.
*/
public void deleteNodes(final List<NaviNode> nodes) {
// This line is moved up here to forward argument checking to
// the conversion function.
final List<INaviViewNode> convertedNodes = GraphConverters.convert(nodes);
getGraph().firePreEvent();
getRawView().getContent().deleteNodes(convertedNodes);
getGraph().firePostEvent();
}
@Override
public void dispose() {
super.dispose();
m_synchronizer.dispose();
removeListeners();
iterate(new INodeCallback<NaviNode>() {
@Override
public IterationMode next(final NaviNode node) {
final IRealizerUpdater<?> updater = node.getRealizer().getUpdater();
if (updater != null) {
updater.dispose();
}
return IterationMode.CONTINUE;
}
});
}
/**
* Returns the raw view that provides the raw data for the graph.
*
* @return The raw view.
*/
public INaviView getRawView() {
return m_rawView;
}
@Override
public Set<NaviNode> getSelectedNodes() {
return m_synchronizer.getSelectedNodes();
}
@Override
public ZyGraphViewSettings getSettings() {
return m_settings;
}
/**
* Removes a listener that was previously notified about changes in the graph.
*
* @param listener The listener to be removed.
*/
public void removeListener(final INaviGraphListener listener) {
super.removeListener(listener);
m_listeners.removeListener(listener);
m_synchronizer.removeListener(listener);
}
/**
* Saves the graph to the database. The difference between this method and the raw view method
* with the same name is that this method also stores the graph settings.
*
* @throws CouldntSaveDataException Thrown if the graph could not be saved.
*/
public boolean save() throws CouldntSaveDataException {
m_rawView.save();
CSettingsFunctions.saveSettings(m_rawView, getView(), m_settings);
return true;
}
/**
* Creates a copy of the current native view and transfers the copied native view into the graph
* object. That means that the graph object changes its underlying raw view when this function is
* called.
*
* @param container The view container where the view is copied to.
* @param name The new name of the raw view.
* @param description The new description of the raw view.
*
* @return The new raw view.
*
* @throws CouldntSaveDataException Thrown if the view could not be saved.
*/
public INaviView saveAs(final IViewContainer container, final String name,
final String description) throws CouldntSaveDataException {
Preconditions.checkNotNull(container, "IE00871: Container argument can not be null");
Preconditions.checkNotNull(name, "IE00872: Name argument can not be null");
Preconditions.checkNotNull(description, "IE00899: Description argument can not be null");
final INaviView oldView = m_rawView;
final INaviView newView = container.createView(name, description);
CViewInserter.insertView(oldView, newView);
final List<INaviViewNode> oldNodes = oldView.getGraph().getNodes();
final List<INaviViewNode> newNodes = newView.getGraph().getNodes();
for (int i = 0; i < oldNodes.size(); i++) {
final INaviViewNode newNode = newNodes.get(i);
final NaviNode oldNode = getMappings().getNode(oldNodes.get(i));
getMappings().setNode(newNode, oldNode);
oldNode.setRawNode(newNode);
for (final INaviGraphListener listener : m_listeners) {
try {
listener.changedModel(this, oldNode);
} catch (final Exception exception) {
CUtilityFunctions.logException(exception);
}
}
}
final List<INaviEdge> oldEdges = oldView.getGraph().getEdges();
final List<INaviEdge> newEdges = newView.getGraph().getEdges();
for (int i = 0; i < oldEdges.size(); i++) {
final INaviEdge newEdge = newEdges.get(i);
final NaviEdge oldEdge = getMappings().getEdge(oldEdges.get(i));
assert oldEdge != null;
getMappings().setEdge(newEdge, oldEdge);
final ZyEdgeRealizer<NaviEdge> realizer = oldEdge.getRealizer();
realizer.setUpdater(new CEdgeUpdater(newEdge));
oldEdge.setRawEdge(newEdge);
}
removeListeners();
newView.save();
CSettingsFunctions.saveSettings(newView, getView(), m_settings);
m_rawView = newView;
initializeListeners();
m_synchronizer.reset();
for (final INaviGraphListener listener : m_listeners) {
// ESCA-JAVA0166: Catch Exception here because we are calling a listener function.
try {
listener.changedView(oldView, newView);
} catch (final Exception exception) {
CUtilityFunctions.logException(exception);
}
}
oldView.close();
return m_rawView;
}
@Override
public void showNodes(final Collection<NaviNode> toShow, final Collection<NaviNode> toHide) {
m_synchronizer.setMultiEdgeUpdatingEnabled(false);
super.showNodes(toShow, toHide);
m_synchronizer.setMultiEdgeUpdatingEnabled(true);
}
/**
* Returns the number of visible nodes in the graph.
*
* @return The number of visible nodes in the graph.
*/
@SuppressWarnings("unchecked")
public int visibleNodeCount() {
return CollectionHelpers.countIf(new NodeList(getGraph().nodes()),
new ICollectionFilter<Node>() {
@Override
public boolean qualifies(final Node item) {
return !(getGraph().getRealizer(item) instanceof ZyProximityNodeRealizer<?>);
}
});
}
/**
* Provides some graph internals for the ViewGraph synchronizer to work with.
*/
private class GraphInternals implements IZyGraphInternals {
@Override
public void notifyNodeDeleted() {
notifyDeletionListeners();
}
@Override
public void removeEdge(final NaviEdge edge) {
if (edge.getEdge().getGraph() != null) {
getGraph().removeEdge(edge.getEdge());
}
getMappings().removeEdge(edge);
NaviNode.unlink(edge.getSource(), edge.getTarget());
}
@Override
public void removeNode(final NaviNode node) {
ZyGraph.this.removeNode(node);
}
}
/**
* Listener that keeps track of graph settings and changes the graph when the settings change.
*/
private class InternalDisplaySettingsListener extends ZyGraphDisplaySettingsListenerAdapter {
@Override
public void changedFunctionNodeInformation(final boolean show) {
for (final NaviNode node : getMappings().getNodes()) {
if (node.getRawNode() instanceof INaviFunctionNode) {
(((ZyNodeRealizer<?>) getGraph().getRealizer(node.getNode()))).regenerate();
}
}
updateViews();
}
@Override
public void changedShowMemoryAddresses(final IDebugger debugger, final boolean selected) {
for (final NaviNode node : getMappings().getNodes()) {
(((ZyNodeRealizer<?>) getGraph().getRealizer(node.getNode()))).regenerate();
}
updateViews();
}
}
/**
* Listens on the graph edge settings and updates the graph if necessary.
*/
private class InternalEdgeSettingsListener extends ZyGraphEdgeSettingsListenerAdapter {
@Override
public void changedDisplayMultipleEdgesAsOne(final boolean value) {
updateMultipleEdgeState();
}
@Override
public void changedDrawSelectedBends(final boolean value) {
iterateEdges(new IEdgeCallback<NaviEdge>() {
@Override
public IterationMode nextEdge(final NaviEdge node) {
node.getRealizer().setDrawBends(value);
return IterationMode.CONTINUE;
}
});
updateViews();
}
}
/**
* Listens on the graph layout settings and updates the graph if necessary.
*/
private class InternalLayoutSettingsListener implements IZyGraphLayoutSettingsListener {
@Override
public void changedAutomaticLayouting(final boolean value) {
if (m_settings.getLayoutSettings().getAutomaticLayouting() && !m_disableLayoutingInternally) {
doLayout();
}
}
}
/**
* Nobody remembers what case 874 was. This was moved from CViewLoader.java since it depends on
* yFiles, but it is unclear if this is even still needed.
*/
// TODO(thomasdullien): Figure out what this is for.
public void workAroundCase874() {
getView().setCenter(
CViewSettingsGenerator.createDoubleSetting(getSettings().rawSettings, "view_center_x", 0),
CViewSettingsGenerator.createDoubleSetting(getSettings().rawSettings, "view_center_y", 0));
getView().setWorldRect(
CViewSettingsGenerator.createIntegerSetting(getSettings().rawSettings, "world_rect_x", 0),
CViewSettingsGenerator.createIntegerSetting(getSettings().rawSettings, "world_rect_y", 0),
CViewSettingsGenerator.createIntegerSetting(
getSettings().rawSettings, "world_rect_width", 800),
CViewSettingsGenerator.createIntegerSetting(
getSettings().rawSettings, "world_rect_height", 600));
getView().setZoom(
CViewSettingsGenerator.createDoubleSetting(getSettings().rawSettings, "zoom", 1));
updateViews();
}
public String getViewName() {
return getView().getName();
}
public Component getViewAsComponent() {
return getView();
}
/**
* Small helper function to get back the node at a given index.
*
* @param index The index of the node.
*
* @return The node at the given index.
*/
public NaviNode getRawNodeFromIndex(int index) {
return getNode(getRawView().getGraph().getNodes().get(index));
}
public void makeRawNodeVisibleAndSelect(int index) {
INaviViewNode rawNode = getRawView().getGraph().getNodes().get(index);
NaviNode naviNode = getNode(rawNode);
if (!rawNode.isVisible()
&& !getSettings().getProximitySettings().getProximityBrowsingFrozen()) {
rawNode.setVisible(true);
}
selectNode(naviNode, !rawNode.isSelected());
}
}
| |
/*
* Copyright 2016-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.datamodel;
import java.io.Serializable;
import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
import org.onosproject.yangutils.datamodel.utils.ResolvableStatus;
import org.onosproject.yangutils.datamodel.utils.builtindatatype.YangDataTypes;
import com.google.common.base.Strings;
import static org.onosproject.yangutils.datamodel.utils.ResolvableStatus.INTRA_FILE_RESOLVED;
import static org.onosproject.yangutils.datamodel.utils.ResolvableStatus.RESOLVED;
import static org.onosproject.yangutils.datamodel.utils.RestrictionResolver.processLengthRestriction;
import static org.onosproject.yangutils.datamodel.utils.RestrictionResolver.processRangeRestriction;
import static org.onosproject.yangutils.datamodel.utils.builtindatatype.YangDataTypeUtils.isOfRangeRestrictedType;
import static org.onosproject.yangutils.datamodel.utils.builtindatatype.YangDataTypes.BINARY;
import static org.onosproject.yangutils.datamodel.utils.builtindatatype.YangDataTypes.BITS;
import static org.onosproject.yangutils.datamodel.utils.builtindatatype.YangDataTypes.BOOLEAN;
import static org.onosproject.yangutils.datamodel.utils.builtindatatype.YangDataTypes.DECIMAL64;
import static org.onosproject.yangutils.datamodel.utils.builtindatatype.YangDataTypes.DERIVED;
import static org.onosproject.yangutils.datamodel.utils.builtindatatype.YangDataTypes.EMPTY;
import static org.onosproject.yangutils.datamodel.utils.builtindatatype.YangDataTypes.ENUMERATION;
import static org.onosproject.yangutils.datamodel.utils.builtindatatype.YangDataTypes.IDENTITYREF;
import static org.onosproject.yangutils.datamodel.utils.builtindatatype.YangDataTypes.LEAFREF;
import static org.onosproject.yangutils.datamodel.utils.builtindatatype.YangDataTypes.STRING;
import static org.onosproject.yangutils.datamodel.utils.builtindatatype.YangDataTypes.UNION;
/**
* Represents the derived information.
*
* @param <T> extended information.
*/
public class YangDerivedInfo<T>
implements LocationInfo, Cloneable, Serializable {
private static final long serialVersionUID = 806201641L;
/**
* YANG typedef reference.
*/
private YangTypeDef referredTypeDef;
/**
* Resolved additional information about data type after linking, example
* restriction info, named values, etc. The extra information is based
* on the data type. Based on the data type, the extended info can vary.
*/
private T resolvedExtendedInfo;
/**
* Line number of pattern restriction in YANG file.
*/
private int lineNumber;
/**
* Position of pattern restriction in line.
*/
private int charPositionInLine;
/**
* Effective built-in type, requried in case type of typedef is again a
* derived type. This information is to be added during linking.
*/
private YangDataTypes effectiveBuiltInType;
/**
* Length restriction string to temporary store the length restriction when the type
* is derived.
*/
private String lengthRestrictionString;
/**
* Range restriction string to temporary store the range restriction when the type
* is derived.
*/
private String rangeRestrictionString;
/**
* Pattern restriction string to temporary store the pattern restriction when the type
* is derived.
*/
private YangPatternRestriction patternRestriction;
/**
* Returns the referred typedef reference.
*
* @return referred typedef reference
*/
public YangTypeDef getReferredTypeDef() {
return referredTypeDef;
}
/**
* Sets the referred typedef reference.
*
* @param referredTypeDef referred typedef reference
*/
public void setReferredTypeDef(YangTypeDef referredTypeDef) {
this.referredTypeDef = referredTypeDef;
}
/**
* Returns resolved extended information after successful linking.
*
* @return resolved extended information
*/
public T getResolvedExtendedInfo() {
return resolvedExtendedInfo;
}
/**
* Sets resolved extended information after successful linking.
*
* @param resolvedExtendedInfo resolved extended information
*/
public void setResolvedExtendedInfo(T resolvedExtendedInfo) {
this.resolvedExtendedInfo = resolvedExtendedInfo;
}
@Override
public int getLineNumber() {
return lineNumber;
}
@Override
public int getCharPosition() {
return charPositionInLine;
}
@Override
public void setLineNumber(int lineNumber) {
this.lineNumber = lineNumber;
}
@Override
public void setCharPosition(int charPositionInLine) {
this.charPositionInLine = charPositionInLine;
}
/**
* Returns the length restriction string.
*
* @return the length restriction string
*/
public String getLengthRestrictionString() {
return lengthRestrictionString;
}
/**
* Sets the length restriction string.
*
* @param lengthRestrictionString the length restriction string
*/
public void setLengthRestrictionString(String lengthRestrictionString) {
this.lengthRestrictionString = lengthRestrictionString;
}
/**
* Returns the range restriction string.
*
* @return the range restriction string
*/
public String getRangeRestrictionString() {
return rangeRestrictionString;
}
/**
* Sets the range restriction string.
*
* @param rangeRestrictionString the range restriction string
*/
public void setRangeRestrictionString(String rangeRestrictionString) {
this.rangeRestrictionString = rangeRestrictionString;
}
/**
* Returns the pattern restriction.
*
* @return the pattern restriction
*/
public YangPatternRestriction getPatternRestriction() {
return patternRestriction;
}
/**
* Sets the pattern restriction.
*
* @param patternRestriction the pattern restriction
*/
public void setPatternRestriction(YangPatternRestriction patternRestriction) {
this.patternRestriction = patternRestriction;
}
/**
* Returns effective built-in type.
*
* @return effective built-in type
*/
public YangDataTypes getEffectiveBuiltInType() {
return effectiveBuiltInType;
}
/**
* Sets effective built-in type.
*
* @param effectiveBuiltInType effective built-in type
*/
public void setEffectiveBuiltInType(YangDataTypes effectiveBuiltInType) {
this.effectiveBuiltInType = effectiveBuiltInType;
}
/**
* Resolves the type derived info, by obtaining the effective built-in type
* and resolving the restrictions.
*
* @return resolution status
* @throws DataModelException a violation in data mode rule
*/
public ResolvableStatus resolve()
throws DataModelException {
YangType<?> baseType = getReferredTypeDef().getTypeDefBaseType();
/*
* Checks the data type of the referred typedef, if it's derived, obtain
* effective built-in type and restrictions from it's derived info,
* otherwise take from the base type of type itself.
*/
if (baseType.getDataType() == DERIVED) {
ResolvableStatus resolvableStatus = resolveTypeDerivedInfo(baseType);
if (resolvableStatus != null) {
return resolvableStatus;
}
} else if ((baseType.getDataType() == LEAFREF) || (baseType.getDataType() == IDENTITYREF)) {
setEffectiveBuiltInType(baseType.getDataType());
return RESOLVED;
} else {
setEffectiveBuiltInType(baseType.getDataType());
/*
* Check whether the effective built-in type can have range
* restrictions, if yes call resolution of range.
*/
if (isOfRangeRestrictedType(getEffectiveBuiltInType())) {
if (baseType.getDataTypeExtendedInfo() == null) {
resolveRangeRestriction(null);
/*
* Return the resolution status as resolved, if it's not
* resolve range/string restriction will throw exception in
* previous function.
*/
return RESOLVED;
} else {
if (!(baseType.getDataTypeExtendedInfo() instanceof YangRangeRestriction)) {
throw new DataModelException("Linker error: Referred typedef restriction info is of invalid " +
"type.");
}
resolveRangeRestriction((YangRangeRestriction) baseType.getDataTypeExtendedInfo());
/*
* Return the resolution status as resolved, if it's not
* resolve range/string restriction will throw exception in
* previous function.
*/
return RESOLVED;
}
/*
* If the effective built-in type is of type string calls for
* string resolution.
*/
} else if (getEffectiveBuiltInType() == STRING) {
if (baseType.getDataTypeExtendedInfo() == null) {
resolveStringRestriction(null);
/*
* Return the resolution status as resolved, if it's not
* resolve range/string restriction will throw exception in
* previous function.
*/
return RESOLVED;
} else {
if (!(baseType.getDataTypeExtendedInfo() instanceof YangStringRestriction)) {
throw new DataModelException("Linker error: Referred typedef restriction info is of invalid " +
"type.");
}
resolveStringRestriction((YangStringRestriction) baseType.getDataTypeExtendedInfo());
/*
* Return the resolution status as resolved, if it's not
* resolve range/string restriction will throw exception in
* previous function.
*/
return RESOLVED;
}
} else if (getEffectiveBuiltInType() == BINARY) {
if (baseType.getDataTypeExtendedInfo() == null) {
resolveBinaryRestriction(null);
/*
* Return the resolution status as resolved, if it's not
* resolve length restriction will throw exception in
* previous function.
*/
return RESOLVED;
} else {
if (!(baseType.getDataTypeExtendedInfo() instanceof YangRangeRestriction)) {
throw new DataModelException("Linker error: Referred typedef restriction info is of invalid " +
"type.");
}
resolveBinaryRestriction((YangRangeRestriction) baseType.getDataTypeExtendedInfo());
/*
* Return the resolution status as resolved, if it's not
* resolve length restriction will throw exception in
* previous function.
*/
return RESOLVED;
}
} else if (getEffectiveBuiltInType() == DECIMAL64) {
if (baseType.getDataTypeExtendedInfo() != null) {
if (((YangDecimal64) baseType.getDataTypeExtendedInfo()).getRangeRestrictedExtendedInfo() == null) {
resolveRangeRestriction(null);
/*
* Return the resolution status as resolved, if it's not;
* resolve range restriction will throw exception in
* previous function.
*/
return RESOLVED;
} else {
if (!(((YangDecimal64) baseType.getDataTypeExtendedInfo())
.getRangeRestrictedExtendedInfo() instanceof YangRangeRestriction)) {
throw new DataModelException("Linker error: Referred typedef restriction info is" +
" of invalid type.");
}
resolveRangeRestriction((YangRangeRestriction) ((YangDecimal64) baseType
.getDataTypeExtendedInfo()).getRangeRestrictedExtendedInfo());
/*
* Return the resolution status as resolved, if it's not
* resolve range/string restriction will throw exception in
* previous function.
*/
return RESOLVED;
}
} else {
throw new DataModelException("Linker error: Unable to find type extended info for decimal64.");
}
}
}
/*
* Check if the data type is the one which can't be restricted, in this
* case check whether no self restrictions should be present.
*/
if (isOfValidNonRestrictedType(getEffectiveBuiltInType())) {
if (Strings.isNullOrEmpty(getLengthRestrictionString())
&& Strings.isNullOrEmpty(getRangeRestrictionString())
&& getPatternRestriction() == null) {
return RESOLVED;
} else {
throw new DataModelException("YANG file error: Restrictions can't be applied to a given type");
}
}
// Throw exception for unsupported types
throw new DataModelException("Linker error: Unable to process the derived type.");
}
/**
* Resolves the type derived info, by obtaining the effective built-in type
* and resolving the restrictions.
*
* @param baseType base type of typedef
* @return resolution status
* @throws DataModelException a violation in data mode rule
*/
public ResolvableStatus resolveTypeDerivedInfo(YangType<?> baseType)
throws DataModelException {
/*
* Check whether the referred typedef is resolved.
*/
if (baseType.getResolvableStatus() != INTRA_FILE_RESOLVED && baseType.getResolvableStatus() != RESOLVED) {
throw new DataModelException("Linker Error: Referred typedef is not resolved for type.");
}
/*
* Check if the referred typedef is intra file resolved, if yes sets
* current status also to intra file resolved .
*/
if (getReferredTypeDef().getTypeDefBaseType().getResolvableStatus() == INTRA_FILE_RESOLVED) {
return INTRA_FILE_RESOLVED;
}
setEffectiveBuiltInType(((YangDerivedInfo<?>) baseType.getDataTypeExtendedInfo())
.getEffectiveBuiltInType());
YangDerivedInfo refDerivedInfo = (YangDerivedInfo<?>) baseType.getDataTypeExtendedInfo();
/*
* Check whether the effective built-in type can have range
* restrictions, if yes call resolution of range.
*/
if (isOfRangeRestrictedType(getEffectiveBuiltInType())) {
if (refDerivedInfo.getResolvedExtendedInfo() == null) {
resolveRangeRestriction(null);
/*
* Return the resolution status as resolved, if it's not
* resolve range/string restriction will throw exception in
* previous function.
*/
return RESOLVED;
} else {
if (!(refDerivedInfo.getResolvedExtendedInfo() instanceof YangRangeRestriction)) {
throw new DataModelException("Linker error: Referred typedef restriction info is of invalid " +
"type.");
}
resolveRangeRestriction((YangRangeRestriction) refDerivedInfo.getResolvedExtendedInfo());
/*
* Return the resolution status as resolved, if it's not
* resolve range/string restriction will throw exception in
* previous function.
*/
return RESOLVED;
}
/*
* If the effective built-in type is of type string calls for
* string resolution.
*/
} else if (getEffectiveBuiltInType() == STRING) {
if (refDerivedInfo.getResolvedExtendedInfo() == null) {
resolveStringRestriction(null);
/*
* Return the resolution status as resolved, if it's not
* resolve range/string restriction will throw exception in
* previous function.
*/
return RESOLVED;
} else {
if (!(refDerivedInfo.getResolvedExtendedInfo() instanceof YangStringRestriction)) {
throw new DataModelException("Linker error: Referred typedef restriction info is of invalid " +
"type.");
}
resolveStringRestriction((YangStringRestriction) refDerivedInfo.getResolvedExtendedInfo());
/*
* Return the resolution status as resolved, if it's not
* resolve range/string restriction will throw exception in
* previous function.
*/
return RESOLVED;
}
} else if (getEffectiveBuiltInType() == BINARY) {
if (refDerivedInfo.getResolvedExtendedInfo() == null) {
resolveBinaryRestriction(null);
/*
* Return the resolution status as resolved, if it's not
* resolve length restriction will throw exception in
* previous function.
*/
return RESOLVED;
} else {
if (!(refDerivedInfo.getResolvedExtendedInfo() instanceof YangRangeRestriction)) {
throw new DataModelException("Linker error: Referred typedef restriction info is of invalid " +
"type.");
}
resolveBinaryRestriction((YangRangeRestriction) refDerivedInfo.getResolvedExtendedInfo());
/*
* Return the resolution status as resolved, if it's not
* resolve length restriction will throw exception in
* previous function.
*/
return RESOLVED;
}
} else if (getEffectiveBuiltInType() == DECIMAL64) {
if (refDerivedInfo.getResolvedExtendedInfo() == null) {
resolveRangeRestriction(null);
/*
* Return the resolution status as resolved, if it's not;
* resolve range restriction will throw exception in
* previous function.
*/
return RESOLVED;
} else {
if (!(refDerivedInfo.getResolvedExtendedInfo() instanceof YangRangeRestriction)) {
throw new DataModelException("Linker error: Referred typedef restriction info is of invalid " +
"type.");
}
resolveRangeRestriction((YangRangeRestriction) refDerivedInfo
.getResolvedExtendedInfo());
/*
* Return the resolution status as resolved, if it's not
* resolve range/string restriction will throw exception in
* previous function.
*/
return RESOLVED;
}
}
return null;
}
/**
* Resolves the string restrictions.
*
* @param refStringRestriction referred string restriction of typedef
* @throws DataModelException a violation in data model rule
*/
private void resolveStringRestriction(YangStringRestriction refStringRestriction)
throws DataModelException {
YangStringRestriction curStringRestriction = null;
YangRangeRestriction refRangeRestriction = null;
YangPatternRestriction refPatternRestriction = null;
/*
* Check that range restriction should be null when built-in type is
* string.
*/
if (!Strings.isNullOrEmpty(getRangeRestrictionString())) {
DataModelException dataModelException = new DataModelException("YANG file error: Range restriction " +
"should't be present for string data type.");
dataModelException.setLine(lineNumber);
dataModelException.setCharPosition(charPositionInLine);
throw dataModelException;
}
/*
* If referred restriction and self restriction both are null, no
* resolution is required.
*/
if (refStringRestriction == null && Strings.isNullOrEmpty(getLengthRestrictionString())
&& getPatternRestriction() == null) {
return;
}
/*
* If referred string restriction is not null, take value of length and
* pattern restriction and assign.
*/
if (refStringRestriction != null) {
refRangeRestriction = refStringRestriction.getLengthRestriction();
refPatternRestriction = refStringRestriction.getPatternRestriction();
}
YangRangeRestriction lengthRestriction = resolveLengthRestriction(refRangeRestriction);
YangPatternRestriction patternRestriction = resolvePatternRestriction(refPatternRestriction);
/*
* Check if either of length or pattern restriction is present, if yes
* create string restriction and assign value.
*/
if (lengthRestriction != null || patternRestriction != null) {
curStringRestriction = new YangStringRestriction();
curStringRestriction.setLengthRestriction(lengthRestriction);
curStringRestriction.setPatternRestriction(patternRestriction);
}
setResolvedExtendedInfo((T) curStringRestriction);
}
/**
* Resolves the binary restrictions.
*
* @param refLengthRestriction referred length restriction of typedef
* @throws DataModelException a violation in data model rule
*/
private void resolveBinaryRestriction(YangRangeRestriction refLengthRestriction)
throws DataModelException {
if (rangeRestrictionString != null || patternRestriction != null) {
DataModelException dataModelException =
new DataModelException("YANG file error: for binary " +
"range restriction or pattern restriction is not allowed.");
dataModelException.setLine(lineNumber);
dataModelException.setCharPosition(charPositionInLine);
throw dataModelException;
}
// Get the final resolved length restriction
YangRangeRestriction lengthRestriction = resolveLengthRestriction(refLengthRestriction);
// Set the lenght restriction.
setResolvedExtendedInfo((T) lengthRestriction);
}
/**
* Resolves pattern restriction.
*
* @param refPatternRestriction referred pattern restriction of typedef
* @return resolved pattern restriction
*/
private YangPatternRestriction resolvePatternRestriction(YangPatternRestriction refPatternRestriction) {
/*
* If referred restriction and self restriction both are null, no
* resolution is required.
*/
if (refPatternRestriction == null && getPatternRestriction() == null) {
return null;
}
/*
* If self restriction is null, and referred restriction is present
* shallow copy the referred to self.
*/
if (getPatternRestriction() == null) {
return refPatternRestriction;
}
/*
* If referred restriction is null, and self restriction is present
* carry out self resolution.
*/
if (refPatternRestriction == null) {
return getPatternRestriction();
}
/*
* Get patterns of referred type and add it to current pattern
* restrictions.
*/
for (String pattern : refPatternRestriction.getPatternList()) {
getPatternRestriction().addPattern(pattern);
}
return getPatternRestriction();
}
/**
* Resolves the length restrictions.
*
* @param refLengthRestriction referred length restriction of typedef
* @return resolved length restriction
* @throws DataModelException a violation in data model rule
*/
private YangRangeRestriction resolveLengthRestriction(YangRangeRestriction refLengthRestriction)
throws DataModelException {
/*
* If referred restriction and self restriction both are null, no
* resolution is required.
*/
if (refLengthRestriction == null && Strings.isNullOrEmpty(getLengthRestrictionString())) {
return null;
}
/*
* If self restriction is null, and referred restriction is present
* shallow copy the referred to self.
*/
if (Strings.isNullOrEmpty(getLengthRestrictionString())) {
return refLengthRestriction;
}
/*
* If referred restriction is null, and self restriction is present
* carry out self resolution.
*/
if (refLengthRestriction == null) {
YangRangeRestriction curLengthRestriction = processLengthRestriction(null, lineNumber,
charPositionInLine, false, getLengthRestrictionString());
return curLengthRestriction;
}
/*
* Carry out self resolution based with obtained effective built-in type
* and MIN/MAX values as per the referred typedef's values.
*/
YangRangeRestriction curLengthRestriction = processLengthRestriction(refLengthRestriction, lineNumber,
charPositionInLine, true, getLengthRestrictionString());
// Resolve the range with referred typedef's restriction.
resolveLengthAndRangeRestriction(refLengthRestriction, curLengthRestriction);
return curLengthRestriction;
}
/**
* Resolves the length/range self and referred restriction, to check whether
* the all the range interval in self restriction is stricter than the
* referred typedef's restriction.
*
* @param refRestriction referred restriction
* @param curRestriction self restriction
*/
private void resolveLengthAndRangeRestriction(YangRangeRestriction refRestriction,
YangRangeRestriction curRestriction)
throws DataModelException {
for (Object curInterval : curRestriction.getAscendingRangeIntervals()) {
if (!(curInterval instanceof YangRangeInterval)) {
throw new DataModelException("Linker error: Current range intervals not processed correctly.");
}
try {
refRestriction.isValidInterval((YangRangeInterval) curInterval);
} catch (DataModelException e) {
DataModelException dataModelException = new DataModelException(e);
dataModelException.setLine(lineNumber);
dataModelException.setCharPosition(charPositionInLine);
throw dataModelException;
}
}
}
/**
* Resolves the range restrictions.
*
* @param refRangeRestriction referred range restriction of typedef
* @throws DataModelException a violation in data model rule
*/
private void resolveRangeRestriction(YangRangeRestriction refRangeRestriction)
throws DataModelException {
/*
* Check that string restriction should be null when built-in type is of
* range type.
*/
if (!Strings.isNullOrEmpty(getLengthRestrictionString()) || getPatternRestriction() != null) {
DataModelException dataModelException = new DataModelException("YANG file error: Length/Pattern " +
"restriction should't be present for int/uint/decimal data type.");
dataModelException.setLine(lineNumber);
dataModelException.setCharPosition(charPositionInLine);
throw dataModelException;
}
/*
* If referred restriction and self restriction both are null, no
* resolution is required.
*/
if (refRangeRestriction == null && Strings.isNullOrEmpty(getRangeRestrictionString())) {
return;
}
/*
* If self restriction is null, and referred restriction is present
* shallow copy the referred to self.
*/
if (Strings.isNullOrEmpty(getRangeRestrictionString())) {
setResolvedExtendedInfo((T) refRangeRestriction);
return;
}
/*
* If referred restriction is null, and self restriction is present
* carry out self resolution.
*/
if (refRangeRestriction == null) {
YangRangeRestriction curRangeRestriction = processRangeRestriction(null, lineNumber,
charPositionInLine, false, getRangeRestrictionString(), getEffectiveBuiltInType());
setResolvedExtendedInfo((T) curRangeRestriction);
return;
}
/*
* Carry out self resolution based with obtained effective built-in type
* and MIN/MAX values as per the referred typedef's values.
*/
YangRangeRestriction curRangeRestriction = processRangeRestriction(refRangeRestriction, lineNumber,
charPositionInLine, true, getRangeRestrictionString(), getEffectiveBuiltInType());
// Resolve the range with referred typedef's restriction.
resolveLengthAndRangeRestriction(refRangeRestriction, curRangeRestriction);
setResolvedExtendedInfo((T) curRangeRestriction);
}
/**
* Returns whether the data type is of non restricted type.
*
* @param dataType data type to be checked
* @return true, if data type can't be restricted, false otherwise
*/
private boolean isOfValidNonRestrictedType(YangDataTypes dataType) {
return dataType == BOOLEAN
|| dataType == ENUMERATION
|| dataType == BITS
|| dataType == EMPTY
|| dataType == UNION
|| dataType == IDENTITYREF
|| dataType == LEAFREF;
}
}
| |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.cluster.routing.allocation.command;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.RecoverySource;
import org.elasticsearch.cluster.routing.RoutingNode;
import org.elasticsearch.cluster.routing.RoutingNodes;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.UnassignedInfo;
import org.elasticsearch.cluster.routing.allocation.RerouteExplanation;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.cluster.routing.allocation.decider.Decision;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.xcontent.ObjectParser;
import org.elasticsearch.xcontent.ParseField;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentParser;
import java.io.IOException;
import java.util.Objects;
/**
* Abstract base class for allocating an unassigned shard to a node
*/
public abstract class AbstractAllocateAllocationCommand implements AllocationCommand {
private static final String INDEX_FIELD = "index";
private static final String SHARD_FIELD = "shard";
private static final String NODE_FIELD = "node";
protected static <T extends Builder<?>> ObjectParser<T, Void> createAllocateParser(String command) {
ObjectParser<T, Void> parser = new ObjectParser<>(command);
parser.declareString(Builder::setIndex, new ParseField(INDEX_FIELD));
parser.declareInt(Builder::setShard, new ParseField(SHARD_FIELD));
parser.declareString(Builder::setNode, new ParseField(NODE_FIELD));
return parser;
}
/**
* Works around ObjectParser not supporting constructor arguments.
*/
protected abstract static class Builder<T extends AbstractAllocateAllocationCommand> {
protected String index;
protected int shard = -1;
protected String node;
public void setIndex(String index) {
this.index = index;
}
public void setShard(int shard) {
this.shard = shard;
}
public void setNode(String node) {
this.node = node;
}
public abstract Builder<T> parse(XContentParser parser) throws IOException;
public abstract T build();
protected void validate() {
if (index == null) {
throw new IllegalArgumentException("Argument [index] must be defined");
}
if (shard < 0) {
throw new IllegalArgumentException("Argument [shard] must be defined and non-negative");
}
if (node == null) {
throw new IllegalArgumentException("Argument [node] must be defined");
}
}
}
protected final String index;
protected final int shardId;
protected final String node;
protected AbstractAllocateAllocationCommand(String index, int shardId, String node) {
this.index = index;
this.shardId = shardId;
this.node = node;
}
/**
* Read from a stream.
*/
protected AbstractAllocateAllocationCommand(StreamInput in) throws IOException {
index = in.readString();
shardId = in.readVInt();
node = in.readString();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(index);
out.writeVInt(shardId);
out.writeString(node);
}
/**
* Get the index name
*
* @return name of the index
*/
public String index() {
return this.index;
}
/**
* Get the shard id
*
* @return id of the shard
*/
public int shardId() {
return this.shardId;
}
/**
* Get the id of the node
*
* @return id of the node
*/
public String node() {
return this.node;
}
/**
* Handle case where a disco node cannot be found in the routing table. Usually means that it's not a data node.
*/
protected RerouteExplanation explainOrThrowMissingRoutingNode(RoutingAllocation allocation, boolean explain, DiscoveryNode discoNode) {
if (discoNode.canContainData() == false) {
return explainOrThrowRejectedCommand(explain, allocation, "allocation can only be done on data nodes, not [" + node + "]");
} else {
return explainOrThrowRejectedCommand(explain, allocation, "could not find [" + node + "] among the routing nodes");
}
}
/**
* Utility method for rejecting the current allocation command based on provided reason
*/
protected RerouteExplanation explainOrThrowRejectedCommand(boolean explain, RoutingAllocation allocation, String reason) {
if (explain) {
return new RerouteExplanation(this, allocation.decision(Decision.NO, name() + " (allocation command)", reason));
}
throw new IllegalArgumentException("[" + name() + "] " + reason);
}
/**
* Utility method for rejecting the current allocation command based on provided exception
*/
protected RerouteExplanation explainOrThrowRejectedCommand(boolean explain, RoutingAllocation allocation, RuntimeException rte) {
if (explain) {
return new RerouteExplanation(this, allocation.decision(Decision.NO, name() + " (allocation command)", rte.getMessage()));
}
throw rte;
}
/**
* Initializes an unassigned shard on a node and removes it from the unassigned
*
* @param allocation the allocation
* @param routingNodes the routing nodes
* @param routingNode the node to initialize it to
* @param shardRouting the shard routing that is to be matched in unassigned shards
*/
protected void initializeUnassignedShard(
RoutingAllocation allocation,
RoutingNodes routingNodes,
RoutingNode routingNode,
ShardRouting shardRouting
) {
initializeUnassignedShard(allocation, routingNodes, routingNode, shardRouting, null, null);
}
/**
* Initializes an unassigned shard on a node and removes it from the unassigned
*
* @param allocation the allocation
* @param routingNodes the routing nodes
* @param routingNode the node to initialize it to
* @param shardRouting the shard routing that is to be matched in unassigned shards
* @param unassignedInfo unassigned info to override
* @param recoverySource recovery source to override
*/
protected void initializeUnassignedShard(
RoutingAllocation allocation,
RoutingNodes routingNodes,
RoutingNode routingNode,
ShardRouting shardRouting,
@Nullable UnassignedInfo unassignedInfo,
@Nullable RecoverySource recoverySource
) {
for (RoutingNodes.UnassignedShards.UnassignedIterator it = routingNodes.unassigned().iterator(); it.hasNext();) {
ShardRouting unassigned = it.next();
if (unassigned.equalsIgnoringMetadata(shardRouting) == false) {
continue;
}
if (unassignedInfo != null || recoverySource != null) {
unassigned = it.updateUnassigned(
unassignedInfo != null ? unassignedInfo : unassigned.unassignedInfo(),
recoverySource != null ? recoverySource : unassigned.recoverySource(),
allocation.changes()
);
}
it.initialize(
routingNode.nodeId(),
null,
allocation.clusterInfo().getShardSize(unassigned, ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE),
allocation.changes()
);
return;
}
assert false : "shard to initialize not found in list of unassigned shards";
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
builder.startObject();
builder.field(INDEX_FIELD, index());
builder.field(SHARD_FIELD, shardId());
builder.field(NODE_FIELD, node());
extraXContent(builder);
return builder.endObject();
}
protected void extraXContent(XContentBuilder builder) throws IOException {}
@Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
AbstractAllocateAllocationCommand other = (AbstractAllocateAllocationCommand) obj;
// Override equals and hashCode for testing
return Objects.equals(index, other.index) && Objects.equals(shardId, other.shardId) && Objects.equals(node, other.node);
}
@Override
public int hashCode() {
// Override equals and hashCode for testing
return Objects.hash(index, shardId, node);
}
}
| |
package org.surrel.messengerbypasser;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RelativeLayout;
import org.surrel.messengerbypasser.activity.BaseFacebookWebViewActivity;
/**
* Facebook Messenger web wrapper activity.
*/
public class MainActivity extends BaseFacebookWebViewActivity {
// Constant
private final static String LOG_TAG = "FbWrapper";
private final static int MENU_DRAWER_GRAVITY = GravityCompat.END;
protected final static int DELAY_RESTORE_STATE = (60 * 1000) * 30;
// Members
private DrawerLayout mDrawerLayout = null;
private RelativeLayout mWebViewContainer = null;
private String mDomainToUse = INIT_URL_MOBILE;
// Preferences stuff
private SharedPreferences mSharedPreferences = null;
/**
* {@inheritDoc}
*/
@Override
protected void onActivityCreated() {
Log.d(LOG_TAG, "onActivityCreated()");
// Set the content view layout
setContentView(R.layout.main_layout);
// Keep a reference of the DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.layout_main);
mWebViewContainer = (RelativeLayout) findViewById(R.id.webview_container);
// // Set the click listener interface for the buttons
// setOnClickListeners();
}
/**
* {@inheritDoc}
*/
@Override
protected void onWebViewInit(Bundle savedInstanceState) {
Log.d(LOG_TAG, "onWebViewInit()");
// Load the application's preferences
loadPreferences();
// Get the Intent data in case we need to load a specific URL
Intent intent = getIntent();
// Get a subject and text and check if this is a link trying to be shared
String sharedSubject = intent.getStringExtra(Intent.EXTRA_SUBJECT);
String sharedUrl = intent.getStringExtra(Intent.EXTRA_TEXT);
// If we have a valid URL that was shared to us, open the sharer
if (sharedUrl != null) {
if (!sharedUrl.equals("")) {
// Check if the URL being shared is a proper web URL
if (!sharedUrl.startsWith("http://") || !sharedUrl.startsWith("https://")) {
// if it's not, let's see if it includes a URL in it (prefixed with a message)
int startUrlIndex = sharedUrl.indexOf("http:");
if (startUrlIndex > 0) {
// Seems like it's prefixed with a message, let's trim the start and get the URL only
sharedUrl = sharedUrl.substring(startUrlIndex);
}
}
String formattedSharedUrl = String.format(mDomainToUse + URL_PAGE_SHARE_LINKS,
sharedUrl, sharedSubject);
Log.d(LOG_TAG, "Loading the sharer page...");
loadNewPage(Uri.parse(formattedSharedUrl).toString());
return;
}
}
// Open the proper URL in case the user clicked on a link that brought us here
if (intent.getData() != null) {
Log.d(LOG_TAG, "Loading a specific Facebook URL a user " +
"clicked on somewhere else");
loadNewPage(intent.getData().toString());
return;
}
boolean loadInitialPage = true;
if (savedInstanceState != null) {
long savedStateTime = savedInstanceState.getLong(KEY_SAVE_STATE_TIME, -1);
if (savedStateTime > 0) {
long timeDiff = System.currentTimeMillis() - savedStateTime;
if ((mWebView != null) && (timeDiff < DELAY_RESTORE_STATE)) {
// Restore the state of the WebView using the saved instance state
Log.d(LOG_TAG, "Restoring the WebView state");
restoreWebView(savedInstanceState);
loadInitialPage = false;
}
}
}
if (loadInitialPage) {
// Load the URL depending on the type of device or preference
Log.d(LOG_TAG, "Loading the init Facebook URL");
loadNewPage(mDomainToUse);
}
}
/**
* {@inheritDoc}
*/
@Override
protected void onResumeActivity() {
Log.d(LOG_TAG, "onResumeActivity()");
// This will allow us to check and see if the domain to be used changed
String previousDomainUsed = mDomainToUse;
// Reload the preferences in case the user changed something critical
loadPreferences();
// If the domain changes, reload the page with the new domain
if (!mDomainToUse.equalsIgnoreCase(previousDomainUsed)) {
loadNewPage(mDomainToUse);
}
}
// /**
// * Sets the click listener on all the buttons in the activity
// */
// private void setOnClickListeners() {
// // Create a new listener
// MenuDrawerButtonListener buttonsListener = new MenuDrawerButtonListener();
//
// // Set this listener to all the buttons
// findViewById(R.id.menu_drawer_right).setOnClickListener(buttonsListener);
// findViewById(R.id.menu_item_jump_to_top).setOnClickListener(buttonsListener);
// findViewById(R.id.menu_item_refresh).setOnClickListener(buttonsListener);
// findViewById(R.id.menu_item_newsfeed).setOnClickListener(buttonsListener);
// findViewById(R.id.menu_items_notifications).setOnClickListener(buttonsListener);
// findViewById(R.id.menu_item_messages).setOnClickListener(buttonsListener);
// findViewById(R.id.menu_share_this).setOnClickListener(buttonsListener);
// findViewById(R.id.menu_preferences).setOnClickListener(buttonsListener);
// findViewById(R.id.menu_about).setOnClickListener(buttonsListener);
// findViewById(R.id.menu_kill).setOnClickListener(buttonsListener);
// }
/**
* Used to open the menu drawer
*/
private void openMenuDrawer() {
if (mDrawerLayout != null) {
mDrawerLayout.openDrawer(MENU_DRAWER_GRAVITY);
}
}
/**
* Used to close the menu drawer
*/
private void closeMenuDrawer() {
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(MENU_DRAWER_GRAVITY);
}
}
/**
* Check to see if the menu drawer is currently open
*
* @return {@link boolean} true if the menu drawer is open,
* false if closed.
*/
private boolean isMenuDrawerOpen() {
if (mDrawerLayout != null) {
return mDrawerLayout.isDrawerOpen(MENU_DRAWER_GRAVITY);
} else {
return false;
}
}
/**
* Used to toggle the menu drawer
*/
private void toggleMenuDrawer() {
if (isMenuDrawerOpen()) {
closeMenuDrawer();
} else {
openMenuDrawer();
}
}
/**
* Set the preferences for this activity {@link org.surrel.messengerbypasser.webview.FacebookWebView}.
*/
private void loadPreferences() {
// if (mSharedPreferences == null) {
// // Get the default shared preferences instance
// mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
// }
//
// // Get the URL to load, check-in and proxy settings
// boolean anyDomain = mSharedPreferences.getBoolean(FacebookPreferences.OPEN_LINKS_INSIDE, false);
// boolean allowCheckins = mSharedPreferences.getBoolean(FacebookPreferences.ALLOW_CHECKINS, false);
// boolean blockImages = mSharedPreferences.getBoolean(FacebookPreferences.BLOCK_IMAGES, false);
// boolean enableProxy = mSharedPreferences.getBoolean(FacebookPreferences.KEY_PROXY_ENABLED, false);
// String proxyHost = mSharedPreferences.getString(FacebookPreferences.KEY_PROXY_HOST, null);
// String proxyPort = mSharedPreferences.getString(FacebookPreferences.KEY_PROXY_PORT, null);
boolean anyDomain=false, blockImages=false, enableProxy=false;
String proxyHost = new String(), proxyPort = new String();
// Set the flags for loading URLs, allowing geolocation and loading network images
setAllowAnyDomain(anyDomain);
setBlockImages(blockImages);
// if (enableProxy && !TextUtils.isEmpty(proxyHost) && !TextUtils.isEmpty(proxyPort)) {
// int proxyPortInt = -1;
// try {
// proxyPortInt = Integer.parseInt(proxyPort);
// } catch (Exception e) {
// e.printStackTrace();
// }
// setProxy(proxyHost, proxyPortInt);
// }
// Force the webview config to mobile
setupFacebookWebViewConfig(true, true, false, false, false);
}
/**
* Configure this {@link org.surrel.messengerbypasser.webview.FacebookWebView}
* with the appropriate preferences depending on the device configuration.<br />
* Use the 'force' flag to force the configuration to either mobile or desktop.
*
* @param force {@link boolean}
* whether to force the configuration or not,
* if false the 'mobile' flag will be ignored
* @param mobile {@link boolean}
* whether to use the mobile or desktop site.
* @param facebookZero {@link boolean}
* whether or not to use Facebook Zero
*/
// TODO: time to fix this mess
private void setupFacebookWebViewConfig(boolean force, boolean mobile, boolean facebookBasic,
boolean facebookZero, boolean facebookOnion) {
if (force && !mobile) {
// Force the desktop site to load
mDomainToUse = INIT_URL_DESKTOP;
} else if (facebookZero) {
// If Facebook zero is set, use that
mDomainToUse = INIT_URL_FACEBOOK_ZERO;
} else if (facebookOnion) {
// If the Onion domain is set, use that
mDomainToUse = INIT_URL_FACEBOOK_ONION;
} else {
// Otherwise, just load the mobile site for all devices
mDomainToUse = INIT_URL_MOBILE;
}
// Set the user agent depending on config
setUserAgent(force, mobile, facebookBasic);
}
/**
* Check whether this device is a phone or a tablet.
*
* @return {@link boolean} whether this device is a phone
* or a tablet
*/
private boolean isDeviceTablet() {
boolean isTablet;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
// There were no tablet devices before Honeycomb, assume is a phone
isTablet = false;
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB
&& Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR2) {
// Honeycomb only allowed tablets, always assume it's a tablet
isTablet = true;
} else {
// If the device's screen width is higher than 720dp, it's a tablet,
// otherwise, it's, at least, a phone (could be a phablet, or small tablet)
Configuration config = getResources().getConfiguration();
isTablet = config.smallestScreenWidthDp >= 720;
}
return isTablet;
}
// /**
// * Show an alert dialog with the information about the application.
// */
// private void showAboutAlert() {
// AlertDialog alertDialog = new AlertDialog.Builder(this).create();
// alertDialog.setTitle(getString(R.string.menu_about));
// alertDialog.setMessage(getString(R.string.txt_about));
// alertDialog.setIcon(R.drawable.ic_launcher);
// alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL,
// getString(R.string.lbl_dialog_close),
// new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // Don't do anything, simply close the dialog
// }
// });
// alertDialog.show();
// }
/**
* {@inheritDoc}
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch(keyCode){
case KeyEvent.KEYCODE_MENU:
toggleMenuDrawer();
return true;
case KeyEvent.KEYCODE_BACK:
// If the back button is pressed while the drawer
// is open try to close it
if (isMenuDrawerOpen()) {
closeMenuDrawer();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
| |
/*
* Copyright (C) 2015 STFC
* 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 uk.ac.ngs.dao;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import uk.ac.ngs.common.Pair;
import uk.ac.ngs.domain.CertificateRow;
/**
* DAO for the CA DB <code>certificate</code> table.
*
* @author David Meredith
*
*/
@Repository
public class JdbcCertificateDao {
private NamedParameterJdbcTemplate jdbcTemplate;
private static final Log log = LogFactory.getLog(JdbcCertificateDao.class);
/*
* Define SQL query fragments used to build the DAOs queries.
*/
public static final String SELECT_PROJECT = "select cert_key, data, dn, cn, email, status, role, notafter from certificate ";
public static final String SELECT_COUNT = "select count(*) from certificate ";
public static final String UPDATE_BY_REQ_KEY = "update certificate set "
+ "data=:data, dn=:dn, cn=:cn, email=:email, status=:status, role=:role, notafter=:notafter "
+ "where cert_key=:cert_key";
private static final String LIMIT_ROWS = "LIMIT :limit OFFSET :offset";
//private static final String ORDER_BY = "ORDER BY cert_key";
private static final String WHERE_BY_ID = "where cert_key = :cert_key ";
private static final String SQL_SELECT_BY_ID = SELECT_PROJECT + WHERE_BY_ID;
private static final String SQL_SELECT_ALL = SELECT_PROJECT + LIMIT_ROWS;
private final static Pattern DATA_CERT_PATTERN = Pattern.compile("-----BEGIN CERTIFICATE-----(.+?)-----END CERTIFICATE-----", Pattern.DOTALL);
private final static Pattern DATA_LAD_PATTERN = Pattern.compile("LAST_ACTION_DATE\\s?=\\s?([^\\n]+)$", Pattern.MULTILINE);
private final static Pattern DATA_RAOP_PATTERN = Pattern.compile("RAOP\\s?=\\s?([0-9]+)\\s*$", Pattern.MULTILINE);
// Date will be of the form: Tue Apr 23 13:47:13 2013 UTC
private final DateFormat utcDateFormat = new SimpleDateFormat("E MMM dd HH:mm:ss yyyy zzz");
/**
* Keys for defining 'where' parameters and values for building queries.
* <p>
* If the key ends with '_LIKE' then the where clause is appended with a SQL
* 'like' clause (e.g. <code>key like 'value'</code>).
* If the key ends with '_EQ' then the where clause is appended with a SQL
* '=' clause (e.g. <code>key = 'value'</code>).
* <p>
* _EQ takes precedence over _LIKE so if both EMAIL_EQ and EMAIL_LIKE are given, then
* only EMAIL_EQ is used to create the query.
*/
public static enum WHERE_PARAMS {
DN_HAS_RA_LIKE, CN_LIKE, EMAIL_LIKE, EMAIL_EQ, DN_LIKE, ROLE_LIKE, STATUS_LIKE, DATA_LIKE, NOTAFTER_GREATERTHAN_CURRENTTIME
};
public JdbcCertificateDao() {
}
private static DateFormat getDateFormat(){
DateFormat utcTimeStampFormatter = new SimpleDateFormat("yyyyMMddHHmmss");
utcTimeStampFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
return utcTimeStampFormatter;
}
/**
* Set the JDBC dataSource.
* @param dataSource
*/
@Autowired
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}
private static final class CertificateRowMapper implements RowMapper<CertificateRow> {
public CertificateRow mapRow(ResultSet rs, int rowNum) throws SQLException {
CertificateRow cr = new CertificateRow();
long lValcert_key = rs.getLong("cert_key");
if(!rs.wasNull()){
cr.setCert_key(lValcert_key);
}
cr.setData(rs.getString("data"));
cr.setEmail(rs.getString("email"));
cr.setStatus(rs.getString("status"));
cr.setRole(rs.getString("role"));
cr.setDn(rs.getString("dn"));
cr.setCn(rs.getString("cn"));
BigDecimal notafterBigD = rs.getBigDecimal("notafter");
if(notafterBigD != null){
String notafterStr = notafterBigD.toString();
try {
Date date = getDateFormat().parse(notafterStr);
cr.setNotAfter(date);
} catch (ParseException ex) {
throw new SQLException(ex);
}
}
return cr;
}
}
/**
* Count the number of <tt>certificate</tt> rows where <tt>status</tt>
* is <tt>VALID</tt> and <tt>dn</tt> is like the given DN and
* <tt>notafter</tt> is greater than the current time after the given
* notafterTolerance is applied.
* <p>
* The notafterTolerance is applied in days, e.g. to subtract 5 days from
* the current time specify -5, to add 5 days from the current time specify 5.
*
* @param rfc2253DN Compare this argument to the value of the <tt>dn</tt> column
* using a case in-sensitive 'LIKE' comparison.
* @param notafterTolerance Tolerance period defined in days.
* @return Number of matching rows.
*/
public int countByStatusIsVALIDNotExpired(String rfc2253DN, int notafterTolerance) {
// If the status of the request is "REVOKED" or "DELETED", then we
// think the certificate doesn't exist.
// In addition, the certificate may also be expired. In this case,
// the certificate CAN still be marked as "VALID" and NOT as "EXPIRED",
// we thus need the manual timestamp check to test for expired certs.
//
// See the ***IMPORTANT NOTE on canonical DN checking***
Calendar calendarLocal = Calendar.getInstance(); // current time in default locale
// Get time in past 'notafterTolerance' number of days ago - used to define how many
// days a certificate can be expired but still eligible for renewal.
// E.g. to subtract 5 days from the current time of the calendar, specify -5
calendarLocal.add(Calendar.DAY_OF_MONTH, notafterTolerance);
String currentTimeUTC = getDateFormat().format(calendarLocal.getTime());
Map<String, Object> namedParameters = new HashMap<String, Object>();
namedParameters.put("currentTime", new Long(currentTimeUTC));
namedParameters.put("dn", rfc2253DN);
//log.debug("notafter: ["+namedParameters.get("currentTime")+"]");
String query = "select count(*) from certificate where dn ILIKE :dn and status='VALID' and notafter > :currentTime";
return this.jdbcTemplate.queryForInt(query, namedParameters);
}
/**
* Return all the certificates in the <code>certificate</code> table.
* @param limit
* @param offset
* @return
*/
public List<CertificateRow> findAll(Integer limit, Integer offset) {
Map<String, Object> namedParameters = new HashMap<String, Object>();
namedParameters.put("limit", limit);
namedParameters.put("offset", offset);
return this.jdbcTemplate.query(SQL_SELECT_ALL, namedParameters, new CertificateRowMapper());
}
/**
* Count all the certificates in the <code>certificate</code> table.
* @return
*/
public int countAll() {
return this.jdbcTemplate.queryForInt("select count(*) from certificate", new HashMap<String, String>(0));
}
/**
* Find the specified certificate in the <code>certificate</code> table with
* the given <code>cert_key</code>.
* @param cert_key
* @return row or null if no row is found
*/
public CertificateRow findById(long cert_key) {
Map<String, Object> namedParameters = new HashMap<String, Object>();
namedParameters.put("cert_key", cert_key);
try {
return this.jdbcTemplate.queryForObject(SQL_SELECT_BY_ID, namedParameters, new CertificateRowMapper());
} catch (EmptyResultDataAccessException ex) {
log.warn("No certificate row found with [" + cert_key + "]");
return null;
}
}
/**
* Search for certificates using the search criteria specified in the given
* where-by parameter map.
* Multiple whereByParams are appended together using 'and' statements.
*
* @param whereByParams Search-by parameters used in where clause of SQL query.
* @param limit Limit the returned row count to this many rows or null not to specify a limit.
* @param offset Return rows from this row number or null not to specify an offset.
* @return
*/
public List<CertificateRow> findBy(Map<WHERE_PARAMS, String> whereByParams, Integer limit, Integer offset) {
Pair<String, Map<String, Object>> p = this.buildQuery(SELECT_PROJECT, whereByParams, limit, offset, true);
return this.jdbcTemplate.query(p.first, p.second, new CertificateRowMapper());
}
/**
* Count the total number of rows that are selected by the given where-by search criteria.
* @see #findBy(java.util.Map, java.lang.Integer, java.lang.Integer)
* @param whereByParams
* @return number of matching rows.
*/
public int countBy(Map<WHERE_PARAMS, String> whereByParams) {
Pair<String, Map<String, Object>> p = this.buildQuery(SELECT_COUNT, whereByParams, null, null, false);
return this.jdbcTemplate.queryForInt(p.first, p.second);
}
/**
* Find all rows with role 'RA Operator' or 'CA Operator' with a
* status of 'VALID' and a 'notafter' time that is in the future with the specified
* loc (L=) and ou (OU=) values in the dn.
* @param loc Locality value (optional, use null to prevent filtering by loc)
* @param ou OrgUnit value (optional, use null to prevent filtering by ou)
* @return
*/
public List<CertificateRow> findActiveRAsBy(String loc, String ou){
String currentTime = getDateFormat().format(new Date());
Map<String, Object> namedParameters = new HashMap<String, Object>();
namedParameters.put("current_time", Long.parseLong(currentTime));
// Build the RA filter
StringBuilder raVal = new StringBuilder("%");
boolean restrictByRa = false;
if(loc != null){
raVal.append("L=").append(loc).append(",");
restrictByRa = true;
}
if(ou != null){
raVal.append("OU=").append(ou);
restrictByRa = true;
}
raVal.append("%");
if(restrictByRa){
//namedParameters.put("ra", "%L="+loc+",OU="+ou+"%");
namedParameters.put("ra", raVal.toString());
}
StringBuilder query = new StringBuilder(SELECT_PROJECT);
query.append("where (role='RA Operator' or role='CA Operator') ");
if (restrictByRa) {
query.append("and dn like :ra ");
}
query.append("and status='VALID' and notafter > :current_time");
return this.jdbcTemplate.query(query.toString(), namedParameters, new CertificateRowMapper());
}
/**
* Update the 'certificate' table with the values from the given CertificateRow.
* The given CertificateRow must have a populated <code>cert_key</code> value to
* identify the correct row in the DB.
*
* @param certRow Extracts values from this certificate to update the db.
* @return Number of rows updated (should always be 1)
*/
public int updateCertificateRow(CertificateRow certRow){
if(certRow.getCert_key() <=0 ){
throw new IllegalArgumentException("Invalid certificateRow, cert_key is zero or negative");
}
Map<String, Object> namedParameters = new HashMap<String, Object>();
namedParameters.put("data", certRow.getData());
namedParameters.put("dn", certRow.getDn());
namedParameters.put("cn", certRow.getCn());
namedParameters.put("email", certRow.getEmail());
namedParameters.put("status", certRow.getStatus());
namedParameters.put("role", certRow.getRole());
namedParameters.put("notafter", new Long(getDateFormat().format(certRow.getNotAfter())));
namedParameters.put("cert_key", certRow.getCert_key());
/*"update certificate set data=:data, dn=:dn, cn=:cn, email=:email,
* status=:status, role=:role, notafter=:notafter where cert_key=:cert_key";*/
return this.jdbcTemplate.update(UPDATE_BY_REQ_KEY, namedParameters);
}
/**
* Extract the PEM string from the given string (if any).
* The returned string excludes the '-----BEGIN CERTIFICATE-----' and
* '-----END CERTIFICATE-----' header and footer.
* @param cert
* @return PEM String
*/
public String getPemStringFromData(String data) {
Matcher certmatcher = DATA_CERT_PATTERN.matcher(data);
if (certmatcher.find()) {
return certmatcher.group();
}
return null;
}
public X509Certificate getX509CertificateFromData(CertificateRow certRow)
throws CertificateException, UnsupportedEncodingException {
String pemString = this.getPemStringFromData(certRow.getData());
X509Certificate certObj = null;
if (pemString != null) {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream is = new ByteArrayInputStream(pemString.getBytes("UTF-8"));
certObj = (X509Certificate) cf.generateCertificate(is);
return certObj;
}
return certObj;
}
/**
* Update the LAST_ACTION_DATE and RAOP values in the given data field.
* The LAST_ACTION_DATE key-value pair is updated/replaced if present or added if not.
* A new RAOP key-value pair is appended after the last RAOP entry.
*
* @param data String to update. If null, then an empty string is created/modified and returned.
* @param raopId the RA operator id used to update the RAOP key value or -1 to exclude RAOP update.
* @return updated string (never null)
*/
public String updateDataCol_LastActionDateRaop(String data, long raopId) {
if(data == null) {
data = "-----END HEADER-----";
}
// Update/add RAOP
if(raopId != -1){
Matcher raopMatcher = DATA_RAOP_PATTERN.matcher(data);
if (raopMatcher.find()) {
// append a new 'RAOP = raopId' line after the last found RAOP line
int lastIndex = raopMatcher.end();
while (raopMatcher.find()) {
lastIndex = raopMatcher.end();
}
String dataStart = data.substring(0, lastIndex);
String dataMiddle = "\nRAOP = "+raopId;
String dataEnd = data.substring(lastIndex, data.length());
data = dataStart+dataMiddle+dataEnd;
// We don't replace all as we want to maintain a history
//data = raopMatcher.replaceAll("RAOP = " + raopId);
} else {
data = data.replaceAll("-----END HEADER-----", "RAOP = " + raopId + "\n-----END HEADER-----");
}
}
// Update or add LAST_ACTION_DATE (add if it can't be found)
Matcher ladmatcher = DATA_LAD_PATTERN.matcher(data);
String dateString = utcDateFormat.format(new Date());
if (ladmatcher.find()) {
data = ladmatcher.replaceAll("LAST_ACTION_DATE = " + dateString);
} else {
data = data.replaceAll("-----END HEADER-----", "LAST_ACTION_DATE = " + dateString + "\n-----END HEADER-----");
}
return data;
}
/**
* Build up the query using the given where by parameters in the map
* and return the query and the named parameter map for subsequent parameter-binding/execution.
*/
protected Pair<String, Map<String, Object>> buildQuery(String selectStatement,
Map<WHERE_PARAMS, String> whereByParams, Integer limit, Integer offset, boolean orderby) {
String whereClause = "";
Map<String, Object> namedParameters = new HashMap<String, Object>();
if (whereByParams != null && !whereByParams.isEmpty()) {
StringBuilder whereBuilder = new StringBuilder("where ");
if (whereByParams.containsKey(WHERE_PARAMS.CN_LIKE)) {
whereBuilder.append("cn like :cn and ");
namedParameters.put("cn", whereByParams.get(WHERE_PARAMS.CN_LIKE));
}
// EQ takes precidence over LIKE
if (whereByParams.containsKey(WHERE_PARAMS.EMAIL_EQ)) {
log.debug("Searching for null email - check val ["+whereByParams.get(WHERE_PARAMS.EMAIL_EQ)+"]");
if(whereByParams.get(WHERE_PARAMS.EMAIL_EQ) == null){
whereBuilder.append("email is null and ");
} else {
whereBuilder.append("email = :email and ");
namedParameters.put("email", whereByParams.get(WHERE_PARAMS.EMAIL_EQ));
}
} else {
if (whereByParams.containsKey(WHERE_PARAMS.EMAIL_LIKE)) {
whereBuilder.append("email like :email and ");
namedParameters.put("email", whereByParams.get(WHERE_PARAMS.EMAIL_LIKE));
}
}
if (whereByParams.containsKey(WHERE_PARAMS.DN_LIKE)) {
whereBuilder.append("dn like :dn and ");
namedParameters.put("dn", whereByParams.get(WHERE_PARAMS.DN_LIKE));
}
if (whereByParams.containsKey(WHERE_PARAMS.ROLE_LIKE)) {
whereBuilder.append("role like :role and ");
namedParameters.put("role", whereByParams.get(WHERE_PARAMS.ROLE_LIKE));
}
if (whereByParams.containsKey(WHERE_PARAMS.STATUS_LIKE)) {
whereBuilder.append("status like :status and ");
namedParameters.put("status", whereByParams.get(WHERE_PARAMS.STATUS_LIKE));
}
if(whereByParams.containsKey(WHERE_PARAMS.DATA_LIKE)){
whereBuilder.append("data like :data and ");
namedParameters.put("data", whereByParams.get(WHERE_PARAMS.DATA_LIKE));
}
if (whereByParams.containsKey(WHERE_PARAMS.NOTAFTER_GREATERTHAN_CURRENTTIME)) {
String currentTime = getDateFormat().format(new Date());
whereBuilder.append("notafter > :current_time and ");
// for old posgres 7 can use a string and PG will do conversion for you to Long
//namedParameters.put("current_time", currentTime);
// PG 8.4 is more strict and requires a Long (it will not convert for you)
namedParameters.put("current_time", Long.parseLong(currentTime));
}
if(whereByParams.containsKey(WHERE_PARAMS.DN_HAS_RA_LIKE)){
whereBuilder.append("dn like :dn_has_ra_like and ");
namedParameters.put("dn_has_ra_like", whereByParams.get(WHERE_PARAMS.DN_HAS_RA_LIKE));
}
// Always trim leading/trailing whitespace and remove trailling and (if any)
whereClause = whereBuilder.toString().trim();
if (whereClause.endsWith("and")) {
whereClause = whereClause.substring(0, whereClause.length() - 3);
}
whereClause = whereClause.trim();
}
// Build up the sql statement.
String sql = selectStatement + whereClause;
if(orderby){
sql = sql + " order by cert_key";
}
if (limit != null) {
sql = sql + " LIMIT :limit";
namedParameters.put("limit", limit);
}
if (offset != null) {
sql = sql + " OFFSET :offset";
namedParameters.put("offset", offset);
}
log.debug(sql);
return Pair.create(sql.trim(), namedParameters);
}
}
| |
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.developerstudio.datamapper.diagram.custom.dialogs;
import java.util.ArrayList;
import org.apache.commons.lang.StringUtils;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.edit.command.AddCommand;
import org.eclipse.emf.edit.command.DeleteCommand;
import org.eclipse.emf.edit.command.SetCommand;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.gef.EditPart;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
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.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.wso2.developerstudio.datamapper.Concat;
import org.wso2.developerstudio.datamapper.DataMapperFactory;
import org.wso2.developerstudio.datamapper.DataMapperPackage;
import org.wso2.developerstudio.datamapper.OperatorLeftConnector;
import org.wso2.developerstudio.datamapper.diagram.edit.parts.ConcatEditPart;
import org.wso2.developerstudio.datamapper.diagram.edit.parts.OperatorRectangle;
import org.wso2.developerstudio.datamapper.impl.ConcatImpl;
public class ConfigureConcatOperatorDialog extends AbstractConfigureOperatorDialog {
private String inputCount;
private String delimiter;
private TransactionalEditingDomain editingDomain;
private ArrayList<OperatorLeftConnector> caseOutputConnectors = new ArrayList<OperatorLeftConnector>();
private ConcatImpl concatImpl;
private EditPart editPart;
public ConfigureConcatOperatorDialog(Shell parentShell, Concat concatOperator,
TransactionalEditingDomain editingDomain, EditPart selectedEP) {
super(parentShell);
this.concatImpl = (ConcatImpl) concatOperator;
this.editingDomain = editingDomain;
this.editPart=selectedEP;
}
@Override
public void create() {
super.create();
setTitle("Configure Concat Operator");
setMessage("Set concat operator properties", IMessageProvider.INFORMATION);
}
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
// Set title.
newShell.setText("Configure Concat Operator");
}
protected Control createDialogArea(Composite parent) {
Composite area = (Composite) super.createDialogArea(parent);
Composite container = new Composite(area, SWT.NONE);
container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
GridLayout layout = new GridLayout(2, false);
container.setLayout(layout);
Label concatInputConnectorCountLabel = new Label(container, SWT.NULL);
concatInputConnectorCountLabel.setText("Number of Inputs : ");
final Text inputConnectorCount = new Text(container, SWT.BORDER);
inputConnectorCount.setLayoutData(dataPropertyConfigText);
inputConnectorCount.setText(concatImpl.getBasicContainer().getLeftContainer().getLeftConnectors().size() + "");
inputCount = inputConnectorCount.getText();
inputConnectorCount.addListener(SWT.Modify, new Listener() {
public void handleEvent(Event event) {
try {
inputCount = new String(inputConnectorCount.getText());
if (!(StringUtils.isEmpty(inputCount) && StringUtils.isEmpty(delimiter))) {
getButton(IDialogConstants.OK_ID).setEnabled(true);
validate();
} else {
getButton(IDialogConstants.OK_ID).setEnabled(false);
}
} catch (Exception e) {
getButton(IDialogConstants.OK_ID).setEnabled(false);
}
}
});
Label concatDelimiterLabel = new Label(container, SWT.NULL);
concatDelimiterLabel.setText("Concat Delimiter : ");
final Text delimiterText = new Text(container, SWT.BORDER);
delimiterText.setLayoutData(dataPropertyConfigText);
if (concatImpl.getDelimiter() != null) {
delimiterText.setText(concatImpl.getDelimiter());
} else {
delimiterText.setText("");
}
delimiter = delimiterText.getText();
delimiterText.addListener(SWT.Modify, new Listener() {
public void handleEvent(Event event) {
try {
delimiter = new String(delimiterText.getText());
if (!(StringUtils.isEmpty(inputCount) && StringUtils.isEmpty(delimiter))) {
getButton(IDialogConstants.OK_ID).setEnabled(true);
validate();
} else {
getButton(IDialogConstants.OK_ID).setEnabled(false);
}
} catch (Exception e) {
getButton(IDialogConstants.OK_ID).setEnabled(false);
}
}
});
return area;
}
/**
* Create contents of the button bar.
*
* @param parent
*/
@Override
protected void createButtonsForButtonBar(Composite parent) {
createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
validate();
}
private void validate() {
boolean isEnabled = false;
Button okButton = getButton(IDialogConstants.OK_ID);
if (delimiter != null && inputCount != null) {
if (!StringUtils.isEmpty(delimiter)) {
if (!inputCount.equals("0") && !StringUtils.isEmpty(inputCount)) {
isEnabled = true;
}
}
}
if (okButton != null) {
okButton.setEnabled(isEnabled);
}
}
protected void okPressed() {
if (!StringUtils.isEmpty(delimiter)) {
Concat concatOperatorInstance = concatImpl;
SetCommand setCmnd = new SetCommand(editingDomain, concatOperatorInstance,
DataMapperPackage.Literals.CONCAT__DELIMITER, delimiter);
if (setCmnd.canExecute()) {
editingDomain.getCommandStack().execute(setCmnd);
}
((OperatorRectangle)((ConcatEditPart)editPart).getConcatFigure()).changeOperatorHeader("Concat : \""+delimiter+"\"");
}
int number = Integer.parseInt(inputCount)
- concatImpl.getBasicContainer().getLeftContainer().getLeftConnectors().size();
if (number > 0) {
for (int i = 0; i < number; ++i) {
OperatorLeftConnector concatOperatorContainers = DataMapperFactory.eINSTANCE
.createOperatorLeftConnector();
AddCommand addCmd = new AddCommand(editingDomain, concatImpl.getBasicContainer().getLeftContainer(),
DataMapperPackage.Literals.OPERATOR_LEFT_CONTAINER__LEFT_CONNECTORS, concatOperatorContainers);
if (addCmd.canExecute()) {
editingDomain.getCommandStack().execute(addCmd);
}
}
} else if (number < 0) {
for (int i = 0; i < Math.abs(number); i++) {
EList<OperatorLeftConnector> listOfLeftConnectors = concatImpl.getBasicContainer().getLeftContainer()
.getLeftConnectors();
OperatorLeftConnector concatOperatorConnector = listOfLeftConnectors
.get(listOfLeftConnectors.size() - 1);
caseOutputConnectors.add(concatOperatorConnector);
DeleteCommand deleteCmd = new DeleteCommand(editingDomain, caseOutputConnectors);
if (deleteCmd.canExecute()) {
editingDomain.getCommandStack().execute(deleteCmd);
}
caseOutputConnectors.remove(concatOperatorConnector);
}
}
super.okPressed();
}
}
| |
/**
* This software is licensed under the Apache 2 license, quoted below.<br>
* <br>
* Copyright 2017 Andras Berkes [andras.berkes@programmer.net]<br>
* <br>
* 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<br>
* <br>
* http://www.apache.org/licenses/LICENSE-2.0<br>
* <br>
* 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 io.datatree.dom.converters;
import static io.datatree.dom.converters.DataConverterRegistry.register;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.UUID;
import org.bson.BsonBoolean;
import org.bson.BsonDateTime;
import org.bson.BsonDouble;
import org.bson.BsonInt32;
import org.bson.BsonInt64;
import org.bson.BsonNull;
import org.bson.BsonRegularExpression;
import org.bson.BsonString;
import org.bson.BsonTimestamp;
import org.bson.BsonUndefined;
import org.bson.types.Binary;
import org.bson.types.Code;
import org.bson.types.Decimal128;
import org.bson.types.ObjectId;
import org.bson.types.Symbol;
import io.datatree.dom.BASE64;
import io.datatree.dom.Config;
import io.datatree.dom.DeepCloner;
/**
* Converters for MongoDB / BSON object types.
*
* @author Andras Berkes [andras.berkes@programmer.net]
*/
final class BsonConverterSet extends AbstractConverterSet {
// --- INIT MONGODB / BSON CONVERTERS ---
static {
// --- VALUE TO STRING CONVERTERS ---
register(String.class, BsonNull.class, (from) -> {
return null;
});
register(String.class, BsonBoolean.class, (from) -> {
return from.getValue() ? "true" : "false";
});
register(String.class, BsonDateTime.class, (from) -> {
return dateToString(new Date(from.getValue()));
});
register(String.class, BsonDouble.class, (from) -> {
return Double.toString(from.getValue());
});
register(String.class, BsonInt32.class, (from) -> {
return Integer.toString(from.getValue());
});
register(String.class, BsonInt64.class, (from) -> {
return Long.toString(from.getValue());
});
register(String.class, BsonString.class, (from) -> {
return from.getValue();
});
register(String.class, BsonTimestamp.class, (from) -> {
return dateToString(new Date(from.getTime() * 1000L));
});
register(String.class, BsonUndefined.class, (from) -> {
return null;
});
register(String.class, Binary.class, (from) -> {
return BASE64.encode(from.getData());
});
register(String.class, Decimal128.class, (from) -> {
return from.bigDecimalValue().toString();
});
register(String.class, Code.class, (from) -> {
return from.getCode();
});
register(String.class, ObjectId.class, (from) -> {
return from.toHexString();
});
register(String.class, Symbol.class, (from) -> {
return from.getSymbol();
});
register(String.class, BsonRegularExpression.class, (from) -> {
return from.getPattern();
});
// --- VALUE TO BYTE ARRAY CONVERTERS ---
register(byte[].class, BsonNull.class, (from) -> {
return null;
});
register(byte[].class, BsonBoolean.class, (from) -> {
return from.getValue() ? new byte[] { 1 } : new byte[] { 0 };
});
register(byte[].class, BsonDateTime.class, (from) -> {
return numberStringToBytes(Long.toString(from.getValue()));
});
register(byte[].class, BsonDouble.class, (from) -> {
return numberStringToBytes(Double.toString(from.getValue()));
});
register(byte[].class, BsonInt32.class, (from) -> {
return numberStringToBytes(Integer.toString(from.getValue()));
});
register(byte[].class, BsonInt64.class, (from) -> {
return numberStringToBytes(Long.toString(from.getValue()));
});
register(byte[].class, BsonString.class, (from) -> {
String txt = from.getValue();
if (isBase64String(txt)) {
return BASE64.decode(txt);
}
return txt.getBytes(StandardCharsets.UTF_8);
});
register(byte[].class, BsonTimestamp.class, (from) -> {
return numberStringToBytes(Integer.toString(from.getTime()));
});
register(byte[].class, BsonUndefined.class, (from) -> {
return null;
});
register(byte[].class, Binary.class, (from) -> {
return from.getData();
});
register(byte[].class, Decimal128.class, (from) -> {
return numberStringToBytes(from.bigDecimalValue().toString());
});
register(byte[].class, Code.class, (from) -> {
return from.getCode().getBytes(StandardCharsets.UTF_8);
});
register(byte[].class, ObjectId.class, (from) -> {
return from.toByteArray();
});
register(byte[].class, Symbol.class, (from) -> {
return from.getSymbol().getBytes(StandardCharsets.UTF_8);
});
register(byte[].class, BsonRegularExpression.class, (from) -> {
return from.getPattern().getBytes(StandardCharsets.UTF_8);
});
// --- VALUE TO BYTE CONVERTERS ---
register(Byte.class, BsonNull.class, (from) -> {
return null;
});
register(Byte.class, BsonBoolean.class, (from) -> {
return from.getValue() ? (byte) 1 : (byte) 0;
});
register(Byte.class, BsonDateTime.class, (from) -> {
return (byte) from.getValue();
});
register(Byte.class, BsonDouble.class, (from) -> {
return (byte) from.getValue();
});
register(Byte.class, BsonInt32.class, (from) -> {
return (byte) from.getValue();
});
register(Byte.class, BsonInt64.class, (from) -> {
return (byte) from.getValue();
});
register(Byte.class, BsonString.class, (from) -> {
return (byte) Long.parseLong(toNumericString(from.getValue(), false));
});
register(Byte.class, BsonTimestamp.class, (from) -> {
return (byte) from.getTime();
});
register(Byte.class, BsonUndefined.class, (from) -> {
return null;
});
register(Byte.class, Binary.class, (from) -> {
byte[] array = from.getData();
return array.length > 0 ? array[0] : 0;
});
register(Byte.class, Decimal128.class, (from) -> {
return from.bigDecimalValue().byteValue();
});
register(Byte.class, Code.class, (from) -> {
return (byte) from.getCode().hashCode();
});
register(Byte.class, ObjectId.class, (from) -> {
return (byte) from.hashCode();
});
register(Byte.class, Symbol.class, (from) -> {
return (byte) from.getSymbol().hashCode();
});
register(Byte.class, BsonRegularExpression.class, (from) -> {
return (byte) from.getPattern().hashCode();
});
// --- VALUE TO SHORT CONVERTERS ---
register(Short.class, BsonNull.class, (from) -> {
return null;
});
register(Short.class, BsonBoolean.class, (from) -> {
return from.getValue() ? (short) 1 : (short) 0;
});
register(Short.class, BsonDateTime.class, (from) -> {
return (short) from.getValue();
});
register(Short.class, BsonDouble.class, (from) -> {
return (short) from.getValue();
});
register(Short.class, BsonInt32.class, (from) -> {
return (short) from.getValue();
});
register(Short.class, BsonInt64.class, (from) -> {
return (short) from.getValue();
});
register(Short.class, BsonString.class, (from) -> {
return Short.parseShort(toNumericString(from.getValue(), false));
});
register(Short.class, BsonTimestamp.class, (from) -> {
return (short) from.getTime();
});
register(Short.class, BsonUndefined.class, (from) -> {
return null;
});
register(Short.class, Binary.class, (from) -> {
return new BigInteger(from.getData()).shortValue();
});
register(Short.class, Decimal128.class, (from) -> {
return from.bigDecimalValue().shortValue();
});
register(Short.class, Code.class, (from) -> {
return (short) from.getCode().hashCode();
});
register(Short.class, ObjectId.class, (from) -> {
return (short) from.hashCode();
});
register(Short.class, Symbol.class, (from) -> {
return (short) from.getSymbol().hashCode();
});
register(Short.class, BsonRegularExpression.class, (from) -> {
return (short) from.getPattern().hashCode();
});
// --- VALUE TO INTEGER CONVERTERS ---
register(Integer.class, BsonNull.class, (from) -> {
return null;
});
register(Integer.class, BsonBoolean.class, (from) -> {
return from.getValue() ? 1 : 0;
});
register(Integer.class, BsonDateTime.class, (from) -> {
return (int) from.getValue();
});
register(Integer.class, BsonDouble.class, (from) -> {
return (int) from.getValue();
});
register(Integer.class, BsonInt32.class, (from) -> {
return from.getValue();
});
register(Integer.class, BsonInt64.class, (from) -> {
return (int) from.getValue();
});
register(Integer.class, BsonString.class, (from) -> {
return Integer.parseInt(toNumericString(from.getValue(), false));
});
register(Integer.class, BsonTimestamp.class, (from) -> {
return from.getTime();
});
register(Integer.class, BsonUndefined.class, (from) -> {
return null;
});
register(Integer.class, Binary.class, (from) -> {
return new BigInteger(from.getData()).intValue();
});
register(Integer.class, Decimal128.class, (from) -> {
return from.bigDecimalValue().intValue();
});
register(Integer.class, Code.class, (from) -> {
return from.getCode().hashCode();
});
register(Integer.class, ObjectId.class, (from) -> {
return from.hashCode();
});
register(Integer.class, Symbol.class, (from) -> {
return from.getSymbol().hashCode();
});
register(Integer.class, BsonRegularExpression.class, (from) -> {
return from.getPattern().hashCode();
});
// --- VALUE TO LONG CONVERTERS ---
register(Long.class, BsonNull.class, (from) -> {
return null;
});
register(Long.class, BsonBoolean.class, (from) -> {
return from.getValue() ? 1l : 0l;
});
register(Long.class, BsonDateTime.class, (from) -> {
return from.getValue();
});
register(Long.class, BsonDouble.class, (from) -> {
return (long) from.getValue();
});
register(Long.class, BsonInt32.class, (from) -> {
return (long) from.getValue();
});
register(Long.class, BsonInt64.class, (from) -> {
return from.getValue();
});
register(Long.class, BsonString.class, (from) -> {
return Long.parseLong(toNumericString(from.getValue(), false));
});
register(Long.class, BsonTimestamp.class, (from) -> {
return (long) from.getTime();
});
register(Long.class, BsonUndefined.class, (from) -> {
return null;
});
register(Long.class, Binary.class, (from) -> {
return new BigInteger(from.getData()).longValue();
});
register(Long.class, Decimal128.class, (from) -> {
return from.bigDecimalValue().longValue();
});
register(Long.class, Code.class, (from) -> {
return (long) from.getCode().hashCode();
});
register(Long.class, ObjectId.class, (from) -> {
return (long) from.hashCode();
});
register(Long.class, Symbol.class, (from) -> {
return (long) from.getSymbol().hashCode();
});
register(Long.class, BsonRegularExpression.class, (from) -> {
return (long) from.getPattern().hashCode();
});
// --- VALUE TO FLOAT CONVERTERS ---
register(Float.class, BsonNull.class, (from) -> {
return null;
});
register(Float.class, BsonBoolean.class, (from) -> {
return from.getValue() ? 1f : 0f;
});
register(Float.class, BsonDateTime.class, (from) -> {
return (float) from.getValue();
});
register(Float.class, BsonDouble.class, (from) -> {
return (float) from.getValue();
});
register(Float.class, BsonInt32.class, (from) -> {
return (float) from.getValue();
});
register(Float.class, BsonInt64.class, (from) -> {
return (float) from.getValue();
});
register(Float.class, BsonString.class, (from) -> {
return Float.parseFloat(toNumericString(from.getValue(), true));
});
register(Float.class, BsonTimestamp.class, (from) -> {
return (float) from.getTime();
});
register(Float.class, BsonUndefined.class, (from) -> {
return null;
});
register(Float.class, Binary.class, (from) -> {
return new BigInteger(from.getData()).floatValue();
});
register(Float.class, Decimal128.class, (from) -> {
return from.bigDecimalValue().floatValue();
});
register(Float.class, Code.class, (from) -> {
return (float) from.getCode().hashCode();
});
register(Float.class, ObjectId.class, (from) -> {
return (float) from.hashCode();
});
register(Float.class, Symbol.class, (from) -> {
return (float) from.getSymbol().hashCode();
});
register(Float.class, BsonRegularExpression.class, (from) -> {
return (float) from.getPattern().hashCode();
});
// --- VALUE TO DOUBLE CONVERTERS ---
register(Double.class, BsonNull.class, (from) -> {
return null;
});
register(Double.class, BsonBoolean.class, (from) -> {
return from.getValue() ? 1d : 0d;
});
register(Double.class, BsonDateTime.class, (from) -> {
return (double) from.getValue();
});
register(Double.class, BsonDouble.class, (from) -> {
return from.doubleValue();
});
register(Double.class, BsonInt32.class, (from) -> {
return (double) from.getValue();
});
register(Double.class, BsonInt64.class, (from) -> {
return (double) from.getValue();
});
register(Double.class, BsonString.class, (from) -> {
return Double.parseDouble(toNumericString(from.getValue(), true));
});
register(Double.class, BsonTimestamp.class, (from) -> {
return (double) from.getTime();
});
register(Double.class, BsonUndefined.class, (from) -> {
return null;
});
register(Double.class, Binary.class, (from) -> {
return new BigInteger(from.getData()).doubleValue();
});
register(Double.class, Decimal128.class, (from) -> {
return from.bigDecimalValue().doubleValue();
});
register(Double.class, Code.class, (from) -> {
return (double) from.getCode().hashCode();
});
register(Double.class, ObjectId.class, (from) -> {
return (double) from.hashCode();
});
register(Double.class, Symbol.class, (from) -> {
return (double) from.getSymbol().hashCode();
});
register(Double.class, BsonRegularExpression.class, (from) -> {
return (double) from.getPattern().hashCode();
});
// --- VALUE TO BIGINTEGER CONVERTERS ---
register(BigInteger.class, BsonNull.class, (from) -> {
return null;
});
register(BigInteger.class, BsonBoolean.class, (from) -> {
return from.getValue() ? BigInteger.ONE : BigInteger.ZERO;
});
register(BigInteger.class, BsonDateTime.class, (from) -> {
return new BigInteger(Long.toString(from.getValue()));
});
register(BigInteger.class, BsonDouble.class, (from) -> {
return new BigInteger(toNumericString(Double.toString(from.getValue()), false));
});
register(BigInteger.class, BsonInt32.class, (from) -> {
return new BigInteger(Integer.toString(from.getValue()));
});
register(BigInteger.class, BsonInt64.class, (from) -> {
return new BigInteger(Long.toString(from.getValue()));
});
register(BigInteger.class, BsonString.class, (from) -> {
return new BigInteger(toNumericString(from.getValue(), false));
});
register(BigInteger.class, BsonTimestamp.class, (from) -> {
return new BigInteger(Integer.toString(from.getTime()));
});
register(BigInteger.class, BsonUndefined.class, (from) -> {
return null;
});
register(BigInteger.class, Binary.class, (from) -> {
return new BigInteger(from.getData());
});
register(BigInteger.class, Decimal128.class, (from) -> {
return from.bigDecimalValue().toBigInteger();
});
register(BigInteger.class, Code.class, (from) -> {
return new BigInteger(Integer.toString(from.getCode().hashCode()));
});
register(BigInteger.class, ObjectId.class, (from) -> {
return new BigInteger(Integer.toString(from.hashCode()));
});
register(BigInteger.class, Symbol.class, (from) -> {
return new BigInteger(Integer.toString(from.getSymbol().hashCode()));
});
register(BigInteger.class, BsonRegularExpression.class, (from) -> {
return new BigInteger(Integer.toString(from.getPattern().hashCode()));
});
// --- VALUE TO BIGDECIMAL CONVERTERS ---
register(BigDecimal.class, BsonNull.class, (from) -> {
return null;
});
register(BigDecimal.class, BsonBoolean.class, (from) -> {
return from.getValue() ? BigDecimal.ONE : BigDecimal.ZERO;
});
register(BigDecimal.class, BsonDateTime.class, (from) -> {
return new BigDecimal(from.getValue());
});
register(BigDecimal.class, BsonDouble.class, (from) -> {
return new BigDecimal(from.getValue());
});
register(BigDecimal.class, BsonInt32.class, (from) -> {
return new BigDecimal(from.getValue());
});
register(BigDecimal.class, BsonInt64.class, (from) -> {
return new BigDecimal(from.getValue());
});
register(BigDecimal.class, BsonString.class, (from) -> {
return new BigDecimal(toNumericString(from.getValue(), true));
});
register(BigDecimal.class, BsonTimestamp.class, (from) -> {
return new BigDecimal(from.getTime());
});
register(BigDecimal.class, BsonUndefined.class, (from) -> {
return null;
});
register(BigDecimal.class, Binary.class, (from) -> {
return new BigDecimal(new BigInteger(from.getData()));
});
register(BigDecimal.class, Decimal128.class, (from) -> {
return from.bigDecimalValue();
});
register(BigDecimal.class, Code.class, (from) -> {
return new BigDecimal(from.getCode().hashCode());
});
register(BigDecimal.class, ObjectId.class, (from) -> {
return new BigDecimal(from.hashCode());
});
register(BigDecimal.class, Symbol.class, (from) -> {
return new BigDecimal(from.getSymbol().hashCode());
});
register(BigDecimal.class, BsonRegularExpression.class, (from) -> {
return new BigDecimal(from.getPattern().hashCode());
});
// --- VALUE TO BOOLEAN CONVERTERS ---
register(Boolean.class, BsonNull.class, (from) -> {
return null;
});
register(Boolean.class, BsonBoolean.class, (from) -> {
return from.getValue();
});
register(Boolean.class, BsonDateTime.class, (from) -> {
return numberStringToBoolean(Long.toString(from.getValue()));
});
register(Boolean.class, BsonDouble.class, (from) -> {
return numberStringToBoolean(Double.toString(from.getValue()));
});
register(Boolean.class, BsonInt32.class, (from) -> {
return numberStringToBoolean(Integer.toString(from.getValue()));
});
register(Boolean.class, BsonInt64.class, (from) -> {
return numberStringToBoolean(Long.toString(from.getValue()));
});
register(Boolean.class, BsonString.class, (from) -> {
String txt = from.getValue().toLowerCase();
if ("true".equals(txt) || "yes".equals(txt) || "on".equals(txt)) {
return true;
}
if ("false".equals(txt) || "no".equals(txt) || "off".equals(txt)) {
return false;
}
txt = toNumericString(String.valueOf(txt), true);
return !(txt.isEmpty() || "0".equals(txt) || txt.indexOf('-') > -1);
});
register(Boolean.class, BsonTimestamp.class, (from) -> {
return numberStringToBoolean(Integer.toString(from.getTime()));
});
register(Boolean.class, BsonUndefined.class, (from) -> {
return null;
});
register(Boolean.class, Binary.class, (from) -> {
for (byte b : from.getData()) {
if (b > 0) {
return true;
}
}
return false;
});
register(Boolean.class, Decimal128.class, (from) -> {
return numberStringToBoolean(from.bigDecimalValue().toString());
});
register(Boolean.class, Code.class, (from) -> {
return from.getCode().hashCode() > 0;
});
register(Boolean.class, ObjectId.class, (from) -> {
return from.hashCode() > 0;
});
register(Boolean.class, Symbol.class, (from) -> {
return from.getSymbol().hashCode() > 0;
});
register(Boolean.class, BsonRegularExpression.class, (from) -> {
return from.getPattern().hashCode() > 0;
});
// --- VALUE TO DATE CONVERTERS ---
register(Date.class, BsonNull.class, (from) -> {
return null;
});
register(Date.class, BsonBoolean.class, (from) -> {
return from.getValue() ? new Date(1) : new Date(0);
});
register(Date.class, BsonDateTime.class, (from) -> {
return new Date(from.getValue());
});
register(Date.class, BsonDouble.class, (from) -> {
return new Date(from.longValue());
});
register(Date.class, BsonInt32.class, (from) -> {
return new Date(from.getValue());
});
register(Date.class, BsonInt64.class, (from) -> {
return new Date(from.getValue());
});
register(Date.class, BsonString.class, (from) -> {
return null;
});
register(Date.class, BsonTimestamp.class, (from) -> {
return new Date(from.getTime() * 1000L);
});
register(Date.class, BsonUndefined.class, (from) -> {
return null;
});
register(Date.class, Binary.class, (from) -> {
return new Date(new BigInteger(from.getData()).longValue());
});
register(Date.class, Decimal128.class, (from) -> {
return new Date(from.bigDecimalValue().longValue());
});
register(Date.class, Code.class, (from) -> {
return new Date(from.getCode().hashCode());
});
register(Date.class, ObjectId.class, (from) -> {
return new Date(from.hashCode());
});
register(Date.class, Symbol.class, (from) -> {
return new Date(from.getSymbol().hashCode());
});
register(Date.class, BsonRegularExpression.class, (from) -> {
return new Date(from.getPattern().hashCode());
});
// --- VALUE TO UUID CONVERTERS ---
register(UUID.class, BsonNull.class, (from) -> {
return null;
});
register(UUID.class, BsonBoolean.class, (from) -> {
return new UUID(from.getValue() ? 1 : 0, 0);
});
register(UUID.class, BsonDateTime.class, (from) -> {
return objectToUUID(from);
});
register(UUID.class, BsonDouble.class, (from) -> {
return objectToUUID(from);
});
register(UUID.class, BsonInt32.class, (from) -> {
return objectToUUID(from);
});
register(UUID.class, BsonInt64.class, (from) -> {
return objectToUUID(from);
});
register(UUID.class, BsonString.class, (from) -> {
return objectToUUID(from);
});
register(UUID.class, BsonTimestamp.class, (from) -> {
return objectToUUID(from);
});
register(UUID.class, BsonUndefined.class, (from) -> {
return null;
});
register(UUID.class, Binary.class, (from) -> {
return byteArrayToUUID(from.getData());
});
register(UUID.class, Decimal128.class, (from) -> {
return objectToUUID(from.bigDecimalValue());
});
register(UUID.class, Code.class, (from) -> {
return objectToUUID(from.getCode().hashCode());
});
register(UUID.class, ObjectId.class, (from) -> {
return objectToUUID(from.hashCode());
});
register(UUID.class, Symbol.class, (from) -> {
return objectToUUID(from.getSymbol().hashCode());
});
register(UUID.class, BsonRegularExpression.class, (from) -> {
return objectToUUID(from.getPattern().hashCode());
});
// --- VALUE TO INETADDRESS CONVERTERS ---
register(InetAddress.class, BsonNull.class, (from) -> {
return null;
});
register(InetAddress.class, BsonBoolean.class, (from) -> {
return toInetAddress(from.getValue() ? 1 : 0);
});
register(InetAddress.class, BsonDateTime.class, (from) -> {
return toInetAddress(from.getValue());
});
register(InetAddress.class, BsonDouble.class, (from) -> {
return toInetAddress(from.getValue());
});
register(InetAddress.class, BsonInt32.class, (from) -> {
return toInetAddress(from.getValue());
});
register(InetAddress.class, BsonInt64.class, (from) -> {
return toInetAddress(from.getValue());
});
register(InetAddress.class, BsonString.class, (from) -> {
return toInetAddress(from.getValue());
});
register(InetAddress.class, BsonTimestamp.class, (from) -> {
return toInetAddress(from.getTime());
});
register(InetAddress.class, BsonUndefined.class, (from) -> {
return null;
});
register(InetAddress.class, Binary.class, (from) -> {
return toInetAddress(from.getData());
});
register(InetAddress.class, Decimal128.class, (from) -> {
return toInetAddress(from.bigDecimalValue());
});
register(InetAddress.class, Code.class, (from) -> {
return toInetAddress(from.getCode().hashCode());
});
register(InetAddress.class, ObjectId.class, (from) -> {
return toInetAddress(from.hashCode());
});
register(InetAddress.class, Symbol.class, (from) -> {
return toInetAddress(from.getSymbol().hashCode());
});
register(InetAddress.class, BsonRegularExpression.class, (from) -> {
return toInetAddress(from.getPattern().hashCode());
});
// --- CLONING ---
// Register immutable classes (for faster Tree cloning)
DeepCloner.addImmutableClass(BsonBoolean.class, BsonDateTime.class, BsonDouble.class, BsonInt32.class,
BsonInt64.class, BsonNull.class, BsonString.class, BsonTimestamp.class, BsonUndefined.class,
Binary.class, Code.class, Decimal128.class, ObjectId.class, Symbol.class);
// --- JSON FORMATTING ---
DataConverterRegistry.addUnquotedClass(BsonBoolean.class, BsonDouble.class, BsonInt32.class, BsonInt64.class,
Decimal128.class);
if (!Config.USE_TIMESTAMPS) {
DataConverterRegistry.addUnquotedClass(BsonTimestamp.class, BsonDateTime.class);
}
}
}
| |
// Copyright 2020 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.analysis;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.packages.Attribute.attr;
import static com.google.devtools.build.lib.packages.BuildType.LABEL_LIST;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.devtools.build.lib.actions.MutableActionGraph.ActionConflictException;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
import com.google.devtools.build.lib.packages.AspectDefinition;
import com.google.devtools.build.lib.packages.AspectParameters;
import com.google.devtools.build.lib.packages.Attribute.AllowedValueSet;
import com.google.devtools.build.lib.packages.NativeAspectClass;
import com.google.devtools.build.lib.packages.RuleClass;
import com.google.devtools.build.lib.packages.Type;
import com.google.devtools.build.lib.rules.java.JavaConfiguration;
import com.google.devtools.build.lib.skyframe.ConfiguredTargetAndData;
import com.google.devtools.build.lib.testutil.TestRuleClassProvider;
import com.google.devtools.build.lib.util.FileTypeSet;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link RequiredConfigFragmentsProvider}. */
@RunWith(JUnit4.class)
public final class RequiredConfigFragmentsTest extends BuildViewTestCase {
@Test
public void provideTransitiveRequiredFragmentsMode() throws Exception {
useConfiguration("--include_config_fragments_provider=transitive");
scratch.file(
"a/BUILD",
"config_setting(name = 'config', values = {'start_end_lib': '1'})",
"py_library(name = 'pylib', srcs = ['pylib.py'])",
"cc_library(name = 'a', srcs = ['A.cc'], data = [':pylib'])");
ImmutableSet<String> ccLibTransitiveFragments =
getConfiguredTarget("//a:a")
.getProvider(RequiredConfigFragmentsProvider.class)
.getRequiredConfigFragments();
assertThat(ccLibTransitiveFragments).containsAtLeast("CppConfiguration", "PythonConfiguration");
ImmutableSet<String> configSettingTransitiveFragments =
getConfiguredTarget("//a:config")
.getProvider(RequiredConfigFragmentsProvider.class)
.getRequiredConfigFragments();
assertThat(configSettingTransitiveFragments).contains("CppOptions");
}
@Test
public void provideDirectRequiredFragmentsMode() throws Exception {
useConfiguration("--include_config_fragments_provider=direct");
scratch.file(
"a/BUILD",
"config_setting(name = 'config', values = {'start_end_lib': '1'})",
"py_library(name = 'pylib', srcs = ['pylib.py'])",
"cc_library(name = 'a', srcs = ['A.cc'], data = [':pylib'])");
ImmutableSet<String> ccLibDirectFragments =
getConfiguredTarget("//a:a")
.getProvider(RequiredConfigFragmentsProvider.class)
.getRequiredConfigFragments();
assertThat(ccLibDirectFragments).contains("CppConfiguration");
assertThat(ccLibDirectFragments).doesNotContain("PythonConfiguration");
ImmutableSet<String> configSettingDirectFragments =
getConfiguredTarget("//a:config")
.getProvider(RequiredConfigFragmentsProvider.class)
.getRequiredConfigFragments();
assertThat(configSettingDirectFragments).contains("CppOptions");
}
@Test
public void provideDirectHostOnlyRequiredFragmentsMode() throws Exception {
useConfiguration("--include_config_fragments_provider=direct_host_only");
scratch.file(
"a/BUILD",
"py_library(name = 'pylib', srcs = ['pylib.py'])",
"cc_library(name = 'cclib', srcs = ['cclb.cc'], data = [':pylib'])");
RequiredConfigFragmentsProvider targetConfigProvider =
getConfiguredTarget("//a:cclib").getProvider(RequiredConfigFragmentsProvider.class);
RequiredConfigFragmentsProvider hostConfigProvider =
getHostConfiguredTarget("//a:cclib").getProvider(RequiredConfigFragmentsProvider.class);
assertThat(targetConfigProvider).isNull();
assertThat(hostConfigProvider).isNotNull();
assertThat(hostConfigProvider.getRequiredConfigFragments()).contains("CppConfiguration");
assertThat(hostConfigProvider.getRequiredConfigFragments())
.doesNotContain("PythonConfiguration");
}
/**
* Helper method that returns a combined set of the common fragments all genrules require plus
* instance-specific requirements passed here.
*/
private ImmutableSortedSet<String> genRuleFragments(String... targetSpecificRequirements)
throws Exception {
scratch.file(
"base_genrule/BUILD",
"genrule(",
" name = 'base_genrule',",
" srcs = [],",
" outs = ['base_genrule.out'],",
" cmd = 'echo hi > $@')");
ImmutableSortedSet.Builder<String> builder = ImmutableSortedSet.naturalOrder();
builder.add(targetSpecificRequirements);
builder.addAll(
getConfiguredTarget("//base_genrule")
.getProvider(RequiredConfigFragmentsProvider.class)
.getRequiredConfigFragments());
return builder.build();
}
@Test
public void requiresMakeVariablesSuppliedByDefine() throws Exception {
useConfiguration("--include_config_fragments_provider=direct", "--define", "myvar=myval");
scratch.file(
"a/BUILD",
"genrule(",
" name = 'myrule',",
" srcs = [],",
" outs = ['myrule.out'],",
" cmd = 'echo $(myvar) $(COMPILATION_MODE) > $@')");
ImmutableSet<String> requiredFragments =
getConfiguredTarget("//a:myrule")
.getProvider(RequiredConfigFragmentsProvider.class)
.getRequiredConfigFragments();
assertThat(requiredFragments)
.containsExactlyElementsIn(genRuleFragments("--define:myvar"))
.inOrder();
}
@Test
public void starlarkExpandMakeVariables() throws Exception {
useConfiguration("--include_config_fragments_provider=direct", "--define", "myvar=myval");
scratch.file(
"a/defs.bzl",
"def _impl(ctx):",
" print(ctx.expand_make_variables('dummy attribute', 'string with $(myvar)!', {}))",
"",
"simple_rule = rule(",
" implementation = _impl,",
" attrs = {}",
")");
scratch.file("a/BUILD", "load('//a:defs.bzl', 'simple_rule')", "simple_rule(name = 'simple')");
ImmutableSet<String> requiredFragments =
getConfiguredTarget("//a:simple")
.getProvider(RequiredConfigFragmentsProvider.class)
.getRequiredConfigFragments();
assertThat(requiredFragments).contains("--define:myvar");
}
/**
* Aspect that requires fragments both in its definition and through an optionally set <code>
* --define custom_define</code>.
*/
private static final class AspectWithConfigFragmentRequirements extends NativeAspectClass
implements ConfiguredAspectFactory {
@Override
public AspectDefinition getDefinition(AspectParameters params) {
return new AspectDefinition.Builder(this)
.requiresConfigurationFragments(JavaConfiguration.class)
.add(attr("custom_define", Type.STRING).allowedValues(new AllowedValueSet("", "myvar")))
.build();
}
@Override
public ConfiguredAspect create(
ConfiguredTargetAndData ctadBase,
RuleContext ruleContext,
AspectParameters params,
String toolsRepository)
throws ActionConflictException, InterruptedException {
ConfiguredAspect.Builder builder = new ConfiguredAspect.Builder(ruleContext);
String customDefine = ruleContext.attributes().get("custom_define", Type.STRING);
if (!customDefine.isEmpty()) {
builder.addRequiredConfigFragments(ImmutableSet.of("--define:" + customDefine));
}
return builder.build();
}
}
private static final AspectWithConfigFragmentRequirements
ASPECT_WITH_CONFIG_FRAGMENT_REQUIREMENTS = new AspectWithConfigFragmentRequirements();
/** Rule that attaches {@link AspectWithConfigFragmentRequirements} to its deps. */
public static final class RuleThatAttachesAspect
implements RuleDefinition, RuleConfiguredTargetFactory {
@Override
public RuleClass build(RuleClass.Builder builder, RuleDefinitionEnvironment env) {
return builder
.add(attr("custom_define", Type.STRING).allowedValues(new AllowedValueSet("", "myvar")))
.add(
attr("deps", LABEL_LIST)
.allowedFileTypes(FileTypeSet.NO_FILE)
.aspect(ASPECT_WITH_CONFIG_FRAGMENT_REQUIREMENTS))
.build();
}
@Override
public Metadata getMetadata() {
return RuleDefinition.Metadata.builder()
.name("rule_that_attaches_aspect")
.ancestors(BaseRuleClasses.BaseRule.class)
.factoryClass(RuleThatAttachesAspect.class)
.build();
}
@Override
public ConfiguredTarget create(RuleContext ruleContext)
throws ActionConflictException, InterruptedException {
return new RuleConfiguredTargetBuilder(ruleContext)
.addProvider(RunfilesProvider.EMPTY)
.build();
}
}
@Override
protected ConfiguredRuleClassProvider createRuleClassProvider() {
ConfiguredRuleClassProvider.Builder builder =
new ConfiguredRuleClassProvider.Builder()
.addRuleDefinition(new RuleThatAttachesAspect())
.addNativeAspectClass(ASPECT_WITH_CONFIG_FRAGMENT_REQUIREMENTS);
TestRuleClassProvider.addStandardRules(builder);
return builder.build();
}
@Test
public void aspectDefinitionRequiresFragments() throws Exception {
scratch.file(
"a/BUILD",
"rule_that_attaches_aspect(",
" name = 'parent',",
" deps = [':dep'])",
"rule_that_attaches_aspect(",
" name = 'dep')");
useConfiguration("--include_config_fragments_provider=transitive");
ImmutableSet<String> requiredFragments =
getConfiguredTarget("//a:parent")
.getProvider(RequiredConfigFragmentsProvider.class)
.getRequiredConfigFragments();
assertThat(requiredFragments).contains("JavaConfiguration");
assertThat(requiredFragments).doesNotContain("--define:myvar");
}
@Test
public void aspectImplementationRequiresFragments() throws Exception {
scratch.file(
"a/BUILD",
"rule_that_attaches_aspect(",
" name = 'parent',",
" deps = [':dep'])",
"rule_that_attaches_aspect(",
" name = 'dep',",
" custom_define = 'myvar')");
useConfiguration("--include_config_fragments_provider=transitive");
ImmutableSet<String> requiredFragments =
getConfiguredTarget("//a:parent")
.getProvider(RequiredConfigFragmentsProvider.class)
.getRequiredConfigFragments();
assertThat(requiredFragments).contains("JavaConfiguration");
assertThat(requiredFragments).contains("--define:myvar");
}
private void writeStarlarkTransitionsAndAllowList() throws Exception {
scratch.file(
"tools/allowlists/function_transition_allowlist/BUILD",
"package_group(",
" name = 'function_transition_allowlist',",
" packages = [",
" '//a/...',",
" ],",
")");
scratch.file(
"transitions/defs.bzl",
"def _java_write_transition_impl(settings, attr):",
" return {'//command_line_option:javacopt': ['foo'] }",
"java_write_transition = transition(",
" implementation = _java_write_transition_impl,",
" inputs = [],",
" outputs = ['//command_line_option:javacopt'],",
")",
"def _cpp_read_transition_impl(settings, attr):",
" return {}",
"cpp_read_transition = transition(",
" implementation = _cpp_read_transition_impl,",
" inputs = ['//command_line_option:copt'],",
" outputs = [],",
")");
scratch.file("transitions/BUILD");
}
@Test
public void starlarkRuleTransitionReadsFragment() throws Exception {
writeStarlarkTransitionsAndAllowList();
scratch.file(
"a/defs.bzl",
"load('//transitions:defs.bzl', 'cpp_read_transition')",
"def _impl(ctx):",
" pass",
"has_cpp_aware_rule_transition = rule(",
" implementation = _impl,",
" cfg = cpp_read_transition,",
" attrs = {",
" '_allowlist_function_transition': attr.label(",
" default = '//tools/allowlists/function_transition_allowlist',",
" ),",
" })");
scratch.file(
"a/BUILD",
"load('//a:defs.bzl', 'has_cpp_aware_rule_transition')",
"has_cpp_aware_rule_transition(name = 'cctarget')");
useConfiguration("--include_config_fragments_provider=direct");
ImmutableSet<String> requiredFragments =
getConfiguredTarget("//a:cctarget")
.getProvider(RequiredConfigFragmentsProvider.class)
.getRequiredConfigFragments();
assertThat(requiredFragments).contains("CppOptions");
assertThat(requiredFragments).doesNotContain("JavaOptions");
}
@Test
public void starlarkRuleTransitionWritesFragment() throws Exception {
writeStarlarkTransitionsAndAllowList();
scratch.file(
"a/defs.bzl",
"load('//transitions:defs.bzl', 'java_write_transition')",
"def _impl(ctx):",
" pass",
"has_java_aware_rule_transition = rule(",
" implementation = _impl,",
" cfg = java_write_transition,",
" attrs = {",
" '_allowlist_function_transition': attr.label(",
" default = '//tools/allowlists/function_transition_allowlist',",
" ),",
" })");
scratch.file(
"a/BUILD",
"load('//a:defs.bzl', 'has_java_aware_rule_transition')",
"has_java_aware_rule_transition(name = 'javatarget')");
useConfiguration("--include_config_fragments_provider=direct");
ImmutableSet<String> requiredFragments =
getConfiguredTarget("//a:javatarget")
.getProvider(RequiredConfigFragmentsProvider.class)
.getRequiredConfigFragments();
assertThat(requiredFragments).contains("JavaOptions");
assertThat(requiredFragments).doesNotContain("CppOptions");
}
@Test
public void starlarkAttrTransition() throws Exception {
writeStarlarkTransitionsAndAllowList();
scratch.file(
"a/defs.bzl",
"load('//transitions:defs.bzl', 'cpp_read_transition', 'java_write_transition')",
"def _impl(ctx):",
" pass",
"has_java_aware_attr_transition = rule(",
" implementation = _impl,",
" attrs = {",
" 'deps': attr.label_list(cfg = java_write_transition),",
" '_allowlist_function_transition': attr.label(",
" default = '//tools/allowlists/function_transition_allowlist',",
" ),",
" })",
"has_cpp_aware_rule_transition = rule(",
" implementation = _impl,",
" cfg = cpp_read_transition,",
" attrs = {",
" '_allowlist_function_transition': attr.label(",
" default = '//tools/allowlists/function_transition_allowlist',",
" ),",
" })");
scratch.file(
"a/BUILD",
"load('//a:defs.bzl', 'has_cpp_aware_rule_transition', 'has_java_aware_attr_transition')",
"has_cpp_aware_rule_transition(name = 'ccchild')",
"has_java_aware_attr_transition(",
" name = 'javaparent',",
" deps = [':ccchild'])");
useConfiguration("--include_config_fragments_provider=direct");
ImmutableSet<String> requiredFragments =
getConfiguredTarget("//a:javaparent")
.getProvider(RequiredConfigFragmentsProvider.class)
.getRequiredConfigFragments();
// We consider the attribute transition over the parent -> child edge a property of the parent.
assertThat(requiredFragments).contains("JavaOptions");
// But not the child's rule transition.
assertThat(requiredFragments).doesNotContain("CppOptions");
}
}
| |
package org.killbill.billing.plugin.ingenico.dao;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Nullable;
import javax.sql.DataSource;
import org.joda.time.DateTime;
import org.jooq.UpdateSetMoreStep;
import org.jooq.impl.DSL;
import org.killbill.billing.catalog.api.Currency;
import org.killbill.billing.payment.api.PluginProperty;
import org.killbill.billing.payment.api.TransactionType;
import org.killbill.billing.plugin.api.PluginProperties;
import org.killbill.billing.plugin.dao.payment.PluginPaymentDao;
import org.killbill.billing.plugin.ingenico.client.model.PaymentModificationResponse;
import org.killbill.billing.plugin.ingenico.client.model.PaymentServiceProviderResult;
import org.killbill.billing.plugin.ingenico.client.model.PurchaseResult;
import org.killbill.billing.plugin.ingenico.dao.gen.tables.IngenicoPaymentMethods;
import org.killbill.billing.plugin.ingenico.dao.gen.tables.IngenicoResponses;
import org.killbill.billing.plugin.ingenico.dao.gen.tables.records.IngenicoPaymentMethodsRecord;
import org.killbill.billing.plugin.ingenico.dao.gen.tables.records.IngenicoResponsesRecord;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import static org.killbill.billing.plugin.ingenico.client.model.PurchaseResult.EXCEPTION_CLASS;
import static org.killbill.billing.plugin.ingenico.client.model.PurchaseResult.EXCEPTION_MESSAGE;
import static org.killbill.billing.plugin.ingenico.client.model.PurchaseResult.INGENICO_CALL_ERROR_STATUS;
import static org.killbill.billing.plugin.ingenico.dao.gen.tables.IngenicoPaymentMethods.INGENICO_PAYMENT_METHODS;
import static org.killbill.billing.plugin.ingenico.dao.gen.tables.IngenicoResponses.INGENICO_RESPONSES;
/**
* Created by otaviosoares on 14/11/16.
*/
public class IngenicoDao extends PluginPaymentDao<IngenicoResponsesRecord, IngenicoResponses, IngenicoPaymentMethodsRecord, IngenicoPaymentMethods> {
private static final ObjectMapper objectMapper = new ObjectMapper();
private static final Joiner JOINER = Joiner.on(",");
public IngenicoDao(final DataSource dataSource) throws SQLException {
super(INGENICO_RESPONSES, INGENICO_PAYMENT_METHODS, dataSource);
}
// Payment methods
public void setPaymentMethodToken(final String kbPaymentMethodId, final String token, final String kbTenantId) throws SQLException {
execute(dataSource.getConnection(),
new WithConnectionCallback<IngenicoResponsesRecord>() {
@Override
public IngenicoResponsesRecord withConnection(final Connection conn) throws SQLException {
DSL.using(conn, dialect, settings)
.update(INGENICO_PAYMENT_METHODS)
.set(INGENICO_PAYMENT_METHODS.TOKEN, token)
.where(INGENICO_PAYMENT_METHODS.KB_PAYMENT_METHOD_ID.equal(kbPaymentMethodId))
.and(INGENICO_PAYMENT_METHODS.KB_TENANT_ID.equal(kbTenantId))
.and(INGENICO_PAYMENT_METHODS.IS_DELETED.equal(FALSE))
.execute();
return null;
}
});
}
public IngenicoResponsesRecord getResponse(final UUID kbPaymentId, final UUID kbTenantId) throws SQLException {
return execute(dataSource.getConnection(),
new WithConnectionCallback<IngenicoResponsesRecord>() {
@Override
public IngenicoResponsesRecord withConnection(final Connection conn) throws SQLException {
return DSL.using(conn, dialect, settings)
.selectFrom(INGENICO_RESPONSES)
.where(DSL.field(INGENICO_RESPONSES.getName() + "." + KB_PAYMENT_ID).equal(kbPaymentId.toString()))
.and(DSL.field(INGENICO_RESPONSES.getName() + "." + KB_TENANT_ID).equal(kbTenantId.toString()))
.orderBy(DSL.field(INGENICO_RESPONSES.getName() + "." + RECORD_ID).desc())
.limit(1)
.fetchOne();
}
});
}
public void addResponse(final UUID kbAccountId,
final UUID kbPaymentId,
final UUID kbPaymentTransactionId,
final TransactionType transactionType,
final BigDecimal amount,
final Currency currency,
final PurchaseResult result,
final DateTime utcNow,
final UUID kbTenantId) throws SQLException {
final String additionalData = getAdditionalData(result);
execute(dataSource.getConnection(),
new WithConnectionCallback<Void>() {
@Override
public Void withConnection(final Connection conn) throws SQLException {
DSL.using(conn, dialect, settings)
.insertInto(INGENICO_RESPONSES,
INGENICO_RESPONSES.KB_ACCOUNT_ID,
INGENICO_RESPONSES.KB_PAYMENT_ID,
INGENICO_RESPONSES.KB_PAYMENT_TRANSACTION_ID,
INGENICO_RESPONSES.TRANSACTION_TYPE,
INGENICO_RESPONSES.AMOUNT,
INGENICO_RESPONSES.CURRENCY,
INGENICO_RESPONSES.INGENICO_PAYMENT_ID,
INGENICO_RESPONSES.INGENICO_STATUS,
INGENICO_RESPONSES.INGENICO_RESULT,
INGENICO_RESPONSES.INGENICO_PAYMENT_REFERENCE,
INGENICO_RESPONSES.INGENICO_AUTHORIZATION_CODE,
INGENICO_RESPONSES.INGENICO_ERROR_CODE,
INGENICO_RESPONSES.INGENICO_ERROR_MESSAGE,
INGENICO_RESPONSES.FRAUD_AVS_RESULT,
INGENICO_RESPONSES.FRAUD_CVV_RESULT,
INGENICO_RESPONSES.FRAUD_SERVICE,
INGENICO_RESPONSES.PAYMENT_INTERNAL_REF,
INGENICO_RESPONSES.ADDITIONAL_DATA,
INGENICO_RESPONSES.CREATED_DATE,
INGENICO_RESPONSES.KB_TENANT_ID)
.values(kbAccountId.toString(),
kbPaymentId.toString(),
kbPaymentTransactionId.toString(),
transactionType.toString(),
amount,
currency.toString(),
result.getPaymentId(),
result.getStatus(),
result.getResult().isPresent() ? result.getResult().get().toString() : null,
result.getPaymentReference(),
result.getAuthorizationCode(),
result.getErrorCode(),
result.getErrorMessage(),
result.getFraudAvsResult(),
result.getFraudCvvResult(),
result.getFraudResult(),
result.getPaymentTransactionExternalKey(),
additionalData,
toTimestamp(utcNow),
kbTenantId.toString())
.execute();
return null;
}
});
}
public void addResponse(final UUID kbAccountId,
final UUID kbPaymentId,
final UUID kbPaymentTransactionId,
final TransactionType transactionType,
@Nullable final BigDecimal amount,
@Nullable final Currency currency,
final PaymentModificationResponse result,
final DateTime utcNow,
final UUID kbTenantId) throws SQLException {
final String additionalData = getAdditionalData(result);
execute(dataSource.getConnection(),
new WithConnectionCallback<Void>() {
@Override
public Void withConnection(final Connection conn) throws SQLException {
DSL.using(conn, dialect, settings)
.insertInto(INGENICO_RESPONSES,
INGENICO_RESPONSES.KB_ACCOUNT_ID,
INGENICO_RESPONSES.KB_PAYMENT_ID,
INGENICO_RESPONSES.KB_PAYMENT_TRANSACTION_ID,
INGENICO_RESPONSES.TRANSACTION_TYPE,
INGENICO_RESPONSES.AMOUNT,
INGENICO_RESPONSES.CURRENCY,
INGENICO_RESPONSES.INGENICO_PAYMENT_ID,
INGENICO_RESPONSES.INGENICO_STATUS,
INGENICO_RESPONSES.INGENICO_RESULT,
INGENICO_RESPONSES.INGENICO_PAYMENT_REFERENCE,
INGENICO_RESPONSES.INGENICO_AUTHORIZATION_CODE,
INGENICO_RESPONSES.INGENICO_ERROR_CODE,
INGENICO_RESPONSES.INGENICO_ERROR_MESSAGE,
INGENICO_RESPONSES.FRAUD_AVS_RESULT,
INGENICO_RESPONSES.FRAUD_CVV_RESULT,
INGENICO_RESPONSES.FRAUD_SERVICE,
INGENICO_RESPONSES.PAYMENT_INTERNAL_REF,
INGENICO_RESPONSES.ADDITIONAL_DATA,
INGENICO_RESPONSES.CREATED_DATE,
INGENICO_RESPONSES.KB_TENANT_ID)
.values(kbAccountId.toString(),
kbPaymentId.toString(),
kbPaymentTransactionId.toString(),
transactionType.toString(),
amount,
currency.toString(),
result.getPaymentId(),
result.getStatus(),
null,
null,
null,
null,
null,
null,
null,
null,
null,
additionalData,
toTimestamp(utcNow),
kbTenantId.toString())
.execute();
return null;
}
});
}
public IngenicoResponsesRecord updateResponse(final UUID kbPaymentTransactionId, final Iterable<PluginProperty> additionalPluginProperties, final UUID kbTenantId) throws SQLException {
return updateResponse(kbPaymentTransactionId, null, null, additionalPluginProperties, kbTenantId);
}
/**
* Update the PSP reference and additional data of the latest response row for a payment transaction
*
* @param kbPaymentTransactionId Kill Bill payment transaction id
* @param status
*@param paymentServiceProviderResult New PSP result (null if unchanged)
* @param additionalPluginProperties Latest properties
* @param kbTenantId Kill Bill tenant id @return the latest version of the response row, null if one couldn't be found
* @throws SQLException For any unexpected SQL error
*/
public IngenicoResponsesRecord updateResponse(final UUID kbPaymentTransactionId, final String status, @Nullable final PaymentServiceProviderResult paymentServiceProviderResult, final Iterable<PluginProperty> additionalPluginProperties, final UUID kbTenantId) throws SQLException {
final Map<String, Object> additionalProperties = PluginProperties.toMap(additionalPluginProperties);
return execute(dataSource.getConnection(),
new WithConnectionCallback<IngenicoResponsesRecord>() {
@Override
public IngenicoResponsesRecord withConnection(final Connection conn) throws SQLException {
final IngenicoResponsesRecord response = DSL.using(conn, dialect, settings)
.selectFrom(INGENICO_RESPONSES)
.where(INGENICO_RESPONSES.KB_PAYMENT_TRANSACTION_ID.equal(kbPaymentTransactionId.toString()))
.and(INGENICO_RESPONSES.KB_TENANT_ID.equal(kbTenantId.toString()))
.orderBy(INGENICO_RESPONSES.RECORD_ID.desc())
.limit(1)
.fetchOne();
if (response == null) {
return null;
}
final Map originalData = new HashMap(fromAdditionalData(response.getAdditionalData()));
originalData.putAll(additionalProperties);
// final String ingenicoPaymentId = response.getIngenicoPaymentId();
// if (ingenicoPaymentId != null) {
// originalData.remove(INGENICO_CALL_ERROR_STATUS);
// originalData.remove(EXCEPTION_CLASS);
// originalData.remove(EXCEPTION_MESSAGE);
// }
final String mergedAdditionalData = asString(originalData);
UpdateSetMoreStep<IngenicoResponsesRecord> step = DSL.using(conn, dialect, settings)
.update(INGENICO_RESPONSES)
.set(INGENICO_RESPONSES.ADDITIONAL_DATA, mergedAdditionalData);
if (status != null) {
step = step.set(INGENICO_RESPONSES.INGENICO_STATUS, status);
}
if (paymentServiceProviderResult != null) {
step = step.set(INGENICO_RESPONSES.INGENICO_RESULT, paymentServiceProviderResult.toString());
}
step.where(INGENICO_RESPONSES.RECORD_ID.equal(response.getRecordId()))
.execute();
return DSL.using(conn, dialect, settings)
.selectFrom(INGENICO_RESPONSES)
.where(INGENICO_RESPONSES.KB_PAYMENT_TRANSACTION_ID.equal(kbPaymentTransactionId.toString()))
.and(INGENICO_RESPONSES.KB_TENANT_ID.equal(kbTenantId.toString()))
.orderBy(INGENICO_RESPONSES.RECORD_ID.desc())
.limit(1)
.fetchOne();
}
});
}
private String getAdditionalData(final PurchaseResult result) throws SQLException {
final Map<String, String> additionalDataMap = new HashMap<String, String>();
if (result.getAdditionalData() != null && !result.getAdditionalData().isEmpty()) {
additionalDataMap.putAll(result.getAdditionalData());
}
if (additionalDataMap.isEmpty()) {
return null;
} else {
return asString(additionalDataMap);
}
}
private String getAdditionalData(final PaymentModificationResponse response) throws SQLException {
return asString(response.getAdditionalData());
}
public static Map fromAdditionalData(@Nullable final String additionalData) {
if (additionalData == null) {
return ImmutableMap.of();
}
try {
return objectMapper.readValue(additionalData, Map.class);
} catch (final IOException e) {
throw new RuntimeException(e);
}
}
}
| |
/*
* Copyright (C) 2008 The Guava 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.
*
* (this file has been modified by Bracket Computing, Inc.)
*/
package com.brkt.thirdparty.guava.base;
import static com.brkt.thirdparty.guava.base.Preconditions.checkArgument;
import static com.brkt.thirdparty.guava.base.Preconditions.checkNotNull;
import com.brkt.thirdparty.guava.annotations.GwtIncompatible;
import com.brkt.thirdparty.guava.annotations.Beta;
import com.brkt.thirdparty.guava.annotations.GwtCompatible;
import java.util.Arrays;
import java.util.BitSet;
import javax.annotation.CheckReturnValue;
/**
* Determines a true or false value for any Java {@code char} value, just as {@link Predicate} does
* for any {@link Object}. Also offers basic text processing methods based on this function.
* Implementations are strongly encouraged to be side-effect-free and immutable.
*
* <p>Throughout the documentation of this class, the phrase "matching character" is used to mean
* "any character {@code c} for which {@code this.matches(c)} returns {@code true}".
*
* <p><b>Note:</b> This class deals only with {@code char} values; it does not understand
* supplementary Unicode code points in the range {@code 0x10000} to {@code 0x10FFFF}. Such logical
* characters are encoded into a {@code String} using surrogate pairs, and a {@code CharMatcher}
* treats these just as two separate characters.
*
* <p>Example usages: <pre>
* String trimmed = {@link #WHITESPACE WHITESPACE}.{@link #trimFrom trimFrom}(userInput);
* if ({@link #ASCII ASCII}.{@link #matchesAllOf matchesAllOf}(s)) { ... }</pre>
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/StringsExplained#CharMatcher">
* {@code CharMatcher}</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@Beta // Possibly change from chars to code points; decide constants vs. methods
@GwtCompatible(emulated = true)
public abstract class CharMatcher implements Predicate<Character> {
// Constants
/**
* Determines whether a character is a breaking whitespace (that is, a whitespace which can be
* interpreted as a break between words for formatting purposes). See {@link #WHITESPACE} for a
* discussion of that term.
*
* @since 2.0
*/
public static final CharMatcher BREAKING_WHITESPACE = new CharMatcher() {
@Override
public boolean matches(char c) {
switch (c) {
case '\t':
case '\n':
case '\013':
case '\f':
case '\r':
case ' ':
case '\u0085':
case '\u1680':
case '\u2028':
case '\u2029':
case '\u205f':
case '\u3000':
return true;
case '\u2007':
return false;
default:
return c >= '\u2000' && c <= '\u200a';
}
}
@Override
public String toString() {
return "CharMatcher.BREAKING_WHITESPACE";
}
};
/**
* Determines whether a character is ASCII, meaning that its code point is less than 128.
*/
public static final CharMatcher ASCII = new NamedFastMatcher("CharMatcher.ASCII") {
@Override
public boolean matches(char c) {
return c <= '\u007f';
}
};
private static class RangesMatcher extends CharMatcher {
private final String description;
private final char[] rangeStarts;
private final char[] rangeEnds;
RangesMatcher(String description, char[] rangeStarts, char[] rangeEnds) {
this.description = description;
this.rangeStarts = rangeStarts;
this.rangeEnds = rangeEnds;
checkArgument(rangeStarts.length == rangeEnds.length);
for (int i = 0; i < rangeStarts.length; i++) {
checkArgument(rangeStarts[i] <= rangeEnds[i]);
if (i + 1 < rangeStarts.length) {
checkArgument(rangeEnds[i] < rangeStarts[i + 1]);
}
}
}
@Override
public boolean matches(char c) {
int index = Arrays.binarySearch(rangeStarts, c);
if (index >= 0) {
return true;
} else {
index = ~index - 1;
return index >= 0 && c <= rangeEnds[index];
}
}
@Override
public String toString() {
return description;
}
}
// Must be in ascending order.
private static final String ZEROES = "0\u0660\u06f0\u07c0\u0966\u09e6\u0a66\u0ae6\u0b66\u0be6"
+ "\u0c66\u0ce6\u0d66\u0e50\u0ed0\u0f20\u1040\u1090\u17e0\u1810\u1946\u19d0\u1b50\u1bb0"
+ "\u1c40\u1c50\ua620\ua8d0\ua900\uaa50\uff10";
/**
* Determines whether a character is a digit according to
* <a href="http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5Cp%7Bdigit%7D">Unicode</a>.
* If you only care to match ASCII digits, you can use {@code inRange('0', '9')}.
*/
public static final CharMatcher DIGIT;
static {
char[] zeroes = ZEROES.toCharArray();
char[] nines = new char[zeroes.length];
for (int i = 0; i < zeroes.length; i++) {
nines[i] = (char) (zeroes[i] + 9);
}
DIGIT = new RangesMatcher("CharMatcher.DIGIT", zeroes, nines);
}
/**
* Determines whether a character is a digit according to {@linkplain Character#isDigit(char)
* Java's definition}. If you only care to match ASCII digits, you can use {@code
* inRange('0', '9')}.
*/
public static final CharMatcher JAVA_DIGIT = new CharMatcher() {
@Override public boolean matches(char c) {
return Character.isDigit(c);
}
@Override public String toString() {
return "CharMatcher.JAVA_DIGIT";
}
};
/**
* Determines whether a character is a letter according to {@linkplain Character#isLetter(char)
* Java's definition}. If you only care to match letters of the Latin alphabet, you can use {@code
* inRange('a', 'z').or(inRange('A', 'Z'))}.
*/
public static final CharMatcher JAVA_LETTER = new CharMatcher() {
@Override public boolean matches(char c) {
return Character.isLetter(c);
}
@Override public String toString() {
return "CharMatcher.JAVA_LETTER";
}
};
/**
* Determines whether a character is a letter or digit according to {@linkplain
* Character#isLetterOrDigit(char) Java's definition}.
*/
public static final CharMatcher JAVA_LETTER_OR_DIGIT = new CharMatcher() {
@Override public boolean matches(char c) {
return Character.isLetterOrDigit(c);
}
@Override public String toString() {
return "CharMatcher.JAVA_LETTER_OR_DIGIT";
}
};
/**
* Determines whether a character is upper case according to {@linkplain
* Character#isUpperCase(char) Java's definition}.
*/
public static final CharMatcher JAVA_UPPER_CASE = new CharMatcher() {
@Override public boolean matches(char c) {
return Character.isUpperCase(c);
}
@Override public String toString() {
return "CharMatcher.JAVA_UPPER_CASE";
}
};
/**
* Determines whether a character is lower case according to {@linkplain
* Character#isLowerCase(char) Java's definition}.
*/
public static final CharMatcher JAVA_LOWER_CASE = new CharMatcher() {
@Override public boolean matches(char c) {
return Character.isLowerCase(c);
}
@Override public String toString() {
return "CharMatcher.JAVA_LOWER_CASE";
}
};
/**
* Determines whether a character is an ISO control character as specified by {@link
* Character#isISOControl(char)}.
*/
public static final CharMatcher JAVA_ISO_CONTROL =
new NamedFastMatcher("CharMatcher.JAVA_ISO_CONTROL") {
@Override public boolean matches(char c) {
return c <= '\u001f' || (c >= '\u007f' && c <= '\u009f');
}
};
/**
* Determines whether a character is invisible; that is, if its Unicode category is any of
* SPACE_SEPARATOR, LINE_SEPARATOR, PARAGRAPH_SEPARATOR, CONTROL, FORMAT, SURROGATE, and
* PRIVATE_USE according to ICU4J.
*/
public static final CharMatcher INVISIBLE = new RangesMatcher("CharMatcher.INVISIBLE", (
"\u0000\u007f\u00ad\u0600\u061c\u06dd\u070f\u1680\u180e\u2000\u2028\u205f\u2066\u2067\u2068"
+ "\u2069\u206a\u3000\ud800\ufeff\ufff9\ufffa").toCharArray(), (
"\u0020\u00a0\u00ad\u0604\u061c\u06dd\u070f\u1680\u180e\u200f\u202f\u2064\u2066\u2067\u2068"
+ "\u2069\u206f\u3000\uf8ff\ufeff\ufff9\ufffb").toCharArray());
private static String showCharacter(char c) {
String hex = "0123456789ABCDEF";
char[] tmp = {'\\', 'u', '\0', '\0', '\0', '\0'};
for (int i = 0; i < 4; i++) {
tmp[5 - i] = hex.charAt(c & 0xF);
c = (char) (c >> 4);
}
return String.copyValueOf(tmp);
}
/**
* Determines whether a character is single-width (not double-width). When in doubt, this matcher
* errs on the side of returning {@code false} (that is, it tends to assume a character is
* double-width).
*
* <p><b>Note:</b> as the reference file evolves, we will modify this constant to keep it up to
* date.
*/
public static final CharMatcher SINGLE_WIDTH = new RangesMatcher("CharMatcher.SINGLE_WIDTH",
"\u0000\u05be\u05d0\u05f3\u0600\u0750\u0e00\u1e00\u2100\ufb50\ufe70\uff61".toCharArray(),
"\u04f9\u05be\u05ea\u05f4\u06ff\u077f\u0e7f\u20af\u213a\ufdff\ufeff\uffdc".toCharArray());
/** Matches any character. */
public static final CharMatcher ANY = new NamedFastMatcher("CharMatcher.ANY") {
@Override public boolean matches(char c) {
return true;
}
@Override public int indexIn(CharSequence sequence, int start) {
int length = sequence.length();
Preconditions.checkPositionIndex(start, length);
return (start == length) ? -1 : start;
}
@Override public int lastIndexIn(CharSequence sequence) {
return sequence.length() - 1;
}
@Override public boolean matchesAllOf(CharSequence sequence) {
checkNotNull(sequence);
return true;
}
@Override public String removeFrom(CharSequence sequence) {
checkNotNull(sequence);
return "";
}
@Override public String replaceFrom(CharSequence sequence, char replacement) {
char[] array = new char[sequence.length()];
Arrays.fill(array, replacement);
return new String(array);
}
@Override public String replaceFrom(CharSequence sequence, CharSequence replacement) {
StringBuilder retval = new StringBuilder(sequence.length() * replacement.length());
for (int i = 0; i < sequence.length(); i++) {
retval.append(replacement);
}
return retval.toString();
}
@Override public String collapseFrom(CharSequence sequence, char replacement) {
return (sequence.length() == 0) ? "" : String.valueOf(replacement);
}
@Override public String trimFrom(CharSequence sequence) {
checkNotNull(sequence);
return "";
}
@Override public int countIn(CharSequence sequence) {
return sequence.length();
}
@Override public CharMatcher and(CharMatcher other) {
return checkNotNull(other);
}
@Override public CharMatcher or(CharMatcher other) {
checkNotNull(other);
return this;
}
@Override public CharMatcher negate() {
return NONE;
}
};
/** Matches no characters. */
public static final CharMatcher NONE = new NamedFastMatcher("CharMatcher.NONE") {
@Override public boolean matches(char c) {
return false;
}
@Override public int indexIn(CharSequence sequence, int start) {
int length = sequence.length();
Preconditions.checkPositionIndex(start, length);
return -1;
}
@Override public int lastIndexIn(CharSequence sequence) {
checkNotNull(sequence);
return -1;
}
@Override public boolean matchesAllOf(CharSequence sequence) {
return sequence.length() == 0;
}
@Override public String removeFrom(CharSequence sequence) {
return sequence.toString();
}
@Override public String collapseFrom(CharSequence sequence, char replacement) {
return sequence.toString();
}
@Override public String trimFrom(CharSequence sequence) {
return sequence.toString();
}
@Override
public String trimLeadingFrom(CharSequence sequence) {
return sequence.toString();
}
@Override
public String trimTrailingFrom(CharSequence sequence) {
return sequence.toString();
}
@Override public int countIn(CharSequence sequence) {
checkNotNull(sequence);
return 0;
}
@Override public CharMatcher and(CharMatcher other) {
checkNotNull(other);
return this;
}
@Override public CharMatcher or(CharMatcher other) {
return checkNotNull(other);
}
@Override public CharMatcher negate() {
return ANY;
}
};
// Static factories
/**
* Returns a {@code char} matcher that matches only one specified character.
*/
public static CharMatcher is(final char match) {
return new FastMatcher() {
@Override public boolean matches(char c) {
return c == match;
}
@Override public String replaceFrom(CharSequence sequence, char replacement) {
return sequence.toString().replace(match, replacement);
}
@Override public CharMatcher and(CharMatcher other) {
return other.matches(match) ? this : NONE;
}
@Override public CharMatcher or(CharMatcher other) {
return other.matches(match) ? other : super.or(other);
}
@Override public CharMatcher negate() {
return isNot(match);
}
@GwtIncompatible("java.util.BitSet")
@Override
void setBits(BitSet table) {
table.set(match);
}
@Override public String toString() {
return "CharMatcher.is('" + showCharacter(match) + "')";
}
};
}
/**
* Returns a {@code char} matcher that matches any character except the one specified.
*
* <p>To negate another {@code CharMatcher}, use {@link #negate()}.
*/
public static CharMatcher isNot(final char match) {
return new FastMatcher() {
@Override public boolean matches(char c) {
return c != match;
}
@Override public CharMatcher and(CharMatcher other) {
return other.matches(match) ? super.and(other) : other;
}
@Override public CharMatcher or(CharMatcher other) {
return other.matches(match) ? ANY : this;
}
@GwtIncompatible("java.util.BitSet")
@Override
void setBits(BitSet table) {
table.set(0, match);
table.set(match + 1, Character.MAX_VALUE + 1);
}
@Override public CharMatcher negate() {
return is(match);
}
@Override public String toString() {
return "CharMatcher.isNot('" + showCharacter(match) + "')";
}
};
}
/**
* Returns a {@code char} matcher that matches any character present in the given character
* sequence.
*/
public static CharMatcher anyOf(final CharSequence sequence) {
switch (sequence.length()) {
case 0:
return NONE;
case 1:
return is(sequence.charAt(0));
case 2:
return isEither(sequence.charAt(0), sequence.charAt(1));
default:
// continue below to handle the general case
}
// TODO(user): is it potentially worth just going ahead and building a precomputed matcher?
final char[] chars = sequence.toString().toCharArray();
Arrays.sort(chars);
return new CharMatcher() {
@Override public boolean matches(char c) {
return Arrays.binarySearch(chars, c) >= 0;
}
@Override
@GwtIncompatible("java.util.BitSet")
void setBits(BitSet table) {
for (char c : chars) {
table.set(c);
}
}
@Override public String toString() {
StringBuilder description = new StringBuilder("CharMatcher.anyOf(\"");
for (char c : chars) {
description.append(showCharacter(c));
}
description.append("\")");
return description.toString();
}
};
}
private static CharMatcher isEither(
final char match1,
final char match2) {
return new FastMatcher() {
@Override public boolean matches(char c) {
return c == match1 || c == match2;
}
@GwtIncompatible("java.util.BitSet")
@Override void setBits(BitSet table) {
table.set(match1);
table.set(match2);
}
@Override public String toString() {
return "CharMatcher.anyOf(\"" + showCharacter(match1) + showCharacter(match2) + "\")";
}
};
}
/**
* Returns a {@code char} matcher that matches any character not present in the given character
* sequence.
*/
public static CharMatcher noneOf(CharSequence sequence) {
return anyOf(sequence).negate();
}
/**
* Returns a {@code char} matcher that matches any character in a given range (both endpoints are
* inclusive). For example, to match any lowercase letter of the English alphabet, use {@code
* CharMatcher.inRange('a', 'z')}.
*
* @throws IllegalArgumentException if {@code endInclusive < startInclusive}
*/
public static CharMatcher inRange(final char startInclusive, final char endInclusive) {
checkArgument(endInclusive >= startInclusive);
return new FastMatcher() {
@Override public boolean matches(char c) {
return startInclusive <= c && c <= endInclusive;
}
@GwtIncompatible("java.util.BitSet")
@Override void setBits(BitSet table) {
table.set(startInclusive, endInclusive + 1);
}
@Override public String toString() {
return "CharMatcher.inRange('" + showCharacter(startInclusive)
+ "', '" + showCharacter(endInclusive) + "')";
}
};
}
/**
* Returns a matcher with identical behavior to the given {@link Character}-based predicate, but
* which operates on primitive {@code char} instances instead.
*/
public static CharMatcher forPredicate(final Predicate<? super Character> predicate) {
checkNotNull(predicate);
if (predicate instanceof CharMatcher) {
return (CharMatcher) predicate;
}
return new CharMatcher() {
@Override public boolean matches(char c) {
return predicate.apply(c);
}
@Override public boolean apply(Character character) {
return predicate.apply(checkNotNull(character));
}
@Override public String toString() {
return "CharMatcher.forPredicate(" + predicate + ")";
}
};
}
// Constructors
/**
* Constructor for use by subclasses. When subclassing, you may want to override
* {@code toString()} to provide a useful description.
*/
protected CharMatcher() {}
// Abstract methods
/** Determines a true or false value for the given character. */
public abstract boolean matches(char c);
// Non-static factories
/**
* Returns a matcher that matches any character not matched by this matcher.
*/
public CharMatcher negate() {
return new NegatedMatcher(this);
}
private static class NegatedMatcher extends CharMatcher {
final CharMatcher original;
NegatedMatcher(CharMatcher original) {
this.original = checkNotNull(original);
}
@Override public boolean matches(char c) {
return !original.matches(c);
}
@Override public boolean matchesAllOf(CharSequence sequence) {
return original.matchesNoneOf(sequence);
}
@Override public boolean matchesNoneOf(CharSequence sequence) {
return original.matchesAllOf(sequence);
}
@Override public int countIn(CharSequence sequence) {
return sequence.length() - original.countIn(sequence);
}
@GwtIncompatible("java.util.BitSet")
@Override
void setBits(BitSet table) {
BitSet tmp = new BitSet();
original.setBits(tmp);
tmp.flip(Character.MIN_VALUE, Character.MAX_VALUE + 1);
table.or(tmp);
}
@Override public CharMatcher negate() {
return original;
}
@Override public String toString() {
return original + ".negate()";
}
}
/**
* Returns a matcher that matches any character matched by both this matcher and {@code other}.
*/
public CharMatcher and(CharMatcher other) {
return new And(this, other);
}
private static class And extends CharMatcher {
final CharMatcher first;
final CharMatcher second;
And(CharMatcher a, CharMatcher b) {
first = checkNotNull(a);
second = checkNotNull(b);
}
@Override
public boolean matches(char c) {
return first.matches(c) && second.matches(c);
}
@GwtIncompatible("java.util.BitSet")
@Override
void setBits(BitSet table) {
BitSet tmp1 = new BitSet();
first.setBits(tmp1);
BitSet tmp2 = new BitSet();
second.setBits(tmp2);
tmp1.and(tmp2);
table.or(tmp1);
}
@Override public String toString() {
return "CharMatcher.and(" + first + ", " + second + ")";
}
}
/**
* Returns a matcher that matches any character matched by either this matcher or {@code other}.
*/
public CharMatcher or(CharMatcher other) {
return new Or(this, other);
}
private static class Or extends CharMatcher {
final CharMatcher first;
final CharMatcher second;
Or(CharMatcher a, CharMatcher b) {
first = checkNotNull(a);
second = checkNotNull(b);
}
@GwtIncompatible("java.util.BitSet")
@Override
void setBits(BitSet table) {
first.setBits(table);
second.setBits(table);
}
@Override
public boolean matches(char c) {
return first.matches(c) || second.matches(c);
}
@Override public String toString() {
return "CharMatcher.or(" + first + ", " + second + ")";
}
}
/**
* Returns a {@code char} matcher functionally equivalent to this one, but which may be faster to
* query than the original; your mileage may vary. Precomputation takes time and is likely to be
* worthwhile only if the precomputed matcher is queried many thousands of times.
*
* <p>This method has no effect (returns {@code this}) when called in GWT: it's unclear whether a
* precomputed matcher is faster, but it certainly consumes more memory, which doesn't seem like a
* worthwhile tradeoff in a browser.
*/
public CharMatcher precomputed() {
return Platform.precomputeCharMatcher(this);
}
private static final int DISTINCT_CHARS = Character.MAX_VALUE - Character.MIN_VALUE + 1;
/**
* This is the actual implementation of {@link #precomputed}, but we bounce calls through a
* method on {@link Platform} so that we can have different behavior in GWT.
*
* <p>This implementation tries to be smart in a number of ways. It recognizes cases where
* the negation is cheaper to precompute than the matcher itself; it tries to build small
* hash tables for matchers that only match a few characters, and so on. In the worst-case
* scenario, it constructs an eight-kilobyte bit array and queries that.
* In many situations this produces a matcher which is faster to query than the original.
*/
@GwtIncompatible("java.util.BitSet")
CharMatcher precomputedInternal() {
final BitSet table = new BitSet();
setBits(table);
int totalCharacters = table.cardinality();
if (totalCharacters * 2 <= DISTINCT_CHARS) {
return precomputedPositive(totalCharacters, table, toString());
} else {
// TODO(user): is it worth it to worry about the last character of large matchers?
table.flip(Character.MIN_VALUE, Character.MAX_VALUE + 1);
int negatedCharacters = DISTINCT_CHARS - totalCharacters;
String suffix = ".negate()";
final String description = toString();
String negatedDescription = description.endsWith(suffix)
? description.substring(0, description.length() - suffix.length())
: description + suffix;
return new NegatedFastMatcher(
precomputedPositive(negatedCharacters, table, negatedDescription)) {
@Override
public String toString() {
return description;
}
};
}
}
/**
* A matcher for which precomputation will not yield any significant benefit.
*/
abstract static class FastMatcher extends CharMatcher {
@Override
public final CharMatcher precomputed() {
return this;
}
@Override
public CharMatcher negate() {
return new NegatedFastMatcher(this);
}
}
abstract static class NamedFastMatcher extends FastMatcher {
private final String description;
NamedFastMatcher(String description) {
this.description = checkNotNull(description);
}
@Override public final String toString() {
return description;
}
}
static class NegatedFastMatcher extends NegatedMatcher {
NegatedFastMatcher(CharMatcher original) {
super(original);
}
@Override
public final CharMatcher precomputed() {
return this;
}
}
/**
* Helper method for {@link #precomputedInternal} that doesn't test if the negation is cheaper.
*/
@GwtIncompatible("java.util.BitSet")
private static CharMatcher precomputedPositive(
int totalCharacters,
BitSet table,
String description) {
switch (totalCharacters) {
case 0:
return NONE;
case 1:
return is((char) table.nextSetBit(0));
case 2:
char c1 = (char) table.nextSetBit(0);
char c2 = (char) table.nextSetBit(c1 + 1);
return isEither(c1, c2);
default:
return isSmall(totalCharacters, table.length())
? SmallCharMatcher.from(table, description)
: new BitSetMatcher(table, description);
}
}
@GwtIncompatible("SmallCharMatcher")
private static boolean isSmall(int totalCharacters, int tableLength) {
return totalCharacters <= SmallCharMatcher.MAX_SIZE
&& tableLength > (totalCharacters * 4 * Character.SIZE);
// err on the side of BitSetMatcher
}
@GwtIncompatible("java.util.BitSet")
private static class BitSetMatcher extends NamedFastMatcher {
private final BitSet table;
private BitSetMatcher(BitSet table, String description) {
super(description);
if (table.length() + Long.SIZE < table.size()) {
table = (BitSet) table.clone();
// If only we could actually call BitSet.trimToSize() ourselves...
}
this.table = table;
}
@Override public boolean matches(char c) {
return table.get(c);
}
@Override
void setBits(BitSet bitSet) {
bitSet.or(table);
}
}
/**
* Sets bits in {@code table} matched by this matcher.
*/
@GwtIncompatible("java.util.BitSet")
void setBits(BitSet table) {
for (int c = Character.MAX_VALUE; c >= Character.MIN_VALUE; c--) {
if (matches((char) c)) {
table.set(c);
}
}
}
// Text processing routines
/**
* Returns {@code true} if a character sequence contains at least one matching character.
* Equivalent to {@code !matchesNoneOf(sequence)}.
*
* <p>The default implementation iterates over the sequence, invoking {@link #matches} for each
* character, until this returns {@code true} or the end is reached.
*
* @param sequence the character sequence to examine, possibly empty
* @return {@code true} if this matcher matches at least one character in the sequence
* @since 8.0
*/
public boolean matchesAnyOf(CharSequence sequence) {
return !matchesNoneOf(sequence);
}
/**
* Returns {@code true} if a character sequence contains only matching characters.
*
* <p>The default implementation iterates over the sequence, invoking {@link #matches} for each
* character, until this returns {@code false} or the end is reached.
*
* @param sequence the character sequence to examine, possibly empty
* @return {@code true} if this matcher matches every character in the sequence, including when
* the sequence is empty
*/
public boolean matchesAllOf(CharSequence sequence) {
for (int i = sequence.length() - 1; i >= 0; i--) {
if (!matches(sequence.charAt(i))) {
return false;
}
}
return true;
}
/**
* Returns {@code true} if a character sequence contains no matching characters. Equivalent to
* {@code !matchesAnyOf(sequence)}.
*
* <p>The default implementation iterates over the sequence, invoking {@link #matches} for each
* character, until this returns {@code false} or the end is reached.
*
* @param sequence the character sequence to examine, possibly empty
* @return {@code true} if this matcher matches every character in the sequence, including when
* the sequence is empty
*/
public boolean matchesNoneOf(CharSequence sequence) {
return indexIn(sequence) == -1;
}
/**
* Returns the index of the first matching character in a character sequence, or {@code -1} if no
* matching character is present.
*
* <p>The default implementation iterates over the sequence in forward order calling {@link
* #matches} for each character.
*
* @param sequence the character sequence to examine from the beginning
* @return an index, or {@code -1} if no character matches
*/
public int indexIn(CharSequence sequence) {
return indexIn(sequence, 0);
}
/**
* Returns the index of the first matching character in a character sequence, starting from a
* given position, or {@code -1} if no character matches after that position.
*
* <p>The default implementation iterates over the sequence in forward order, beginning at {@code
* start}, calling {@link #matches} for each character.
*
* @param sequence the character sequence to examine
* @param start the first index to examine; must be nonnegative and no greater than {@code
* sequence.length()}
* @return the index of the first matching character, guaranteed to be no less than {@code start},
* or {@code -1} if no character matches
* @throws IndexOutOfBoundsException if start is negative or greater than {@code
* sequence.length()}
*/
public int indexIn(CharSequence sequence, int start) {
int length = sequence.length();
Preconditions.checkPositionIndex(start, length);
for (int i = start; i < length; i++) {
if (matches(sequence.charAt(i))) {
return i;
}
}
return -1;
}
/**
* Returns the index of the last matching character in a character sequence, or {@code -1} if no
* matching character is present.
*
* <p>The default implementation iterates over the sequence in reverse order calling {@link
* #matches} for each character.
*
* @param sequence the character sequence to examine from the end
* @return an index, or {@code -1} if no character matches
*/
public int lastIndexIn(CharSequence sequence) {
for (int i = sequence.length() - 1; i >= 0; i--) {
if (matches(sequence.charAt(i))) {
return i;
}
}
return -1;
}
/**
* Returns the number of matching characters found in a character sequence.
*/
public int countIn(CharSequence sequence) {
int count = 0;
for (int i = 0; i < sequence.length(); i++) {
if (matches(sequence.charAt(i))) {
count++;
}
}
return count;
}
/**
* Returns a string containing all non-matching characters of a character sequence, in order. For
* example: <pre> {@code
*
* CharMatcher.is('a').removeFrom("bazaar")}</pre>
*
* ... returns {@code "bzr"}.
*/
@CheckReturnValue
public String removeFrom(CharSequence sequence) {
String string = sequence.toString();
int pos = indexIn(string);
if (pos == -1) {
return string;
}
char[] chars = string.toCharArray();
int spread = 1;
// This unusual loop comes from extensive benchmarking
OUT: while (true) {
pos++;
while (true) {
if (pos == chars.length) {
break OUT;
}
if (matches(chars[pos])) {
break;
}
chars[pos - spread] = chars[pos];
pos++;
}
spread++;
}
return new String(chars, 0, pos - spread);
}
/**
* Returns a string containing all matching characters of a character sequence, in order. For
* example: <pre> {@code
*
* CharMatcher.is('a').retainFrom("bazaar")}</pre>
*
* ... returns {@code "aaa"}.
*/
@CheckReturnValue
public String retainFrom(CharSequence sequence) {
return negate().removeFrom(sequence);
}
/**
* Returns a string copy of the input character sequence, with each character that matches this
* matcher replaced by a given replacement character. For example: <pre> {@code
*
* CharMatcher.is('a').replaceFrom("radar", 'o')}</pre>
*
* ... returns {@code "rodor"}.
*
* <p>The default implementation uses {@link #indexIn(CharSequence)} to find the first matching
* character, then iterates the remainder of the sequence calling {@link #matches(char)} for each
* character.
*
* @param sequence the character sequence to replace matching characters in
* @param replacement the character to append to the result string in place of each matching
* character in {@code sequence}
* @return the new string
*/
@CheckReturnValue
public String replaceFrom(CharSequence sequence, char replacement) {
String string = sequence.toString();
int pos = indexIn(string);
if (pos == -1) {
return string;
}
char[] chars = string.toCharArray();
chars[pos] = replacement;
for (int i = pos + 1; i < chars.length; i++) {
if (matches(chars[i])) {
chars[i] = replacement;
}
}
return new String(chars);
}
/**
* Returns a string copy of the input character sequence, with each character that matches this
* matcher replaced by a given replacement sequence. For example: <pre> {@code
*
* CharMatcher.is('a').replaceFrom("yaha", "oo")}</pre>
*
* ... returns {@code "yoohoo"}.
*
* <p><b>Note:</b> If the replacement is a fixed string with only one character, you are better
* off calling {@link #replaceFrom(CharSequence, char)} directly.
*
* @param sequence the character sequence to replace matching characters in
* @param replacement the characters to append to the result string in place of each matching
* character in {@code sequence}
* @return the new string
*/
@CheckReturnValue
public String replaceFrom(CharSequence sequence, CharSequence replacement) {
int replacementLen = replacement.length();
if (replacementLen == 0) {
return removeFrom(sequence);
}
if (replacementLen == 1) {
return replaceFrom(sequence, replacement.charAt(0));
}
String string = sequence.toString();
int pos = indexIn(string);
if (pos == -1) {
return string;
}
int len = string.length();
StringBuilder buf = new StringBuilder((len * 3 / 2) + 16);
int oldpos = 0;
do {
buf.append(string, oldpos, pos);
buf.append(replacement);
oldpos = pos + 1;
pos = indexIn(string, oldpos);
} while (pos != -1);
buf.append(string, oldpos, len);
return buf.toString();
}
/**
* Returns a substring of the input character sequence that omits all characters this matcher
* matches from the beginning and from the end of the string. For example: <pre> {@code
*
* CharMatcher.anyOf("ab").trimFrom("abacatbab")}</pre>
*
* ... returns {@code "cat"}.
*
* <p>Note that: <pre> {@code
*
* CharMatcher.inRange('\0', ' ').trimFrom(str)}</pre>
*
* ... is equivalent to {@link String#trim()}.
*/
@CheckReturnValue
public String trimFrom(CharSequence sequence) {
int len = sequence.length();
int first;
int last;
for (first = 0; first < len; first++) {
if (!matches(sequence.charAt(first))) {
break;
}
}
for (last = len - 1; last > first; last--) {
if (!matches(sequence.charAt(last))) {
break;
}
}
return sequence.subSequence(first, last + 1).toString();
}
/**
* Returns a substring of the input character sequence that omits all characters this matcher
* matches from the beginning of the string. For example: <pre> {@code
*
* CharMatcher.anyOf("ab").trimLeadingFrom("abacatbab")}</pre>
*
* ... returns {@code "catbab"}.
*/
@CheckReturnValue
public String trimLeadingFrom(CharSequence sequence) {
int len = sequence.length();
for (int first = 0; first < len; first++) {
if (!matches(sequence.charAt(first))) {
return sequence.subSequence(first, len).toString();
}
}
return "";
}
/**
* Returns a substring of the input character sequence that omits all characters this matcher
* matches from the end of the string. For example: <pre> {@code
*
* CharMatcher.anyOf("ab").trimTrailingFrom("abacatbab")}</pre>
*
* ... returns {@code "abacat"}.
*/
@CheckReturnValue
public String trimTrailingFrom(CharSequence sequence) {
int len = sequence.length();
for (int last = len - 1; last >= 0; last--) {
if (!matches(sequence.charAt(last))) {
return sequence.subSequence(0, last + 1).toString();
}
}
return "";
}
/**
* Returns a string copy of the input character sequence, with each group of consecutive
* characters that match this matcher replaced by a single replacement character. For example:
* <pre> {@code
*
* CharMatcher.anyOf("eko").collapseFrom("bookkeeper", '-')}</pre>
*
* ... returns {@code "b-p-r"}.
*
* <p>The default implementation uses {@link #indexIn(CharSequence)} to find the first matching
* character, then iterates the remainder of the sequence calling {@link #matches(char)} for each
* character.
*
* @param sequence the character sequence to replace matching groups of characters in
* @param replacement the character to append to the result string in place of each group of
* matching characters in {@code sequence}
* @return the new string
*/
@CheckReturnValue
public String collapseFrom(CharSequence sequence, char replacement) {
// This implementation avoids unnecessary allocation.
int len = sequence.length();
for (int i = 0; i < len; i++) {
char c = sequence.charAt(i);
if (matches(c)) {
if (c == replacement
&& (i == len - 1 || !matches(sequence.charAt(i + 1)))) {
// a no-op replacement
i++;
} else {
StringBuilder builder = new StringBuilder(len)
.append(sequence.subSequence(0, i))
.append(replacement);
return finishCollapseFrom(sequence, i + 1, len, replacement, builder, true);
}
}
}
// no replacement needed
return sequence.toString();
}
/**
* Collapses groups of matching characters exactly as {@link #collapseFrom} does, except that
* groups of matching characters at the start or end of the sequence are removed without
* replacement.
*/
@CheckReturnValue
public String trimAndCollapseFrom(CharSequence sequence, char replacement) {
// This implementation avoids unnecessary allocation.
int len = sequence.length();
int first;
int last;
for (first = 0; first < len && matches(sequence.charAt(first)); first++) {}
for (last = len - 1; last > first && matches(sequence.charAt(last)); last--) {}
return (first == 0 && last == len - 1)
? collapseFrom(sequence, replacement)
: finishCollapseFrom(
sequence, first, last + 1, replacement,
new StringBuilder(last + 1 - first),
false);
}
private String finishCollapseFrom(
CharSequence sequence, int start, int end, char replacement,
StringBuilder builder, boolean inMatchingGroup) {
for (int i = start; i < end; i++) {
char c = sequence.charAt(i);
if (matches(c)) {
if (!inMatchingGroup) {
builder.append(replacement);
inMatchingGroup = true;
}
} else {
builder.append(c);
inMatchingGroup = false;
}
}
return builder.toString();
}
/**
* @deprecated Provided only to satisfy the {@link Predicate} interface; use {@link #matches}
* instead.
*/
@Deprecated
@Override
public boolean apply(Character character) {
return matches(character);
}
/**
* Returns a string representation of this {@code CharMatcher}, such as
* {@code CharMatcher.or(WHITESPACE, JAVA_DIGIT)}.
*/
@Override
public String toString() {
return super.toString();
}
static final String WHITESPACE_TABLE = ""
+ "\u2002\u3000\r\u0085\u200A\u2005\u2000\u3000"
+ "\u2029\u000B\u3000\u2008\u2003\u205F\u3000\u1680"
+ "\u0009\u0020\u2006\u2001\u202F\u00A0\u000C\u2009"
+ "\u3000\u2004\u3000\u3000\u2028\n\u2007\u3000";
static final int WHITESPACE_MULTIPLIER = 1682554634;
static final int WHITESPACE_SHIFT = Integer.numberOfLeadingZeros(WHITESPACE_TABLE.length() - 1);
/**
* Determines whether a character is whitespace according to the latest Unicode standard, as
* illustrated
* <a href="http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5Cp%7Bwhitespace%7D">here</a>.
* This is not the same definition used by other Java APIs. (See a
* <a href="http://spreadsheets.google.com/pub?key=pd8dAQyHbdewRsnE5x5GzKQ">comparison of several
* definitions of "whitespace"</a>.)
*
* <p><b>Note:</b> as the Unicode definition evolves, we will modify this constant to keep it up
* to date.
*/
public static final CharMatcher WHITESPACE = new NamedFastMatcher("WHITESPACE") {
@Override
public boolean matches(char c) {
return WHITESPACE_TABLE.charAt((WHITESPACE_MULTIPLIER * c) >>> WHITESPACE_SHIFT) == c;
}
@GwtIncompatible("java.util.BitSet")
@Override
void setBits(BitSet table) {
for (int i = 0; i < WHITESPACE_TABLE.length(); i++) {
table.set(WHITESPACE_TABLE.charAt(i));
}
}
};
}
| |
/*
Copyright 2010-2021 BusinessCode GmbH, Germany
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 de.businesscode.bcdui.web.wrs;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.InvocationTargetException;
import java.net.SocketException;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import de.businesscode.util.xml.SecureXmlFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import de.businesscode.bcdui.subjectsettings.SecurityHelper;
import de.businesscode.bcdui.toolbox.Configuration;
import de.businesscode.bcdui.toolbox.ServletUtils;
import de.businesscode.bcdui.wrs.IRequestOptions;
import de.businesscode.bcdui.wrs.load.DataLoader;
import de.businesscode.bcdui.wrs.load.IDataWriter;
import de.businesscode.bcdui.wrs.load.ISqlGenerator;
import de.businesscode.bcdui.wrs.load.Wrq2Sql;
import de.businesscode.bcdui.wrs.load.WrsDataWriter;
import de.businesscode.bcdui.wrs.save.DataSaver;
/**
* Servlet for calling Wrs services
* GET: It turns a WrsRequest into SQL and returns a Wrs document with wrs:R rows
* POST: It turns a Wrs into updates of the database based on wrs:M wrs:D rows
*/
public class WrsServlet extends HttpServlet {
private static final long serialVersionUID = 4633486737694422868L;
private final Logger log = LogManager.getLogger(getClass());
private final Logger virtLoggerAccess = LogManager.getLogger("de.businesscode.bcdui.logging.virtlogger.access");
private final Map< String, Class<? extends ISqlGenerator> > services = new HashMap< String, Class<? extends ISqlGenerator> >();
protected int maxRowsDefault = 4000;
/**
* stores last modified stamps on resources
*/
private final static Map<String,Long> lastModifiedResourceMap = Collections.synchronizedMap(new HashMap<String, Long>());
/**
*
* @return the IMMUTABLE map containing lastModified resources with their timestamps
*/
public static Map<String, Long> getLastModifiedResourceMap() {
return Collections.unmodifiableMap(lastModifiedResourceMap);
}
/**
* convenience method to check if given resource has been modified
*
* @param resourceUri Resource to be checked
* @param lastReadDate if this parameter is NULL the method returns TRUE as is assumes the resource has never been read
* @return true if the given resource has been modified
*/
public static boolean wasResourceModified(String resourceUri, Date lastReadDate) {
return wasResourceModified(resourceUri, (Long)(lastReadDate != null ? lastReadDate.getTime() : null));
}
/**
* convenience method
* @param resourceUri Resource to be checked
* @param lastReadStamp if this parameter is NULL the method returns TRUE as is assumes the resource has never been read
* @return true if the given resource has been modified
*/
public static boolean wasResourceModified(String resourceUri, Long lastReadStamp) {
Long lm = lastModifiedResourceMap.get(resourceUri);
return lm != null && (lastReadStamp == null || lm>lastReadStamp);
}
/**
* WrsServlet
*/
public WrsServlet() {
}
/**
* @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
*/
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
//-------------------------------------------------------
// Read application-wide max rows setting default
if (config.getInitParameter("MaxRows") != null) {
try { maxRowsDefault = Integer.parseInt(config.getInitParameter("MaxRows")); } catch(Exception e) {}
}
//-------------------------------------------------------
// Register services
// - default (empty name) comes from Configuration.getClassoption(Configuration.OPT_CLASSES.WRQ2SQL)
// - further classes can be defined in web.xml with init param UserServices
// Standard Wrs Servlet: empty serviceName in request
services.put("", Wrq2Sql.class);
// Beside the standard Wrs servlet, we allow ISQLGenerators to be called by serviceName
// initParameter "UserServices" has the form: "svcName1:svcClass1 svcName2:svcClass2"
final String servicesString = config.getInitParameter("UserServices");
if( servicesString != null )
{
String[] serviceDefs = servicesString.split("(\\s+|\\s*:\\s*)");
for( int s=0; s<serviceDefs.length; s+=2 ) {
try {
services.put(serviceDefs[s], Class.forName(serviceDefs[s+1]).asSubclass(ISqlGenerator.class) );
} catch (Exception e) {
log.error("BCD-UI: Wrong definition of Wrs Service '"+serviceDefs[s]+"' for "+this.getClass().getName());
}
}
}
}
/**
* @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doGet(HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
// Max rows is default or overwritten on user level with SubjectSetting bcdWrs:maxRows
int maxRows = maxRowsDefault;
try {
if (SecurityUtils.getSubject() != null && SecurityUtils.getSubject().isAuthenticated()) {
Set<String> perms = SecurityHelper.getPermissions(SecurityUtils.getSubject(), "bcdWrs:maxRows");
try { if (perms.iterator().hasNext()) maxRows = Integer.parseInt(perms.iterator().next()); } catch (Exception e) {}
}
}
catch (UnavailableSecurityManagerException e) {}
if (log.isTraceEnabled()) {
log.trace(String.format("processing url: %s", ServletUtils.getInstance().reconstructURL(request)));
}
//
response.setContentType("text/xml");
response.setCharacterEncoding("UTF-8");
// Read data and stream to client
IDataWriter dataWriter = null;
try {
IRequestOptions options = new HttpRequestOptions(getServletContext(), request, maxRows);
IRequestOptions loaderOptions = new HttpRequestOptions(getServletContext(), request, maxRows + 1); // +1 because we want to define the exceed-attribute in the dataWriter
// We dynamically derive the ISqlGenerator from the serviceName attribute, empty means default
final String serviceName = options.getRequestDoc() == null || options.getRequestDoc().getDocumentElement() == null ? "" : options.getRequestDoc().getDocumentElement().getAttribute("serviceName");
ISqlGenerator generator = Configuration.getClassInstance(services.get(serviceName), new Class[]{IRequestOptions.class}, options);
dataWriter = createDataWriter(request, response, options);
DataLoader loader = new DataLoader(loaderOptions, generator, dataWriter);
loader.run();
//
// log wrs-access
WrsAccessLogEvent logEvent = new WrsAccessLogEvent(WrsAccessLogEvent.ACCESS_TYPE_WRS, request, options, generator, loader, dataWriter);
virtLoggerAccess.info(logEvent);
} catch (SocketException e) {
// no need to log Exception 'Connection reset by peer: socket write error'
if (e.getMessage().indexOf("Connection reset by peer") < 0)
throw new ServletException("SocketException while processing the WRS-request.", e); // Trigger rollback
} catch (InvocationTargetException e) {
throw new ServletException("InvocationTargetException while processing the WRS-request.", e.getCause()); // Trigger rollback
} catch (Exception e) {
throw new ServletException("Exception while processing the WRS-request.", e); // Trigger rollback
} finally {
try {
if (dataWriter != null)
dataWriter.close();
} catch (Exception ignore) { }
}
if (log.isTraceEnabled()) {
log.trace("processed.");
}
}
/**
* create data writer
*
* @param request
* @param response
* @param options
* @return
*/
protected IDataWriter createDataWriter(HttpServletRequest request, final HttpServletResponse response, IRequestOptions options) {
return new WrsDataWriter() {
@Override
protected Writer getLazyStream() throws Exception {
return response.getWriter(); // called lazy by start writing
}
};
}
/**
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Max rows is default or overwritten on user level with SubjectSetting bcdWrs:maxRows
int maxRows = maxRowsDefault;
try {
if (SecurityUtils.getSubject() != null && SecurityUtils.getSubject().isAuthenticated()) {
Set<String> perms = SecurityHelper.getPermissions(SecurityUtils.getSubject(), "bcdWrs:maxRows");
try { if (perms.iterator().hasNext()) maxRows = Integer.parseInt(perms.iterator().next()); } catch (Exception e) {}
}
}
catch (UnavailableSecurityManagerException e) {}
if (log.isTraceEnabled()) {
log.trace(String.format("WRS post url: %s", ServletUtils.getInstance().reconstructURL(request)));
}
// Write data into database streamed from client
IRequestOptions options = new HttpRequestOptions(getServletContext(), request,maxRows);
XMLEventReader reader;
try {
log.trace("try to write data in Database");
XMLInputFactory inputFactory = SecureXmlFactory.newXMLInputFactory();
inputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
reader = inputFactory.createXMLEventReader(request.getInputStream());
DataSaver dataSaver = new DataSaver();
dataSaver.init(options, reader, log);
dataSaver.run();
log.trace("after saving");
if(request.getPathInfo()!= null){
tagUpdate(request.getPathInfo());
}
}
catch (Exception e) {
throw new ServletException(e); // Re-throw to trigger rollback and logging
}
}
/**
* tags a resource (which is set by pathInfo) with current millis,
* which is considered as a lastModified tag on that resource
*
* @param resourceUri
*/
protected void tagUpdate(String resourceUri) {
if(log.isDebugEnabled())
log.debug("set update stamp for resourceUri: " + resourceUri);
lastModifiedResourceMap.put(resourceUri, System.currentTimeMillis());
}
}
| |
/*
* 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.uima.util.impl;
import java.util.List;
import org.apache.uima.util.ProcessTrace;
import org.apache.uima.util.ProcessTraceEvent;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
public class ProcessTrace_implTest {
/*
* @see TestCase#setUp()
*/
@Test
public void testStartAndEndEvent() {
ProcessTrace pt = new ProcessTrace_impl();
// should be nothing on event list
Assert.assertTrue(pt.getEvents().isEmpty());
// start two events
pt.startEvent("c1", "t1", "testing");
pt.startEvent("c1", "t2", "testing");
// should be nothing on event list until both are closed
Assert.assertTrue(pt.getEvents().isEmpty());
pt.endEvent("c1", "t2", "success");
Assert.assertTrue(pt.getEvents().isEmpty());
pt.endEvent("c1", "t1", "success");
Assert.assertEquals(1, pt.getEvents().size());
// start two more events
pt.startEvent("c2", "t1", "testing");
pt.startEvent("c2", "t2", "testing");
// close one and start another
pt.endEvent("c2", "t2", "testing");
Assert.assertEquals(1, pt.getEvents().size());
pt.startEvent("c2", "t3", "testing");
pt.endEvent("c2", "t3", "testing");
Assert.assertEquals(1, pt.getEvents().size());
// start another event and then end the original event
pt.startEvent("c2", "t4", "testing");
pt.endEvent("c2", "t1", "success");
Assert.assertEquals(2, pt.getEvents().size());
// verify contents of the ProcessTrace
List<ProcessTraceEvent> evts = pt.getEvents();
ProcessTraceEvent evt0 = evts.get(0);
Assert.assertEquals("c1", evt0.getComponentName());
Assert.assertEquals("t1", evt0.getType());
Assert.assertEquals("testing", evt0.getDescription());
Assert.assertEquals("success", evt0.getResultMessage());
List<ProcessTraceEvent> subEvts = evt0.getSubEvents();
ProcessTraceEvent subEvt0 = subEvts.get(0);
Assert.assertEquals("c1", subEvt0.getComponentName());
Assert.assertEquals("t2", subEvt0.getType());
Assert.assertEquals("testing", subEvt0.getDescription());
Assert.assertEquals("success", subEvt0.getResultMessage());
Assert.assertTrue(subEvt0.getSubEvents().isEmpty());
ProcessTraceEvent evt1 = evts.get(1);
Assert.assertEquals("c2", evt1.getComponentName());
Assert.assertEquals("t1", evt1.getType());
Assert.assertEquals("testing", evt1.getDescription());
Assert.assertEquals("success", evt1.getResultMessage());
Assert.assertEquals(3, evt1.getSubEvents().size());
}
@Test
public void testAddEvent() {
ProcessTrace_impl pt = new ProcessTrace_impl();
// should be nothing on event list
Assert.assertTrue(pt.getEvents().isEmpty());
// add event
pt.addEvent("c1", "t1", "testing", 0, "success");
// should be one thing on list
Assert.assertEquals(1, pt.getEvents().size());
// start an event
pt.startEvent("c2", "t1", "testing");
// add event
pt.addEvent("c2", "t2", "testing", 0, "success");
// should still be one thing on list
Assert.assertEquals(1, pt.getEvents().size());
// end event that we started
pt.endEvent("c2", "t1", "success");
// should be 2 events on list
Assert.assertEquals(2, pt.getEvents().size());
// 2nd event should have a sub-event
ProcessTraceEvent evt = pt.getEvents().get(1);
Assert.assertEquals(1, evt.getSubEvents().size());
}
/*
* Test for List getEventsByComponentName(String, boolean)
*/
@Test
public void testGetEventsByComponentName() {
ProcessTrace pt = new ProcessTrace_impl();
// create some events
pt.startEvent("c1", "t1", "testing");
pt.startEvent("c1", "t2", "testing");
pt.endEvent("c1", "t2", "success");
pt.endEvent("c1", "t1", "success");
pt.startEvent("c2", "t1", "testing");
pt.startEvent("c2", "t2", "testing");
pt.endEvent("c2", "t2", "testing");
pt.startEvent("c2", "t3", "testing");
pt.endEvent("c2", "t3", "testing");
pt.startEvent("c2", "t4", "testing");
pt.endEvent("c2", "t1", "success");
// get top-level events for component c1
List<ProcessTraceEvent> c1evts = pt.getEventsByComponentName("c1", false);
Assert.assertEquals(1, c1evts.size());
ProcessTraceEvent evt = c1evts.get(0);
Assert.assertEquals(evt.getType(), "t1");
// get all events for component c1
c1evts = pt.getEventsByComponentName("c1", true);
Assert.assertEquals(2, c1evts.size());
evt = c1evts.get(1);
Assert.assertEquals(evt.getType(), "t2");
// get top-level events for component c2
List<ProcessTraceEvent> c2evts = pt.getEventsByComponentName("c2", false);
Assert.assertEquals(1, c2evts.size());
evt = c2evts.get(0);
Assert.assertEquals(evt.getType(), "t1");
// get all events for component c2
c2evts = pt.getEventsByComponentName("c2", true);
Assert.assertEquals(4, c2evts.size());
evt = c2evts.get(3);
Assert.assertEquals(evt.getType(), "t4");
}
/*
* Test for List getEventsByType(String, boolean)
*/
@Test
public void testGetEventsByType() {
ProcessTrace pt = new ProcessTrace_impl();
// create some events
pt.startEvent("c1", "t1", "testing");
pt.startEvent("c1", "t2", "testing");
pt.endEvent("c1", "t2", "success");
pt.endEvent("c1", "t1", "success");
pt.startEvent("c2", "t1", "testing");
pt.startEvent("c2", "t2", "testing");
pt.endEvent("c2", "t2", "testing");
pt.startEvent("c3", "t1", "testing");
pt.endEvent("c3", "t1", "testing");
pt.startEvent("c2", "t3", "testing");
pt.endEvent("c2", "t1", "success");
// get top-level events of type t1
List<ProcessTraceEvent> t1evts = pt.getEventsByType("t1", false);
Assert.assertEquals(2, t1evts.size());
ProcessTraceEvent evt = t1evts.get(0);
Assert.assertEquals(evt.getComponentName(), "c1");
evt = t1evts.get(1);
Assert.assertEquals(evt.getComponentName(), "c2");
// get all events for type t1
t1evts = pt.getEventsByType("t1", true);
Assert.assertEquals(3, t1evts.size());
evt = t1evts.get(2);
Assert.assertEquals(evt.getComponentName(), "c3");
}
/*
* Test for ProcessTraceEvent getEvent(String, String)
*/
@Test
public void testGetEvent() {
ProcessTrace_impl pt = new ProcessTrace_impl();
// create some events
pt.startEvent("c1", "t1", "testing");
pt.startEvent("c1", "t2", "testing");
pt.endEvent("c1", "t2", "success");
pt.endEvent("c1", "t1", "success");
pt.startEvent("c2", "t1", "testing");
pt.startEvent("c2", "t2", "testing");
pt.endEvent("c2", "t2", "testing");
pt.startEvent("c3", "t1", "testing");
pt.endEvent("c3", "t1", "testing");
pt.startEvent("c2", "t3", "testing");
pt.endEvent("c2", "t1", "success");
ProcessTraceEvent evt = pt.getEvent("c2", "t2");
Assert.assertEquals("c2", evt.getComponentName());
Assert.assertEquals("t2", evt.getType());
evt = pt.getEvent("c3", "t2");
Assert.assertNull(evt);
}
@Test
public void testAggregate() {
// create two ProcessTrace objects
ProcessTrace_impl pt1 = new ProcessTrace_impl();
pt1.addEvent("c1", "t1", "testing", 1000, "success");
pt1.startEvent("c2", "t1", "testing");
pt1.addEvent("c2", "t2", "testing", 500, "success");
pt1.endEvent("c2", "t1", "success");
ProcessTrace_impl pt2 = new ProcessTrace_impl();
pt2.startEvent("c2", "t1", "testing");
pt2.addEvent("c2", "t2", "testing", 500, "success");
pt2.endEvent("c2", "t1", "success");
pt2.addEvent("c1", "t1", "testing", 250, "success");
pt1.aggregate(pt2);
ProcessTraceEvent c1evt = pt1.getEvents().get(0);
ProcessTraceEvent c2evt = pt1.getEvents().get(1);
ProcessTraceEvent c2subEvt = c2evt.getSubEvents().get(0);
Assert.assertEquals(1250, c1evt.getDuration());
Assert.assertEquals(1000, c2subEvt.getDuration());
}
}
| |
/*
* 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.facebook.presto.security;
import com.facebook.presto.metadata.QualifiedObjectName;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.connector.ConnectorAccessControl;
import com.facebook.presto.spi.connector.ConnectorTransactionHandle;
import com.facebook.presto.spi.security.Identity;
import com.facebook.presto.spi.security.SystemAccessControl;
import com.facebook.presto.spi.security.SystemAccessControlFactory;
import com.facebook.presto.transaction.TransactionId;
import com.facebook.presto.transaction.TransactionManager;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import io.airlift.log.Logger;
import io.airlift.stats.CounterStat;
import org.weakref.jmx.Managed;
import org.weakref.jmx.Nested;
import javax.inject.Inject;
import java.io.File;
import java.io.FileInputStream;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static com.facebook.presto.spi.StandardErrorCode.SERVER_STARTING_UP;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.Maps.fromProperties;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
public class AccessControlManager
implements AccessControl
{
private static final Logger log = Logger.get(AccessControlManager.class);
private static final File ACCESS_CONTROL_CONFIGURATION = new File("etc/access-control.properties");
private static final String ACCESS_CONTROL_PROPERTY_NAME = "access-control.name";
public static final String ALLOW_ALL_ACCESS_CONTROL = "allow-all";
private final TransactionManager transactionManager;
private final Map<String, SystemAccessControlFactory> systemAccessControlFactories = new ConcurrentHashMap<>();
private final Map<String, CatalogAccessControlEntry> catalogAccessControl = new ConcurrentHashMap<>();
private final AtomicReference<SystemAccessControl> systemAccessControl = new AtomicReference<>(new InitializingSystemAccessControl());
private final AtomicBoolean systemAccessControlLoading = new AtomicBoolean();
private final CounterStat authenticationSuccess = new CounterStat();
private final CounterStat authenticationFail = new CounterStat();
private final CounterStat authorizationSuccess = new CounterStat();
private final CounterStat authorizationFail = new CounterStat();
@Inject
public AccessControlManager(TransactionManager transactionManager)
{
this.transactionManager = requireNonNull(transactionManager, "transactionManager is null");
systemAccessControlFactories.put(ALLOW_ALL_ACCESS_CONTROL, new SystemAccessControlFactory()
{
@Override
public String getName()
{
return ALLOW_ALL_ACCESS_CONTROL;
}
@Override
public SystemAccessControl create(Map<String, String> config)
{
requireNonNull(config, "config is null");
checkArgument(config.isEmpty(), "The none access-controller does not support any configuration properties");
return new AllowAllSystemAccessControl();
}
});
}
public void addSystemAccessControlFactory(SystemAccessControlFactory accessControlFactory)
{
requireNonNull(accessControlFactory, "accessControlFactory is null");
if (systemAccessControlFactories.putIfAbsent(accessControlFactory.getName(), accessControlFactory) != null) {
throw new IllegalArgumentException(format("Access control '%s' is already registered", accessControlFactory.getName()));
}
}
public void addCatalogAccessControl(String connectorId, String catalogName, ConnectorAccessControl accessControl)
{
requireNonNull(connectorId, "connectorId is null");
requireNonNull(catalogName, "catalogName is null");
requireNonNull(accessControl, "accessControl is null");
if (catalogAccessControl.putIfAbsent(catalogName, new CatalogAccessControlEntry(connectorId, accessControl)) != null) {
throw new IllegalArgumentException(format("Access control for catalog '%s' is already registered", catalogName));
}
}
public void loadSystemAccessControl()
throws Exception
{
if (ACCESS_CONTROL_CONFIGURATION.exists()) {
Map<String, String> properties = new HashMap<>(loadProperties(ACCESS_CONTROL_CONFIGURATION));
String accessControlName = properties.remove(ACCESS_CONTROL_PROPERTY_NAME);
checkArgument(!isNullOrEmpty(accessControlName),
"Access control configuration %s does not contain %s", ACCESS_CONTROL_CONFIGURATION.getAbsoluteFile(), ACCESS_CONTROL_PROPERTY_NAME);
setSystemAccessControl(accessControlName, properties);
}
else {
setSystemAccessControl(ALLOW_ALL_ACCESS_CONTROL, ImmutableMap.of());
}
}
@VisibleForTesting
protected void setSystemAccessControl(String name, Map<String, String> properties)
{
requireNonNull(name, "name is null");
requireNonNull(properties, "properties is null");
checkState(systemAccessControlLoading.compareAndSet(false, true), "System access control already initialized");
log.info("-- Loading system access control --");
SystemAccessControlFactory systemAccessControlFactory = systemAccessControlFactories.get(name);
checkState(systemAccessControlFactory != null, "Access control %s is not registered", name);
SystemAccessControl systemAccessControl = systemAccessControlFactory.create(ImmutableMap.copyOf(properties));
this.systemAccessControl.set(systemAccessControl);
log.info("-- Loaded system access control %s --", name);
}
@Override
public void checkCanSetUser(Principal principal, String userName)
{
requireNonNull(userName, "userName is null");
authenticationCheck(() -> systemAccessControl.get().checkCanSetUser(principal, userName));
}
@Override
public void checkCanCreateTable(TransactionId transactionId, Identity identity, QualifiedObjectName tableName)
{
requireNonNull(identity, "identity is null");
requireNonNull(tableName, "tableName is null");
CatalogAccessControlEntry entry = catalogAccessControl.get(tableName.getCatalogName());
if (entry != null) {
authorizationCheck(() -> entry.getAccessControl().checkCanCreateTable(entry.getTransactionHandle(transactionId), identity, tableName.asSchemaTableName()));
}
}
@Override
public void checkCanDropTable(TransactionId transactionId, Identity identity, QualifiedObjectName tableName)
{
requireNonNull(identity, "identity is null");
requireNonNull(tableName, "tableName is null");
CatalogAccessControlEntry entry = catalogAccessControl.get(tableName.getCatalogName());
if (entry != null) {
authorizationCheck(() -> entry.getAccessControl().checkCanDropTable(entry.getTransactionHandle(transactionId), identity, tableName.asSchemaTableName()));
}
}
@Override
public void checkCanRenameTable(TransactionId transactionId, Identity identity, QualifiedObjectName tableName, QualifiedObjectName newTableName)
{
requireNonNull(identity, "identity is null");
requireNonNull(tableName, "tableName is null");
requireNonNull(newTableName, "newTableName is null");
CatalogAccessControlEntry entry = catalogAccessControl.get(tableName.getCatalogName());
if (entry != null) {
authorizationCheck(() -> entry.getAccessControl().checkCanRenameTable(entry.getTransactionHandle(transactionId), identity, tableName.asSchemaTableName(), newTableName.asSchemaTableName()));
}
}
@Override
public void checkCanAddColumns(TransactionId transactionId, Identity identity, QualifiedObjectName tableName)
{
requireNonNull(identity, "identity is null");
requireNonNull(tableName, "tableName is null");
CatalogAccessControlEntry entry = catalogAccessControl.get(tableName.getCatalogName());
if (entry != null) {
authorizationCheck(() -> entry.getAccessControl().checkCanAddColumn(entry.getTransactionHandle(transactionId), identity, tableName.asSchemaTableName()));
}
}
@Override
public void checkCanRenameColumn(TransactionId transactionId, Identity identity, QualifiedObjectName tableName)
{
requireNonNull(identity, "identity is null");
requireNonNull(tableName, "tableName is null");
CatalogAccessControlEntry entry = catalogAccessControl.get(tableName.getCatalogName());
if (entry != null) {
authorizationCheck(() -> entry.getAccessControl().checkCanRenameColumn(entry.getTransactionHandle(transactionId), identity, tableName.asSchemaTableName()));
}
}
@Override
public void checkCanSelectFromTable(TransactionId transactionId, Identity identity, QualifiedObjectName tableName)
{
requireNonNull(identity, "identity is null");
requireNonNull(tableName, "tableName is null");
CatalogAccessControlEntry entry = catalogAccessControl.get(tableName.getCatalogName());
if (entry != null) {
authorizationCheck(() -> entry.getAccessControl().checkCanSelectFromTable(entry.getTransactionHandle(transactionId), identity, tableName.asSchemaTableName()));
}
}
@Override
public void checkCanInsertIntoTable(TransactionId transactionId, Identity identity, QualifiedObjectName tableName)
{
requireNonNull(identity, "identity is null");
requireNonNull(tableName, "tableName is null");
CatalogAccessControlEntry entry = catalogAccessControl.get(tableName.getCatalogName());
if (entry != null) {
authorizationCheck(() -> entry.getAccessControl().checkCanInsertIntoTable(entry.getTransactionHandle(transactionId), identity, tableName.asSchemaTableName()));
}
}
@Override
public void checkCanDeleteFromTable(TransactionId transactionId, Identity identity, QualifiedObjectName tableName)
{
requireNonNull(identity, "identity is null");
requireNonNull(tableName, "tableName is null");
CatalogAccessControlEntry entry = catalogAccessControl.get(tableName.getCatalogName());
if (entry != null) {
authorizationCheck(() -> entry.getAccessControl().checkCanDeleteFromTable(entry.getTransactionHandle(transactionId), identity, tableName.asSchemaTableName()));
}
}
@Override
public void checkCanCreateView(TransactionId transactionId, Identity identity, QualifiedObjectName viewName)
{
requireNonNull(identity, "identity is null");
requireNonNull(viewName, "viewName is null");
CatalogAccessControlEntry entry = catalogAccessControl.get(viewName.getCatalogName());
if (entry != null) {
authorizationCheck(() -> entry.getAccessControl().checkCanCreateView(entry.getTransactionHandle(transactionId), identity, viewName.asSchemaTableName()));
}
}
@Override
public void checkCanDropView(TransactionId transactionId, Identity identity, QualifiedObjectName viewName)
{
requireNonNull(identity, "identity is null");
requireNonNull(viewName, "viewName is null");
CatalogAccessControlEntry entry = catalogAccessControl.get(viewName.getCatalogName());
if (entry != null) {
authorizationCheck(() -> entry.getAccessControl().checkCanDropView(entry.getTransactionHandle(transactionId), identity, viewName.asSchemaTableName()));
}
}
@Override
public void checkCanSelectFromView(TransactionId transactionId, Identity identity, QualifiedObjectName viewName)
{
requireNonNull(identity, "identity is null");
requireNonNull(viewName, "viewName is null");
CatalogAccessControlEntry entry = catalogAccessControl.get(viewName.getCatalogName());
if (entry != null) {
authorizationCheck(() -> entry.getAccessControl().checkCanSelectFromView(entry.getTransactionHandle(transactionId), identity, viewName.asSchemaTableName()));
}
}
@Override
public void checkCanCreateViewWithSelectFromTable(TransactionId transactionId, Identity identity, QualifiedObjectName tableName)
{
requireNonNull(identity, "identity is null");
requireNonNull(tableName, "tableName is null");
CatalogAccessControlEntry entry = catalogAccessControl.get(tableName.getCatalogName());
if (entry != null) {
authorizationCheck(() -> entry.getAccessControl().checkCanCreateViewWithSelectFromTable(entry.getTransactionHandle(transactionId), identity, tableName.asSchemaTableName()));
}
}
@Override
public void checkCanCreateViewWithSelectFromView(TransactionId transactionId, Identity identity, QualifiedObjectName viewName)
{
requireNonNull(identity, "identity is null");
requireNonNull(viewName, "viewName is null");
CatalogAccessControlEntry entry = catalogAccessControl.get(viewName.getCatalogName());
if (entry != null) {
authorizationCheck(() -> entry.getAccessControl().checkCanCreateViewWithSelectFromView(entry.getTransactionHandle(transactionId), identity, viewName.asSchemaTableName()));
}
}
@Override
public void checkCanSetSystemSessionProperty(Identity identity, String propertyName)
{
requireNonNull(identity, "identity is null");
requireNonNull(propertyName, "propertyName is null");
authorizationCheck(() -> systemAccessControl.get().checkCanSetSystemSessionProperty(identity, propertyName));
}
@Override
public void checkCanSetCatalogSessionProperty(Identity identity, String catalogName, String propertyName)
{
requireNonNull(identity, "identity is null");
requireNonNull(catalogName, "catalogName is null");
requireNonNull(propertyName, "propertyName is null");
CatalogAccessControlEntry entry = catalogAccessControl.get(catalogName);
if (entry != null) {
authorizationCheck(() -> entry.getAccessControl().checkCanSetCatalogSessionProperty(identity, propertyName));
}
}
@Managed
@Nested
public CounterStat getAuthenticationSuccess()
{
return authenticationSuccess;
}
@Managed
@Nested
public CounterStat getAuthenticationFail()
{
return authenticationFail;
}
@Managed
@Nested
public CounterStat getAuthorizationSuccess()
{
return authorizationSuccess;
}
@Managed
@Nested
public CounterStat getAuthorizationFail()
{
return authorizationFail;
}
private void authenticationCheck(Runnable runnable)
{
try {
runnable.run();
authenticationSuccess.update(1);
}
catch (PrestoException e) {
authenticationFail.update(1);
throw e;
}
}
private void authorizationCheck(Runnable runnable)
{
try {
runnable.run();
authorizationSuccess.update(1);
}
catch (PrestoException e) {
authorizationFail.update(1);
throw e;
}
}
private static Map<String, String> loadProperties(File file)
throws Exception
{
requireNonNull(file, "file is null");
Properties properties = new Properties();
try (FileInputStream in = new FileInputStream(file)) {
properties.load(in);
}
return fromProperties(properties);
}
private class CatalogAccessControlEntry
{
private final String connectorId;
private final ConnectorAccessControl accessControl;
public CatalogAccessControlEntry(String connectorId, ConnectorAccessControl accessControl)
{
this.connectorId = requireNonNull(connectorId, "connectorId is null");
this.accessControl = requireNonNull(accessControl, "accessControl is null");
}
public ConnectorAccessControl getAccessControl()
{
return accessControl;
}
public ConnectorTransactionHandle getTransactionHandle(TransactionId transactionId)
{
return transactionManager.getConnectorTransaction(transactionId, connectorId).getTransactionHandle();
}
}
private static class InitializingSystemAccessControl
implements SystemAccessControl
{
@Override
public void checkCanSetUser(Principal principal, String userName)
{
throw new PrestoException(SERVER_STARTING_UP, "Presto server is still initializing");
}
@Override
public void checkCanSetSystemSessionProperty(Identity identity, String propertyName)
{
throw new PrestoException(SERVER_STARTING_UP, "Presto server is still initializing");
}
}
private static class AllowAllSystemAccessControl
implements SystemAccessControl
{
@Override
public void checkCanSetUser(Principal principal, String userName)
{
}
@Override
public void checkCanSetSystemSessionProperty(Identity identity, String propertyName)
{
}
}
}
| |
/*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2014 Eric Lafortune (eric@graphics.cornell.edu)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package proguard;
import proguard.classfile.*;
import proguard.classfile.attribute.annotation.visitor.AllElementValueVisitor;
import proguard.classfile.attribute.visitor.AllAttributeVisitor;
import proguard.classfile.constant.visitor.AllConstantVisitor;
import proguard.classfile.instruction.visitor.AllInstructionVisitor;
import proguard.classfile.util.*;
import proguard.classfile.visitor.*;
import proguard.util.*;
import java.io.IOException;
import java.util.*;
/**
* This class initializes class pools.
*
* @author Eric Lafortune
*/
public class Initializer
{
private final Configuration configuration;
/**
* Creates a new Initializer to initialize classes according to the given
* configuration.
*/
public Initializer(Configuration configuration)
{
this.configuration = configuration;
}
/**
* Initializes the classes in the given program class pool and library class
* pool, performs some basic checks, and shrinks the library class pool.
*/
public void execute(ClassPool programClassPool,
ClassPool libraryClassPool) throws IOException
{
int originalLibraryClassPoolSize = libraryClassPool.size();
// Perform basic checks on the configuration.
WarningPrinter fullyQualifiedClassNameNotePrinter = new WarningPrinter(System.out, configuration.note);
FullyQualifiedClassNameChecker fullyQualifiedClassNameChecker =
new FullyQualifiedClassNameChecker(programClassPool,
libraryClassPool,
fullyQualifiedClassNameNotePrinter);
fullyQualifiedClassNameChecker.checkClassSpecifications(configuration.keep);
fullyQualifiedClassNameChecker.checkClassSpecifications(configuration.assumeNoSideEffects);
StringMatcher keepAttributesMatcher = configuration.keepAttributes != null ?
new ListParser(new NameParser()).parse(configuration.keepAttributes) :
new EmptyStringMatcher();
WarningPrinter getAnnotationNotePrinter = new WarningPrinter(System.out, configuration.note);
if (!keepAttributesMatcher.matches(ClassConstants.ATTR_RuntimeVisibleAnnotations))
{
programClassPool.classesAccept(
new AllConstantVisitor(
new GetAnnotationChecker(getAnnotationNotePrinter)));
}
WarningPrinter getSignatureNotePrinter = new WarningPrinter(System.out, configuration.note);
if (!keepAttributesMatcher.matches(ClassConstants.ATTR_Signature))
{
programClassPool.classesAccept(
new AllConstantVisitor(
new GetSignatureChecker(getSignatureNotePrinter)));
}
WarningPrinter getEnclosingClassNotePrinter = new WarningPrinter(System.out, configuration.note);
if (!keepAttributesMatcher.matches(ClassConstants.ATTR_InnerClasses))
{
programClassPool.classesAccept(
new AllConstantVisitor(
new GetEnclosingClassChecker(getEnclosingClassNotePrinter)));
}
WarningPrinter getEnclosingMethodNotePrinter = new WarningPrinter(System.out, configuration.note);
if (!keepAttributesMatcher.matches(ClassConstants.ATTR_EnclosingMethod))
{
programClassPool.classesAccept(
new AllConstantVisitor(
new GetEnclosingMethodChecker(getEnclosingMethodNotePrinter)));
}
// Construct a reduced library class pool with only those library
// classes whose hierarchies are referenced by the program classes.
// We can't do this if we later have to come up with the obfuscated
// class member names that are globally unique.
ClassPool reducedLibraryClassPool = configuration.useUniqueClassMemberNames ?
null : new ClassPool();
WarningPrinter classReferenceWarningPrinter = new WarningPrinter(System.err, configuration.warn);
WarningPrinter dependencyWarningPrinter = new WarningPrinter(System.err, configuration.warn);
// Initialize the superclass hierarchies for program classes.
programClassPool.classesAccept(
new ClassSuperHierarchyInitializer(programClassPool,
libraryClassPool,
classReferenceWarningPrinter,
null));
// Initialize the superclass hierarchy of all library classes, without
// warnings.
libraryClassPool.classesAccept(
new ClassSuperHierarchyInitializer(programClassPool,
libraryClassPool,
null,
dependencyWarningPrinter));
// Initialize the class references of program class members and
// attributes. Note that all superclass hierarchies have to be
// initialized for this purpose.
WarningPrinter programMemberReferenceWarningPrinter = new WarningPrinter(System.err, configuration.warn);
WarningPrinter libraryMemberReferenceWarningPrinter = new WarningPrinter(System.err, configuration.warn);
programClassPool.classesAccept(
new ClassReferenceInitializer(programClassPool,
libraryClassPool,
classReferenceWarningPrinter,
programMemberReferenceWarningPrinter,
libraryMemberReferenceWarningPrinter,
null));
if (reducedLibraryClassPool != null)
{
// Collect the library classes that are directly referenced by
// program classes, without introspection.
programClassPool.classesAccept(
new ReferencedClassVisitor(
new LibraryClassFilter(
new ClassPoolFiller(reducedLibraryClassPool))));
// Reinitialize the superclass hierarchies of referenced library
// classes, this time with warnings.
reducedLibraryClassPool.classesAccept(
new ClassSuperHierarchyInitializer(programClassPool,
libraryClassPool,
classReferenceWarningPrinter,
null));
}
// Initialize the enum annotation references.
programClassPool.classesAccept(
new AllAttributeVisitor(true,
new AllElementValueVisitor(true,
new EnumFieldReferenceInitializer())));
// Initialize the Class.forName references.
WarningPrinter dynamicClassReferenceNotePrinter = new WarningPrinter(System.out, configuration.note);
WarningPrinter classForNameNotePrinter = new WarningPrinter(System.out, configuration.note);
programClassPool.classesAccept(
new AllMethodVisitor(
new AllAttributeVisitor(
new AllInstructionVisitor(
new DynamicClassReferenceInitializer(programClassPool,
libraryClassPool,
dynamicClassReferenceNotePrinter,
null,
classForNameNotePrinter,
createClassNoteExceptionMatcher(configuration.keep))))));
// Initialize the Class.get[Declared]{Field,Method} references.
WarningPrinter getMemberNotePrinter = new WarningPrinter(System.out, configuration.note);
programClassPool.classesAccept(
new AllMethodVisitor(
new AllAttributeVisitor(
new AllInstructionVisitor(
new DynamicMemberReferenceInitializer(programClassPool,
libraryClassPool,
getMemberNotePrinter,
createClassMemberNoteExceptionMatcher(configuration.keep, true),
createClassMemberNoteExceptionMatcher(configuration.keep, false))))));
// Initialize other string constant references, if requested.
if (configuration.adaptClassStrings != null)
{
programClassPool.classesAccept(
new ClassNameFilter(configuration.adaptClassStrings,
new AllConstantVisitor(
new StringReferenceInitializer(programClassPool,
libraryClassPool))));
}
// Initialize the class references of library class members.
if (reducedLibraryClassPool != null)
{
// Collect the library classes that are referenced by program
// classes, directly or indirectly, with or without reflection.
programClassPool.classesAccept(
new ReferencedClassVisitor(
new LibraryClassFilter(
new ClassHierarchyTraveler(true, true, true, false,
new LibraryClassFilter(
new ClassPoolFiller(reducedLibraryClassPool))))));
// Initialize the class references of referenced library
// classes, without warnings.
reducedLibraryClassPool.classesAccept(
new ClassReferenceInitializer(programClassPool,
libraryClassPool,
null,
null,
null,
dependencyWarningPrinter));
// Reset the library class pool.
libraryClassPool.clear();
// Copy the library classes that are referenced directly by program
// classes and the library classes that are referenced by referenced
// library classes.
reducedLibraryClassPool.classesAccept(
new MultiClassVisitor(new ClassVisitor[]
{
new ClassHierarchyTraveler(true, true, true, false,
new LibraryClassFilter(
new ClassPoolFiller(libraryClassPool))),
new ReferencedClassVisitor(
new LibraryClassFilter(
new ClassHierarchyTraveler(true, true, true, false,
new LibraryClassFilter(
new ClassPoolFiller(libraryClassPool)))))
}));
}
else
{
// Initialize the class references of all library class members.
libraryClassPool.classesAccept(
new ClassReferenceInitializer(programClassPool,
libraryClassPool,
null,
null,
null,
dependencyWarningPrinter));
}
// Initialize the subclass hierarchies.
programClassPool.classesAccept(new ClassSubHierarchyInitializer());
libraryClassPool.classesAccept(new ClassSubHierarchyInitializer());
// Share strings between the classes, to reduce heap memory usage.
programClassPool.classesAccept(new StringSharer());
libraryClassPool.classesAccept(new StringSharer());
// Check for any unmatched class members.
WarningPrinter classMemberNotePrinter = new WarningPrinter(System.out, configuration.note);
ClassMemberChecker classMemberChecker =
new ClassMemberChecker(programClassPool,
classMemberNotePrinter);
classMemberChecker.checkClassSpecifications(configuration.keep);
classMemberChecker.checkClassSpecifications(configuration.assumeNoSideEffects);
// Check for unkept descriptor classes of kept class members.
WarningPrinter descriptorKeepNotePrinter = new WarningPrinter(System.out, configuration.note);
new DescriptorKeepChecker(programClassPool,
libraryClassPool,
descriptorKeepNotePrinter).checkClassSpecifications(configuration.keep);
// Check for keep options that only match library classes.
WarningPrinter libraryKeepNotePrinter = new WarningPrinter(System.out, configuration.note);
new LibraryKeepChecker(programClassPool,
libraryClassPool,
libraryKeepNotePrinter).checkClassSpecifications(configuration.keep);
// Print out a summary of the notes, if necessary.
int fullyQualifiedNoteCount = fullyQualifiedClassNameNotePrinter.getWarningCount();
if (fullyQualifiedNoteCount > 0)
{
System.out.println("Note: there were " + fullyQualifiedNoteCount +
" references to unknown classes.");
System.out.println(" You should check your configuration for typos.");
System.out.println(" (http://proguard.sourceforge.net/manual/troubleshooting.html#unknownclass)");
}
int classMemberNoteCount = classMemberNotePrinter.getWarningCount();
if (classMemberNoteCount > 0)
{
System.out.println("Note: there were " + classMemberNoteCount +
" references to unknown class members.");
System.out.println(" You should check your configuration for typos.");
}
int getAnnotationNoteCount = getAnnotationNotePrinter.getWarningCount();
if (getAnnotationNoteCount > 0)
{
System.out.println("Note: there were " + getAnnotationNoteCount +
" classes trying to access annotations using reflection.");
System.out.println(" You should consider keeping the annotation attributes");
System.out.println(" (using '-keepattributes *Annotation*').");
System.out.println(" (http://proguard.sourceforge.net/manual/troubleshooting.html#attributes)");
}
int getSignatureNoteCount = getSignatureNotePrinter.getWarningCount();
if (getSignatureNoteCount > 0)
{
System.out.println("Note: there were " + getSignatureNoteCount +
" classes trying to access generic signatures using reflection.");
System.out.println(" You should consider keeping the signature attributes");
System.out.println(" (using '-keepattributes Signature').");
System.out.println(" (http://proguard.sourceforge.net/manual/troubleshooting.html#attributes)");
}
int getEnclosingClassNoteCount = getEnclosingClassNotePrinter.getWarningCount();
if (getEnclosingClassNoteCount > 0)
{
System.out.println("Note: there were " + getEnclosingClassNoteCount +
" classes trying to access enclosing classes using reflection.");
System.out.println(" You should consider keeping the inner classes attributes");
System.out.println(" (using '-keepattributes InnerClasses').");
System.out.println(" (http://proguard.sourceforge.net/manual/troubleshooting.html#attributes)");
}
int getEnclosingMethodNoteCount = getEnclosingMethodNotePrinter.getWarningCount();
if (getEnclosingMethodNoteCount > 0)
{
System.out.println("Note: there were " + getEnclosingMethodNoteCount +
" classes trying to access enclosing methods using reflection.");
System.out.println(" You should consider keeping the enclosing method attributes");
System.out.println(" (using '-keepattributes InnerClasses,EnclosingMethod').");
System.out.println(" (http://proguard.sourceforge.net/manual/troubleshooting.html#attributes)");
}
int descriptorNoteCount = descriptorKeepNotePrinter.getWarningCount();
if (descriptorNoteCount > 0)
{
System.out.println("Note: there were " + descriptorNoteCount +
" unkept descriptor classes in kept class members.");
System.out.println(" You should consider explicitly keeping the mentioned classes");
System.out.println(" (using '-keep').");
System.out.println(" (http://proguard.sourceforge.net/manual/troubleshooting.html#descriptorclass)");
}
int libraryNoteCount = libraryKeepNotePrinter.getWarningCount();
if (libraryNoteCount > 0)
{
System.out.println("Note: there were " + libraryNoteCount +
" library classes explicitly being kept.");
System.out.println(" You don't need to keep library classes; they are already left unchanged.");
System.out.println(" (http://proguard.sourceforge.net/manual/troubleshooting.html#libraryclass)");
}
int dynamicClassReferenceNoteCount = dynamicClassReferenceNotePrinter.getWarningCount();
if (dynamicClassReferenceNoteCount > 0)
{
System.out.println("Note: there were " + dynamicClassReferenceNoteCount +
" unresolved dynamic references to classes or interfaces.");
System.out.println(" You should check if you need to specify additional program jars.");
System.out.println(" (http://proguard.sourceforge.net/manual/troubleshooting.html#dynamicalclass)");
}
int classForNameNoteCount = classForNameNotePrinter.getWarningCount();
if (classForNameNoteCount > 0)
{
System.out.println("Note: there were " + classForNameNoteCount +
" class casts of dynamically created class instances.");
System.out.println(" You might consider explicitly keeping the mentioned classes and/or");
System.out.println(" their implementations (using '-keep').");
System.out.println(" (http://proguard.sourceforge.net/manual/troubleshooting.html#dynamicalclasscast)");
}
int getmemberNoteCount = getMemberNotePrinter.getWarningCount();
if (getmemberNoteCount > 0)
{
System.out.println("Note: there were " + getmemberNoteCount +
" accesses to class members by means of introspection.");
System.out.println(" You should consider explicitly keeping the mentioned class members");
System.out.println(" (using '-keep' or '-keepclassmembers').");
System.out.println(" (http://proguard.sourceforge.net/manual/troubleshooting.html#dynamicalclassmember)");
}
// Print out a summary of the warnings, if necessary.
int classReferenceWarningCount = classReferenceWarningPrinter.getWarningCount();
if (classReferenceWarningCount > 0)
{
System.err.println("Warning: there were " + classReferenceWarningCount +
" unresolved references to classes or interfaces.");
System.err.println(" You may need to add missing library jars or update their versions.");
System.err.println(" If your code works fine without the missing classes, you can suppress");
System.err.println(" the warnings with '-dontwarn' options.");
if (configuration.skipNonPublicLibraryClasses)
{
System.err.println(" You may also have to remove the option '-skipnonpubliclibraryclasses'.");
}
System.err.println(" (http://proguard.sourceforge.net/manual/troubleshooting.html#unresolvedclass)");
}
int dependencyWarningCount = dependencyWarningPrinter.getWarningCount();
if (dependencyWarningCount > 0)
{
System.err.println("Warning: there were " + dependencyWarningCount +
" instances of library classes depending on program classes.");
System.err.println(" You must avoid such dependencies, since the program classes will");
System.err.println(" be processed, while the library classes will remain unchanged.");
System.err.println(" (http://proguard.sourceforge.net/manual/troubleshooting.html#dependency)");
}
int programMemberReferenceWarningCount = programMemberReferenceWarningPrinter.getWarningCount();
if (programMemberReferenceWarningCount > 0)
{
System.err.println("Warning: there were " + programMemberReferenceWarningCount +
" unresolved references to program class members.");
System.err.println(" Your input classes appear to be inconsistent.");
System.err.println(" You may need to recompile the code.");
System.err.println(" (http://proguard.sourceforge.net/manual/troubleshooting.html#unresolvedprogramclassmember)");
}
int libraryMemberReferenceWarningCount = libraryMemberReferenceWarningPrinter.getWarningCount();
if (libraryMemberReferenceWarningCount > 0)
{
System.err.println("Warning: there were " + libraryMemberReferenceWarningCount +
" unresolved references to library class members.");
System.err.println(" You probably need to update the library versions.");
if (!configuration.skipNonPublicLibraryClassMembers)
{
System.err.println(" Alternatively, you may have to specify the option ");
System.err.println(" '-dontskipnonpubliclibraryclassmembers'.");
}
if (configuration.skipNonPublicLibraryClasses)
{
System.err.println(" You may also have to remove the option '-skipnonpubliclibraryclasses'.");
}
System.err.println(" (http://proguard.sourceforge.net/manual/troubleshooting.html#unresolvedlibraryclassmember)");
}
if ((classReferenceWarningCount > 0 ||
dependencyWarningCount > 0 ||
programMemberReferenceWarningCount > 0 ||
libraryMemberReferenceWarningCount > 0) &&
!configuration.ignoreWarnings)
{
throw new IOException("Please correct the above warnings first.");
}
if ((configuration.note == null ||
!configuration.note.isEmpty()) &&
(configuration.warn != null &&
configuration.warn.isEmpty() ||
configuration.ignoreWarnings))
{
System.out.println("Note: you're ignoring all warnings!");
}
// Discard unused library classes.
if (configuration.verbose)
{
System.out.println("Ignoring unused library classes...");
System.out.println(" Original number of library classes: " + originalLibraryClassPoolSize);
System.out.println(" Final number of library classes: " + libraryClassPool.size());
}
}
/**
* Extracts a list of exceptions of classes for which not to print notes,
* from the keep configuration.
*/
private StringMatcher createClassNoteExceptionMatcher(List noteExceptions)
{
if (noteExceptions != null)
{
List noteExceptionNames = new ArrayList(noteExceptions.size());
for (int index = 0; index < noteExceptions.size(); index++)
{
KeepClassSpecification keepClassSpecification = (KeepClassSpecification)noteExceptions.get(index);
if (keepClassSpecification.markClasses)
{
// If the class itself is being kept, it's ok.
String className = keepClassSpecification.className;
if (className != null)
{
noteExceptionNames.add(className);
}
// If all of its extensions are being kept, it's ok too.
String extendsClassName = keepClassSpecification.extendsClassName;
if (extendsClassName != null)
{
noteExceptionNames.add(extendsClassName);
}
}
}
if (noteExceptionNames.size() > 0)
{
return new ListParser(new ClassNameParser()).parse(noteExceptionNames);
}
}
return null;
}
/**
* Extracts a list of exceptions of field or method names for which not to
* print notes, from the keep configuration.
*/
private StringMatcher createClassMemberNoteExceptionMatcher(List noteExceptions,
boolean isField)
{
if (noteExceptions != null)
{
List noteExceptionNames = new ArrayList();
for (int index = 0; index < noteExceptions.size(); index++)
{
KeepClassSpecification keepClassSpecification = (KeepClassSpecification)noteExceptions.get(index);
List memberSpecifications = isField ?
keepClassSpecification.fieldSpecifications :
keepClassSpecification.methodSpecifications;
if (memberSpecifications != null)
{
for (int index2 = 0; index2 < memberSpecifications.size(); index2++)
{
MemberSpecification memberSpecification =
(MemberSpecification)memberSpecifications.get(index2);
String memberName = memberSpecification.name;
if (memberName != null)
{
noteExceptionNames.add(memberName);
}
}
}
}
if (noteExceptionNames.size() > 0)
{
return new ListParser(new ClassNameParser()).parse(noteExceptionNames);
}
}
return null;
}
}
| |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002-2010 Oracle. All rights reserved.
*
* $Id: SharedCacheTest.java,v 1.17 2010/01/04 15:51:01 cwl Exp $
*/
package com.sleepycat.je.evictor;
import java.io.File;
import junit.framework.TestCase;
import com.sleepycat.bind.tuple.IntegerBinding;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.DbInternal;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.EnvironmentMutableConfig;
import com.sleepycat.je.EnvironmentStats;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.StatsConfig;
import com.sleepycat.je.dbi.DatabaseImpl;
import com.sleepycat.je.tree.IN;
import com.sleepycat.je.util.TestUtils;
/**
* Tests the shared cache feature enabled via Environment.setSharedCache(true).
*/
public class SharedCacheTest extends TestCase {
private static final int N_ENVS = 5;
private static final int ONE_MB = 1 << 20;
private static final int ENV_CACHE_SIZE = ONE_MB;
private static final int TOTAL_CACHE_SIZE = N_ENVS * ENV_CACHE_SIZE;
private static final int LOG_BUFFER_SIZE = (ENV_CACHE_SIZE * 7) / 100;
private static final int MIN_DATA_SIZE = 50 * 1024;
private static final int LRU_ACCURACY_PCT = 60;
private static final int ENTRY_DATA_SIZE = 500;
private static final String TEST_PREFIX = "SharedCacheTest_";
private static final StatsConfig CLEAR_CONFIG = new StatsConfig();
static {
CLEAR_CONFIG.setClear(true);
}
private File envHome;
private File[] dirs;
private Environment[] envs;
private Database[] dbs;
private boolean sharedCache = true;
public SharedCacheTest() {
envHome = new File(System.getProperty(TestUtils.DEST_DIR));
}
@Override
public void setUp() {
dirs = new File[N_ENVS];
envs = new Environment[N_ENVS];
dbs = new Database[N_ENVS];
for (int i = 0; i < N_ENVS; i += 1) {
dirs[i] = new File(envHome, TEST_PREFIX + i);
dirs[i].mkdir();
assertTrue(dirs[i].isDirectory());
TestUtils.removeLogFiles("Setup", dirs[i], false);
}
}
@Override
public void tearDown() {
for (int i = 0; i < N_ENVS; i += 1) {
if (dbs[i] != null) {
try {
dbs[i].close();
} catch (Throwable e) {
System.out.println("tearDown: " + e);
}
dbs[i] = null;
}
if (envs[i] != null) {
try {
envs[i].close();
} catch (Throwable e) {
System.out.println("tearDown: " + e);
}
envs[i] = null;
}
if (dirs[i] != null) {
try {
TestUtils.removeLogFiles("TearDown", dirs[i], false);
} catch (Throwable e) {
System.out.println("tearDown: " + e);
}
dirs[i] = null;
}
}
envHome = null;
dirs = null;
envs = null;
dbs = null;
}
public void testBaseline()
throws DatabaseException {
/* Open all DBs in the same environment. */
final int N_DBS = N_ENVS;
sharedCache = false;
openOne(0);
DatabaseConfig dbConfig = dbs[0].getConfig();
for (int i = 1; i < N_DBS; i += 1) {
dbs[i] = envs[0].openDatabase(null, "foo" + i, dbConfig);
}
for (int i = 0; i < N_DBS; i += 1) {
write(i, ENV_CACHE_SIZE);
}
for (int repeat = 0; repeat < 50; repeat += 1) {
/* Read all DBs evenly. */
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry data = new DatabaseEntry();
boolean done = false;
for (int i = 0; !done; i += 1) {
IntegerBinding.intToEntry(i, key);
for (int j = 0; j < N_DBS; j += 1) {
if (dbs[j].get(null, key, data, null) !=
OperationStatus.SUCCESS) {
done = true;
}
}
}
/*
* Check that each DB uses approximately equal portions of the
* cache.
*/
StringBuffer buf = new StringBuffer();
long low = Long.MAX_VALUE;
long high = 0;
for (int i = 0; i < N_DBS; i += 1) {
long val = getDatabaseCacheBytes(dbs[i]);
buf.append(" db=" + i + " bytes=" + val);
if (low > val) {
low = val;
}
if (high < val) {
high = val;
}
}
long pct = (low * 100) / high;
assertTrue("failed with pct=" + pct + buf,
pct >= LRU_ACCURACY_PCT);
}
for (int i = 1; i < N_DBS; i += 1) {
dbs[i].close();
dbs[i] = null;
}
closeOne(0);
}
private long getDatabaseCacheBytes(Database db) {
long total = 0;
DatabaseImpl dbImpl = DbInternal.getDatabaseImpl(db);
for (IN in : dbImpl.getDbEnvironment().getInMemoryINs()) {
if (in.getDatabase() == dbImpl) {
total += in.getInMemorySize();
}
}
return total;
}
/**
* Writes to each env one at a time, writing enough data in each env to
* fill the entire cache. Each env in turn takes up a large majority of
* the cache.
*/
public void testWriteOneEnvAtATime()
throws DatabaseException {
final int SMALL_DATA_SIZE = MIN_DATA_SIZE + (20 * 1024);
final int SMALL_TOTAL_SIZE = SMALL_DATA_SIZE + LOG_BUFFER_SIZE;
final int BIG_TOTAL_SIZE = ENV_CACHE_SIZE -
((N_ENVS - 1) * SMALL_TOTAL_SIZE);
openAll();
for (int i = 0; i < N_ENVS; i += 1) {
write(i, TOTAL_CACHE_SIZE);
EnvironmentStats stats = envs[i].getStats(null);
String msg = "env=" + i +
" total=" + stats.getCacheTotalBytes() +
" shared=" + stats.getSharedCacheTotalBytes();
assertTrue(stats.getSharedCacheTotalBytes() >= BIG_TOTAL_SIZE);
assertTrue(msg, stats.getCacheTotalBytes() >= BIG_TOTAL_SIZE);
}
closeAll();
}
/**
* Writes alternating records to each env, writing enough data to fill the
* entire cache. Each env takes up roughly equal portions of the cache.
*/
public void testWriteAllEnvsEvenly()
throws DatabaseException {
openAll();
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry data = new DatabaseEntry(new byte[ENTRY_DATA_SIZE]);
for (int i = 0; i < ENV_CACHE_SIZE / ENTRY_DATA_SIZE; i += 1) {
IntegerBinding.intToEntry(i, key);
for (int j = 0; j < N_ENVS; j += 1) {
dbs[j].put(null, key, data);
}
checkStatsConsistency();
}
checkEvenCacheUsage();
closeAll();
}
/**
* Checks that the cache usage changes appropriately as environments are
* opened and closed.
*/
public void testOpenClose()
throws DatabaseException {
openAll();
int nRecs = 0;
for (int i = 0; i < N_ENVS; i += 1) {
int n = write(i, TOTAL_CACHE_SIZE);
if (nRecs < n) {
nRecs = n;
}
}
closeAll();
openAll();
readEvenly(nRecs);
/* Close only one. */
for (int i = 0; i < N_ENVS; i += 1) {
closeOne(i);
readEvenly(nRecs);
openOne(i);
readEvenly(nRecs);
}
/* Close all but one. */
for (int i = 0; i < N_ENVS; i += 1) {
for (int j = 0; j < N_ENVS; j += 1) {
if (j != i) {
closeOne(j);
}
}
readEvenly(nRecs);
for (int j = 0; j < N_ENVS; j += 1) {
if (j != i) {
openOne(j);
}
}
readEvenly(nRecs);
}
closeAll();
}
/**
* Checks that an environment with hot data uses more of the cache.
*/
public void testHotness()
throws DatabaseException {
final int HOT_CACHE_SIZE = (int) (1.5 * ENV_CACHE_SIZE);
openAll();
int nRecs = Integer.MAX_VALUE;
for (int i = 0; i < N_ENVS; i += 1) {
int n = write(i, TOTAL_CACHE_SIZE);
if (nRecs > n) {
nRecs = n;
}
}
readEvenly(nRecs);
/* Keep one env "hot". */
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry data = new DatabaseEntry();
for (int i = 0; i < N_ENVS; i += 1) {
for (int j = 0; j < N_ENVS; j += 1) {
for (int k = 0; k < nRecs; k += 1) {
IntegerBinding.intToEntry(k, key);
dbs[i].get(null, key, data, null);
dbs[j].get(null, key, data, null);
}
checkStatsConsistency();
EnvironmentStats iStats = envs[i].getStats(null);
EnvironmentStats jStats = envs[j].getStats(null);
if (iStats.getCacheTotalBytes() < HOT_CACHE_SIZE ||
jStats.getCacheTotalBytes() < HOT_CACHE_SIZE) {
StringBuilder msg = new StringBuilder();
msg.append("Hot cache size is below " + HOT_CACHE_SIZE +
" for env " + i + " or " + j);
for (int k = 0; k < N_ENVS; k += 1) {
msg.append("\n**** ENV " + k + " ****\n");
msg.append(envs[k].getStats(null));
}
fail(msg.toString());
}
}
}
closeAll();
}
/**
* Tests changing the cache size.
*/
public void testMutateCacheSize()
throws DatabaseException {
final int HALF_CACHE_SIZE = TOTAL_CACHE_SIZE / 2;
openAll();
int nRecs = 0;
for (int i = 0; i < N_ENVS; i += 1) {
int n = write(i, ENV_CACHE_SIZE);
if (nRecs < n) {
nRecs = n;
}
}
/* Full cache size. */
readEvenly(nRecs);
EnvironmentStats stats = envs[0].getStats(null);
assertTrue(Math.abs
(TOTAL_CACHE_SIZE - stats.getSharedCacheTotalBytes())
< (TOTAL_CACHE_SIZE / 10));
/* Halve cache size. */
EnvironmentMutableConfig config = envs[0].getMutableConfig();
config.setCacheSize(HALF_CACHE_SIZE);
envs[0].setMutableConfig(config);
readEvenly(nRecs);
stats = envs[0].getStats(null);
assertTrue(Math.abs
(HALF_CACHE_SIZE - stats.getSharedCacheTotalBytes())
< (HALF_CACHE_SIZE / 10));
/* Full cache size. */
config = envs[0].getMutableConfig();
config.setCacheSize(TOTAL_CACHE_SIZE);
envs[0].setMutableConfig(config);
readEvenly(nRecs);
stats = envs[0].getStats(null);
assertTrue(Math.abs
(TOTAL_CACHE_SIZE - stats.getSharedCacheTotalBytes())
< (TOTAL_CACHE_SIZE / 10));
closeAll();
}
private void openAll()
throws DatabaseException {
for (int i = 0; i < N_ENVS; i += 1) {
openOne(i);
}
}
private void openOne(int i)
throws DatabaseException {
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setAllowCreate(true);
envConfig.setSharedCache(sharedCache);
envConfig.setCacheSize(TOTAL_CACHE_SIZE);
envConfig.setConfigParam("je.tree.minMemory",
String.valueOf(MIN_DATA_SIZE));
envConfig.setConfigParam("je.env.runCleaner", "false");
envConfig.setConfigParam("je.env.runCheckpointer", "false");
envConfig.setConfigParam("je.env.runINCompressor", "false");
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setAllowCreate(true);
envs[i] = new Environment(dirs[i], envConfig);
dbs[i] = envs[i].openDatabase(null, "foo", dbConfig);
}
private void closeAll()
throws DatabaseException {
for (int i = 0; i < N_ENVS; i += 1) {
closeOne(i);
}
}
private void closeOne(int i)
throws DatabaseException {
if (dbs[i] != null) {
dbs[i].close();
dbs[i] = null;
}
if (envs[i] != null) {
envs[i].close();
envs[i] = null;
}
}
/**
* Writes enough records in the given envIndex environment to cause at
* least minSizeToWrite bytes to be used in the cache.
*/
private int write(int envIndex, int minSizeToWrite)
throws DatabaseException {
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry data = new DatabaseEntry(new byte[ENTRY_DATA_SIZE]);
int i;
for (i = 0; i < minSizeToWrite / ENTRY_DATA_SIZE; i += 1) {
IntegerBinding.intToEntry(i, key);
dbs[envIndex].put(null, key, data);
}
checkStatsConsistency();
return i;
}
/**
* Reads alternating records from each env, reading all records from each
* env. Checks that all environments use roughly equal portions of the
* cache.
*/
private void readEvenly(int nRecs)
throws DatabaseException {
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry data = new DatabaseEntry();
/* Repeat reads twice to give the LRU a fighting chance. */
for (int repeat = 0; repeat < 2; repeat += 1) {
for (int i = 0; i < nRecs; i += 1) {
IntegerBinding.intToEntry(i, key);
for (int j = 0; j < N_ENVS; j += 1) {
if (dbs[j] != null) {
dbs[j].get(null, key, data, null);
}
}
checkStatsConsistency();
}
}
checkEvenCacheUsage();
}
/**
* Checks that each env uses approximately equal portions of the cache.
* How equal the portions are depends on the accuracy of the LRU.
*/
private void checkEvenCacheUsage()
throws DatabaseException {
StringBuffer buf = new StringBuffer();
long low = Long.MAX_VALUE;
long high = 0;
for (int i = 0; i < N_ENVS; i += 1) {
if (envs[i] != null) {
EnvironmentStats stats = envs[i].getStats(null);
long val = stats.getCacheTotalBytes();
buf.append(" env=" + i + " bytes=" + val);
if (low > val) {
low = val;
}
if (high < val) {
high = val;
}
}
}
long pct = (low * 100) / high;
assertTrue("failed with pct=" + pct + buf, pct >= LRU_ACCURACY_PCT);
}
/**
* Checks that the sum of all env cache usages is the total cache usage,
* and other self-consistency checks.
*/
private void checkStatsConsistency()
throws DatabaseException {
if (!sharedCache) {
return;
}
long total = 0;
long sharedTotal = -1;
int nShared = 0;
EnvironmentStats stats = null;
for (int i = 0; i < N_ENVS; i += 1) {
if (envs[i] != null) {
stats = envs[i].getStats(null);
total += stats.getCacheTotalBytes();
nShared += 1;
if (sharedTotal == -1) {
sharedTotal = stats.getSharedCacheTotalBytes();
} else {
assertEquals(sharedTotal, stats.getSharedCacheTotalBytes());
}
}
}
assertEquals(sharedTotal, total);
assertTrue(sharedTotal < TOTAL_CACHE_SIZE + (TOTAL_CACHE_SIZE / 10));
assertEquals(nShared, stats.getNSharedCacheEnvironments());
}
}
| |
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.workbench.common.stunner.bpmn.forms.validation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.validation.ConstraintValidatorContext;
import com.google.gwt.junit.client.GWTTestCase;
import org.junit.Test;
import org.kie.workbench.common.stunner.bpmn.definition.property.event.timer.TimerSettingsValue;
public class TimerSettingsValueValidatorTest
extends GWTTestCase {
private TimerSettingsValueValidator validator;
private ConstraintValidatorContext context;
private TimerSettingsValue value;
private List<String> errorMessages = new ArrayList<>();
private List<TestElement> testElements = new ArrayList<>();
private static final String[] VALID_TIME_DURATIONS = {
"P6D",
"P6DT1H",
"P6DT1H8M",
"P6DT1H8M15S",
"PT1H",
"PT1H8M",
"PT1H8M5S",
"PT8M",
"PT3S"
};
private static final String[] INVALID_TIME_DURATIONS = {
"P4Y",
"P4Y2M",
"P4Y2M6D",
"P4Y2M6DT1H",
"P4Y2M6DT1H8M",
"P4Y2M6DT1H8M15S",
"",
"PPP",
"23EE",
"etc",
};
private static final String[] VALID_ISO_TIME_CYCLE_DURATIONS = {
"R/P6D",
"R/P6DT1H",
"R/P6DT1H8M",
"R/P6DT1H8M15S",
"R/PT1H",
"R/PT1H8M",
"R/PT1H8M5S",
"R/PT8M",
"R/PT3S",
"R2/P6D",
"R2/P6DT1H",
"R2/P6DT1H8M",
"R2/P6DT1H8M15S",
"R2/PT1H",
"R2/PT1H8M",
"R2/PT1H8M5S",
"R2/PT8M",
"R2/PT3S"
};
private static final String[] INVALID_ISO_TIME_CYCLE_DURATIONS = {
"R/P4Y",
"R/P4Y2M",
"R/P4Y2M6D",
"R/P4Y2M6DT1H",
"R/P4Y2M6DT1H8M",
"R/P4Y2M6DT1H8M15S",
"R2/P4Y",
"R2/P4Y2M",
"R2/P4Y2M6D",
"R2/P4Y2M6DT1H",
"R2/P4Y2M6DT1H8M",
"R2/P4Y2M6DT1H8M15S",
"",
"R/",
"R/4Y2M",
"A",
"/P4Y2M6D",
"R2PT1H",
"etc"
};
private static final String[] VALID_CRON_TIME_CYCLE_DURATIONS = {
"1",
"11",
"2d",
"2d5m",
"2d5m30s",
"2d5m30s40ms",
"5m30s",
"5m30s40ms",
"30s",
"30s40ms",
"40ms",
"2d 5m",
"2d 5m30s",
"2d 5m 30s 40ms",
"5m 30s",
"5m 30s 40ms",
"30s",
"30s 40ms",
"40ms"
};
private static final String[] INVALID_CRON_TIME_CYCLE_DURATIONS = {
"",
"d",
"d1",
"5m2d",
"5h8d",
"8ms5s",
"etc"
};
private static final String[] VALID_TIME_DATES = {
"2013-10-24T20:15:00.000+00:00",
"2013-10-24T20:15:00+02:05"
};
private static final String[] INVALID_TIME_DATES = {
"201AA3-12-24T20:15:00.000+00:00",
"2013-13-24T20:15:00+02:05",
"2013-10-40T20:15:00+02:05",
"2013-10-24T25:15:00+02:05",
"2013-10-24T20:75:47+00:00",
"2013-10-24T20:15:75+00:00",
"etc"
};
private static final String[] VALID_EXPRESSIONS = {
"#{something}"
};
private static final String[] INVALID_EXPRESSIONS = {
"#",
"{",
"#{",
"#{}",
"#}",
"}",
"etc"
};
@Override
protected void gwtSetUp() throws Exception {
super.gwtSetUp();
validator = new TimerSettingsValueValidator();
value = new TimerSettingsValue();
context = new ConstraintValidatorContext() {
@Override
public void disableDefaultConstraintViolation() {
}
@Override
public String getDefaultConstraintMessageTemplate() {
return null;
}
@Override
public ConstraintViolationBuilder buildConstraintViolationWithTemplate(String message) {
errorMessages.add(message);
return new ConstraintViolationBuilder() {
@Override
public NodeBuilderDefinedContext addNode(String name) {
return null;
}
@Override
public ConstraintValidatorContext addConstraintViolation() {
return context;
}
};
}
};
}
@Override
public String getModuleName() {
return "org.kie.workbench.common.stunner.bpmn.forms.validation.TimerSettingsValueValidatorTest";
}
@Test
public void testValidateTimeDuration() {
clear();
loadValidTestElements(VALID_TIME_DURATIONS);
loadValidTestElements(VALID_EXPRESSIONS);
loadInvalidTestElements(TimerSettingsValueValidator.TimeDurationInvalid,
INVALID_TIME_DURATIONS);
loadInvalidTestElements(TimerSettingsValueValidator.TimeDurationInvalid,
INVALID_EXPRESSIONS);
testElements.add(new TestElement(null,
false,
TimerSettingsValueValidator.NoValueHasBeenProvided));
testElements.forEach(testElement -> {
value.setTimeDuration(testElement.getValue());
testElement.setResult(validator.isValid(value,
context));
});
verifyTestResults();
}
@Test
public void testValidateISOTimeCycle() {
clear();
loadValidTestElements(VALID_ISO_TIME_CYCLE_DURATIONS);
loadValidTestElements(VALID_EXPRESSIONS);
loadInvalidTestElements(TimerSettingsValueValidator.ISOTimeCycleInvalid,
INVALID_ISO_TIME_CYCLE_DURATIONS);
loadInvalidTestElements(TimerSettingsValueValidator.ISOTimeCycleInvalid,
INVALID_EXPRESSIONS);
testElements.forEach(testElement -> {
value.setTimeCycleLanguage(TimerSettingsValueValidator.ISO);
value.setTimeCycle(testElement.getValue());
testElement.setResult(validator.isValid(value,
context));
});
testElements.add(new TestElement(null,
false,
TimerSettingsValueValidator.NoValueHasBeenProvided));
value.setTimeCycleLanguage(null);
value.setTimeCycle(null);
testElements.get(testElements.size() - 1).setResult(validator.isValid(value,
context));
verifyTestResults();
}
@Test
public void testValidateCronTimeCycle() {
clear();
loadValidTestElements(VALID_CRON_TIME_CYCLE_DURATIONS);
loadValidTestElements(VALID_EXPRESSIONS);
loadInvalidTestElements(TimerSettingsValueValidator.CronTimeCycleInvalid,
INVALID_CRON_TIME_CYCLE_DURATIONS);
loadInvalidTestElements(TimerSettingsValueValidator.CronTimeCycleInvalid,
INVALID_EXPRESSIONS);
testElements.forEach(testElement -> {
value.setTimeCycleLanguage(TimerSettingsValueValidator.CRON);
value.setTimeCycle(testElement.getValue());
testElement.setResult(validator.isValid(value,
context));
});
testElements.add(new TestElement(null,
false,
TimerSettingsValueValidator.NoValueHasBeenProvided));
value.setTimeCycleLanguage(null);
value.setTimeCycle(null);
testElements.get(testElements.size() - 1).setResult(validator.isValid(value,
context));
verifyTestResults();
}
@Test
public void testValidateTimeDate() {
clear();
loadValidTestElements(VALID_TIME_DATES);
loadValidTestElements(VALID_EXPRESSIONS);
loadInvalidTestElements(TimerSettingsValueValidator.TimeDateInvalid,
INVALID_TIME_DATES);
loadInvalidTestElements(TimerSettingsValueValidator.TimeDateInvalid,
INVALID_EXPRESSIONS);
testElements.add(new TestElement(null,
false,
TimerSettingsValueValidator.NoValueHasBeenProvided));
testElements.forEach(testElement -> {
value.setTimeDate(testElement.getValue());
testElement.setResult(validator.isValid(value,
context));
});
verifyTestResults();
}
private void loadValidTestElements(String... values) {
Arrays.stream(values).forEach(value -> testElements.add(new TestElement(value,
true)));
}
private void loadInvalidTestElements(String errorMessage,
String... values) {
Arrays.stream(values).forEach(value -> testElements.add(new TestElement(value,
false,
errorMessage)));
}
private void verifyTestResults() {
int error = 0;
for (int i = 0; i < testElements.size(); i++) {
TestElement testElement = testElements.get(i);
assertEquals("Invalid validation for item: " + testElement.toString(),
testElement.getExpectedResult(),
testElement.getResult());
if (!testElement.getExpectedResult()) {
assertEquals("Invalid validation: " + testElement.toString(),
testElement.getExpectedError(),
errorMessages.get(error));
error++;
}
}
}
private void clear() {
testElements.clear();
errorMessages.clear();
}
private class TestElement {
private String value = null;
private boolean expectedResult;
private String expectedError = null;
private boolean result;
public TestElement(String value,
boolean expectedResult) {
this.value = value;
this.expectedResult = expectedResult;
}
public TestElement(String value,
boolean expectedResult,
String expectedError) {
this.value = value;
this.expectedResult = expectedResult;
this.expectedError = expectedError;
}
public String getValue() {
return value;
}
public boolean getExpectedResult() {
return expectedResult;
}
public String getExpectedError() {
return expectedError;
}
public boolean getResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
@Override
public String toString() {
return "TestElement{" +
"value='" + value + '\'' +
", expectedResult=" + expectedResult +
", expectedError='" + expectedError + '\'' +
", result=" + result +
'}';
}
}
}
| |
/**
*
*/
package de.chaosbutterfly.smcombat.client.vaadin.view;
import java.util.Collection;
import java.util.List;
import java.util.function.Supplier;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import com.vaadin.cdi.CDIView;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.MenuBar.Command;
import com.vaadin.ui.MenuBar.MenuItem;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Notification.Type;
import com.vaadin.ui.UI;
import com.vaadin.ui.Window;
import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.Window.CloseListener;
import de.chaosbutterfly.smcombat.client.vaadin.session.SMVaadinSession;
import de.chaosbutterfly.smcombat.client.vaadin.session.VaadinSessionManager;
import de.chaosbutterfly.smcombat.client.vaadin.window.UserEditDialog;
import de.chaosbutterfly.smcombat.client.vaadin.window.UserListEditDialog;
import de.chaosbutterfly.smcombat.core.session.service.KnownUserAdminService;
import de.chaosbutterfly.smcombat.model.session.UserSession;
import de.chaosbutterfly.smcombat.model.user.KnownUser;
/**
* @author Alti
*
*/
@CDIView("Main")
public class MainView extends CustomComponent implements View {
private static final Logger LOGGER = Logger.getLogger(MainView.class.getName());
private static final long serialVersionUID = 1L;
public static final String NAME = "Main";
private static final String UI_TXT_MENU_ADMIN = "Admin";
private static final String UI_TXT_MENU_ADMIN_ADD_USER = "Add User";
private static final String UI_TXT_MENU_ADMIN_EDIT_USERS = "Edit Users";
private static final String UI_TXT_MENU_USER = "User";
private static final String UI_TXT_MENU_USER_PROFILE = "Profile";
private static final String UI_TXT_MENU_USER_LOGOUT = "Logout";
private transient VaadinSessionManager sessionManager;
private transient KnownUserAdminService userAdminService;
//========= UI Components =============
private MenuBar menuBar;
private Label userNameLB = new Label();
@Inject
public MainView(VaadinSessionManager sessionManager, KnownUserAdminService userAdminService) {
this.sessionManager = sessionManager;
this.userAdminService = userAdminService;
}
@PostConstruct
public void buildView() {
GridLayout mainGrid = new GridLayout(1, 1);
//build menu bar
menuBar = new MenuBar();
createUserMenu();
createAdminMenu();
mainGrid.addComponent(menuBar);
mainGrid.addComponent(userNameLB);
//build table with characters
//build list with active sessions
setCompositionRoot(mainGrid);
}
private void createAdminMenu() {
MenuItem menuUser = menuBar.addItem(UI_TXT_MENU_ADMIN, null, null);
menuUser.addItem(UI_TXT_MENU_ADMIN_ADD_USER, provideAddUserCommand());
menuUser.addItem(UI_TXT_MENU_ADMIN_EDIT_USERS, provideEditUsersCommand());
}
private void createUserMenu() {
Supplier<KnownUser> currentUserSupplier = () -> {
SMVaadinSession smVaadinSession = getSmVaadinSession();
String userName = smVaadinSession.getUserSession().getUserName();
return userAdminService.getUser(userName);
};
MenuItem menuUser = menuBar.addItem(UI_TXT_MENU_USER, null, null);
menuUser.addItem(UI_TXT_MENU_USER_PROFILE, provideUserEditCommand(currentUserSupplier));
menuUser.addSeparator();
menuUser.addItem(UI_TXT_MENU_USER_LOGOUT, provideLogOutCommand());
}
@Override
public void enter(ViewChangeEvent event) {
SMVaadinSession session = getSmVaadinSession();
UserSession userSession = session.getUserSession();
if (Boolean.TRUE.equals(userSession.getIsAdmin())) {
setAdminMenuVisible(true);
} else {
setAdminMenuVisible(false);
}
// Get the user name from the session
String username = userSession.getUserName();
// And show the username
userNameLB.setValue("Hello " + username);
}
private void setAdminMenuVisible(boolean visible) {
List<MenuItem> mainItems = menuBar.getItems();
for (MenuItem menuItem : mainItems) {
if (UI_TXT_MENU_ADMIN.equals(menuItem.getText())) {
menuItem.setVisible(visible);
}
}
}
private SMVaadinSession getSmVaadinSession() {
Object attribute = getSession().getAttribute(ViewConstants.ATTRIBUTE_NAME_SM_VAADIN_SESSION);
return (SMVaadinSession) attribute;
}
private Command provideLogOutCommand() {
Command logoutCommand = new Command() {
/** */
private static final long serialVersionUID = 1L;
@Override
public void menuSelected(MenuItem selectedItem) {
// "Logout" the user
SMVaadinSession sessionToEnd = getSmVaadinSession();
if (sessionManager.logOut(sessionToEnd)) {
getSession().setAttribute(ViewConstants.ATTRIBUTE_NAME_SM_VAADIN_SESSION, null);
}
//remove/close all open windows
UI ui = getUI();
Collection<Window> windows = ui.getWindows();
for (Window window : windows) {
ui.removeWindow(window);
}
// Refresh this view, should redirect to login view
getUI().getNavigator().navigateTo(LoginView.NAME);
Notification.show("Logout completed", Type.TRAY_NOTIFICATION);
}
};
return logoutCommand;
}
private Command provideUserEditCommand(Supplier<KnownUser> provider) {
//open user edit dialog at first
Command editUserCommand = new Command() {
private static final long serialVersionUID = 1L;
Supplier<KnownUser> knownUserProvider = provider;
@Override
public void menuSelected(MenuItem selectedItem) {
KnownUser user = knownUserProvider.get();
//open user edit dialog
//create dialog
UserEditDialog myUserEditWindow = new UserEditDialog("Edit user: " + user);
myUserEditWindow.setKnownUserData(cloneUser(user));
//close listener
myUserEditWindow.addCloseListener(new CloseListener() {
private static final long serialVersionUID = 1L;
@Override
public void windowClose(CloseEvent e) {
UserEditDialog editWindow = (UserEditDialog) e.getWindow();
int result = editWindow.getResult();
switch (result) {
case UserEditDialog.RESULT_SAVE:
//get new data and save
KnownUser editedUser = editWindow.getKnownUserData();
LOGGER.finest("User edited: old(" + user + "),new:" + editedUser);
userAdminService.editUser(user.getId(), editedUser);
Notification.show("User changed", Type.TRAY_NOTIFICATION);
break;
default:
Notification.show("User edit cancelled", Type.TRAY_NOTIFICATION);
LOGGER.finest("UserEdit cancelled");
break;
}
}
});
//open
UI.getCurrent().addWindow(myUserEditWindow);
}
};
return editUserCommand;
}
private KnownUser cloneUser(KnownUser selectedUser) {
// TODO Auto-generated method stub
return selectedUser;
}
private Command provideAddUserCommand() {
Command addUserCommand = new Command() {
private static final long serialVersionUID = 1L;
@Override
public void menuSelected(MenuItem selectedItem) {
//open user edit dialog
//create dialog
UserEditDialog addUserWindow = new UserEditDialog("Add user");
addUserWindow.setKnownUserData(new KnownUser());
//close listener
addUserWindow.addCloseListener(new CloseListener() {
private static final long serialVersionUID = 1L;
@Override
public void windowClose(CloseEvent e) {
UserEditDialog editWindow = (UserEditDialog) e.getWindow();
int result = editWindow.getResult();
switch (result) {
case UserEditDialog.RESULT_SAVE:
//get new data and save
KnownUser editedUser = editWindow.getKnownUserData();
LOGGER.finest("User added:" + editedUser);
userAdminService.addUser(editedUser.getUserName(), editedUser.getPassword(),
editedUser.getIsAdmin());
Notification.show("User added", Type.TRAY_NOTIFICATION);
break;
default:
LOGGER.finest("User adding cancelled");
Notification.show("User adding cancelled", Type.TRAY_NOTIFICATION);
break;
}
}
});
//open
UI.getCurrent().addWindow(addUserWindow);
}
};
return addUserCommand;
}
private Command provideEditUsersCommand() {
Command editUsersCommand = new Command() {
/** */
private static final long serialVersionUID = 1L;
@Override
public void menuSelected(MenuItem selectedItem) {
UserListEditDialog listDialog = new UserListEditDialog("User list", userAdminService);
//open
UI.getCurrent().addWindow(listDialog);
}
};
return editUsersCommand;
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
@Override
public int hashCode() {
return super.hashCode();
}
}
| |
/*
* 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.watcher;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.concurrent.FutureUtils;
import org.elasticsearch.threadpool.ThreadPool;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ScheduledFuture;
/**
* Generic resource watcher service
*
* Other elasticsearch services can register their resource watchers with this service using {@link #add(ResourceWatcher)}
* method. This service will call {@link org.elasticsearch.watcher.ResourceWatcher#checkAndNotify()} method of all
* registered watcher periodically. The frequency of checks can be specified using {@code resource.reload.interval} setting, which
* defaults to {@code 60s}. The service can be disabled by setting {@code resource.reload.enabled} setting to {@code false}.
*/
public class ResourceWatcherService extends AbstractLifecycleComponent<ResourceWatcherService> {
public enum Frequency {
/**
* Defaults to 5 seconds
*/
HIGH(TimeValue.timeValueSeconds(5)),
/**
* Defaults to 30 seconds
*/
MEDIUM(TimeValue.timeValueSeconds(30)),
/**
* Defaults to 60 seconds
*/
LOW(TimeValue.timeValueSeconds(60));
final TimeValue interval;
Frequency(TimeValue interval) {
this.interval = interval;
}
}
public static final Setting<Boolean> ENABLED = Setting.boolSetting("resource.reload.enabled", true, Property.NodeScope);
public static final Setting<TimeValue> RELOAD_INTERVAL_HIGH =
Setting.timeSetting("resource.reload.interval.high", Frequency.HIGH.interval, Property.NodeScope);
public static final Setting<TimeValue> RELOAD_INTERVAL_MEDIUM = Setting.timeSetting("resource.reload.interval.medium",
Setting.timeSetting("resource.reload.interval", Frequency.MEDIUM.interval), Property.NodeScope);
public static final Setting<TimeValue> RELOAD_INTERVAL_LOW =
Setting.timeSetting("resource.reload.interval.low", Frequency.LOW.interval, Property.NodeScope);
private final boolean enabled;
private final ThreadPool threadPool;
final ResourceMonitor lowMonitor;
final ResourceMonitor mediumMonitor;
final ResourceMonitor highMonitor;
private volatile ScheduledFuture lowFuture;
private volatile ScheduledFuture mediumFuture;
private volatile ScheduledFuture highFuture;
@Inject
public ResourceWatcherService(Settings settings, ThreadPool threadPool) {
super(settings);
this.enabled = ENABLED.get(settings);
this.threadPool = threadPool;
TimeValue interval = RELOAD_INTERVAL_LOW.get(settings);
lowMonitor = new ResourceMonitor(interval, Frequency.LOW);
interval = RELOAD_INTERVAL_MEDIUM.get(settings);
mediumMonitor = new ResourceMonitor(interval, Frequency.MEDIUM);
interval = RELOAD_INTERVAL_HIGH.get(settings);
highMonitor = new ResourceMonitor(interval, Frequency.HIGH);
logRemovedSetting("watcher.enabled", "resource.reload.enabled");
logRemovedSetting("watcher.interval", "resource.reload.interval");
logRemovedSetting("watcher.interval.low", "resource.reload.interval.low");
logRemovedSetting("watcher.interval.medium", "resource.reload.interval.medium");
logRemovedSetting("watcher.interval.high", "resource.reload.interval.high");
}
@Override
protected void doStart() {
if (!enabled) {
return;
}
lowFuture = threadPool.scheduleWithFixedDelay(lowMonitor, lowMonitor.interval);
mediumFuture = threadPool.scheduleWithFixedDelay(mediumMonitor, mediumMonitor.interval);
highFuture = threadPool.scheduleWithFixedDelay(highMonitor, highMonitor.interval);
}
@Override
protected void doStop() {
if (!enabled) {
return;
}
FutureUtils.cancel(lowFuture);
FutureUtils.cancel(mediumFuture);
FutureUtils.cancel(highFuture);
}
@Override
protected void doClose() {
}
/**
* Register new resource watcher that will be checked in default {@link Frequency#MEDIUM MEDIUM} frequency
*/
public <W extends ResourceWatcher> WatcherHandle<W> add(W watcher) throws IOException {
return add(watcher, Frequency.MEDIUM);
}
/**
* Register new resource watcher that will be checked in the given frequency
*/
public <W extends ResourceWatcher> WatcherHandle<W> add(W watcher, Frequency frequency) throws IOException {
watcher.init();
switch (frequency) {
case LOW:
return lowMonitor.add(watcher);
case MEDIUM:
return mediumMonitor.add(watcher);
case HIGH:
return highMonitor.add(watcher);
default:
throw new IllegalArgumentException("Unknown frequency [" + frequency + "]");
}
}
public void notifyNow() {
notifyNow(Frequency.MEDIUM);
}
public void notifyNow(Frequency frequency) {
switch (frequency) {
case LOW:
lowMonitor.run();
break;
case MEDIUM:
mediumMonitor.run();
break;
case HIGH:
highMonitor.run();
break;
default:
throw new IllegalArgumentException("Unknown frequency [" + frequency + "]");
}
}
class ResourceMonitor implements Runnable {
final TimeValue interval;
final Frequency frequency;
final Set<ResourceWatcher> watchers = new CopyOnWriteArraySet<>();
private ResourceMonitor(TimeValue interval, Frequency frequency) {
this.interval = interval;
this.frequency = frequency;
}
private <W extends ResourceWatcher> WatcherHandle<W> add(W watcher) {
watchers.add(watcher);
return new WatcherHandle<>(this, watcher);
}
@Override
public synchronized void run() {
for(ResourceWatcher watcher : watchers) {
try {
watcher.checkAndNotify();
} catch (IOException e) {
logger.trace("failed to check resource watcher", e);
}
}
}
}
}
| |
package com.jamesmorrisstudios.googleplaylibrary.listAdapters;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.jamesmorrisstudios.appbaselibrary.listAdapters.BaseRecycleItem;
import com.jamesmorrisstudios.appbaselibrary.listAdapters.BaseRecycleViewHolder;
import com.jamesmorrisstudios.appbaselibrary.time.DateTimeItem;
import com.jamesmorrisstudios.appbaselibrary.time.UtilsTime;
import com.jamesmorrisstudios.googleplaylibrary.R;
import com.jamesmorrisstudios.googleplaylibrary.game.GameDetails;
import com.jamesmorrisstudios.googleplaylibrary.data.OnlineLoadHeader;
import com.jamesmorrisstudios.googleplaylibrary.data.OnlineSaveItem;
/**
* Online load game view holder that manages the view for all Online load game items and headers.
*
* Created by James on 8/3/2015.
*/
public class OnlineLoadGameViewHolder extends BaseRecycleViewHolder {
private TextView headerTitle, timestamp, name1, name2, name3, name4, name5, name6;
private Toolbar toolbar;
private ImageView gameImage, variant, teams, addon1, addon2, addon3, addon4, addon5, addon6;
private LinearLayout playerRow1, playerRow2;
/**
* Constructor
* @param view Top View
* @param isHeader True if header, false if item
* @param mListener Click listener
*/
public OnlineLoadGameViewHolder(@NonNull View view, boolean isHeader, @NonNull cardClickListener mListener) {
super(view, isHeader, mListener);
}
/**
* Init the header view
* @param view Top header view
*/
@Override
protected void initHeader(@NonNull View view) {
headerTitle = (TextView) view.findViewById(R.id.title);
}
/**
* Init the item view
* @param view Top item view
*/
@Override
protected void initItem(@NonNull View view) {
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
gameImage = (ImageView) view.findViewById(R.id.game_image);
variant = (ImageView) view.findViewById(R.id.match_variant);
teams = (ImageView) view.findViewById(R.id.match_teams);
addon1 = (ImageView) view.findViewById(R.id.match_addon_1);
addon2 = (ImageView) view.findViewById(R.id.match_addon_2);
addon3 = (ImageView) view.findViewById(R.id.match_addon_3);
addon4 = (ImageView) view.findViewById(R.id.match_addon_4);
addon5 = (ImageView) view.findViewById(R.id.match_addon_5);
addon6 = (ImageView) view.findViewById(R.id.match_addon_6);
playerRow1 = (LinearLayout) view.findViewById(R.id.names_row_1);
playerRow2 = (LinearLayout) view.findViewById(R.id.names_row_2);
timestamp = (TextView) view.findViewById(R.id.timestamp);
name1 = (TextView) view.findViewById(R.id.name_1);
name2 = (TextView) view.findViewById(R.id.name_2);
name3 = (TextView) view.findViewById(R.id.name_3);
name4 = (TextView) view.findViewById(R.id.name_4);
name5 = (TextView) view.findViewById(R.id.name_5);
name6 = (TextView) view.findViewById(R.id.name_6);
}
/**
* Bind the header data
* @param baseRecycleItem Base header data
* @param expanded True if expanded form, false if normal
*/
@Override
protected void bindHeader(@NonNull BaseRecycleItem baseRecycleItem, boolean expanded) {
OnlineLoadHeader item = (OnlineLoadHeader) baseRecycleItem;
headerTitle.setText(item.title);
}
/**
* Bind the item data
* @param baseRecycleItem Base item data
* @param expanded True if expanded form, false if normal
*/
@Override
protected void bindItem(@NonNull BaseRecycleItem baseRecycleItem, boolean expanded) {
toolbar.getMenu().clear();
OnlineSaveItem item = (OnlineSaveItem) baseRecycleItem;
if (item.canRematch()) {
toolbar.inflateMenu(R.menu.load_game_rematch);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
//TODO
return false;
}
});
} else {
toolbar.inflateMenu(R.menu.load_game);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
//TODO
return false;
}
});
}
if (item.image == null) {
gameImage.setBackgroundResource(R.drawable.ic_blank_game_image);
} else {
gameImage.setImageBitmap(item.image);
}
//Addons
if (item.matchAddons.contains(GameDetails.MatchAddon.ADDON_1)) {
addon1.setVisibility(View.VISIBLE);
} else {
addon1.setVisibility(View.INVISIBLE);
}
if (item.matchAddons.contains(GameDetails.MatchAddon.ADDON_2)) {
addon2.setVisibility(View.VISIBLE);
} else {
addon2.setVisibility(View.INVISIBLE);
}
if (item.matchAddons.contains(GameDetails.MatchAddon.ADDON_3)) {
addon3.setVisibility(View.VISIBLE);
} else {
addon3.setVisibility(View.INVISIBLE);
}
if (item.matchAddons.contains(GameDetails.MatchAddon.ADDON_4)) {
addon4.setVisibility(View.VISIBLE);
} else {
addon4.setVisibility(View.INVISIBLE);
}
if (item.matchAddons.contains(GameDetails.MatchAddon.ADDON_5)) {
addon5.setVisibility(View.VISIBLE);
} else {
addon5.setVisibility(View.INVISIBLE);
}
if (item.matchAddons.contains(GameDetails.MatchAddon.ADDON_6)) {
addon6.setVisibility(View.VISIBLE);
} else {
addon6.setVisibility(View.INVISIBLE);
}
switch (item.matchVariant) {
case VARIANT_1:
variant.setBackgroundResource(R.drawable.ic_variant_1);
break;
case VARIANT_2:
variant.setBackgroundResource(R.drawable.ic_variant_2);
break;
case VARIANT_3:
variant.setBackgroundResource(R.drawable.ic_variant_3);
break;
case VARIANT_4:
variant.setBackgroundResource(R.drawable.ic_variant_4);
break;
case VARIANT_5:
variant.setBackgroundResource(R.drawable.ic_variant_5);
break;
case VARIANT_6:
variant.setBackgroundResource(R.drawable.ic_variant_6);
break;
}
switch (item.numberTeams) {
case FREE_FOR_ALL:
teams.setBackgroundResource(R.drawable.ic_free_for_all);
break;
case TWO:
teams.setBackgroundResource(R.drawable.ic_two_teams);
break;
}
if (item.numberPlayers == GameDetails.NumberPlayers.ONE) {
playerRow1.setVisibility(View.GONE);
playerRow2.setVisibility(View.GONE);
} else if (item.numberPlayers == GameDetails.NumberPlayers.TWO || item.numberPlayers == GameDetails.NumberPlayers.THREE) {
playerRow1.setVisibility(View.VISIBLE);
playerRow2.setVisibility(View.GONE);
setPlayerNames(item.playerNames);
} else if (item.numberPlayers == GameDetails.NumberPlayers.FOUR || item.numberPlayers == GameDetails.NumberPlayers.FIVE || item.numberPlayers == GameDetails.NumberPlayers.SIX) {
playerRow1.setVisibility(View.VISIBLE);
playerRow2.setVisibility(View.VISIBLE);
setPlayerNames(item.playerNames);
}
timestamp.setText(UtilsTime.getDateTimeFormatted(new DateTimeItem(item.getLastUpdateTimeStamp())));
}
/**
* Apply the player names
* @param names Array of names
*/
private void setPlayerNames(@NonNull String[] names) {
for (int i = 0; i < names.length; i++) {
switch (i) {
case 0:
name1.setText(names[i]);
break;
case 1:
name2.setText(names[i]);
break;
case 2:
name3.setText(names[i]);
break;
case 3:
name4.setText(names[i]);
break;
case 4:
name5.setText(names[i]);
break;
case 5:
name6.setText(names[i]);
break;
}
}
}
}
| |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.machinelearningservices.v2019_05_01.implementation;
import retrofit2.Retrofit;
import com.google.common.reflect.TypeToken;
import com.microsoft.azure.AzureServiceFuture;
import com.microsoft.azure.CloudException;
import com.microsoft.azure.ListOperationCallback;
import com.microsoft.azure.Page;
import com.microsoft.azure.PagedList;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceResponse;
import java.io.IOException;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.Url;
import retrofit2.Response;
import rx.functions.Func1;
import rx.Observable;
/**
* An instance of this class provides access to all the operations defined
* in Usages.
*/
public class UsagesInner {
/** The Retrofit service to perform REST calls. */
private UsagesService service;
/** The service client containing this operation class. */
private AzureMachineLearningWorkspacesImpl client;
/**
* Initializes an instance of UsagesInner.
*
* @param retrofit the Retrofit instance built from a Retrofit Builder.
* @param client the instance of the service client containing this operation class.
*/
public UsagesInner(Retrofit retrofit, AzureMachineLearningWorkspacesImpl client) {
this.service = retrofit.create(UsagesService.class);
this.client = client;
}
/**
* The interface defining all the services for Usages to be
* used by Retrofit to perform actually REST calls.
*/
interface UsagesService {
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.machinelearningservices.v2019_05_01.Usages list" })
@GET("subscriptions/{subscriptionId}/providers/Microsoft.MachineLearningServices/locations/{location}/usages")
Observable<Response<ResponseBody>> list(@Path("subscriptionId") String subscriptionId, @Path("location") String location, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.machinelearningservices.v2019_05_01.Usages listNext" })
@GET
Observable<Response<ResponseBody>> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
}
/**
* Gets the current usage information as well as limits for AML resources for given subscription and location.
*
* @param location The location for which resource usage is queried.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<UsageInner> object if successful.
*/
public PagedList<UsageInner> list(final String location) {
ServiceResponse<Page<UsageInner>> response = listSinglePageAsync(location).toBlocking().single();
return new PagedList<UsageInner>(response.body()) {
@Override
public Page<UsageInner> nextPage(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Gets the current usage information as well as limits for AML resources for given subscription and location.
*
* @param location The location for which resource usage is queried.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<UsageInner>> listAsync(final String location, final ListOperationCallback<UsageInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listSinglePageAsync(location),
new Func1<String, Observable<ServiceResponse<Page<UsageInner>>>>() {
@Override
public Observable<ServiceResponse<Page<UsageInner>>> call(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Gets the current usage information as well as limits for AML resources for given subscription and location.
*
* @param location The location for which resource usage is queried.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<UsageInner> object
*/
public Observable<Page<UsageInner>> listAsync(final String location) {
return listWithServiceResponseAsync(location)
.map(new Func1<ServiceResponse<Page<UsageInner>>, Page<UsageInner>>() {
@Override
public Page<UsageInner> call(ServiceResponse<Page<UsageInner>> response) {
return response.body();
}
});
}
/**
* Gets the current usage information as well as limits for AML resources for given subscription and location.
*
* @param location The location for which resource usage is queried.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<UsageInner> object
*/
public Observable<ServiceResponse<Page<UsageInner>>> listWithServiceResponseAsync(final String location) {
return listSinglePageAsync(location)
.concatMap(new Func1<ServiceResponse<Page<UsageInner>>, Observable<ServiceResponse<Page<UsageInner>>>>() {
@Override
public Observable<ServiceResponse<Page<UsageInner>>> call(ServiceResponse<Page<UsageInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Gets the current usage information as well as limits for AML resources for given subscription and location.
*
ServiceResponse<PageImpl1<UsageInner>> * @param location The location for which resource usage is queried.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<UsageInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<UsageInner>>> listSinglePageAsync(final String location) {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (location == null) {
throw new IllegalArgumentException("Parameter location is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.list(this.client.subscriptionId(), location, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<UsageInner>>>>() {
@Override
public Observable<ServiceResponse<Page<UsageInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl1<UsageInner>> result = listDelegate(response);
return Observable.just(new ServiceResponse<Page<UsageInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl1<UsageInner>> listDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl1<UsageInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl1<UsageInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Gets the current usage information as well as limits for AML resources for given subscription and location.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<UsageInner> object if successful.
*/
public PagedList<UsageInner> listNext(final String nextPageLink) {
ServiceResponse<Page<UsageInner>> response = listNextSinglePageAsync(nextPageLink).toBlocking().single();
return new PagedList<UsageInner>(response.body()) {
@Override
public Page<UsageInner> nextPage(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Gets the current usage information as well as limits for AML resources for given subscription and location.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param serviceFuture the ServiceFuture object tracking the Retrofit calls
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<UsageInner>> listNextAsync(final String nextPageLink, final ServiceFuture<List<UsageInner>> serviceFuture, final ListOperationCallback<UsageInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listNextSinglePageAsync(nextPageLink),
new Func1<String, Observable<ServiceResponse<Page<UsageInner>>>>() {
@Override
public Observable<ServiceResponse<Page<UsageInner>>> call(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Gets the current usage information as well as limits for AML resources for given subscription and location.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<UsageInner> object
*/
public Observable<Page<UsageInner>> listNextAsync(final String nextPageLink) {
return listNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<UsageInner>>, Page<UsageInner>>() {
@Override
public Page<UsageInner> call(ServiceResponse<Page<UsageInner>> response) {
return response.body();
}
});
}
/**
* Gets the current usage information as well as limits for AML resources for given subscription and location.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<UsageInner> object
*/
public Observable<ServiceResponse<Page<UsageInner>>> listNextWithServiceResponseAsync(final String nextPageLink) {
return listNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<UsageInner>>, Observable<ServiceResponse<Page<UsageInner>>>>() {
@Override
public Observable<ServiceResponse<Page<UsageInner>>> call(ServiceResponse<Page<UsageInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Gets the current usage information as well as limits for AML resources for given subscription and location.
*
ServiceResponse<PageImpl1<UsageInner>> * @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<UsageInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<UsageInner>>> listNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<UsageInner>>>>() {
@Override
public Observable<ServiceResponse<Page<UsageInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl1<UsageInner>> result = listNextDelegate(response);
return Observable.just(new ServiceResponse<Page<UsageInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl1<UsageInner>> listNextDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl1<UsageInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl1<UsageInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
}
| |
/*
* The MIT License
*
* Copyright (c) 2004-, Kohsuke Kawaguchi, Sun Microsystems, Inc., and a number of other of contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.plugins.ec2.ssh;
import hudson.FilePath;
import hudson.Util;
import hudson.ProxyConfiguration;
import hudson.model.Descriptor;
import hudson.model.Hudson;
import hudson.model.TaskListener;
import hudson.plugins.ec2.EC2AbstractSlave;
import hudson.plugins.ec2.EC2ComputerLauncher;
import hudson.plugins.ec2.EC2Computer;
import hudson.plugins.ec2.SlaveTemplate;
import hudson.remoting.Channel;
import hudson.remoting.Channel.Listener;
import hudson.slaves.CommandLauncher;
import hudson.slaves.ComputerLauncher;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.List;
import org.apache.commons.io.IOUtils;
import com.amazonaws.AmazonClientException;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.KeyPair;
import com.trilead.ssh2.Connection;
import com.trilead.ssh2.HTTPProxyData;
import com.trilead.ssh2.SCPClient;
import com.trilead.ssh2.ServerHostKeyVerifier;
import com.trilead.ssh2.Session;
/**
* {@link ComputerLauncher} that connects to a Unix slave on EC2 by using SSH.
*
* @author Kohsuke Kawaguchi
*/
public class EC2UnixLauncher extends EC2ComputerLauncher {
private final int FAILED=-1;
private final int SAMEUSER=0;
private final int RECONNECT=-2;
protected String buildUpCommand(EC2Computer computer, String command) {
if (!computer.getRemoteAdmin().equals("root")) {
command = computer.getRootCommandPrefix() + " " + command;
}
return command;
}
@Override
protected void launch(EC2Computer computer, TaskListener listener, Instance inst) throws IOException, AmazonClientException, InterruptedException {
final Connection bootstrapConn;
final Connection conn;
Connection cleanupConn = null; // java's code path analysis for final doesn't work that well.
boolean successful = false;
PrintStream logger = listener.getLogger();
try {
bootstrapConn = connectToSsh(computer, logger);
int bootstrapResult = bootstrap(bootstrapConn, computer, logger);
if (bootstrapResult == FAILED) {
logger.println("bootstrapresult failed");
return; // bootstrap closed for us.
}
else if (bootstrapResult == SAMEUSER) {
cleanupConn = bootstrapConn; // take over the connection
logger.println("take over connection");
}
else {
// connect fresh as ROOT
logger.println("connect fresh as root");
cleanupConn = connectToSsh(computer, logger);
KeyPair key = computer.getCloud().getKeyPair();
if (!cleanupConn.authenticateWithPublicKey(computer.getRemoteAdmin(), key.getKeyMaterial().toCharArray(), "")) {
logger.println("Authentication failed");
return; // failed to connect as root.
}
}
conn = cleanupConn;
SCPClient scp = conn.createSCPClient();
String initScript = computer.getNode().initScript;
String tmpDir = (Util.fixEmptyAndTrim(computer.getNode().tmpDir) != null ? computer.getNode().tmpDir : "/tmp");
logger.println("Creating tmp directory (" + tmpDir + ") if it does not exist");
conn.exec("mkdir -p " + tmpDir, logger);
if(initScript!=null && initScript.trim().length()>0 && conn.exec("test -e ~/.hudson-run-init", logger) !=0) {
logger.println("Executing init script");
scp.put(initScript.getBytes("UTF-8"),"init.sh",tmpDir,"0700");
Session sess = conn.openSession();
sess.requestDumbPTY(); // so that the remote side bundles stdout and stderr
sess.execCommand(buildUpCommand(computer, tmpDir + "/init.sh"));
sess.getStdin().close(); // nothing to write here
sess.getStderr().close(); // we are not supposed to get anything from stderr
IOUtils.copy(sess.getStdout(),logger);
int exitStatus = waitCompletion(sess);
if (exitStatus!=0) {
logger.println("init script failed: exit code="+exitStatus);
return;
}
sess.close();
// Needs a tty to run sudo.
sess = conn.openSession();
sess.requestDumbPTY(); // so that the remote side bundles stdout and stderr
sess.execCommand(buildUpCommand(computer, "touch ~/.hudson-run-init"));
sess.close();
}
// TODO: parse the version number. maven-enforcer-plugin might help
logger.println("Verifying that java exists");
if(conn.exec("java -fullversion", logger) !=0) {
logger.println("Installing Java");
String jdk = "java1.6.0_12";
String path = "/hudson-ci/jdk/linux-i586/" + jdk + ".tgz";
URL url = computer.getCloud().buildPresignedURL(path);
if(conn.exec("wget -nv -O " + tmpDir + "/" + jdk + ".tgz '" + url + "'", logger) !=0) {
logger.println("Failed to download Java");
return;
}
if(conn.exec(buildUpCommand(computer, "tar xz -C /usr -f " + tmpDir + "/" + jdk + ".tgz"), logger) !=0) {
logger.println("Failed to install Java");
return;
}
if(conn.exec(buildUpCommand(computer, "ln -s /usr/" + jdk + "/bin/java /bin/java"), logger) !=0) {
logger.println("Failed to symlink Java");
return;
}
}
// TODO: on Windows with ec2-sshd, this scp command ends up just putting slave.jar as c:\tmp
// bug in ec2-sshd?
logger.println("Copying slave.jar");
scp.put(Hudson.getInstance().getJnlpJars("slave.jar").readFully(),
"slave.jar",tmpDir);
String jvmopts = computer.getNode().jvmopts;
String launchString = "java " + (jvmopts != null ? jvmopts : "") + " -jar " + tmpDir + "/slave.jar";
// TODO: I don't get these templates. How are they named/labeled and when will there be multiples?
// Need to find out how to map this stuff onto the EC2AbstractSlave instance as it seems to have
// some of the same props.
List<SlaveTemplate> templates = computer.getCloud().getTemplates();
SlaveTemplate slaveTemplate = null;
if (templates != null && !templates.isEmpty()) {
slaveTemplate = templates.get(0);
}
if (slaveTemplate != null && slaveTemplate.isConnectBySSHProcess()) {
EC2AbstractSlave node = computer.getNode();
File identityKeyFile = createIdentityKeyFile(computer);
try {
// Obviously the master must have an installed ssh client.
String sshClientLaunchString =
String.format("ssh -o StrictHostKeyChecking=no -i %s %s@%s -p %d %s",
identityKeyFile.getAbsolutePath(),
node.remoteAdmin,
getEC2HostAddress(computer, inst),
node.getSshPort(),
launchString);
logger.println("Launching slave agent (via SSH client process): " + sshClientLaunchString);
CommandLauncher commandLauncher = new CommandLauncher(sshClientLaunchString);
commandLauncher.launch(computer, listener);
} finally {
identityKeyFile.delete();
}
} else {
logger.println("Launching slave agent (via Trilead SSH2 Connection): " + launchString);
final Session sess = conn.openSession();
sess.execCommand(launchString);
computer.setChannel(sess.getStdout(),sess.getStdin(),logger,new Listener() {
@Override
public void onClosed(Channel channel, IOException cause) {
sess.close();
conn.close();
}
});
}
successful = true;
} finally {
if(cleanupConn != null && !successful)
cleanupConn.close();
}
}
private File createIdentityKeyFile(EC2Computer computer) throws IOException {
String privateKey = computer.getCloud().getPrivateKey().getPrivateKey();
File tempFile = File.createTempFile("ec2_", ".pem");
try {
FileWriter writer = new FileWriter(tempFile);
try {
writer.write(privateKey);
writer.flush();
} finally {
writer.close();
}
FilePath filePath = new FilePath(tempFile);
filePath.chmod(0400); // octal file mask - readonly by owner
return tempFile;
} catch (Exception e) {
tempFile.delete();
throw new IOException("Error creating temporary identity key file for connecting to EC2 slave.", e);
}
}
private int bootstrap(Connection bootstrapConn, EC2Computer computer, PrintStream logger) throws IOException, InterruptedException, AmazonClientException {
logger.println("bootstrap()" );
boolean closeBootstrap = true;
try {
int tries = 20;
boolean isAuthenticated = false;
logger.println("Getting keypair..." );
KeyPair key = computer.getCloud().getKeyPair();
logger.println("Using key: " + key.getKeyName() + "\n" + key.getKeyFingerprint() + "\n" + key.getKeyMaterial().substring(0, 160) );
while (tries-- > 0) {
logger.println("Authenticating as " + computer.getRemoteAdmin());
isAuthenticated = bootstrapConn.authenticateWithPublicKey(computer.getRemoteAdmin(), key.getKeyMaterial().toCharArray(), "");
if (isAuthenticated) {
break;
}
logger.println("Authentication failed. Trying again...");
Thread.sleep(10000);
}
if (!isAuthenticated) {
logger.println("Authentication failed");
return FAILED;
}
closeBootstrap = false;
return SAMEUSER;
} finally {
if (closeBootstrap)
bootstrapConn.close();
}
}
private Connection connectToSsh(EC2Computer computer, PrintStream logger) throws AmazonClientException, InterruptedException {
final long timeout = computer.getNode().getLaunchTimeoutInMillis();
final long startTime = System.currentTimeMillis();
while(true) {
try {
long waitTime = System.currentTimeMillis() - startTime;
if ( timeout > 0 && waitTime > timeout )
{
throw new AmazonClientException("Timed out after "+ (waitTime / 1000) + " seconds of waiting for ssh to become available. (maximum timeout configured is "+ (timeout / 1000) + ")" );
}
Instance instance = computer.updateInstanceDescription();
String host = getEC2HostAddress(computer, instance);
if ("0.0.0.0".equals(host)) {
logger.println("Invalid host 0.0.0.0, your host is most likely waiting for an ip address.");
throw new IOException("goto sleep");
}
int port = computer.getSshPort();
Integer slaveConnectTimeout = Integer.getInteger("hudson.ec2.slaveConnectTimeout", 10000);
logger.println("Connecting to " + host + " on port " + port + ", with timeout " + slaveConnectTimeout + ".");
Connection conn = new Connection(host, port);
ProxyConfiguration proxyConfig = Hudson.getInstance().proxy;
Proxy proxy = proxyConfig == null ? Proxy.NO_PROXY : proxyConfig.createProxy();
if (! proxy.equals(Proxy.NO_PROXY) && proxy.address() instanceof InetSocketAddress) {
InetSocketAddress address = (InetSocketAddress) proxy.address();
HTTPProxyData proxyData = null;
if (null != proxyConfig.getUserName()) {
proxyData = new HTTPProxyData(address.getHostName(), address.getPort(), proxyConfig.getUserName(), proxyConfig.getPassword());
} else {
proxyData = new HTTPProxyData(address.getHostName(), address.getPort());
}
conn.setProxyData(proxyData);
logger.println("Using HTTP Proxy Configuration");
}
// currently OpenSolaris offers no way of verifying the host certificate, so just accept it blindly,
// hoping that no man-in-the-middle attack is going on.
conn.connect(new ServerHostKeyVerifier() {
public boolean verifyServerHostKey(String hostname, int port, String serverHostKeyAlgorithm, byte[] serverHostKey) throws Exception {
return true;
}
}, slaveConnectTimeout, slaveConnectTimeout);
logger.println("Connected via SSH.");
return conn; // successfully connected
} catch (IOException e) {
// keep retrying until SSH comes up
logger.println("Failed to connect via ssh: " + e.getMessage());
logger.println("Waiting for SSH to come up. Sleeping 5.");
Thread.sleep(5000);
}
}
}
private String getEC2HostAddress(EC2Computer computer, Instance inst) {
if (computer.getNode().usePrivateDnsName) {
return inst.getPrivateDnsName();
} else {
String host = inst.getPublicDnsName();
// If we fail to get a public DNS name, use the private IP.
if (host == null || host.equals("")) {
host = inst.getPrivateIpAddress();
}
return host;
}
}
private int waitCompletion(Session session) throws InterruptedException {
// I noticed that the exit status delivery often gets delayed. Wait up to 1 sec.
for( int i=0; i<10; i++ ) {
Integer r = session.getExitStatus();
if(r!=null) return r;
Thread.sleep(100);
}
return -1;
}
@Override
public Descriptor<ComputerLauncher> getDescriptor() {
throw new UnsupportedOperationException();
}
}
| |
/*
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* 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.drools.core.marshalling.impl;
import com.google.protobuf.ByteString;
import org.drools.core.InitialFact;
import org.drools.core.WorkingMemoryEntryPoint;
import org.drools.core.beliefsystem.BeliefSet;
import org.drools.core.beliefsystem.ModedAssertion;
import org.drools.core.common.ActivationIterator;
import org.drools.core.common.AgendaGroupQueueImpl;
import org.drools.core.common.AgendaItem;
import org.drools.core.common.BaseNode;
import org.drools.core.common.DefaultFactHandle;
import org.drools.core.common.EqualityKey;
import org.drools.core.common.EventFactHandle;
import org.drools.core.common.InternalAgenda;
import org.drools.core.common.InternalFactHandle;
import org.drools.core.common.InternalWorkingMemory;
import org.drools.core.common.InternalWorkingMemoryEntryPoint;
import org.drools.core.common.LeftTupleIterator;
import org.drools.core.common.LogicalDependency;
import org.drools.core.common.Memory;
import org.drools.core.common.NamedEntryPoint;
import org.drools.core.common.NodeMemories;
import org.drools.core.common.ObjectStore;
import org.drools.core.common.ObjectTypeConfigurationRegistry;
import org.drools.core.common.QueryElementFactHandle;
import org.drools.core.common.TruthMaintenanceSystem;
import org.drools.core.common.WorkingMemoryAction;
import org.drools.core.definitions.rule.impl.RuleImpl;
import org.drools.core.impl.StatefulKnowledgeSessionImpl;
import org.drools.core.marshalling.impl.ProtobufMessages.FactHandle;
import org.drools.core.marshalling.impl.ProtobufMessages.ObjectTypeConfiguration;
import org.drools.core.marshalling.impl.ProtobufMessages.ProcessData.Builder;
import org.drools.core.marshalling.impl.ProtobufMessages.Timers;
import org.drools.core.marshalling.impl.ProtobufMessages.Timers.Timer;
import org.drools.core.marshalling.impl.ProtobufMessages.Tuple;
import org.drools.core.phreak.PropagationEntry;
import org.drools.core.phreak.RuleAgendaItem;
import org.drools.core.process.instance.WorkItem;
import org.drools.core.reteoo.AccumulateNode.AccumulateContext;
import org.drools.core.reteoo.AccumulateNode.AccumulateMemory;
import org.drools.core.reteoo.BetaMemory;
import org.drools.core.reteoo.BetaNode;
import org.drools.core.reteoo.FromNode.FromMemory;
import org.drools.core.reteoo.LeftTuple;
import org.drools.core.reteoo.NodeTypeEnums;
import org.drools.core.reteoo.ObjectSink;
import org.drools.core.reteoo.ObjectTypeConf;
import org.drools.core.reteoo.ObjectTypeNode;
import org.drools.core.reteoo.ObjectTypeNode.ObjectTypeNodeMemory;
import org.drools.core.reteoo.QueryElementNode.QueryElementNodeMemory;
import org.drools.core.reteoo.RightInputAdapterNode;
import org.drools.core.reteoo.RightTuple;
import org.drools.core.spi.Activation;
import org.drools.core.spi.AgendaGroup;
import org.drools.core.spi.RuleFlowGroup;
import org.drools.core.time.JobContext;
import org.drools.core.time.SelfRemovalJobContext;
import org.drools.core.time.Trigger;
import org.drools.core.time.impl.CompositeMaxDurationTrigger;
import org.drools.core.time.impl.CronTrigger;
import org.drools.core.time.impl.IntervalTrigger;
import org.drools.core.time.impl.PointInTimeTrigger;
import org.drools.core.time.impl.PseudoClockScheduler;
import org.drools.core.time.impl.TimerJobInstance;
import org.drools.core.util.FastIterator;
import org.drools.core.util.LinkedListEntry;
import org.drools.core.util.ObjectHashMap;
import org.kie.api.marshalling.ObjectMarshallingStrategy;
import org.kie.api.marshalling.ObjectMarshallingStrategyStore;
import org.kie.api.runtime.rule.EntryPoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* An output marshaller that uses ProtoBuf as the marshalling framework
* in order to provide backward compatibility with marshalled sessions
*
* @author etirelli
*/
public class ProtobufOutputMarshaller {
private static ProcessMarshaller processMarshaller = createProcessMarshaller();
private static ProcessMarshaller createProcessMarshaller() {
try {
return ProcessMarshallerFactory.newProcessMarshaller();
} catch ( IllegalArgumentException e ) {
return null;
}
}
public static void writeSession(MarshallerWriteContext context) throws IOException {
ProtobufMessages.KnowledgeSession _session = serializeSession( context );
// System.out.println("=============================================================================");
// System.out.println(_session);
PersisterHelper.writeToStreamWithHeader( context,
_session );
}
private static ProtobufMessages.KnowledgeSession serializeSession(MarshallerWriteContext context) throws IOException {
StatefulKnowledgeSessionImpl wm = (StatefulKnowledgeSessionImpl) context.wm;
try {
wm.getLock().lock();
for (WorkingMemoryEntryPoint ep : wm.getWorkingMemoryEntryPoints().values()) {
if (ep instanceof NamedEntryPoint) {
((NamedEntryPoint)ep).lock();
}
}
wm.getAgenda().unstageActivations();
evaluateRuleActivations( wm );
ProtobufMessages.RuleData.Builder _ruleData = ProtobufMessages.RuleData.newBuilder();
long time = 0;
if ( context.wm.getTimerService() instanceof PseudoClockScheduler ) {
time = context.clockTime;
}
_ruleData.setLastId( wm.getFactHandleFactory().getId() );
_ruleData.setLastRecency( wm.getFactHandleFactory().getRecency() );
InternalFactHandle handle = context.wm.getInitialFactHandle();
if ( handle != null ) {
// can be null for RETE, if fireAllRules has not yet been called
ProtobufMessages.FactHandle _ifh = ProtobufMessages.FactHandle.newBuilder()
.setType( ProtobufMessages.FactHandle.HandleType.INITIAL_FACT )
.setId( handle.getId() )
.setRecency( handle.getRecency() )
.build();
_ruleData.setInitialFact( _ifh );
}
writeAgenda( context, _ruleData );
writeNodeMemories( context, _ruleData );
for ( EntryPoint wmep : wm.getWorkingMemoryEntryPoints().values() ) {
org.drools.core.marshalling.impl.ProtobufMessages.EntryPoint.Builder _epb = ProtobufMessages.EntryPoint.newBuilder();
_epb.setEntryPointId( wmep.getEntryPointId() );
writeObjectTypeConfiguration( context,
((InternalWorkingMemoryEntryPoint)wmep).getObjectTypeConfigurationRegistry(),
_epb );
writeFactHandles( context,
_epb,
((NamedEntryPoint) wmep).getObjectStore() );
writeTruthMaintenanceSystem( context,
wmep,
_epb );
_ruleData.addEntryPoint( _epb.build() );
}
writeActionQueue( context,
_ruleData );
ProtobufMessages.KnowledgeSession.Builder _session = ProtobufMessages.KnowledgeSession.newBuilder()
.setMultithread( false )
.setTime( time )
.setRuleData( _ruleData.build() );
if ( processMarshaller != null ) {
Builder _pdata = ProtobufMessages.ProcessData.newBuilder();
if ( context.marshalProcessInstances ) {
context.parameterObject = _pdata;
processMarshaller.writeProcessInstances( context );
}
if ( context.marshalWorkItems ) {
context.parameterObject = _pdata;
processMarshaller.writeWorkItems( context );
}
// this now just assigns the writer, it will not write out any timer information
context.parameterObject = _pdata;
processMarshaller.writeProcessTimers( context );
_session.setProcessData( _pdata.build() );
}
Timers _timers = writeTimers( context.wm.getTimerService().getTimerJobInstances( context.wm.getIdentifier() ),
context );
if ( _timers != null ) {
_session.setTimers( _timers );
}
return _session.build();
} finally {
for (WorkingMemoryEntryPoint ep : wm.getWorkingMemoryEntryPoints().values()) {
if (ep instanceof NamedEntryPoint) {
((NamedEntryPoint)ep).unlock();
}
}
wm.getLock().unlock();
}
}
private static void writeObjectTypeConfiguration( MarshallerWriteContext context,
ObjectTypeConfigurationRegistry otcr,
org.drools.core.marshalling.impl.ProtobufMessages.EntryPoint.Builder _epb) {
Collection<ObjectTypeConf> values = otcr.values();
ObjectTypeConf[] otcs = values.toArray( new ObjectTypeConf[ values.size() ] );
Arrays.sort( otcs,
new Comparator<ObjectTypeConf>() {
@Override
public int compare(ObjectTypeConf o1, ObjectTypeConf o2) {
return o1.getTypeName().compareTo(o2.getTypeName());
}
});
for( ObjectTypeConf otc : otcs ) {
ObjectTypeNode objectTypeNode = otc.getConcreteObjectTypeNode();
if (objectTypeNode != null) {
final ObjectTypeNodeMemory memory = context.wm.getNodeMemory(objectTypeNode);
if (memory != null) {
ObjectTypeConfiguration _otc = ObjectTypeConfiguration.newBuilder()
.setType(otc.getTypeName())
.setTmsEnabled(otc.isTMSEnabled())
.build();
_epb.addOtc(_otc);
}
}
}
}
private static void evaluateRuleActivations(StatefulKnowledgeSessionImpl wm) {
// ET: NOTE: initially we were only resolving partially evaluated rules
// but some tests fail because of that. Have to resolve all rule agenda items
// in order to fix the tests
// find all partially evaluated rule activations
// ActivationIterator it = ActivationIterator.iterator( wm );
// Set<String> evaluated = new HashSet<String>();
// for ( org.drools.core.spi.Activation item = (org.drools.core.spi.Activation) it.next(); item != null; item = (org.drools.core.spi.Activation) it.next() ) {
// if ( !item.isRuleAgendaItem() ) {
// evaluated.add( item.getRule().getPackageName()+"."+item.getRule().getName() );
// }
// }
// need to evaluate all lazy partially evaluated activations before serializing
boolean dirty = true;
while ( dirty) {
for ( Activation activation : wm.getAgenda().getActivations() ) {
if ( activation.isRuleAgendaItem() /*&& evaluated.contains( activation.getRule().getPackageName()+"."+activation.getRule().getName() )*/ ) {
// evaluate it
((RuleAgendaItem)activation).getRuleExecutor().reEvaluateNetwork( wm );
((RuleAgendaItem)activation).getRuleExecutor().removeRuleAgendaItemWhenEmpty( wm );
}
}
dirty = false;
if ( wm.getKnowledgeBase().getConfiguration().isPhreakEnabled() ) {
// network evaluation with phreak and TMS may make previous processed rules dirty again, so need to reprocess until all is flushed.
for ( Activation activation : wm.getAgenda().getActivations() ) {
if ( activation.isRuleAgendaItem() && ((RuleAgendaItem)activation).getRuleExecutor().isDirty() ) {
dirty = true;
break;
}
}
}
wm.flushNonMarshallablePropagations();
}
}
private static void writeAgenda(MarshallerWriteContext context,
ProtobufMessages.RuleData.Builder _ksb) throws IOException {
InternalWorkingMemory wm = context.wm;
InternalAgenda agenda = wm.getAgenda();
org.drools.core.marshalling.impl.ProtobufMessages.Agenda.Builder _ab = ProtobufMessages.Agenda.newBuilder();
AgendaGroup[] agendaGroups = agenda.getAgendaGroupsMap().values().toArray( new AgendaGroup[agenda.getAgendaGroupsMap().size()] );
Arrays.sort( agendaGroups,
AgendaGroupSorter.instance );
for ( AgendaGroup ag : agendaGroups ) {
AgendaGroupQueueImpl group = (AgendaGroupQueueImpl) ag;
org.drools.core.marshalling.impl.ProtobufMessages.Agenda.AgendaGroup.Builder _agb = ProtobufMessages.Agenda.AgendaGroup.newBuilder();
_agb.setName( group.getName() )
.setIsActive( group.isActive() )
.setIsAutoDeactivate( group.isAutoDeactivate() )
.setClearedForRecency( group.getClearedForRecency() )
.setHasRuleFlowLister( group.isRuleFlowListener() )
.setActivatedForRecency( group.getActivatedForRecency() );
Map<Long, String> nodeInstances = group.getNodeInstances();
for ( Map.Entry<Long, String> entry : nodeInstances.entrySet() ) {
org.drools.core.marshalling.impl.ProtobufMessages.Agenda.AgendaGroup.NodeInstance.Builder _nib = ProtobufMessages.Agenda.AgendaGroup.NodeInstance.newBuilder();
_nib.setProcessInstanceId( entry.getKey() );
_nib.setNodeInstanceId( entry.getValue() );
_agb.addNodeInstance( _nib.build() );
}
_ab.addAgendaGroup( _agb.build() );
}
org.drools.core.marshalling.impl.ProtobufMessages.Agenda.FocusStack.Builder _fsb = ProtobufMessages.Agenda.FocusStack.newBuilder();
LinkedList<AgendaGroup> focusStack = agenda.getStackList();
for ( AgendaGroup group : focusStack ) {
_fsb.addGroupName( group.getName() );
}
_ab.setFocusStack( _fsb.build() );
// serialize all dormant activations
org.drools.core.util.Iterator it = ActivationIterator.iterator( wm );
List<org.drools.core.spi.Activation> dormant = new ArrayList<org.drools.core.spi.Activation>();
for ( org.drools.core.spi.Activation item = (org.drools.core.spi.Activation) it.next(); item != null; item = (org.drools.core.spi.Activation) it.next() ) {
if ( !item.isQueued() ) {
dormant.add( item );
}
}
Collections.sort( dormant, ActivationsSorter.INSTANCE );
for ( org.drools.core.spi.Activation activation : dormant ) {
_ab.addMatch( writeActivation( context, (AgendaItem) activation ) );
}
// serialize all network evaluator activations
for ( Activation activation : agenda.getActivations() ) {
if ( activation.isRuleAgendaItem() ) {
// serialize it
_ab.addRuleActivation( writeActivation( context, (AgendaItem) activation ) );
}
}
_ksb.setAgenda( _ab.build() );
}
private static void writeNodeMemories(MarshallerWriteContext context,
ProtobufMessages.RuleData.Builder _ksb) throws IOException {
InternalWorkingMemory wm = context.wm;
NodeMemories memories = wm.getNodeMemories();
// only some of the node memories require special serialization handling
// so we iterate over all of them and process only those that require it
for ( int i = 0; i < memories.length(); i++ ) {
Memory memory = memories.peekNodeMemory( i );
// some nodes have no memory, so we need to check for nulls
if ( memory != null ) {
ProtobufMessages.NodeMemory _node = null;
switch ( memory.getNodeType() ) {
case NodeTypeEnums.AccumulateNode : {
_node = writeAccumulateNodeMemory( i, memory );
break;
}
case NodeTypeEnums.RightInputAdaterNode : {
_node = writeRIANodeMemory( i, context.sinks.get(i), memories );
break;
}
case NodeTypeEnums.FromNode : {
_node = writeFromNodeMemory( i, memory );
break;
}
case NodeTypeEnums.QueryElementNode : {
_node = writeQueryElementNodeMemory( i, memory, wm );
break;
}
}
if ( _node != null ) {
// not all node memories require serialization
_ksb.addNodeMemory( _node );
}
}
}
}
private static ProtobufMessages.NodeMemory writeAccumulateNodeMemory(final int nodeId,
final Memory memory) {
// for accumulate nodes, we need to store the ID of created (result) handles
AccumulateMemory accmem = (AccumulateMemory) memory;
if ( accmem.getBetaMemory().getLeftTupleMemory().size() > 0 ) {
ProtobufMessages.NodeMemory.AccumulateNodeMemory.Builder _accumulate = ProtobufMessages.NodeMemory.AccumulateNodeMemory.newBuilder();
final org.drools.core.util.Iterator<LeftTuple> tupleIter = accmem.getBetaMemory().getLeftTupleMemory().iterator();
for ( LeftTuple leftTuple = tupleIter.next(); leftTuple != null; leftTuple = tupleIter.next() ) {
AccumulateContext accctx = (AccumulateContext) leftTuple.getContextObject();
if ( accctx.getResultFactHandle() != null ) {
FactHandle _handle = ProtobufMessages.FactHandle.newBuilder()
.setId( accctx.getResultFactHandle().getId() )
.setRecency( accctx.getResultFactHandle().getRecency() )
.build();
_accumulate.addContext(
ProtobufMessages.NodeMemory.AccumulateNodeMemory.AccumulateContext.newBuilder()
.setTuple( PersisterHelper.createTuple( leftTuple ) )
.setResultHandle( _handle )
.build() );
}
}
return ProtobufMessages.NodeMemory.newBuilder()
.setNodeId( nodeId )
.setNodeType( ProtobufMessages.NodeMemory.NodeType.ACCUMULATE )
.setAccumulate( _accumulate.build() )
.build();
}
return null;
}
private static ProtobufMessages.NodeMemory writeRIANodeMemory(final int nodeId,
final BaseNode node,
final NodeMemories memories) {
RightInputAdapterNode riaNode = (RightInputAdapterNode) node;
ObjectSink[] sinks = riaNode.getObjectSinkPropagator().getSinks();
BetaNode betaNode = (BetaNode) sinks[0];
Memory betaMemory = memories.peekNodeMemory( betaNode.getId() );
if ( betaMemory == null ) {
return null;
}
BetaMemory bm;
if ( betaNode.getType() == NodeTypeEnums.AccumulateNode ) {
bm = ((AccumulateMemory) betaMemory).getBetaMemory();
} else {
bm = (BetaMemory) betaMemory;
}
// for RIA nodes, we need to store the ID of the created handles
bm.getRightTupleMemory().iterator();
if ( bm.getRightTupleMemory().size() > 0 ) {
ProtobufMessages.NodeMemory.RIANodeMemory.Builder _ria = ProtobufMessages.NodeMemory.RIANodeMemory.newBuilder();
final org.drools.core.util.Iterator it = bm.getRightTupleMemory().iterator();
// iterates over all propagated handles and assert them to the new sink
for ( RightTuple entry = (RightTuple) it.next(); entry != null; entry = (RightTuple) it.next() ) {
LeftTuple leftTuple = entry instanceof LeftTuple ?
(LeftTuple) entry : // with phreak the entry is always both a right and a left tuple
(LeftTuple) entry.getFactHandle().getObject(); // this is necessary only for reteoo
InternalFactHandle handle = (InternalFactHandle) leftTuple.getFactHandle();
if (handle == null) {
continue;
}
FactHandle _handle = ProtobufMessages.FactHandle.newBuilder()
.setId( handle.getId() )
.setRecency( handle.getRecency() )
.build();
_ria.addContext( ProtobufMessages.NodeMemory.RIANodeMemory.RIAContext.newBuilder()
.setTuple( PersisterHelper.createTuple( leftTuple ) )
.setResultHandle( _handle )
.build() );
}
return ProtobufMessages.NodeMemory.newBuilder()
.setNodeId( nodeId )
.setNodeType( ProtobufMessages.NodeMemory.NodeType.RIA )
.setRia( _ria.build() )
.build();
}
return null;
}
@SuppressWarnings("unchecked")
private static ProtobufMessages.NodeMemory writeFromNodeMemory(final int nodeId,
final Memory memory) {
FromMemory fromMemory = (FromMemory) memory;
if ( fromMemory.getBetaMemory().getLeftTupleMemory().size() > 0 ) {
ProtobufMessages.NodeMemory.FromNodeMemory.Builder _from = ProtobufMessages.NodeMemory.FromNodeMemory.newBuilder();
final org.drools.core.util.Iterator<LeftTuple> tupleIter = fromMemory.getBetaMemory().getLeftTupleMemory().iterator();
for ( LeftTuple leftTuple = tupleIter.next(); leftTuple != null; leftTuple = tupleIter.next() ) {
Map<Object, RightTuple> matches = (Map<Object, RightTuple>) leftTuple.getContextObject();
ProtobufMessages.NodeMemory.FromNodeMemory.FromContext.Builder _context = ProtobufMessages.NodeMemory.FromNodeMemory.FromContext.newBuilder()
.setTuple( PersisterHelper.createTuple( leftTuple ) );
for ( RightTuple rightTuple : matches.values() ) {
FactHandle _handle = ProtobufMessages.FactHandle.newBuilder()
.setId( rightTuple.getFactHandle().getId() )
.setRecency( rightTuple.getFactHandle().getRecency() )
.build();
_context.addHandle( _handle );
}
_from.addContext( _context.build() );
}
return ProtobufMessages.NodeMemory.newBuilder()
.setNodeId( nodeId )
.setNodeType( ProtobufMessages.NodeMemory.NodeType.FROM )
.setFrom( _from.build() )
.build();
}
return null;
}
private static ProtobufMessages.NodeMemory writeQueryElementNodeMemory(final int nodeId,
final Memory memory,
final InternalWorkingMemory wm) {
org.drools.core.util.Iterator<LeftTuple> it = LeftTupleIterator.iterator( wm, ((QueryElementNodeMemory) memory).getNode() );
ProtobufMessages.NodeMemory.QueryElementNodeMemory.Builder _query = ProtobufMessages.NodeMemory.QueryElementNodeMemory.newBuilder();
for ( LeftTuple leftTuple = it.next(); leftTuple != null; leftTuple = it.next() ) {
InternalFactHandle handle = (InternalFactHandle) leftTuple.getContextObject();
FactHandle _handle = ProtobufMessages.FactHandle.newBuilder()
.setId( handle.getId() )
.setRecency( handle.getRecency() )
.build();
ProtobufMessages.NodeMemory.QueryElementNodeMemory.QueryContext.Builder _context = ProtobufMessages.NodeMemory.QueryElementNodeMemory.QueryContext.newBuilder()
.setTuple( PersisterHelper.createTuple( leftTuple ) )
.setHandle( _handle );
LeftTuple childLeftTuple = leftTuple.getFirstChild();
while ( childLeftTuple != null ) {
RightTuple rightParent = childLeftTuple.getRightParent();
_context.addResult( ProtobufMessages.FactHandle.newBuilder()
.setId( rightParent.getFactHandle().getId() )
.setRecency( rightParent.getFactHandle().getRecency() )
.build() );
while ( childLeftTuple != null && childLeftTuple.getRightParent() == rightParent ) {
// skip to the next child that has a different right parent
childLeftTuple = childLeftTuple.getHandleNext();
}
}
_query.addContext( _context.build() );
}
return _query.getContextCount() > 0 ?
ProtobufMessages.NodeMemory.newBuilder()
.setNodeId( nodeId )
.setNodeType( ProtobufMessages.NodeMemory.NodeType.QUERY_ELEMENT )
.setQueryElement( _query.build() )
.build()
: null;
}
private static class AgendaGroupSorter
implements
Comparator<AgendaGroup> {
public static final AgendaGroupSorter instance = new AgendaGroupSorter();
public int compare(AgendaGroup group1,
AgendaGroup group2) {
return group1.getName().compareTo( group2.getName() );
}
}
private static class RuleFlowGroupSorter
implements
Comparator<RuleFlowGroup> {
public static final RuleFlowGroupSorter instance = new RuleFlowGroupSorter();
public int compare(RuleFlowGroup group1,
RuleFlowGroup group2) {
return group1.getName().compareTo( group2.getName() );
}
}
public static void writeActionQueue(MarshallerWriteContext context,
ProtobufMessages.RuleData.Builder _session) throws IOException {
if ( context.wm.hasPendingPropagations() ) {
ProtobufMessages.ActionQueue.Builder _queue = ProtobufMessages.ActionQueue.newBuilder();
Iterator<? extends PropagationEntry> i = context.wm.getActionsIterator();
while ( i.hasNext() ) {
PropagationEntry entry = i.next();
if (entry instanceof WorkingMemoryAction) {
_queue.addAction(((WorkingMemoryAction) entry).serialize(context));
}
}
_session.setActionQueue( _queue.build() );
}
}
public static void writeTruthMaintenanceSystem(MarshallerWriteContext context,
EntryPoint wmep,
ProtobufMessages.EntryPoint.Builder _epb) throws IOException {
TruthMaintenanceSystem tms = ((NamedEntryPoint) wmep).getTruthMaintenanceSystem();
ObjectHashMap justifiedMap = tms.getEqualityKeyMap();
if ( !justifiedMap.isEmpty() ) {
EqualityKey[] keys = new EqualityKey[justifiedMap.size()];
org.drools.core.util.Iterator it = justifiedMap.iterator();
int i = 0;
for ( org.drools.core.util.ObjectHashMap.ObjectEntry entry = (org.drools.core.util.ObjectHashMap.ObjectEntry) it.next(); entry != null; entry = (org.drools.core.util.ObjectHashMap.ObjectEntry) it.next() ) {
EqualityKey key = (EqualityKey) entry.getKey();
keys[i++] = key;
}
Arrays.sort( keys,
EqualityKeySorter.instance );
ProtobufMessages.TruthMaintenanceSystem.Builder _tms = ProtobufMessages.TruthMaintenanceSystem.newBuilder();
// write the assert map of Equality keys
for ( EqualityKey key : keys ) {
ProtobufMessages.EqualityKey.Builder _key = ProtobufMessages.EqualityKey.newBuilder();
_key.setStatus( key.getStatus() );
_key.setHandleId( key.getFactHandle().getId() );
if ( key.size() > 1 ) {
// add all the other key's if they exist
FastIterator keyIter = key.fastIterator();
for ( DefaultFactHandle handle = key.getFirst().getNext(); handle != null; handle = (DefaultFactHandle) keyIter.next( handle ) ) {
_key.addOtherHandle( handle.getId() );
}
}
if ( key.getBeliefSet() != null ) {
writeBeliefSet( context, key.getBeliefSet(), _key );
}
_tms.addKey( _key.build() );
}
_epb.setTms( _tms.build() );
}
}
private static void writeBeliefSet(MarshallerWriteContext context,
BeliefSet beliefSet,
org.drools.core.marshalling.impl.ProtobufMessages.EqualityKey.Builder _key) throws IOException {
ProtobufMessages.BeliefSet.Builder _beliefSet = ProtobufMessages.BeliefSet.newBuilder();
_beliefSet.setHandleId( beliefSet.getFactHandle().getId() );
ObjectMarshallingStrategyStore objectMarshallingStrategyStore = context.objectMarshallingStrategyStore;
// for ( LinkedListEntry node = (LinkedListEntry) beliefSet.getFirst(); node != null; node = (LinkedListEntry) node.getNext() ) {
FastIterator it = beliefSet.iterator();
for ( LinkedListEntry node = (LinkedListEntry) beliefSet.getFirst(); node != null; node = (LinkedListEntry) it.next(node) ) {
LogicalDependency belief = (LogicalDependency) node.getObject();
ProtobufMessages.LogicalDependency.Builder _logicalDependency = ProtobufMessages.LogicalDependency.newBuilder();
//_belief.setActivation( value )
LogicalDependency dependency = (LogicalDependency) node.getObject();
org.drools.core.spi.Activation activation = dependency.getJustifier();
ProtobufMessages.Activation _activation = ProtobufMessages.Activation.newBuilder()
.setPackageName( activation.getRule().getPackage() )
.setRuleName( activation.getRule().getName() )
.setTuple( PersisterHelper.createTuple( activation.getTuple() ) )
.build();
_logicalDependency.setActivation( _activation );
if ( belief.getObject() != null ) {
ObjectMarshallingStrategy strategy = objectMarshallingStrategyStore.getStrategyObject( belief.getObject() );
Integer index = context.getStrategyIndex( strategy );
_logicalDependency.setObjectStrategyIndex( index );
_logicalDependency.setObject( ByteString.copyFrom( strategy.marshal( context.strategyContext.get( strategy ),
context,
belief.getObject() ) ) );
}
if ( belief.getMode() != null ) {
ObjectMarshallingStrategy strategy = objectMarshallingStrategyStore.getStrategyObject( belief.getMode() );
Integer index = context.getStrategyIndex( strategy );
_logicalDependency.setValueStrategyIndex( index );
_logicalDependency.setValue( ByteString.copyFrom( strategy.marshal( context.strategyContext.get( strategy ),
context,
belief.getMode() ) ) );
}
_beliefSet.addLogicalDependency( _logicalDependency.build() );
}
_key.setBeliefSet( _beliefSet );
}
public static class EqualityKeySorter
implements
Comparator<EqualityKey> {
public static final EqualityKeySorter instance = new EqualityKeySorter();
public int compare(EqualityKey key1,
EqualityKey key2) {
return key1.getFactHandle().getId() - key2.getFactHandle().getId();
}
}
private static void writeFactHandles(MarshallerWriteContext context,
org.drools.core.marshalling.impl.ProtobufMessages.EntryPoint.Builder _epb,
ObjectStore objectStore) throws IOException {
ObjectMarshallingStrategyStore objectMarshallingStrategyStore = context.objectMarshallingStrategyStore;
// Write out FactHandles
for ( InternalFactHandle handle : orderFacts( objectStore ) ) {
ProtobufMessages.FactHandle _handle = writeFactHandle( context,
objectMarshallingStrategyStore,
handle );
_epb.addHandle( _handle );
}
}
private static ProtobufMessages.FactHandle writeFactHandle(MarshallerWriteContext context,
ObjectMarshallingStrategyStore objectMarshallingStrategyStore,
InternalFactHandle handle) throws IOException {
ProtobufMessages.FactHandle.Builder _handle = ProtobufMessages.FactHandle.newBuilder();
_handle.setType( getHandleType( handle ) );
_handle.setId( handle.getId() );
_handle.setRecency( handle.getRecency() );
if ( _handle.getType() == ProtobufMessages.FactHandle.HandleType.EVENT ) {
// is event
EventFactHandle efh = (EventFactHandle) handle;
_handle.setTimestamp( efh.getStartTimestamp() );
_handle.setDuration( efh.getDuration() );
_handle.setIsExpired( efh.isExpired() );
_handle.setActivationsCount( efh.getActivationsCount() );
_handle.setOtnCount( efh.getOtnCount() );
}
if ( handle.getEqualityKey() != null &&
handle.getEqualityKey().getStatus() == EqualityKey.JUSTIFIED ) {
_handle.setIsJustified( true );
} else {
_handle.setIsJustified( false );
}
Object object = handle.getObject();
if ( object != null ) {
ObjectMarshallingStrategy strategy = objectMarshallingStrategyStore.getStrategyObject( object );
Integer index = context.getStrategyIndex( strategy );
_handle.setStrategyIndex( index );
_handle.setObject( ByteString.copyFrom( strategy.marshal( context.strategyContext.get( strategy ),
context,
object ) ) );
}
return _handle.build();
}
private static ProtobufMessages.FactHandle.HandleType getHandleType(InternalFactHandle handle) {
if ( handle instanceof EventFactHandle ) {
return ProtobufMessages.FactHandle.HandleType.EVENT;
} else if ( handle instanceof QueryElementFactHandle ) {
return ProtobufMessages.FactHandle.HandleType.QUERY;
} else if ( handle.getObject() instanceof InitialFact ) {
return ProtobufMessages.FactHandle.HandleType.INITIAL_FACT;
}
return ProtobufMessages.FactHandle.HandleType.FACT;
}
public static InternalFactHandle[] orderFacts(ObjectStore objectStore) {
// this method is just needed for testing purposes, to allow round tripping
int size = objectStore.size();
InternalFactHandle[] handles = new InternalFactHandle[size];
int i = 0;
for ( Iterator<InternalFactHandle> it = objectStore.iterateFactHandles(); it.hasNext(); ) {
handles[i++] = it.next();
}
Arrays.sort( handles,
new HandleSorter() );
return handles;
}
public static InternalFactHandle[] orderFacts(List<InternalFactHandle> handlesList) {
// this method is just needed for testing purposes, to allow round tripping
int size = handlesList.size();
InternalFactHandle[] handles = handlesList.toArray( new InternalFactHandle[size] );
Arrays.sort( handles,
new HandleSorter() );
return handles;
}
public static class HandleSorter
implements
Comparator<InternalFactHandle> {
public int compare(InternalFactHandle h1,
InternalFactHandle h2) {
return h1.getId() - h2.getId();
}
}
public static class ActivationsSorter
implements
Comparator<org.drools.core.spi.Activation> {
public static final ActivationsSorter INSTANCE = new ActivationsSorter();
public int compare(org.drools.core.spi.Activation o1,
org.drools.core.spi.Activation o2) {
int result = o1.getRule().getName().compareTo( o2.getRule().getName() );
if ( result == 0 ) {
org.drools.core.spi.Tuple t1 = o1.getTuple();
org.drools.core.spi.Tuple t2 = o2.getTuple();
while ( result == 0 && t1 != null && t2 != null ) {
if ( t1.getFactHandle() != null && t2.getFactHandle() != null ) {
// can be null for eval, not and exists that have no right input
result = t1.getFactHandle().getId() - t2.getFactHandle().getId();
}
t1 = t1.getParent();
t2 = t2.getParent();
}
}
return result;
}
}
public static <M extends ModedAssertion<M>> ProtobufMessages.Activation writeActivation(MarshallerWriteContext context,
AgendaItem<M> agendaItem) {
ProtobufMessages.Activation.Builder _activation = ProtobufMessages.Activation.newBuilder();
RuleImpl rule = agendaItem.getRule();
_activation.setPackageName( rule.getPackage() );
_activation.setRuleName( rule.getName() );
_activation.setTuple( writeTuple( agendaItem.getTuple() ) );
_activation.setSalience( agendaItem.getSalience() );
_activation.setIsActivated( agendaItem.isQueued() );
_activation.setEvaluated( agendaItem.isRuleAgendaItem() );
if ( agendaItem.getActivationGroupNode() != null ) {
_activation.setActivationGroup( agendaItem.getActivationGroupNode().getActivationGroup().getName() );
}
if ( agendaItem.getActivationFactHandle() != null ) {
_activation.setHandleId( agendaItem.getActivationFactHandle().getId() );
}
org.drools.core.util.LinkedList<LogicalDependency<M>> list = agendaItem.getLogicalDependencies();
if ( list != null && !list.isEmpty() ) {
for ( LogicalDependency<?> node = list.getFirst(); node != null; node = node.getNext() ) {
_activation.addLogicalDependency( ((BeliefSet) node.getJustified()).getFactHandle().getId() );
}
}
return _activation.build();
}
public static Tuple writeTuple(org.drools.core.spi.Tuple tuple) {
ProtobufMessages.Tuple.Builder _tb = ProtobufMessages.Tuple.newBuilder();
for ( org.drools.core.spi.Tuple entry = tuple; entry != null; entry = entry.getParent() ) {
InternalFactHandle handle = entry.getFactHandle();
if ( handle != null ) {
// can be null for eval, not and exists that have no right input
_tb.addHandleId( handle.getId() );
}
}
return _tb.build();
}
private static ProtobufMessages.Timers writeTimers(Collection<TimerJobInstance> timers,
MarshallerWriteContext outCtx) {
if ( !timers.isEmpty() ) {
List<TimerJobInstance> sortedTimers = new ArrayList<TimerJobInstance>( timers );
Collections.sort( sortedTimers,
new Comparator<TimerJobInstance>() {
public int compare(TimerJobInstance o1,
TimerJobInstance o2) {
return (int) (o1.getJobHandle().getId() - o2.getJobHandle().getId());
}
} );
ProtobufMessages.Timers.Builder _timers = ProtobufMessages.Timers.newBuilder();
for ( TimerJobInstance timer : sortedTimers ) {
JobContext jctx = ((SelfRemovalJobContext) timer.getJobContext()).getJobContext();
if (jctx instanceof ObjectTypeNode.ExpireJobContext &&
!((ObjectTypeNode.ExpireJobContext) jctx).getExpireAction().getFactHandle().isValid()) {
continue;
}
TimersOutputMarshaller writer = outCtx.writersByClass.get( jctx.getClass() );
Timer _timer = writer.serialize( jctx, outCtx );
if ( _timer != null ) {
_timers.addTimer( _timer );
}
}
return _timers.build();
}
return null;
}
public static ProtobufMessages.Trigger writeTrigger(Trigger trigger,
MarshallerWriteContext outCtx) {
if ( trigger instanceof CronTrigger ) {
CronTrigger cronTrigger = (CronTrigger) trigger;
ProtobufMessages.Trigger.CronTrigger.Builder _cron = ProtobufMessages.Trigger.CronTrigger.newBuilder()
.setStartTime( cronTrigger.getStartTime().getTime() )
.setRepeatLimit( cronTrigger.getRepeatLimit() )
.setRepeatCount( cronTrigger.getRepeatCount() )
.setCronExpression( cronTrigger.getCronEx().getCronExpression() );
if ( cronTrigger.getEndTime() != null ) {
_cron.setEndTime( cronTrigger.getEndTime().getTime() );
}
if ( cronTrigger.getNextFireTime() != null ) {
_cron.setNextFireTime( cronTrigger.getNextFireTime().getTime() );
}
if ( cronTrigger.getCalendarNames() != null ) {
for ( String calendarName : cronTrigger.getCalendarNames() ) {
_cron.addCalendarName( calendarName );
}
}
return ProtobufMessages.Trigger.newBuilder()
.setType( ProtobufMessages.Trigger.TriggerType.CRON )
.setCron( _cron.build() )
.build();
} else if ( trigger instanceof IntervalTrigger ) {
IntervalTrigger intTrigger = (IntervalTrigger) trigger;
ProtobufMessages.Trigger.IntervalTrigger.Builder _interval = ProtobufMessages.Trigger.IntervalTrigger.newBuilder()
.setStartTime( intTrigger.getStartTime().getTime() )
.setRepeatLimit( intTrigger.getRepeatLimit() )
.setRepeatCount( intTrigger.getRepeatCount() )
.setPeriod( intTrigger.getPeriod() );
if ( intTrigger.getEndTime() != null ) {
_interval.setEndTime( intTrigger.getEndTime().getTime() );
}
if ( intTrigger.getNextFireTime() != null ) {
_interval.setNextFireTime( intTrigger.getNextFireTime().getTime() );
}
if ( intTrigger.getCalendarNames() != null ) {
for ( String calendarName : intTrigger.getCalendarNames() ) {
_interval.addCalendarName( calendarName );
}
}
return ProtobufMessages.Trigger.newBuilder()
.setType( ProtobufMessages.Trigger.TriggerType.INTERVAL )
.setInterval( _interval.build() )
.build();
} else if ( trigger instanceof PointInTimeTrigger ) {
PointInTimeTrigger pinTrigger = (PointInTimeTrigger) trigger;
return ProtobufMessages.Trigger.newBuilder()
.setType( ProtobufMessages.Trigger.TriggerType.POINT_IN_TIME )
.setPit( ProtobufMessages.Trigger.PointInTimeTrigger.newBuilder()
.setNextFireTime( pinTrigger.hasNextFireTime().getTime() )
.build() )
.build();
} else if ( trigger instanceof CompositeMaxDurationTrigger ) {
CompositeMaxDurationTrigger cmdTrigger = (CompositeMaxDurationTrigger) trigger;
ProtobufMessages.Trigger.CompositeMaxDurationTrigger.Builder _cmdt = ProtobufMessages.Trigger.CompositeMaxDurationTrigger.newBuilder();
if ( cmdTrigger.getMaxDurationTimestamp() != null ) {
_cmdt.setMaxDurationTimestamp( cmdTrigger.getMaxDurationTimestamp().getTime() );
}
if ( cmdTrigger.getTimerCurrentDate() != null ) {
_cmdt.setTimerCurrentDate( cmdTrigger.getTimerCurrentDate().getTime() );
}
if ( cmdTrigger.getTimerTrigger() != null ) {
_cmdt.setTimerTrigger( writeTrigger(cmdTrigger.getTimerTrigger(), outCtx) );
}
return ProtobufMessages.Trigger.newBuilder()
.setType( ProtobufMessages.Trigger.TriggerType.COMPOSITE_MAX_DURATION )
.setCmdt( _cmdt.build() )
.build();
}
throw new RuntimeException( "Unable to serialize Trigger for type: " + trigger.getClass() );
}
public static void writeWorkItem( MarshallerWriteContext context, WorkItem workItem ) {
processMarshaller.writeWorkItem( context, workItem );
}
}
| |
/*
* 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.flink.types;
import org.apache.flink.annotation.Public;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataOutputView;
import org.apache.flink.util.ReflectionUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/**
* Generic list base type for PACT programs that implements the Value and List interfaces. PactList
* encapsulates a Java ArrayList object.
*
* @see org.apache.flink.types.Value
* @see java.util.List
* @see java.util.ArrayList
* @param <V> Type of the list elements.
*/
@Public
public abstract class ListValue<V extends Value> implements Value, List<V> {
private static final long serialVersionUID = 1L;
// Type of list elements
private final Class<V> valueClass;
// Encapsulated list
private final List<V> list;
/**
* Initializes the encapsulated list with an empty ArrayList.
*
* @see java.util.ArrayList
*/
public ListValue() {
this.valueClass = ReflectionUtil.<V>getTemplateType1(this.getClass());
this.list = new ArrayList<V>();
}
/**
* Initializes the encapsulated list with an ArrayList filled with all object contained in the
* specified Collection object.
*
* @see java.util.ArrayList
* @see java.util.Collection
* @param c Collection of initial element of the encapsulated list.
*/
public ListValue(final Collection<V> c) {
this.valueClass = ReflectionUtil.<V>getTemplateType1(this.getClass());
this.list = new ArrayList<V>(c);
}
/*
* (non-Javadoc)
* @see java.util.List#iterator()
*/
@Override
public Iterator<V> iterator() {
return this.list.iterator();
}
@Override
public void read(final DataInputView in) throws IOException {
int size = in.readInt();
this.list.clear();
try {
for (; size > 0; size--) {
final V val = this.valueClass.newInstance();
val.read(in);
this.list.add(val);
}
} catch (final InstantiationException e) {
throw new RuntimeException(e);
} catch (final IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Override
public void write(final DataOutputView out) throws IOException {
out.writeInt(this.list.size());
for (final V value : this.list) {
value.write(out);
}
}
/*
* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 41;
int result = 1;
result = prime * result + (this.list == null ? 0 : this.list.hashCode());
return result;
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
final ListValue<?> other = (ListValue<?>) obj;
if (this.list == null) {
if (other.list != null) {
return false;
}
} else if (!this.list.equals(other.list)) {
return false;
}
return true;
}
/*
* (non-Javadoc)
* @see java.util.List#add(int, java.lang.Object)
*/
@Override
public void add(final int index, final V element) {
this.list.add(index, element);
}
/*
* (non-Javadoc)
* @see java.util.List#add(java.lang.Object)
*/
@Override
public boolean add(final V e) {
return this.list.add(e);
}
/*
* (non-Javadoc)
* @see java.util.List#addAll(java.util.Collection)
*/
@Override
public boolean addAll(final Collection<? extends V> c) {
return this.list.addAll(c);
}
/*
* (non-Javadoc)
* @see java.util.List#addAll(int, java.util.Collection)
*/
@Override
public boolean addAll(final int index, final Collection<? extends V> c) {
return this.list.addAll(index, c);
}
/*
* (non-Javadoc)
* @see java.util.List#clear()
*/
@Override
public void clear() {
this.list.clear();
}
/*
* (non-Javadoc)
* @see java.util.List#contains(java.lang.Object)
*/
@Override
public boolean contains(final Object o) {
return this.list.contains(o);
}
@Override
public String toString() {
return this.list.toString();
}
/*
* (non-Javadoc)
* @see java.util.List#containsAll(java.util.Collection)
*/
@Override
public boolean containsAll(final Collection<?> c) {
return this.list.containsAll(c);
}
/*
* (non-Javadoc)
* @see java.util.List#get(int)
*/
@Override
public V get(final int index) {
return this.list.get(index);
}
/*
* (non-Javadoc)
* @see java.util.List#indexOf(java.lang.Object)
*/
@Override
public int indexOf(final Object o) {
return this.list.indexOf(o);
}
/*
* (non-Javadoc)
* @see java.util.List#isEmpty()
*/
@Override
public boolean isEmpty() {
return this.list.isEmpty();
}
/*
* (non-Javadoc)
* @see java.util.List#lastIndexOf(java.lang.Object)
*/
@Override
public int lastIndexOf(final Object o) {
return this.list.lastIndexOf(o);
}
/*
* (non-Javadoc)
* @see java.util.List#listIterator()
*/
@Override
public ListIterator<V> listIterator() {
return this.list.listIterator();
}
/*
* (non-Javadoc)
* @see java.util.List#listIterator(int)
*/
@Override
public ListIterator<V> listIterator(final int index) {
return this.list.listIterator(index);
}
/*
* (non-Javadoc)
* @see java.util.List#remove(int)
*/
@Override
public V remove(final int index) {
return this.list.remove(index);
}
/*
* (non-Javadoc)
* @see java.util.List#remove(java.lang.Object)
*/
@Override
public boolean remove(final Object o) {
return this.list.remove(o);
}
/*
* (non-Javadoc)
* @see java.util.List#removeAll(java.util.Collection)
*/
@Override
public boolean removeAll(final Collection<?> c) {
return this.list.removeAll(c);
}
/*
* (non-Javadoc)
* @see java.util.List#retainAll(java.util.Collection)
*/
@Override
public boolean retainAll(final Collection<?> c) {
return this.list.retainAll(c);
}
/*
* (non-Javadoc)
* @see java.util.List#set(int, java.lang.Object)
*/
@Override
public V set(final int index, final V element) {
return this.list.set(index, element);
}
/*
* (non-Javadoc)
* @see java.util.List#size()
*/
@Override
public int size() {
return this.list.size();
}
/*
* (non-Javadoc)
* @see java.util.List#subList(int, int)
*/
@Override
public List<V> subList(final int fromIndex, final int toIndex) {
return this.list.subList(fromIndex, toIndex);
}
/*
* (non-Javadoc)
* @see java.util.List#toArray()
*/
@Override
public Object[] toArray() {
return this.list.toArray();
}
/*
* (non-Javadoc)
* @see java.util.List#toArray(T[])
*/
@Override
public <T> T[] toArray(final T[] a) {
return this.list.toArray(a);
}
}
| |
package org.basex.io.serial;
import static org.basex.query.QueryError.*;
import static org.basex.util.Token.*;
import java.io.*;
import java.util.*;
import org.basex.build.csv.*;
import org.basex.build.json.*;
import org.basex.core.*;
import org.basex.io.*;
import org.basex.query.*;
import org.basex.query.func.*;
import org.basex.query.value.item.*;
import org.basex.query.value.node.*;
import org.basex.util.*;
import org.basex.util.options.*;
/**
* This class defines all available serialization parameters.
*
* @author BaseX Team 2005-16, BSD License
* @author Christian Gruen
*/
public final class SerializerOptions extends Options {
/** Serialization parameter: yes/no. */
public static final EnumOption<YesNo> BYTE_ORDER_MARK =
new EnumOption<>("byte-order-mark", YesNo.NO);
/** Serialization parameter: list of QNames. */
public static final StringOption CDATA_SECTION_ELEMENTS =
new StringOption("cdata-section-elements", "");
/** Serialization parameter. */
public static final StringOption DOCTYPE_PUBLIC =
new StringOption("doctype-public", "");
/** Serialization parameter. */
public static final StringOption DOCTYPE_SYSTEM =
new StringOption("doctype-system", "");
/** Serialization parameter: valid encoding. */
public static final StringOption ENCODING =
new StringOption("encoding", Strings.UTF8);
/** Serialization parameter: yes/no. */
public static final EnumOption<YesNo> ESCAPE_URI_ATTRIBUTES =
new EnumOption<>("escape-uri-attributes", YesNo.NO);
/** Serialization parameter: yes/no. */
public static final EnumOption<YesNo> INCLUDE_CONTENT_TYPE =
new EnumOption<>("include-content-type", YesNo.NO);
/** Serialization parameter: yes/no. */
public static final EnumOption<YesNo> INDENT =
new EnumOption<>("indent", YesNo.YES);
/** Serialization parameter. */
public static final StringOption SUPPRESS_INDENTATION =
new StringOption("suppress-indentation", "");
/** Serialization parameter. */
public static final StringOption MEDIA_TYPE =
new StringOption("media-type", "");
/** Serialization parameter: xml/xhtml/html/text/json/csv/raw/adaptive. */
public static final EnumOption<SerialMethod> METHOD =
new EnumOption<>("method", SerialMethod.BASEX);
/** Serialization parameter: NFC/NFD/NFKC/NKFD/fully-normalized/none. */
public static final StringOption NORMALIZATION_FORM =
new StringOption("normalization-form", Text.NONE);
/** Serialization parameter: yes/no. */
public static final EnumOption<YesNo> OMIT_XML_DECLARATION =
new EnumOption<>("omit-xml-declaration", YesNo.YES);
/** Serialization parameter: yes/no/omit. */
public static final EnumOption<YesNoOmit> STANDALONE =
new EnumOption<>("standalone", YesNoOmit.OMIT);
/** Serialization parameter: yes/no. */
public static final EnumOption<YesNo> UNDECLARE_PREFIXES =
new EnumOption<>("undeclare-prefixes", YesNo.NO);
/** Serialization parameter. */
public static final StringOption USE_CHARACTER_MAPS =
new StringOption("use-character-maps", "");
/** Serialization parameter. */
public static final StringOption ITEM_SEPARATOR =
new StringOption("item-separator");
/** Serialization parameter: 1.0/1.1. */
public static final StringOption VERSION =
new StringOption("version", "");
/** Serialization parameter: 4.0/4.01/5.0. */
public static final StringOption HTML_VERSION =
new StringOption("html-version", "");
/** Parameter document. */
public static final StringOption PARAMETER_DOCUMENT =
new StringOption("parameter-document", "");
/** Serialization parameter: xml/xhtml/html/text. */
public static final EnumOption<YesNo> ALLOW_DUPLICATE_NAMES =
new EnumOption<>("allow-duplicate-names", YesNo.NO);
/** Serialization parameter: xml/xhtml/html/text. */
public static final EnumOption<SerialMethod> JSON_NODE_OUTPUT_METHOD =
new EnumOption<>("json-node-output-method", SerialMethod.XML);
/** Specific serialization parameter. */
public static final OptionsOption<CsvOptions> CSV =
new OptionsOption<>("csv", new CsvOptions());
/** Specific serialization parameter. */
public static final OptionsOption<JsonSerialOptions> JSON =
new OptionsOption<>("json", new JsonSerialOptions());
/** Specific serialization parameter: newline. */
public static final EnumOption<Newline> NEWLINE =
new EnumOption<>("newline",
"\r".equals(Prop.NL) ? Newline.CR : "\n".equals(Prop.NL) ? Newline.NL : Newline.CRNL);
/** Specific serialization parameter: indent with spaces or tabs. */
public static final EnumOption<YesNo> TABULATOR =
new EnumOption<>("tabulator", YesNo.NO);
/** Specific serialization parameter: number of spaces to indent. */
public static final NumberOption INDENTS =
new NumberOption("indents", 2);
/** Specific serialization parameter: maximum number of bytes to serialize. */
public static final NumberOption LIMIT =
new NumberOption("limit", -1);
/** Specific serialization parameter: binary serialization. */
public static final EnumOption<YesNo> BINARY =
new EnumOption<>("binary", YesNo.YES);
/** Static WebDAV character map. */
public static final String WEBDAV = "\u00a0= ";
/** Newlines. */
public enum Newline {
/** NL. */ NL("\\n", "\n"),
/** CR. */ CR("\\r", "\r"),
/** CRNL. */ CRNL("\\r\\n", "\r\n");
/** Name. */
private final String name;
/** Newline. */
private final String newline;
/**
* Constructor.
* @param name name
* @param newline newline string
*/
Newline(final String name, final String newline) {
this.name = name;
this.newline = newline;
}
/**
* Returns the newline string.
* @return newline string
*/
String newline() {
return newline;
}
@Override
public String toString() {
return name;
}
}
/**
* Checks if the specified option is true.
* @param option option
* @return value
*/
public boolean yes(final EnumOption<YesNo> option) {
return get(option) == YesNo.YES;
}
/**
* Default constructor.
*/
public SerializerOptions() {
}
/**
* Constructor with options to be copied.
* @param opts options
*/
public SerializerOptions(final SerializerOptions opts) {
super(opts);
}
/**
* Parses options.
* @param name name of option
* @param value value
* @param sc static context
* @param info input info
* @throws QueryException query exception
*/
public void parse(final String name, final byte[] value, final StaticContext sc,
final InputInfo info) throws QueryException {
try {
if(name.equals(USE_CHARACTER_MAPS.name()) && !eq(value, token(WEBDAV)))
throw OUTMAP_X.get(info, value);
assign(name, string(value));
} catch(final BaseXException ex) {
for(final Option<?> o : this) if(o.name().equals(name)) throw SER_X.get(info, ex);
throw OUTINVALID_X.get(info, ex);
}
if(name.equals(PARAMETER_DOCUMENT.name())) {
Uri uri = Uri.uri(value);
if(!uri.isValid()) throw INVURI_X.get(info, value);
if(!uri.isAbsolute()) uri = sc.baseURI().resolve(uri, info);
final IO io = IO.get(string(uri.string()));
try {
// check parameters and add values to serialization parameters
final ANode root = new DBNode(io).children().next();
FuncOptions.serializer(root, this, info);
final HashMap<String, String> free = free();
if(!free.isEmpty()) throw SEROPTION_X.get(info, free.keySet().iterator().next());
final byte[] mapsId = QNm.get(USE_CHARACTER_MAPS.name(), QueryText.OUTPUT_URI).id();
final byte[] mapId = QNm.get("character-map", QueryText.OUTPUT_URI).id();
if(!get(USE_CHARACTER_MAPS).isEmpty()) {
final TokenBuilder tb = new TokenBuilder();
for(final ANode option : XMLAccess.children(root, mapsId)) {
for(final ANode child : XMLAccess.children(option, mapId)) {
if(!tb.isEmpty()) tb.add(',');
tb.add(child.attribute("character")).add('=').add(child.attribute("map-string"));
}
}
set(USE_CHARACTER_MAPS, tb.toString());
}
} catch(final IOException ex) {
Util.debug(ex);
throw OUTDOC_X.get(info, value);
}
}
}
}
| |
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.camunda.bpm.engine.test.api.identity;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.time.DateUtils;
import org.camunda.bpm.engine.BadUserRequestException;
import org.camunda.bpm.engine.IdentityService;
import org.camunda.bpm.engine.OptimisticLockingException;
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.ProcessEngineConfiguration;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.ProcessEngines;
import org.camunda.bpm.engine.authorization.Authorization;
import org.camunda.bpm.engine.exception.NullValueException;
import org.camunda.bpm.engine.identity.Group;
import org.camunda.bpm.engine.identity.Picture;
import org.camunda.bpm.engine.identity.Tenant;
import org.camunda.bpm.engine.identity.User;
import org.camunda.bpm.engine.impl.identity.Account;
import org.camunda.bpm.engine.impl.identity.Authentication;
import org.camunda.bpm.engine.impl.util.ClockUtil;
import org.camunda.bpm.engine.test.ProcessEngineRule;
import org.camunda.bpm.engine.test.util.ProvidedProcessEngineRule;
import org.camunda.commons.testing.ProcessEngineLoggingRule;
import org.camunda.commons.testing.WatchLogger;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
/**
* @author Frederik Heremans
*/
public class IdentityServiceTest {
private final String INVALID_ID_MESSAGE = "%s has an invalid id: '%s' is not a valid resource identifier.";
private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
private static final String INDENTITY_LOGGER = "org.camunda.bpm.engine.identity";
@Rule
public ProcessEngineRule engineRule = new ProvidedProcessEngineRule();
@Rule
public ProcessEngineLoggingRule loggingRule = new ProcessEngineLoggingRule();
protected IdentityService identityService;
protected ProcessEngine processEngine;
@Before
public void init() {
identityService = engineRule.getIdentityService();
}
@After
public void cleanUp() {
for (User user : identityService.createUserQuery().list()) {
identityService.deleteUser(user.getId());
}
for (Group group : identityService.createGroupQuery().list()) {
identityService.deleteGroup(group.getId());
}
ClockUtil.setCurrentTime(new Date());
if (processEngine != null) {
for (User user : processEngine.getIdentityService().createUserQuery().list()) {
processEngine.getIdentityService().deleteUser(user.getId());
}
for (Group group : processEngine.getIdentityService().createGroupQuery().list()) {
processEngine.getIdentityService().deleteGroup(group.getId());
}
for (Tenant tenant : processEngine.getIdentityService().createTenantQuery().list()) {
processEngine.getIdentityService().deleteTenant(tenant.getId());
}
for (Authorization authorization : processEngine.getAuthorizationService().createAuthorizationQuery().list()) {
processEngine.getAuthorizationService().deleteAuthorization(authorization.getId());
}
processEngine.close();
ProcessEngines.unregister(processEngine);
processEngine = null;
}
}
@Test
public void testIsReadOnly() {
assertFalse(identityService.isReadOnly());
}
@Test
public void testUserInfo() {
User user = identityService.newUser("testuser");
identityService.saveUser(user);
identityService.setUserInfo("testuser", "myinfo", "myvalue");
assertEquals("myvalue", identityService.getUserInfo("testuser", "myinfo"));
identityService.setUserInfo("testuser", "myinfo", "myvalue2");
assertEquals("myvalue2", identityService.getUserInfo("testuser", "myinfo"));
identityService.deleteUserInfo("testuser", "myinfo");
assertNull(identityService.getUserInfo("testuser", "myinfo"));
identityService.deleteUser(user.getId());
}
@Test
public void testUserAccount() {
User user = identityService.newUser("testuser");
identityService.saveUser(user);
identityService.setUserAccount("testuser", "123", "google", "mygoogleusername", "mygooglepwd", null);
Account googleAccount = identityService.getUserAccount("testuser", "123", "google");
assertEquals("google", googleAccount.getName());
assertEquals("mygoogleusername", googleAccount.getUsername());
assertEquals("mygooglepwd", googleAccount.getPassword());
identityService.setUserAccount("testuser", "123", "google", "mygoogleusername2", "mygooglepwd2", null);
googleAccount = identityService.getUserAccount("testuser", "123", "google");
assertEquals("google", googleAccount.getName());
assertEquals("mygoogleusername2", googleAccount.getUsername());
assertEquals("mygooglepwd2", googleAccount.getPassword());
identityService.setUserAccount("testuser", "123", "alfresco", "myalfrescousername", "myalfrescopwd", null);
identityService.setUserInfo("testuser", "myinfo", "myvalue");
identityService.setUserInfo("testuser", "myinfo2", "myvalue2");
List<String> expectedUserAccountNames = new ArrayList<String>();
expectedUserAccountNames.add("google");
expectedUserAccountNames.add("alfresco");
List<String> userAccountNames = identityService.getUserAccountNames("testuser");
assertListElementsMatch(expectedUserAccountNames, userAccountNames);
identityService.deleteUserAccount("testuser", "google");
expectedUserAccountNames.remove("google");
userAccountNames = identityService.getUserAccountNames("testuser");
assertListElementsMatch(expectedUserAccountNames, userAccountNames);
identityService.deleteUser(user.getId());
}
private void assertListElementsMatch(List<String> list1, List<String> list2) {
if (list1 != null) {
assertNotNull(list2);
assertEquals(list1.size(), list2.size());
for (String value : list1) {
assertTrue(list2.contains(value));
}
} else {
assertNull(list2);
}
}
@Test
public void testUserAccountDetails() {
User user = identityService.newUser("testuser");
identityService.saveUser(user);
Map<String, String> accountDetails = new HashMap<String, String>();
accountDetails.put("server", "localhost");
accountDetails.put("port", "35");
identityService.setUserAccount("testuser", "123", "google", "mygoogleusername", "mygooglepwd", accountDetails);
Account googleAccount = identityService.getUserAccount("testuser", "123", "google");
assertEquals(accountDetails, googleAccount.getDetails());
identityService.deleteUser(user.getId());
}
@Test
public void testCreateExistingUser() {
User user = identityService.newUser("testuser");
identityService.saveUser(user);
User secondUser = identityService.newUser("testuser");
try {
identityService.saveUser(secondUser);
fail("BadUserRequestException is expected");
} catch (Exception ex) {
if (!(ex instanceof BadUserRequestException)) {
fail("BadUserRequestException is expected, but another exception was received: " + ex);
}
assertEquals("The user already exists", ex.getMessage());
}
}
@Test
public void testUpdateUser() {
// First, create a new user
User user = identityService.newUser("johndoe");
user.setFirstName("John");
user.setLastName("Doe");
user.setEmail("johndoe@alfresco.com");
user.setPassword("s3cret");
identityService.saveUser(user);
// Fetch and update the user
user = identityService.createUserQuery().userId("johndoe").singleResult();
user.setEmail("updated@alfresco.com");
user.setFirstName("Jane");
user.setLastName("Donnel");
identityService.saveUser(user);
user = identityService.createUserQuery().userId("johndoe").singleResult();
assertEquals("Jane", user.getFirstName());
assertEquals("Donnel", user.getLastName());
assertEquals("updated@alfresco.com", user.getEmail());
assertTrue(identityService.checkPassword("johndoe", "s3cret"));
identityService.deleteUser(user.getId());
}
@Test
public void testUserPicture() {
// First, create a new user
User user = identityService.newUser("johndoe");
identityService.saveUser(user);
String userId = user.getId();
Picture picture = new Picture("niceface".getBytes(), "image/string");
identityService.setUserPicture(userId, picture);
picture = identityService.getUserPicture(userId);
// Fetch and update the user
user = identityService.createUserQuery().userId("johndoe").singleResult();
assertTrue("byte arrays differ", Arrays.equals("niceface".getBytes(), picture.getBytes()));
assertEquals("image/string", picture.getMimeType());
identityService.deleteUserPicture("johndoe");
// this is ignored
identityService.deleteUserPicture("someone-else-we-dont-know");
// picture does not exist
picture = identityService.getUserPicture("johndoe");
assertNull(picture);
// add new picture
picture = new Picture("niceface".getBytes(), "image/string");
identityService.setUserPicture(userId, picture);
// makes the picture go away
identityService.deleteUser(user.getId());
}
@Test
public void testCreateExistingGroup() {
Group group = identityService.newGroup("greatGroup");
identityService.saveGroup(group);
Group secondGroup = identityService.newGroup("greatGroup");
try {
identityService.saveGroup(secondGroup);
fail("BadUserRequestException is expected");
} catch (Exception ex) {
if (!(ex instanceof BadUserRequestException)) {
fail("BadUserRequestException is expected, but another exception was received: " + ex);
}
assertEquals("The group already exists", ex.getMessage());
}
}
@Test
public void testUpdateGroup() {
Group group = identityService.newGroup("sales");
group.setName("Sales");
identityService.saveGroup(group);
group = identityService.createGroupQuery().groupId("sales").singleResult();
group.setName("Updated");
identityService.saveGroup(group);
group = identityService.createGroupQuery().groupId("sales").singleResult();
assertEquals("Updated", group.getName());
identityService.deleteGroup(group.getId());
}
@Test
public void findUserByUnexistingId() {
User user = identityService.createUserQuery().userId("unexistinguser").singleResult();
assertNull(user);
}
@Test
public void findGroupByUnexistingId() {
Group group = identityService.createGroupQuery().groupId("unexistinggroup").singleResult();
assertNull(group);
}
@Test
public void testCreateMembershipUnexistingGroup() {
User johndoe = identityService.newUser("johndoe");
identityService.saveUser(johndoe);
// when/then
assertThatThrownBy(() -> identityService.createMembership(johndoe.getId(), "unexistinggroup"))
.isInstanceOf(NullValueException.class)
.hasMessageContaining("No group found with id 'unexistinggroup'.: group is null");
}
@Test
public void testCreateMembershipUnexistingUser() {
Group sales = identityService.newGroup("sales");
identityService.saveGroup(sales);
// when/then
assertThatThrownBy(() -> identityService.createMembership("unexistinguser", sales.getId()))
.isInstanceOf(NullValueException.class)
.hasMessageContaining("No user found with id 'unexistinguser'.: user is null");
}
@Test
public void testCreateMembershipAlreadyExisting() {
Group sales = identityService.newGroup("sales");
identityService.saveGroup(sales);
User johndoe = identityService.newUser("johndoe");
identityService.saveUser(johndoe);
// Create the membership
identityService.createMembership(johndoe.getId(), sales.getId());
// when/then
assertThatThrownBy(() -> identityService.createMembership(johndoe.getId(), sales.getId()))
.isInstanceOf(ProcessEngineException.class);
}
@Test
public void testSaveGroupNullArgument() {
// when/then
assertThatThrownBy(() -> identityService.saveGroup(null))
.isInstanceOf(ProcessEngineException.class)
.hasMessageContaining("group is null");
}
@Test
public void testSaveUserNullArgument() {
// when/then
assertThatThrownBy(() -> identityService.saveUser(null))
.isInstanceOf(ProcessEngineException.class)
.hasMessageContaining("user is null");
}
@Test
public void testFindGroupByIdNullArgument() {
// when/then
assertThatThrownBy(() -> identityService.createGroupQuery().groupId(null).singleResult())
.isInstanceOf(ProcessEngineException.class)
.hasMessageContaining("id is null");
}
@Test
public void testCreateMembershipNullUserArgument() {
// when/then
assertThatThrownBy(() -> identityService.createMembership(null, "group"))
.isInstanceOf(ProcessEngineException.class)
.hasMessageContaining("userId is null");
}
@Test
public void testCreateMembershipNullGroupArgument() {
// when/then
assertThatThrownBy(() -> identityService.createMembership("userId", null))
.isInstanceOf(ProcessEngineException.class)
.hasMessageContaining("groupId is null");
}
@Test
public void testFindGroupsByUserIdNullArguments() {
// when/then
assertThatThrownBy(() -> identityService.createGroupQuery().groupMember(null).singleResult())
.isInstanceOf(ProcessEngineException.class)
.hasMessageContaining("userId is null");
}
@Test
public void testFindUsersByGroupUnexistingGroup() {
List<User> users = identityService.createUserQuery().memberOfGroup("unexistinggroup").list();
assertNotNull(users);
assertTrue(users.isEmpty());
}
@Test
public void testDeleteGroupNullArguments() {
// when/then
assertThatThrownBy(() -> identityService.deleteGroup(null))
.isInstanceOf(ProcessEngineException.class)
.hasMessageContaining("groupId is null");
}
@Test
public void testDeleteMembership() {
Group sales = identityService.newGroup("sales");
identityService.saveGroup(sales);
User johndoe = identityService.newUser("johndoe");
identityService.saveUser(johndoe);
// Add membership
identityService.createMembership(johndoe.getId(), sales.getId());
List<Group> groups = identityService.createGroupQuery().groupMember(johndoe.getId()).list();
assertTrue(groups.size() == 1);
assertEquals("sales", groups.get(0).getId());
// Delete the membership and check members of sales group
identityService.deleteMembership(johndoe.getId(), sales.getId());
groups = identityService.createGroupQuery().groupMember(johndoe.getId()).list();
assertTrue(groups.size() == 0);
identityService.deleteGroup("sales");
identityService.deleteUser("johndoe");
}
@Test
public void testDeleteMembershipWhenUserIsNoMember() {
Group sales = identityService.newGroup("sales");
identityService.saveGroup(sales);
User johndoe = identityService.newUser("johndoe");
identityService.saveUser(johndoe);
// Delete the membership when the user is no member
identityService.deleteMembership(johndoe.getId(), sales.getId());
identityService.deleteGroup("sales");
identityService.deleteUser("johndoe");
}
@Test
public void testDeleteMembershipUnexistingGroup() {
User johndoe = identityService.newUser("johndoe");
identityService.saveUser(johndoe);
// No exception should be thrown when group doesn't exist
identityService.deleteMembership(johndoe.getId(), "unexistinggroup");
identityService.deleteUser(johndoe.getId());
}
@Test
public void testDeleteMembershipUnexistingUser() {
Group sales = identityService.newGroup("sales");
identityService.saveGroup(sales);
// No exception should be thrown when user doesn't exist
identityService.deleteMembership("unexistinguser", sales.getId());
identityService.deleteGroup(sales.getId());
}
@Test
public void testDeleteMemberschipNullUserArgument() {
// when/then
assertThatThrownBy(() -> identityService.deleteMembership(null, "group"))
.isInstanceOf(ProcessEngineException.class)
.hasMessageContaining("userId is null");
}
@Test
public void testDeleteMemberschipNullGroupArgument() {
// when/then
assertThatThrownBy(() -> identityService.deleteMembership("user", null))
.isInstanceOf(ProcessEngineException.class)
.hasMessageContaining("groupId is null");
}
@Test
public void testDeleteUserNullArguments() {
// when/then
assertThatThrownBy(() -> identityService.deleteUser(null))
.isInstanceOf(ProcessEngineException.class)
.hasMessageContaining("userId is null");
}
@Test
public void testDeleteUserUnexistingUserId() {
// No exception should be thrown. Deleting an unexisting user should
// be ignored silently
identityService.deleteUser("unexistinguser");
}
@Test
public void testCheckPassword() {
// store user with password
User user = identityService.newUser("secureUser");
user.setPassword("s3cret");
identityService.saveUser(user);
assertTrue(identityService.checkPassword(user.getId(), "s3cret"));
assertFalse(identityService.checkPassword(user.getId(), "wrong"));
identityService.deleteUser(user.getId());
}
@Test
public void testUpdatePassword() {
// store user with password
User user = identityService.newUser("secureUser");
user.setPassword("s3cret");
identityService.saveUser(user);
assertTrue(identityService.checkPassword(user.getId(), "s3cret"));
user.setPassword("new-password");
identityService.saveUser(user);
assertTrue(identityService.checkPassword(user.getId(), "new-password"));
identityService.deleteUser(user.getId());
}
@Test
public void testCheckPasswordNullSafe() {
assertFalse(identityService.checkPassword("userId", null));
assertFalse(identityService.checkPassword(null, "passwd"));
assertFalse(identityService.checkPassword(null, null));
}
@Test
public void testUserOptimisticLockingException() {
User user = identityService.newUser("kermit");
identityService.saveUser(user);
User user1 = identityService.createUserQuery().singleResult();
User user2 = identityService.createUserQuery().singleResult();
user1.setFirstName("name one");
identityService.saveUser(user1);
user2.setFirstName("name two");
// when/then
assertThatThrownBy(() -> identityService.saveUser(user2))
.isInstanceOf(OptimisticLockingException.class);
}
@Test
public void testGroupOptimisticLockingException() {
Group group = identityService.newGroup("group");
identityService.saveGroup(group);
Group group1 = identityService.createGroupQuery().singleResult();
Group group2 = identityService.createGroupQuery().singleResult();
group1.setName("name one");
identityService.saveGroup(group1);
group2.setName("name two");
// when/then
assertThatThrownBy(() -> identityService.saveGroup(group2))
.isInstanceOf(OptimisticLockingException.class);
}
@Test
public void testSaveUserWithGenericResourceId() {
processEngine = ProcessEngineConfiguration
.createProcessEngineConfigurationFromResource("org/camunda/bpm/engine/test/api/identity/generic.resource.id.whitelist.camunda.cfg.xml")
.buildProcessEngine();
User user = processEngine.getIdentityService().newUser("*");
// when/then
assertThatThrownBy(() -> processEngine.getIdentityService().saveUser(user))
.isInstanceOf(ProcessEngineException.class)
.hasMessageContaining("has an invalid id: id cannot be *. * is a reserved identifier.");
}
@Test
public void testSaveGroupWithGenericResourceId() {
processEngine = ProcessEngineConfiguration
.createProcessEngineConfigurationFromResource("org/camunda/bpm/engine/test/api/identity/generic.resource.id.whitelist.camunda.cfg.xml")
.buildProcessEngine();
Group group = processEngine.getIdentityService().newGroup("*");
// when/then
assertThatThrownBy(() -> processEngine.getIdentityService().saveGroup(group))
.isInstanceOf(ProcessEngineException.class)
.hasMessageContaining("has an invalid id: id cannot be *. * is a reserved identifier.");
}
@Test
public void testSetAuthenticatedIdToGenericId() {
// when/then
assertThatThrownBy(() -> identityService.setAuthenticatedUserId("*"))
.isInstanceOf(ProcessEngineException.class)
.hasMessageContaining("Invalid user id provided: id cannot be *. * is a reserved identifier.");
}
@Test
public void testSetAuthenticationUserIdToGenericId() {
// when/then
assertThatThrownBy(() -> identityService.setAuthentication("aUserId", Arrays.asList("*")))
.isInstanceOf(ProcessEngineException.class)
.hasMessageContaining("invalid group id provided: id cannot be *. * is a reserved identifier.");
}
@Test
public void testSetAuthenticatedTenantIdToGenericId() {
// when/then
assertThatThrownBy(() -> identityService.setAuthentication(null, null, Arrays.asList("*")))
.isInstanceOf(ProcessEngineException.class)
.hasMessageContaining("invalid tenant id provided: id cannot be *. * is a reserved identifier.");
}
@Test
public void testSetAuthenticatedUserId() {
identityService.setAuthenticatedUserId("john");
Authentication currentAuthentication = identityService.getCurrentAuthentication();
assertNotNull(currentAuthentication);
assertEquals("john", currentAuthentication.getUserId());
assertNull(currentAuthentication.getGroupIds());
assertNull(currentAuthentication.getTenantIds());
}
@Test
public void testSetAuthenticatedUserAndGroups() {
List<String> groups = Arrays.asList("sales", "development");
identityService.setAuthentication("john", groups);
Authentication currentAuthentication = identityService.getCurrentAuthentication();
assertNotNull(currentAuthentication);
assertEquals("john", currentAuthentication.getUserId());
assertEquals(groups, currentAuthentication.getGroupIds());
assertNull(currentAuthentication.getTenantIds());
}
@Test
public void testSetAuthenticatedUserGroupsAndTenants() {
List<String> groups = Arrays.asList("sales", "development");
List<String> tenants = Arrays.asList("tenant1", "tenant2");
identityService.setAuthentication("john", groups, tenants);
Authentication currentAuthentication = identityService.getCurrentAuthentication();
assertNotNull(currentAuthentication);
assertEquals("john", currentAuthentication.getUserId());
assertEquals(groups, currentAuthentication.getGroupIds());
assertEquals(tenants, currentAuthentication.getTenantIds());
}
@Test
public void testAuthentication() {
User user = identityService.newUser("johndoe");
user.setPassword("xxx");
identityService.saveUser(user);
assertTrue(identityService.checkPassword("johndoe", "xxx"));
assertFalse(identityService.checkPassword("johndoe", "invalid pwd"));
identityService.deleteUser("johndoe");
}
@Test
@WatchLogger(loggerNames = {INDENTITY_LOGGER}, level = "INFO")
public void testUsuccessfulAttemptsResultInBlockedUser() throws ParseException {
// given
User user = identityService.newUser("johndoe");
user.setPassword("xxx");
identityService.saveUser(user);
Date now = sdf.parse("2000-01-24T13:00:00");
ClockUtil.setCurrentTime(now);
// when
for (int i = 0; i < 11; i++) {
assertFalse(identityService.checkPassword("johndoe", "invalid pwd"));
now = DateUtils.addMinutes(now, 1);
ClockUtil.setCurrentTime(now);
}
// then
assertThat(loggingRule.getFilteredLog(INDENTITY_LOGGER, "The user with id 'johndoe' is permanently locked.").size()).isEqualTo(1);
}
@Test
public void testSuccessfulLoginAfterFailureAndDelay() {
User user = identityService.newUser("johndoe");
user.setPassword("xxx");
identityService.saveUser(user);
Date now = ClockUtil.getCurrentTime();
ClockUtil.setCurrentTime(now);
assertFalse(identityService.checkPassword("johndoe", "invalid pwd"));
ClockUtil.setCurrentTime(DateUtils.addSeconds(now, 30));
assertTrue(identityService.checkPassword("johndoe", "xxx"));
identityService.deleteUser("johndoe");
}
@Test
@WatchLogger(loggerNames = {INDENTITY_LOGGER}, level = "INFO")
public void testSuccessfulLoginAfterFailureWithoutDelay() {
// given
User user = identityService.newUser("johndoe");
user.setPassword("xxx");
identityService.saveUser(user);
Date now = ClockUtil.getCurrentTime();
ClockUtil.setCurrentTime(now);
assertFalse(identityService.checkPassword("johndoe", "invalid pwd"));
assertFalse(identityService.checkPassword("johndoe", "xxx"));
// assume
assertThat(loggingRule.getFilteredLog(INDENTITY_LOGGER, "The user with id 'johndoe' is locked.").size()).isEqualTo(1);
// when
ClockUtil.setCurrentTime(DateUtils.addSeconds(now, 30));
boolean checkPassword = identityService.checkPassword("johndoe", "xxx");
// then
assertTrue(checkPassword);
}
@Test
@WatchLogger(loggerNames = {INDENTITY_LOGGER}, level = "INFO")
public void testUnsuccessfulLoginAfterFailureWithoutDelay() {
// given
User user = identityService.newUser("johndoe");
user.setPassword("xxx");
identityService.saveUser(user);
Date now = ClockUtil.getCurrentTime();
ClockUtil.setCurrentTime(now);
assertFalse(identityService.checkPassword("johndoe", "invalid pwd"));
ClockUtil.setCurrentTime(DateUtils.addSeconds(now, 1));
Date expectedLockExpitation = DateUtils.addSeconds(now, 3);
// when try again before exprTime
assertFalse(identityService.checkPassword("johndoe", "invalid pwd"));
// then
assertThat(loggingRule.getFilteredLog(INDENTITY_LOGGER, "The lock will expire at " + expectedLockExpitation).size()).isEqualTo(1);
}
@Test
public void testFindGroupsByUserAndType() {
Group sales = identityService.newGroup("sales");
sales.setType("hierarchy");
identityService.saveGroup(sales);
Group development = identityService.newGroup("development");
development.setType("hierarchy");
identityService.saveGroup(development);
Group admin = identityService.newGroup("admin");
admin.setType("security-role");
identityService.saveGroup(admin);
Group user = identityService.newGroup("user");
user.setType("security-role");
identityService.saveGroup(user);
User johndoe = identityService.newUser("johndoe");
identityService.saveUser(johndoe);
User joesmoe = identityService.newUser("joesmoe");
identityService.saveUser(joesmoe);
User jackblack = identityService.newUser("jackblack");
identityService.saveUser(jackblack);
identityService.createMembership("johndoe", "sales");
identityService.createMembership("johndoe", "user");
identityService.createMembership("johndoe", "admin");
identityService.createMembership("joesmoe", "user");
List<Group> groups = identityService.createGroupQuery().groupMember("johndoe").groupType("security-role").list();
Set<String> groupIds = getGroupIds(groups);
Set<String> expectedGroupIds = new HashSet<String>();
expectedGroupIds.add("user");
expectedGroupIds.add("admin");
assertEquals(expectedGroupIds, groupIds);
groups = identityService.createGroupQuery().groupMember("joesmoe").groupType("security-role").list();
groupIds = getGroupIds(groups);
expectedGroupIds = new HashSet<String>();
expectedGroupIds.add("user");
assertEquals(expectedGroupIds, groupIds);
groups = identityService.createGroupQuery().groupMember("jackblack").groupType("security-role").list();
assertTrue(groups.isEmpty());
identityService.deleteGroup("sales");
identityService.deleteGroup("development");
identityService.deleteGroup("admin");
identityService.deleteGroup("user");
identityService.deleteUser("johndoe");
identityService.deleteUser("joesmoe");
identityService.deleteUser("jackblack");
}
@Test
public void testUser() {
User user = identityService.newUser("johndoe");
user.setFirstName("John");
user.setLastName("Doe");
user.setEmail("johndoe@alfresco.com");
identityService.saveUser(user);
user = identityService.createUserQuery().userId("johndoe").singleResult();
assertEquals("johndoe", user.getId());
assertEquals("John", user.getFirstName());
assertEquals("Doe", user.getLastName());
assertEquals("johndoe@alfresco.com", user.getEmail());
identityService.deleteUser("johndoe");
}
@Test
public void testGroup() {
Group group = identityService.newGroup("sales");
group.setName("Sales division");
identityService.saveGroup(group);
group = identityService.createGroupQuery().groupId("sales").singleResult();
assertEquals("sales", group.getId());
assertEquals("Sales division", group.getName());
identityService.deleteGroup("sales");
}
@Test
public void testMembership() {
Group sales = identityService.newGroup("sales");
identityService.saveGroup(sales);
Group development = identityService.newGroup("development");
identityService.saveGroup(development);
User johndoe = identityService.newUser("johndoe");
identityService.saveUser(johndoe);
User joesmoe = identityService.newUser("joesmoe");
identityService.saveUser(joesmoe);
User jackblack = identityService.newUser("jackblack");
identityService.saveUser(jackblack);
identityService.createMembership("johndoe", "sales");
identityService.createMembership("joesmoe", "sales");
identityService.createMembership("joesmoe", "development");
identityService.createMembership("jackblack", "development");
List<Group> groups = identityService.createGroupQuery().groupMember("johndoe").list();
assertEquals(createStringSet("sales"), getGroupIds(groups));
groups = identityService.createGroupQuery().groupMember("joesmoe").list();
assertEquals(createStringSet("sales", "development"), getGroupIds(groups));
groups = identityService.createGroupQuery().groupMember("jackblack").list();
assertEquals(createStringSet("development"), getGroupIds(groups));
List<User> users = identityService.createUserQuery().memberOfGroup("sales").list();
assertEquals(createStringSet("johndoe", "joesmoe"), getUserIds(users));
users = identityService.createUserQuery().memberOfGroup("development").list();
assertEquals(createStringSet("joesmoe", "jackblack"), getUserIds(users));
identityService.deleteGroup("sales");
identityService.deleteGroup("development");
identityService.deleteUser("jackblack");
identityService.deleteUser("joesmoe");
identityService.deleteUser("johndoe");
}
@Test
public void testInvalidUserId() {
String invalidId = "john doe";
User user = identityService.newUser(invalidId);
try {
identityService.saveUser(user);
fail("Invalid user id exception expected!");
} catch (ProcessEngineException ex) {
assertEquals(String.format(INVALID_ID_MESSAGE, "User", invalidId), ex.getMessage());
}
}
@Test
public void testInvalidUserIdOnSave() {
String invalidId = "john doe";
try {
User updatedUser = identityService.newUser("john");
updatedUser.setId(invalidId);
identityService.saveUser(updatedUser);
fail("Invalid user id exception expected!");
} catch (ProcessEngineException ex) {
assertEquals(String.format(INVALID_ID_MESSAGE, "User", invalidId), ex.getMessage());
}
}
@Test
public void testInvalidGroupId() {
String invalidId = "john's group";
Group group = identityService.newGroup(invalidId);
try {
identityService.saveGroup(group);
fail("Invalid group id exception expected!");
} catch (ProcessEngineException ex) {
assertEquals(String.format(INVALID_ID_MESSAGE, "Group", invalidId), ex.getMessage());
}
}
@Test
public void testInvalidGroupIdOnSave() {
String invalidId = "john's group";
try {
Group updatedGroup = identityService.newGroup("group");
updatedGroup.setId(invalidId);
identityService.saveGroup(updatedGroup);
fail("Invalid group id exception expected!");
} catch (ProcessEngineException ex) {
assertEquals(String.format(INVALID_ID_MESSAGE, "Group", invalidId), ex.getMessage());
}
}
@Test
public void testCamundaAdminId() {
String camundaAdminID = "camunda-admin";
try {
identityService.newUser(camundaAdminID);
identityService.newGroup(camundaAdminID);
identityService.newTenant(camundaAdminID);
} catch (ProcessEngineException ex) {
fail(camundaAdminID + " should be a valid id.");
}
}
@Test
public void testCustomResourceWhitelist() {
processEngine = ProcessEngineConfiguration
.createProcessEngineConfigurationFromResource("org/camunda/bpm/engine/test/api/identity/custom.whitelist.camunda.cfg.xml")
.buildProcessEngine();
IdentityService identityService = processEngine.getIdentityService();
String invalidUserId = "johnDoe";
String invalidGroupId = "johnsGroup";
String invalidTenantId = "johnsTenant";
User user = identityService.newUser(invalidUserId);
try {
identityService.saveUser(user);
fail("Invalid user id exception expected!");
} catch (ProcessEngineException ex) {
assertEquals(String.format(INVALID_ID_MESSAGE, "User", invalidUserId), ex.getMessage());
}
Group johnsGroup = identityService.newGroup("johnsGroup");
try {
identityService.saveGroup(johnsGroup);
fail("Invalid group id exception expected!");
} catch (ProcessEngineException ex) {
assertEquals(String.format(INVALID_ID_MESSAGE, "Group", invalidGroupId), ex.getMessage());
}
Tenant tenant = identityService.newTenant(invalidTenantId);
try {
identityService.saveTenant(tenant);
fail("Invalid tenant id exception expected!");
} catch (ProcessEngineException ex) {
assertEquals(String.format(INVALID_ID_MESSAGE, "Tenant", invalidTenantId), ex.getMessage());
}
}
@Test
public void testSeparateResourceWhitelistPatterns() {
processEngine = ProcessEngineConfiguration
.createProcessEngineConfigurationFromResource("org/camunda/bpm/engine/test/api/identity/custom.resource.whitelist.camunda.cfg.xml")
.buildProcessEngine();
IdentityService identityService = processEngine.getIdentityService();
String invalidUserId = "12345";
String invalidGroupId = "johnsGroup";
String invalidTenantId = "!@##$%";
User user = identityService.newUser(invalidUserId);
// pattern: [a-zA-Z]+
try {
identityService.saveUser(user);
fail("Invalid user id exception expected!");
} catch (ProcessEngineException ex) {
assertEquals(String.format(INVALID_ID_MESSAGE, "User", invalidUserId), ex.getMessage());
}
Group group = identityService.newGroup(invalidGroupId);
// pattern: \d+
try {
identityService.saveGroup(group);
fail("Invalid group id exception expected!");
} catch (ProcessEngineException ex) {
assertEquals(String.format(INVALID_ID_MESSAGE, "Group", invalidGroupId), ex.getMessage());
}
Tenant tenant = identityService.newTenant(invalidTenantId);
// new general pattern (used for tenant whitelisting): [a-zA-Z0-9]+
try {
identityService.saveTenant(tenant);
fail("Invalid tenant id exception expected!");
} catch (ProcessEngineException ex) {
assertEquals(String.format(INVALID_ID_MESSAGE, "Tenant", invalidTenantId), ex.getMessage());
}
}
@Test
public void shouldCreateUserWithEmptyUserId() {
User user = identityService.newUser("");
assertThat(user).isNotNull();
}
private Object createStringSet(String... strings) {
Set<String> stringSet = new HashSet<String>();
for (String string : strings) {
stringSet.add(string);
}
return stringSet;
}
protected Set<String> getGroupIds(List<Group> groups) {
Set<String> groupIds = new HashSet<String>();
for (Group group : groups) {
groupIds.add(group.getId());
}
return groupIds;
}
protected Set<String> getUserIds(List<User> users) {
Set<String> userIds = new HashSet<String>();
for (User user : users) {
userIds.add(user.getId());
}
return userIds;
}
}
| |
/******************************************************************
* File: RequestProcessor.java
* Created by: Dave Reynolds
* Created on: 21 Jan 2013
*
* (c) Copyright 2013, Epimorphics Limited
*
* 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.epimorphics.registry.webapi;
import static com.epimorphics.webapi.marshalling.RDFXMLMarshaller.FULL_MIME_RDFXML;
import static com.epimorphics.webapi.marshalling.RDFXMLMarshaller.MIME_RDFXML;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.StreamingOutput;
import javax.ws.rs.core.UriInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.epimorphics.registry.commands.CommandUpdate;
import com.epimorphics.registry.core.Command;
import com.epimorphics.registry.core.Command.Operation;
import com.epimorphics.registry.core.ForwardingRecord;
import com.epimorphics.registry.core.ForwardingRecord.Type;
import com.epimorphics.registry.core.ForwardingService;
import com.epimorphics.registry.core.MatchResult;
import com.epimorphics.registry.core.Registry;
import com.epimorphics.registry.security.UserInfo;
import com.epimorphics.registry.util.JSONLDSupport;
import com.epimorphics.registry.util.PATCH;
import com.epimorphics.registry.util.UiForm;
import com.epimorphics.server.core.ServiceConfig;
import com.epimorphics.server.templates.VelocityRender;
import com.epimorphics.server.webapi.BaseEndpoint;
import com.epimorphics.server.webapi.WebApiException;
import com.epimorphics.util.NameUtils;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.util.FileManager;
import com.hp.hpl.jena.util.FileUtils;
import com.sun.jersey.api.NotFoundException;
import com.sun.jersey.multipart.FormDataBodyPart;
import com.sun.jersey.multipart.FormDataMultiPart;
import com.sun.jersey.multipart.FormDataParam;
/**
* Filter all requests as possible register API requests.
* @author <a href="mailto:dave@epimorphics.com">Dave Reynolds</a>
*/
@Path("{path: .*}")
public class RequestProcessor extends BaseEndpoint {
static final Logger log = LoggerFactory.getLogger( RequestProcessor.class );
public static final String FULL_MIME_TURTLE = "text/turtle; charset=UTF-8";
public static final String FORWARDED_FOR_HEADER = "X-Forwarded-For";
public static final String CONTENT_DISPOSITION_HEADER = "Content-Disposition";
public static final String CONTENT_DISPOSITION_FMT = "attachment; filename=\"%s.%s\"";
public static final String VARY_HEADER = "Vary";
public static final String UI_PATH = "ui";
private static final String SYSTEM_QUERY = "system/query";
@GET
@Produces("text/html")
public Response htmlrender() {
String path = uriInfo.getPath();
if (path.startsWith(UI_PATH) ) {
String template = path.substring(UI_PATH.length()+1) + ".vm";
try {
return render(template, uriInfo, context, request);
} catch (ResourceNotFoundException e) {
// Will chain through to file serving
throw new NotFoundException();
}
} else if (path.startsWith(SYSTEM_QUERY) || path.equals("favicon.ico")) {
// Pass to the generic velocity handler, which in turn falls through to file serving
throw new NotFoundException();
}
PassThroughResult result = checkForPassThrough();
if (result != null && result.isDone()) {
return result.getResponse();
}
MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters();
if (parameters.containsKey(Parameters.FORMAT)) {
String mime = MIME_RDFXML;
String extension = "rdf";
String format = parameters.getFirst(Parameters.FORMAT);
if (format.equals("ttl")) {
mime = FULL_MIME_TURTLE;
extension = "ttl";
} else if (format.equals("jsonld")) {
mime = JSONLDSupport.FULL_MIME_JSONLD;
extension = "json";
}
return readAsRDF(result, mime, extension);
} if (parameters.containsKey(Parameters.ANNOTATION)) {
return readAsRDF(result, FULL_MIME_TURTLE, "ttl");
} else {
return render("main.vm", uriInfo, context, request);
}
}
private Response readAsRDF(PassThroughResult ptr, String mime, String ext) {
Response response = doRead(ptr);
Object location = response.getMetadata().getFirst(HttpHeaders.LOCATION);
ResponseBuilder builder = Response.ok().type(mime).entity(response.getEntity());
if (location != null) {
String fname = NameUtils.lastSegment(location.toString());
builder.header(CONTENT_DISPOSITION_HEADER, String.format(CONTENT_DISPOSITION_FMT, fname, ext));
}
builder = builder.header(VARY_HEADER, "Accept"); // Help proxies cope with conneg
return builder.build();
}
public static Response render(String template, UriInfo uriInfo, ServletContext context, HttpServletRequest request, Object...params) {
String language = request.getLocale().getLanguage();
if (language.isEmpty()) {
language = "en";
}
Object[] fullParams = new Object[params.length + 10];
int i = 0;
while (i < params.length) {
fullParams[i] = params[i];
i++;
}
fullParams[i++] = "registry";
fullParams[i++] = Registry.get();
fullParams[i++] = "subject";
fullParams[i++] = SecurityUtils.getSubject();
fullParams[i++] = "requestor";
fullParams[i++] = getRequestor(request);
fullParams[i++] = "request";
fullParams[i++] = request;
fullParams[i++] = "language";
fullParams[i++] = language;
VelocityRender velocity = ServiceConfig.get().getServiceAs(Registry.VELOCITY_SERVICE, VelocityRender.class);
StreamingOutput out = velocity.render(template, uriInfo.getPath(), context, uriInfo.getQueryParameters(), fullParams);
ResponseBuilder builder = Response.ok().type("text/html");
if (SecurityUtils.getSubject().isAuthenticated()) {
builder.header("Cache-control", "no-cache");
}
return builder.entity(out).build();
}
public static String getRequestor(HttpServletRequest request) {
try {
UserInfo user = (UserInfo) SecurityUtils.getSubject().getPrincipal();
if (user != null) {
return NameUtils.encodeSafeName(user.toString());
}
} catch (UnavailableSecurityManagerException e) {
// shiro not running, presumably test mode, fall through to default requestor based on IP
}
if (request.getHeader(FORWARDED_FOR_HEADER) != null) {
return request.getHeader(FORWARDED_FOR_HEADER);
}
return request.getRemoteAddr();
}
@GET
@Produces({FULL_MIME_TURTLE, FULL_MIME_RDFXML, JSONLDSupport.FULL_MIME_JSONLD, MediaType.APPLICATION_JSON})
public Response read() {
PassThroughResult result = checkForPassThrough();
if (result != null && result.isDone()) {
return result.getResponse();
} else {
return doRead(result);
}
}
@GET
public Response defaultRead() {
// Default to text/html case which in turn will default to file serving for image files etc
return htmlrender();
}
private Response doRead(PassThroughResult ptr) {
String path = uriInfo.getPath();
if (path.startsWith(SYSTEM_QUERY) || path.startsWith(UI_PATH) ) {
// Will chain through to file serving/fuseki
throw new NotFoundException();
}
Command command = null;
if (uriInfo.getQueryParameters().containsKey(Parameters.QUERY)) {
command = makeCommand( Operation.Search );
} else {
command = makeCommand( Operation.Read );
if (ptr != null) {
command.setDelegation(ptr.getRecord());
}
}
return command.execute();
}
private PassThroughResult checkForPassThrough() {
String path = uriInfo.getPath();
ForwardingService fs = Registry.get().getForwarder();
if (fs != null) {
MatchResult match = fs.match(path);
if (match != null) {
ForwardingRecord fr = match.getRecord();
PassThroughResult result = new PassThroughResult(fr);
if (fr.getType() == Type.DELEGATE) {
// Delegation should bubble up to the read command
return result;
}
String forwardTo = fr.getTarget();
String remainder = match.getPathRemainder();
if (!remainder.isEmpty()) {
if (!forwardTo.endsWith("/")) {
forwardTo += "/";
}
forwardTo += remainder;
}
URI location = null;
try {
location = new URI(forwardTo);
} catch (Exception e) {
throw new WebApiException(Response.Status.INTERNAL_SERVER_ERROR, "Illegal URI registered at " + fr.getLocation() + " - " + fr.getTarget());
}
result.setResponse( Response.ok().status(fr.getForwardingCode()).location(location).build() );
return result;
}
}
return null;
}
private Command makeCommand(Operation op) {
Command c = Registry.get().make(op, uriInfo.getPath(), uriInfo.getQueryParameters());
c.setRequestor(getRequestor(request));
return c;
}
@POST
@Consumes({"text/plain"})
public Response validate(@Context HttpHeaders hh, InputStream body) {
MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters();
if ( parameters.get(Parameters.VALIDATE) != null ) {
if (body != null) {
for (String uri : FileManager.get().readWholeFileAsUTF8(body).split("\\s")) {
parameters.add(Parameters.VALIDATE, uri);
}
}
Command command = makeCommand(Operation.Validate);
return command.execute();
} else {
throw new WebApiException(Response.Status.BAD_REQUEST, "No operations supported on text/plain other than validate");
}
}
@POST
@Consumes({MIME_TURTLE, MIME_RDFXML, JSONLDSupport.MIME_JSONLD})
public Response register(@Context HttpHeaders hh, InputStream body) {
MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters();
Command command = null;
if ( parameters.get(Parameters.VALIDATE) != null ) {
return validate(hh , body);
} else if ( parameters.get(Parameters.TAG) != null ) {
// TODO to support tagging delegated regsiter would need a checkForPassThrough here
command = makeCommand(Operation.Tag);
} else if ( parameters.get(Parameters.STATUS_UPDATE) != null ) {
command = makeCommand(Operation.StatusUpdate);
} else if (body != null) {
command = makeCommand(Operation.Register);
setPayload(command, hh, body, true);
} else {
throw new WebApiException(Status.BAD_REQUEST, "Did not recognize request");
}
return command.execute();
}
private void setPayload(Command command, HttpHeaders hh, InputStream body, boolean isPOST) {
try {
Model model = getBodyModel(hh, body, isPOST);
if (model == null) {
throw new WebApiException(Status.BAD_REQUEST, "Did not recognize request");
}
command.setPayload( model );
} catch(Exception e) {
throw new WebApiException(Response.Status.BAD_REQUEST, "Payload failed to parse: " + e.getMessage());
}
}
@PUT
@Consumes({MIME_TURTLE, MIME_RDFXML, JSONLDSupport.MIME_JSONLD})
public Response update(@Context HttpHeaders hh, InputStream body) {
MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters();
Command command = null;
if ( parameters.get(Parameters.GRAPH) != null ) {
command = makeCommand( Operation.GraphRegister );
setPayload(command, hh, body, true);
} else if ( parameters.get(Parameters.ANNOTATION) != null ) {
command = makeCommand( Operation.Annotate );
setPayload(command, hh, body, true);
} else {
command = makeCommand( Operation.Update );
setPayload(command, hh, body, false);
}
return command.execute();
}
@DELETE
public Object delete() {
Command command = makeCommand( Operation.Delete );
return command.execute();
}
@PATCH
@Consumes({MIME_TURTLE, MIME_RDFXML, JSONLDSupport.MIME_JSONLD})
public Response updatePatch(@Context HttpHeaders hh, InputStream body) {
Command command = makeCommand( Operation.Update );
((CommandUpdate)command).setToPatch();
setPayload(command, hh, body, false);
return command.execute();
}
@POST
@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
public Response simpleForm(@Context HttpHeaders hh, MultivaluedMap<String, String> form) {
String action = form.getFirst("action");
if ("register-inline".equals(action)) {
String target = uriInfo.getPath();
target = Registry.get().getBaseURI() + (target.isEmpty() ? "/" : "/" + target + "/");
Resource r = UiForm.create(form, target);
// // TEMP debug
// System.out.println("Form created resource:");
// r.getModel().setNsPrefixes(Prefixes.get());
// r.getModel().write(System.out, "Turtle");
Command command = makeCommand( Operation.Register );
command.setPayload( r.getModel() );
return command.execute();
} else {
// Default is to invoke register, e.g. for status update processing
return register(hh, null);
}
}
@POST
public Response nullForm(@Context HttpHeaders hh, InputStream body) {
// Default is to invoke register, e.g. for status update processing
return register(hh, body);
}
@POST
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Response fileForm(@Context HttpHeaders hh, FormDataMultiPart multiPart,
// @FormDataParam("file") InputStream uploadedInputStream,
// @FormDataParam("file") FormDataContentDisposition fileDetail,
@FormDataParam("action") String action) {
List<FormDataBodyPart> fields = multiPart.getFields("file");
List<String> successfullyProcessed = new ArrayList<>();
int success = 0;
int failure = 0;
StringBuffer errorMessages = new StringBuffer();
for(FormDataBodyPart field : fields){
InputStream uploadedInputStream = field.getValueAs(InputStream.class);
String filename = field.getContentDisposition().getFileName();
log.debug("Multipart form invoked on file " + filename + " action=" + action);
if (filename == null) {
throw new WebApiException(Status.BAD_REQUEST, "No filename to upload");
}
Model payload = ModelFactory.createDefaultModel();
String base = baseURI(true);
if (filename.endsWith(".ttl")) {
payload.read(uploadedInputStream, base, FileUtils.langTurtle);
} else if (filename.endsWith(".jsonld") || filename.endsWith(".json")) {
payload = JSONLDSupport.readModel(base, uploadedInputStream);
} else {
payload.read(uploadedInputStream, base, FileUtils.langXML);
}
Command command = null;
if (action.equals("register")) {
command = makeCommand( Operation.Register );
} else if (action.equals("annotate")) {
command = makeCommand( Operation.Annotate );
}
if (command == null) {
throw new WebApiException(Response.Status.BAD_REQUEST, "Action " + action + " not recognized");
}
command.setPayload(payload);
try {
Response response = command.execute();
if (response.getStatus() >= 400) {
failure++;
errorMessages.append("<p>" + filename + " - " + response.getEntity() + "</p>");
} else {
success++;
successfullyProcessed.add(filename);
}
} catch (WebApiException e) {
failure++;
log.warn("Error processing uploaded file", e);
errorMessages.append("<p>" + filename + " - " + e.getResponse().getStatus() + " (" + e.getMessage() + ") </p>");
throw e;
} catch (Exception e) {
failure++;
log.warn("Error processing uploaded file", e);
errorMessages.append("<p>" + filename + " - internal error (" + e.getMessage() + ") </p>");
}
}
if (failure != 0) {
if (success > 0) {
errorMessages.append("<p>Other file were successfully processed: ");
for (String succeeded : successfullyProcessed) {
errorMessages.append(" " + succeeded);
}
errorMessages.append("</p>");
}
throw new WebApiException(Response.Status.BAD_REQUEST, errorMessages.toString());
}
if (success == 0) {
throw new WebApiException(Response.Status.BAD_REQUEST, "No file uploaded");
}
return Response.ok().build();
}
public Model getBodyModel(HttpHeaders hh, InputStream body, boolean isPOST) {
MediaType mediaType = hh.getMediaType();
if (mediaType == null) return null;
String mime = mediaType.getType() + "/" + mediaType.getSubtype(); // ignore parameters
if (mime.equals(JSONLDSupport.MIME_JSONLD)) {
return JSONLDSupport.readModel(baseURI(isPOST), body);
} else {
String lang = null;
if ( MIME_RDFXML.equals( mime ) ) {
lang = FileUtils.langXML;
} else if ( MIME_TURTLE.equals( mime ) ) {
lang = FileUtils.langTurtle;
} else {
return null;
}
Model m = ModelFactory.createDefaultModel();
m.read(body, baseURI(isPOST), lang);
return m;
}
}
/**
* Determine a suitable base URI to use for parsing RDF payloads.
* For POSTs the base is derived from the URL to which the post was made,
* for PUT/PATCH it is the parent of the target URL.
*/
public String baseURI(boolean isPOST) {
String base = Registry.get().getBaseURI();
String path = uriInfo.getPath();
if (!isPOST) {
if (path.contains("/")) {
path = NameUtils.splitBeforeLast(path, "/");
} else {
path = "";
}
}
if ( ! path.isEmpty()) {
base += "/" + path;
}
// log.debug("Base URI for payload parse: " + base + "/" );
return base + "/";
}
static class PassThroughResult {
Response response;
ForwardingRecord record;
public PassThroughResult(ForwardingRecord record) {
this.record = record;
}
public boolean isDone() {
return response != null;
}
public Response getResponse() {
return response;
}
public void setResponse(Response response) {
this.response = response;
}
public ForwardingRecord getRecord() {
return record;
}
}
}
| |
/**
* JBoss, Home of Professional Open Source
* Copyright Red Hat, Inc., and individual contributors.
*
* 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.jboss.aerogear.unifiedpush.service.impl;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.inject.Inject;
import org.apache.commons.lang3.StringUtils;
import org.jboss.aerogear.unifiedpush.api.Alias;
import org.jboss.aerogear.unifiedpush.api.AndroidVariant;
import org.jboss.aerogear.unifiedpush.api.Category;
import org.jboss.aerogear.unifiedpush.api.Installation;
import org.jboss.aerogear.unifiedpush.api.PushApplication;
import org.jboss.aerogear.unifiedpush.api.Variant;
import org.jboss.aerogear.unifiedpush.api.VariantType;
import org.jboss.aerogear.unifiedpush.dao.CategoryDao;
import org.jboss.aerogear.unifiedpush.dao.InstallationDao;
import org.jboss.aerogear.unifiedpush.dao.PushApplicationDao;
import org.jboss.aerogear.unifiedpush.dao.ResultsStream;
import org.jboss.aerogear.unifiedpush.service.AliasService;
import org.jboss.aerogear.unifiedpush.service.ClientInstallationService;
import org.jboss.aerogear.unifiedpush.service.VerificationService;
import org.jboss.aerogear.unifiedpush.service.util.FCMTopicManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* (Default) implementation of the {@code ClientInstallationService} interface.
* Delegates work to an injected DAO object.
*/
@Service
@Transactional
public class ClientInstallationServiceImpl implements ClientInstallationService {
private final Logger logger = LoggerFactory.getLogger(ClientInstallationServiceImpl.class);
@Inject
private InstallationDao installationDao;
@Inject
private CategoryDao categoryDao;
@Inject
private AliasService aliasService;
@Inject
private PushApplicationDao pushApplicationDao;
@Inject
private VerificationService verificationService;
@Override
public Variant associateInstallation(Installation installation, Variant currentVariant) {
if (installation.getAlias() == null) {
logger.warn("Unable to associate, installation alias is missing!");
return null;
}
Alias alias = aliasService.find(null, installation.getAlias());
if (alias == null) {
return null;
}
PushApplication application = pushApplicationDao
.findByPushApplicationID(alias.getPushApplicationId().toString());
if (application == null) {
logger.warn(String.format(
"Unable to find application for alias %s, this behaviour "
+ "might occur when application is deleted and orphans aliases exists. "
+ "Use DELETE /rest/alias/THE-ALIAS in order to remove orphans.",
StringUtils.isEmpty(alias.getEmail()) ? alias.getOther() : alias.getEmail()));
return null;
}
List<Variant> variants = application.getVariants();
for (Variant variant : variants) {
// Match variant type according to previous variant.
if (variant.getType().equals(currentVariant.getType())) {
installation.setVariant(variant);
updateInstallation(installation);
return variant;
}
}
// TODO - Make sure user is associated to a KC client.
// If not, associate to appropriate rules.
return null;
}
@Override
public void addInstallation(Variant variant, Installation entity) {
addInstallation(variant, entity, false);
}
/**
* TODO - Once only KC based registration are publised (android/ios) we can
* remove shouldVerifiy condition.
*/
public void addInstallation(Variant variant, Installation entity, boolean shouldVerifiy) {
// does it already exist ?
Installation installation = this.findInstallationForVariantByDeviceToken(variant.getVariantID(),
entity.getDeviceToken());
// Needed for the Admin UI Only. Help for setting up Routes
entity.setPlatform(variant.getType().getTypeName());
// new device/client ?
if (installation == null) {
logger.trace("Performing new device/client registration");
// store the installation:
storeInstallationAndSetReferences(variant, entity);
} else {
// We only update the metadata, if the device is enabled:
if (installation.isEnabled()) {
logger.trace("Updating received metadata for an 'enabled' installation");
// fix variant property of installation object
installation.setVariant(variant);
// update the entity:
this.updateInstallation(installation, entity);
}
}
// TODO - Remove according to top comment
if (shouldVerifiy)
verificationService.initiateDeviceVerification(entity, variant);
}
@Override
public void addInstallations(Variant variant, List<Installation> installations) {
// don't bother
if (installations == null || installations.isEmpty()) {
return;
}
// TODO - On a large scale database, we can't load entire device list.
Set<String> existingTokens = installationDao.findAllDeviceTokenForVariantID(variant.getVariantID());
// clear out:
installationDao.flushAndClear();
for (int i = 0; i < installations.size(); i++) {
Installation current = installations.get(i);
// let's avoid duplicated tokens/devices per variant
// For devices without a token, let's also not bother the DAO layer
// to throw BeanValidation exception
if (!existingTokens.contains(current.getDeviceToken()) && hasTokenValue(current)) {
logger.trace("Importing device with token: {}", current.getDeviceToken());
storeInstallationAndSetReferences(variant, current);
// and add a reference to the existing tokens set, to ensure the
// JSON file contains no duplicates:
existingTokens.add(current.getDeviceToken());
// some tunings, ever 10k devices releasing resources
if (i % 10000 == 0) {
logger.trace("releasing some resources during import");
installationDao.flushAndClear();
}
} else {
// for now, we ignore them.... no update applied!
logger.trace("Device with token '{}' already exists. Ignoring it ", current.getDeviceToken());
}
}
// clear out:
installationDao.flushAndClear();
}
@Override
public void removeInstallations(List<Installation> installations) {
// uh..., fancy method reference :)
installations.forEach(this::removeInstallation);
}
@Override
public void updateInstallation(Installation installation) {
installationDao.update(installation);
}
@Override
public void updateInstallation(Installation installationToUpdate, Installation postedInstallation) {
// copy the "updateable" values:
mergeCategories(installationToUpdate, postedInstallation.getCategories());
installationToUpdate.setDeviceToken(postedInstallation.getDeviceToken());
installationToUpdate.setAlias(postedInstallation.getAlias());
installationToUpdate.setDeviceType(postedInstallation.getDeviceType());
installationToUpdate.setOperatingSystem(postedInstallation.getOperatingSystem());
installationToUpdate.setOsVersion(postedInstallation.getOsVersion());
installationToUpdate.setEnabled(postedInstallation.isEnabled());
installationToUpdate.setPlatform(postedInstallation.getPlatform());
// update it:
updateInstallation(installationToUpdate);
// unsubscribe Android devices from topics that device should no longer
// be subscribed to
if (installationToUpdate.getVariant().getType() == VariantType.ANDROID) {
unsubscribeOldTopics(installationToUpdate);
}
}
@Override
public Installation findById(String primaryKey) {
return installationDao.find(primaryKey);
}
@Override
public void removeInstallation(Installation installation) {
installationDao.delete(installation);
}
@Override
public void removeInstallationsForVariantByDeviceTokens(String variantID, Set<String> deviceTokens) {
// collect inactive installations for the given variant:
List<Installation> inactiveInstallations = installationDao.findInstallationsForVariantByDeviceTokens(variantID,
deviceTokens);
// get rid of them
this.removeInstallations(inactiveInstallations);
}
@Override
public void removeInstallationForVariantByDeviceToken(String variantID, String deviceToken) {
removeInstallation(findInstallationForVariantByDeviceToken(variantID, deviceToken));
}
@Override
public Installation findInstallationForVariantByDeviceToken(String variantID, String deviceToken) {
return installationDao.findInstallationForVariantByDeviceToken(variantID, deviceToken);
}
@Override
public void unsubscribeOldTopics(Installation installation) {
FCMTopicManager topicManager = new FCMTopicManager((AndroidVariant) installation.getVariant());
Set<String> oldCategories = topicManager.getSubscribedCategories(installation);
// Remove current categories from the set of old ones
oldCategories.removeAll(convertToNames(installation.getCategories()));
// Remove global variant topic because we don't want to unsubscribe it
oldCategories.remove(installation.getVariant().getVariantID());
for (String categoryName : oldCategories) {
topicManager.unsubscribe(installation, categoryName);
}
}
// =====================================================================
// ======== Various finder services for the Sender REST API ============
// =====================================================================
/**
* Finder for 'send', used for Android, iOS and SimplePush clients
*/
@Override
public ResultsStream.QueryBuilder<String> findAllDeviceTokenForVariantIDByCriteria(String variantID,
List<String> categories, List<String> aliases, List<String> deviceTypes, int maxResults,
String lastTokenFromPreviousBatch) {
return installationDao.findAllDeviceTokenForVariantIDByCriteria(variantID, categories, aliases, deviceTypes,
maxResults, lastTokenFromPreviousBatch, false);
}
@Override
public ResultsStream.QueryBuilder<String> findAllOldGoogleCloudMessagingDeviceTokenForVariantIDByCriteria(
String variantID, List<String> categories, List<String> aliases, List<String> deviceTypes, int maxResults,
String lastTokenFromPreviousBatch) {
return installationDao.findAllDeviceTokenForVariantIDByCriteria(variantID, categories, aliases, deviceTypes,
maxResults, lastTokenFromPreviousBatch, true);
}
/**
* A simple validation util that checks if a token is present
*/
private boolean hasTokenValue(Installation installation) {
return installation.getDeviceToken() != null && !installation.getDeviceToken().isEmpty();
}
/**
* When an installation is created or updated, the categories are passed without
* IDs. This method solve this issue by checking for existing categories and
* updating them (otherwise it would persist a new object).
*
* @param entity to merge the categories for
* @param categoriesToMerge are the categories to merge with the existing one
*/
private void mergeCategories(Installation entity, Set<Category> categoriesToMerge) {
if (entity.getCategories() != null) {
final List<String> categoryNames = convertToNames(categoriesToMerge);
final List<Category> existingCategoriesFromDB = categoryDao.findByNames(categoryNames);
// Replace json dematerialised categories with their persistent
// counter parts (see Category.equals),
// by remove existing/persistent categories from the new collection,
// and adding them back in (with their PK).
categoriesToMerge.removeAll(existingCategoriesFromDB);
categoriesToMerge.addAll(existingCategoriesFromDB);
// and apply the passed in ones.
entity.setCategories(categoriesToMerge);
}
}
private static List<String> convertToNames(Set<Category> categories) {
return categories.stream().map(Category::getName).collect(Collectors.toList());
}
/*
* Helper to set references and perform the actual storage
*/
protected void storeInstallationAndSetReferences(Variant variant, Installation entity) {
// ensure lower case for iOS
if (variant.getType() == VariantType.IOS) {
entity.setDeviceToken(entity.getDeviceToken().toLowerCase());
}
// set reference
entity.setVariant(variant);
// update attached categories
mergeCategories(entity, entity.getCategories());
// store Installation entity
installationDao.create(entity);
}
@Override
public void removeInstallations(String alias) {
List<Installation> insts = installationDao.findInstallationsByAlias(alias);
if (insts != null) {
insts.forEach(item -> installationDao.delete(item));
}
}
public List<Installation> findByAlias(String alias) {
return installationDao.findInstallationsByAlias(alias);
}
public long getNumberOfDevicesForVariantID(String variantId) {
return installationDao.getNumberOfDevicesForVariantID(variantId);
}
}
| |
/*
* Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.andes.store.rdbms;
/**
* JDBC storage related prepared statements, table names, column names and tasks are grouped
* in this class.
*/
public class RDBMSConstants {
// jndi lookup
protected static final String H2_MEM_JNDI_LOOKUP_NAME = "WSO2MBInMemoryStoreDB";
// Configuration properties
protected static final String PROP_JNDI_LOOKUP_NAME = "dataSource";
// Message Store tables
protected static final String CONTENT_TABLE = "MB_CONTENT";
protected static final String METADATA_TABLE = "MB_METADATA";
protected static final String QUEUES_TABLE = "MB_QUEUE_MAPPING";
protected static final String EXPIRATION_TABLE = "MB_EXPIRATION_DATA";
// Message Store table columns
protected static final String MESSAGE_ID = "MESSAGE_ID";
protected static final String QUEUE_ID = "QUEUE_ID";
protected static final String QUEUE_NAME = "QUEUE_NAME";
protected static final String METADATA = "MESSAGE_METADATA";
protected static final String MSG_OFFSET = "CONTENT_OFFSET";
protected static final String MESSAGE_CONTENT = "MESSAGE_CONTENT";
protected static final String EXPIRATION_TIME = "EXPIRATION_TIME";
protected static final String DESTINATION_QUEUE = "MESSAGE_DESTINATION";
// Andes Context Store tables
protected static final String DURABLE_SUB_TABLE = "MB_DURABLE_SUBSCRIPTION";
protected static final String NODE_INFO_TABLE = "MB_NODE";
protected static final String EXCHANGES_TABLE = "MB_EXCHANGE";
protected static final String BINDINGS_TABLE = "MB_BINDING";
protected static final String QUEUE_INFO_TABLE = "MB_QUEUE";
protected static final String QUEUE_COUNTER_TABLE = "MB_QUEUE_COUNTER";
// Andes Context Store table columns
protected static final String DURABLE_SUB_ID = "SUBSCRIPTION_ID";
protected static final String DESTINATION_IDENTIFIER = "DESTINATION_IDENTIFIER";
protected static final String DURABLE_SUB_DATA = "SUBSCRIPTION_DATA";
protected static final String NODE_ID = "NODE_ID";
protected static final String NODE_INFO = "NODE_DATA";
protected static final String EXCHANGE_NAME = "EXCHANGE_NAME";
protected static final String EXCHANGE_DATA = "EXCHANGE_DATA";
protected static final String BINDING_INFO = "BINDING_DETAILS";
protected static final String BINDING_QUEUE_NAME = "QUEUE_NAME";
protected static final String BINDING_EXCHANGE_NAME = "EXCHANGE_NAME";
protected static final String QUEUE_DATA = "QUEUE_DATA";
protected static final String MESSAGE_COUNT = "MESSAGE_COUNT";
// prepared statements for Message Store
protected static final String PS_INSERT_MESSAGE_PART =
"INSERT INTO " + CONTENT_TABLE + "(" +
MESSAGE_ID + "," +
MSG_OFFSET + "," +
MESSAGE_CONTENT + ") " +
"VALUES (?, ?, ?)";
protected static final String PS_DELETE_MESSAGE_PARTS =
"DELETE " +
" FROM " + CONTENT_TABLE +
" WHERE " + MESSAGE_ID + "=?";
protected static final String PS_RETRIEVE_MESSAGE_PART =
"SELECT " + MESSAGE_CONTENT +
" FROM " + CONTENT_TABLE +
" WHERE " + MESSAGE_ID + "=?" +
" AND " + MSG_OFFSET + "=?";
protected static final String PS_INSERT_METADATA =
"INSERT INTO " + METADATA_TABLE + " (" +
MESSAGE_ID + "," +
QUEUE_ID + "," +
METADATA + ")" +
" VALUES ( ?,?,? )";
protected static final String PS_INSERT_EXPIRY_DATA =
"INSERT INTO " + EXPIRATION_TABLE + " (" +
MESSAGE_ID + "," +
EXPIRATION_TIME + "," +
DESTINATION_QUEUE + ")" +
" VALUES ( ?,?,? )";
protected static final String PS_INSERT_QUEUE =
"INSERT INTO " + RDBMSConstants.QUEUES_TABLE + " (" +
RDBMSConstants.QUEUE_NAME + ") " +
" VALUES (?)";
protected static final String PS_ALIAS_FOR_COUNT = "count";
protected static final String PS_SELECT_QUEUE_MESSAGE_COUNT =
"SELECT COUNT(" + QUEUE_ID + ") AS " + PS_ALIAS_FOR_COUNT +
" FROM " + METADATA_TABLE +
" WHERE " + QUEUE_ID + "=?";
protected static final String PS_SELECT_METADATA =
"SELECT " + METADATA +
" FROM " + METADATA_TABLE +
" WHERE " + MESSAGE_ID + "=?";
protected static final String PS_SELECT_METADATA_RANGE_FROM_QUEUE =
"SELECT " + MESSAGE_ID + "," + METADATA +
" FROM " + METADATA_TABLE +
" WHERE " + QUEUE_ID + "=?" +
" AND " + MESSAGE_ID +
" BETWEEN ?" +
" AND ?" +
" ORDER BY " + MESSAGE_ID;
protected static final String PS_SELECT_METADATA_FROM_QUEUE =
"SELECT " + MESSAGE_ID + "," + METADATA +
" FROM " + METADATA_TABLE +
" WHERE " + MESSAGE_ID + ">?" +
" AND " + QUEUE_ID + "=?" +
" ORDER BY " + MESSAGE_ID;
protected static final String PS_SELECT_MESSAGE_IDS_FROM_METADATA_FOR_QUEUE =
"SELECT " + MESSAGE_ID +
" FROM " + METADATA_TABLE +
" WHERE " + QUEUE_ID + "=?" +
" ORDER BY " + MESSAGE_ID ;
protected static final String PS_DELETE_EXPIRY_DATA = "DELETE " +
" FROM " + EXPIRATION_TABLE +
" WHERE " + MESSAGE_ID + "=?";
protected static final String PS_DELETE_METADATA_FROM_QUEUE =
"DELETE " +
" FROM " + METADATA_TABLE +
" WHERE " + QUEUE_ID + "=?" +
" AND " + MESSAGE_ID + "=?";
protected static final String PS_CLEAR_QUEUE_FROM_METADATA = "DELETE " +
" FROM " + METADATA_TABLE +
" WHERE " + QUEUE_ID + "=?";
protected static final String PS_SELECT_EXPIRED_MESSAGES =
"SELECT " + MESSAGE_ID + "," + DESTINATION_QUEUE +
" FROM " + EXPIRATION_TABLE +
" WHERE " + EXPIRATION_TIME + "<" + System.currentTimeMillis();
protected static final String PS_SELECT_QUEUE_ID =
"SELECT " + QUEUE_ID +
" FROM " + QUEUES_TABLE +
" WHERE " + QUEUE_NAME + "=?";
// prepared statements for Andes Context Store
protected static final String PS_INSERT_DURABLE_SUBSCRIPTION =
"INSERT INTO " + DURABLE_SUB_TABLE + " (" +
DESTINATION_IDENTIFIER + ", " +
DURABLE_SUB_ID + ", " +
DURABLE_SUB_DATA + ") " +
" VALUES (?,?,?)";
protected static final String PS_UPDATE_DURABLE_SUBSCRIPTION =
"UPDATE " + DURABLE_SUB_TABLE +
" SET " + DURABLE_SUB_DATA + "=? " +
" WHERE " + DESTINATION_IDENTIFIER + "=? AND " +
DURABLE_SUB_ID + "=?";
protected static final String PS_SELECT_ALL_DURABLE_SUBSCRIPTIONS =
"SELECT " + DESTINATION_IDENTIFIER + "," + DURABLE_SUB_DATA +
" FROM " + DURABLE_SUB_TABLE;
protected static final String PS_DELETE_DURABLE_SUBSCRIPTION =
"DELETE FROM " + DURABLE_SUB_TABLE +
" WHERE " + DESTINATION_IDENTIFIER + "=? " +
" AND " + DURABLE_SUB_ID + "=?";
protected static final String PS_INSERT_NODE_INFO =
"INSERT INTO " + NODE_INFO_TABLE + " ( " +
NODE_ID + "," +
NODE_INFO + ") " +
" VALUES (?,?)";
protected static final String PS_SELECT_ALL_NODE_INFO =
"SELECT * " +
"FROM " + NODE_INFO_TABLE;
protected static final String PS_DELETE_NODE_INFO =
"DELETE FROM " + NODE_INFO_TABLE +
" WHERE " + NODE_ID + "=?";
protected static final String PS_STORE_EXCHANGE_INFO =
"INSERT INTO " + EXCHANGES_TABLE + " (" +
EXCHANGE_NAME + "," +
EXCHANGE_DATA + ") " +
" VALUES (?,?)";
protected static final String PS_SELECT_ALL_EXCHANGE_INFO =
"SELECT " + EXCHANGE_DATA +
" FROM " + EXCHANGES_TABLE;
protected static final String PS_SELECT_EXCHANGE =
"SELECT " + EXCHANGE_DATA +
" FROM " + EXCHANGES_TABLE +
" WHERE " + EXCHANGE_NAME + "=?";
protected static final String PS_DELETE_EXCHANGE =
"DELETE FROM " + EXCHANGES_TABLE +
" WHERE " + EXCHANGE_NAME + "=?";
protected static final String PS_INSERT_QUEUE_INFO =
"INSERT INTO " + QUEUE_INFO_TABLE + " (" +
QUEUE_NAME + "," + QUEUE_DATA + ") " +
" VALUES (?,?)";
protected static final String PS_SELECT_ALL_QUEUE_INFO =
"SELECT " + QUEUE_DATA +
" FROM " + QUEUE_INFO_TABLE;
protected static final String PS_DELETE_QUEUE_INFO =
"DELETE FROM " + QUEUE_INFO_TABLE +
" WHERE " + QUEUE_NAME + "=?";
protected static final String PS_INSERT_BINDING =
"INSERT INTO " + BINDINGS_TABLE + " ( " +
BINDING_EXCHANGE_NAME + "," +
BINDING_QUEUE_NAME + "," +
BINDING_INFO + " ) " +
" VALUES (?,?,?)";
protected static final String PS_SELECT_BINDINGS_FOR_EXCHANGE =
"SELECT " + BINDING_INFO +
" FROM " + BINDINGS_TABLE +
" WHERE " + BINDING_EXCHANGE_NAME + "=?";
protected static final String PS_DELETE_BINDING =
"DELETE FROM " + BINDINGS_TABLE +
" WHERE " + BINDING_EXCHANGE_NAME + "=? " +
" AND " + BINDING_QUEUE_NAME + "=?";
protected static final String PS_UPDATE_METADATA_QUEUE =
"UPDATE " + METADATA_TABLE +
" SET " + QUEUE_ID + " = ? " +
"WHERE " + MESSAGE_ID + " = ? " +
"AND " + QUEUE_ID + " = ?";
protected static final String PS_UPDATE_METADATA =
"UPDATE " + METADATA_TABLE +
" SET " + QUEUE_ID + " = ?," + METADATA + " = ?" +
" WHERE " + MESSAGE_ID + " = ?" +
" AND " + QUEUE_ID + " = ?";
/**
* Prepared Statement to insert a new queue counter.
*/
protected static final String PS_INSERT_QUEUE_COUNTER =
"INSERT INTO " + QUEUE_COUNTER_TABLE + " (" +
QUEUE_NAME + "," + MESSAGE_COUNT + " ) " +
" VALUES ( ?,? )";
/**
* Prepared Statement to select count for a queue prepared statement
*/
protected static final String PS_SELECT_QUEUE_COUNT =
"SELECT " + MESSAGE_COUNT +
" FROM " + QUEUE_COUNTER_TABLE +
" WHERE " + QUEUE_NAME + "=?";
/**
* Prepared Statement to delete queue counter with a given queue name
*/
protected static final String PS_DELETE_QUEUE_COUNTER =
"DELETE FROM " + QUEUE_COUNTER_TABLE +
" WHERE " + QUEUE_NAME + "=?";
/**
* Increments the queue count by a given value in a atomic db update
*/
protected static final String PS_INCREMENT_QUEUE_COUNT =
"UPDATE " + QUEUE_COUNTER_TABLE +
" SET " + MESSAGE_COUNT + "=" + MESSAGE_COUNT + "+? " +
" WHERE " + QUEUE_NAME + "=?";
/**
* Decrement the queue count by a given value in a atomic db update
*/
protected static final String PS_DECREMENT_QUEUE_COUNT =
"UPDATE " + QUEUE_COUNTER_TABLE +
" SET " + MESSAGE_COUNT + "=" + MESSAGE_COUNT + "-? " +
" WHERE " + QUEUE_NAME + "=?";
protected static final String PS_RESET_QUEUE_COUNT =
"UPDATE " + QUEUE_COUNTER_TABLE +
" SET " + MESSAGE_COUNT + "= 0" +
" WHERE " + QUEUE_NAME + "=?";
protected static final String PS_GET_QUEUE_DATA =
"SELECT "+QUEUE_DATA+
" FROM "+ QUEUE_INFO_TABLE +
" WHERE " + QUEUE_NAME + "=?";
protected static final String PS_UPDATE_EXCLUSIVE_CONSUMER =
"UPDATE "+ QUEUE_INFO_TABLE +
" SET "+ QUEUE_DATA + "=?"+
" WHERE "+ QUEUE_NAME +"=?";
// Message Store related jdbc tasks executed
protected static final String TASK_STORING_MESSAGE_PARTS = "storing message parts.";
protected static final String TASK_DELETING_MESSAGE_PARTS = "deleting message parts.";
protected static final String TASK_RETRIEVING_MESSAGE_PARTS = "retrieving message parts.";
protected static final String TASK_RETRIEVING_CONTENT_FOR_MESSAGES = "retrieving content for multiple messages";
protected static final String TASK_ADDING_METADATA_LIST = "adding metadata list.";
protected static final String TASK_ADDING_METADATA = "adding metadata.";
protected static final String TASK_ADDING_METADATA_TO_QUEUE = "adding metadata to " +
"destination. ";
protected static final String TASK_ADDING_METADATA_LIST_TO_QUEUE = "adding metadata list to " +
"destination. ";
protected static final String TASK_RETRIEVING_QUEUE_MSG_COUNT = "retrieving message count for" +
" queue. ";
protected static final String TASK_RETRIEVING_METADATA = "retrieving metadata for message id. ";
protected static final String TASK_RETRIEVING_METADATA_RANGE_FROM_QUEUE = "retrieving " +
"metadata within a range from queue. ";
protected static final String TASK_RETRIEVING_NEXT_N_METADATA_FROM_QUEUE = "retrieving " +
"metadata list from queue. ";
protected static final String TASK_RETRIEVING_NEXT_N_MESSAGE_IDS_OF_QUEUE = "retrieving " +
"message ID list from queue. ";
protected static final String TASK_DELETING_FROM_EXPIRY_TABLE = "deleting from expiry table.";
protected static final String TASK_DELETING_MESSAGE_LIST = "deleting message list.";
protected static final String TASK_DELETING_METADATA_FROM_QUEUE = "deleting metadata from " +
"queue. ";
protected static final String TASK_RESETTING_MESSAGE_COUNTER = "Resetting message counter for queue";
protected static final String TASK_RETRIEVING_EXPIRED_MESSAGES = "retrieving expired messages.";
protected static final String TASK_RETRIEVING_QUEUE_ID = "retrieving queue id for queue. ";
protected static final String TASK_CREATING_QUEUE = "creating queue. ";
// Andes Context Store related jdbc tasks executed
protected static final String TASK_STORING_DURABLE_SUBSCRIPTION = "storing durable subscription";
protected static final String TASK_UPDATING_DURABLE_SUBSCRIPTION = "updating durable subscription";
protected static final String TASK_RETRIEVING_ALL_DURABLE_SUBSCRIPTION = "retrieving " +
"all durable subscriptions. ";
protected static final String TASK_REMOVING_DURABLE_SUBSCRIPTION = "removing durable " +
"subscription. ";
protected static final String TASK_STORING_NODE_INFORMATION = "storing node information";
protected static final String TASK_RETRIEVING_ALL_NODE_DETAILS = "retrieving all node " +
"information. ";
protected static final String TASK_REMOVING_NODE_INFORMATION = "removing node information";
protected static final String TASK_STORING_EXCHANGE_INFORMATION = "storing exchange information";
protected static final String TASK_RETRIEVING_ALL_EXCHANGE_INFO = "retrieving all exchange " +
"information. ";
protected static final String TASK_IS_EXCHANGE_EXIST = "checking whether an exchange " +
"exist. ";
protected static final String TASK_DELETING_EXCHANGE = "deleting an exchange ";
protected static final String TASK_STORING_QUEUE_INFO = "storing queue information ";
protected static final String TASK_RETRIEVING_ALL_QUEUE_INFO = "retrieving all queue " +
"information. ";
protected static final String TASK_DELETING_QUEUE_INFO = "deleting queue information. ";
protected static final String TASK_STORING_BINDING = "storing binding information. ";
protected static final String TASK_RETRIEVING_BINDING_INFO = "retrieving binding information.";
protected static final String TASK_DELETING_BINDING = "deleting binding information. ";
protected static final String TASK_UPDATING_META_DATA_QUEUE = "updating message meta data queue.";
protected static final String TASK_UPDATING_META_DATA = "updating message meta data.";
protected static final String TASK_ADDING_QUEUE_COUNTER = "adding counter for queue";
protected static final String TASK_CHECK_QUEUE_COUNTER_EXIST = "checking queue counter exist";
protected static final String TASK_RETRIEVING_QUEUE_COUNT = "retrieving queue count";
protected static final String TASK_DELETING_QUEUE_COUNTER = "deleting queue counter";
protected static final String TASK_INCREMENTING_QUEUE_COUNT = "incrementing queue count";
protected static final String TASK_DECREMENTING_QUEUE_COUNT = "decrementing queue count";
protected static final String TASK_RETRIEVING_AND_UPDATING_QUEUE_DATA = "Retrieving and updating queue details";
/**
* Only public static constants are in this class. No need to instantiate.
*/
private RDBMSConstants() {
}
}
| |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.eas.client.controls.geopane.cache;
import com.eas.client.controls.geopane.TilesBoundaries;
import com.eas.concurrent.PlatypusThreadFactory;
import java.awt.Image;
import java.awt.Point;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.geotools.map.MapContent;
import org.geotools.renderer.GTRenderer;
import org.geotools.renderer.lite.StreamingRenderer;
/**
*
* @author mg
*/
public class AsyncMapTilesCache extends MapTilesCache {
public class AsyncRenderingTask extends RenderingTask {
protected Thread executingThread;
private boolean rendered = false;
public AsyncRenderingTask(Point aTilePoint) throws NoninvertibleTransformException {
super(aTilePoint);
}
@Override
public void run() {
mapContextLock.readLock().lock();
try {
executingThread = Thread.currentThread();
if (!isStopped() && isActual()) {
try {
super.run();
setRendered(true);
} finally {
offeredTasks.remove(tilePoint);
// fireRenderingTaskCompleted() must be called strictly after offeredTasks.remove() !
fireRenderingTaskCompleted(this);
}
} else {
offeredTasks.remove(tilePoint);
}
} finally {
mapContextLock.readLock().unlock();
}
}
@Override
protected boolean isActual() {
return getActualArea().contains(tilePoint);
}
@Override
protected GTRenderer archieveRenderer() {
return new StreamingRenderer();
}
public void stop() throws InterruptedException {
assert taskRenderer != null;
taskRenderer.stopRendering();
setStopped(true);
}
/**
* @return the rendered
*/
public synchronized boolean isRendered() {
return rendered;
}
/**
* @param aRendered the rendered to set
*/
public synchronized void setRendered(boolean aRendered) {
rendered = aRendered;
}
}
protected Map<Point, AsyncRenderingTask> offeredTasks = new ConcurrentHashMap<>();
protected ExecutorService executor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().availableProcessors(),
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(), new PlatypusThreadFactory());
protected Set<RenderingTaskListener> listeners = new HashSet<>();
protected ReadWriteLock mapContextLock;
public AsyncMapTilesCache(int aCacheSize, MapContent aDisplayContext, ReadWriteLock aMapContextLock, AffineTransform aTransform) {
super(aCacheSize, aDisplayContext, aTransform);
mapContextLock = aMapContextLock;
}
public AsyncMapTilesCache(MapContent aDisplayContext, ReadWriteLock aMapContextLock, AffineTransform aTransform) {
super(aDisplayContext, aTransform);
mapContextLock = aMapContextLock;
}
@Override
protected Image renderTile(Point ptKey) {
try {
AsyncRenderingTask task = new AsyncRenderingTask(ptKey);
assert !executor.isShutdown();
offeredTasks.put(ptKey, task);
executor.execute(task);
return null;
} catch (NoninvertibleTransformException ex) {
Logger.getLogger(AsyncMapTilesCache.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
public void shutdown() {
try2StopSomeTasks();
wait4AllTasksCompleted();
executor.shutdown();
super.clear();
}
@Override
public void clear() {
// all tasks are invalid and cache entries to.
// hint some tasks to quikly complete their's work.
try2StopSomeTasks();
// wait while ALL tasks complete (hinted to shutdown and all others)
wait4AllTasksCompleted();
// clear the cache
super.clear();
}
@Override
public synchronized Image get(Point ptKey) {
if (offeredTasks.containsKey(ptKey)) {
// may be one of the working rendering tasks alreadey have put results in the cache.
return cache.get(ptKey);
}
// There is no task rendering ptKey tile, and so let's relay on the super get/offer mechanism
return super.get(ptKey);
}
@Override
public void setActualArea(TilesBoundaries aActualArea) {
// let's hint invalid, but already offered tasks.
try2StopSomeUnactualTasks(aActualArea);
super.setActualArea(aActualArea);
}
/**
* Makes to executing and queued tasks a hint to shutdown any work and remove thereselfs from
* offeredTasks collection.
* This is only hint because of multithreaded environment. Not all the tasks will undestand it.
*/
protected void try2StopSomeTasks() {
try2StopSomeUnactualTasks(TilesBoundaries.EMPTY);
}
protected void try2StopSomeUnactualTasks(TilesBoundaries aActualArea) {
for (Point taskPoint : offeredTasks.keySet()) {
if (!aActualArea.contains(taskPoint)) {
AsyncRenderingTask task = offeredTasks.get(taskPoint);
if (task != null && task.isRendered()) {
try {
task.stop();
} catch (InterruptedException ex) {
Logger.getLogger(AsyncMapTilesCache.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
protected void wait4AllTasksCompleted() {
// wait while all tasks complete execution
while (!offeredTasks.isEmpty()) {
try {
assert !executor.isShutdown();
Thread.sleep(4);
} catch (InterruptedException ex) {
Logger.getLogger(AsyncMapTilesCache.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
@Override
public void scaleChanged() {
// clear the cache.
clear();
}
public synchronized void addRenderingTaskListener(RenderingTaskListener l) {
listeners.add(l);
}
public synchronized void removeRenderingTaskListener(RenderingTaskListener l) {
listeners.remove(l);
}
/**
* Fires an event that rendering task had completed
* WARNING!!! This method is called from executor service thread and it
* have to use all appropriate synchronization.
*/
protected synchronized void fireRenderingTaskCompleted(AsyncRenderingTask aTask) {
for (RenderingTaskListener l : listeners) {
l.taskCompleted(aTask);
}
}
}
| |
package com.ppot14.futbol7;
import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Filters.elemMatch;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.exists;
import static com.mongodb.client.model.Updates.set;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import org.bson.BsonDocument;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.result.UpdateResult;
public class DBConnector {
private static final Logger logger = Logger.getLogger(DBConnector.class.getName());
private static final String LOCAL_DB_SERVER = "127.0.0.1";
private static final String PROD_DB_SERVER = "vps238730.ovh.net";
private static MongoClient mongo;
private static String dbServer = PROD_DB_SERVER;
private static SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
private static MongoCollection<Document> getCollection(String collectionName) throws Exception {
if (mongo == null){
MongoCredential credential = MongoCredential.createCredential("ppot14", "admin", "1468314a".toCharArray());
mongo = new MongoClient(new ServerAddress(dbServer, 27017), Arrays.asList(credential));
}
MongoCollection<Document> collection = mongo.getDatabase("futbol7").getCollection(collectionName);
return collection;
}
public static Document getConfig(){
try {
MongoCollection<Document> configCollection;
configCollection = getCollection("Config");
Bson filter = exists("permanents");
FindIterable<Document> result = configCollection.find(filter);
if(result!=null && result.first()!=null){
logger.info(""+(result.first()!=null));
return (Document) result.first();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Document getPlayer(JsonNode jsonNode){
String name = jsonNode.get("name").asText();
String id = jsonNode.get("id").asText();
try {
MongoCollection<Document> configCollection;
configCollection = getCollection("Players");
Bson filter = and(eq("name", name),eq("id",id));
FindIterable<Document> result = configCollection.find(filter);
if(result!=null && result.first()!=null){
Bson update = set("lastAccess", new Date().getTime());
//Bson update = and(set("picture", jsonNode.get("picture").asText()),set("lastAccess", new Date().getTime()));
configCollection.updateOne(filter,update);
logger.fine("player exists: "+result.first().getString("name")+" ("+result.first().getString("nameweb")+")");
return (Document) result.first();
}else{
((ObjectNode)jsonNode).put("created", new Date().getTime());
ObjectMapper mapper = new ObjectMapper();
configCollection.insertOne(new Document((Map<String, Object>) mapper.convertValue(jsonNode, Map.class)));
logger.info("new player: "+jsonNode.get("name").asText());
return new Document("newuser",true);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Map<String,String> getPlayersPictures(){
Map<String,String> playersPictures = new HashMap<String,String>();
try {
MongoCollection<Document> configCollection;
configCollection = getCollection("Players");
for (Document document : configCollection.find()) {
playersPictures.put(document.getString("nameweb")!=null?document.getString("nameweb"):document.getString("name"), document.getString("picture"));
}
} catch (Exception e) {
e.printStackTrace();
}
return playersPictures;
}
public static boolean setPlayerPicture(String player, String picture){
boolean result = false;
try {
MongoCollection<Document> configCollection;
configCollection = getCollection("Players");
UpdateResult updateResult = configCollection.updateMany(eq("nameweb", player),set("picture", picture));
logger.info("setPlayerPicture "+player+" with "+picture+" to "+updateResult.getModifiedCount()+" records");
result = updateResult.getModifiedCount()>0;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static Document hasVoted(JsonNode jsonNode){
String name = jsonNode.get("name")!=null?jsonNode.get("name").asText():jsonNode.get("voter").asText();
String season = jsonNode.get("season").asText();
Long dateL = jsonNode.get("date").asLong();
String date = formatter.format(new Date(dateL));
try {
MongoCollection<Document> configCollection;
configCollection = getCollection("Scores");
Bson filter = and(eq("scoresMVP.voter",name),eq("date",date),eq("season",season));
FindIterable<Document> result = configCollection.find(filter);
if(result!=null && result.first()!=null){
logger.info("player voted: "+jsonNode);
return (Document) result.first();
}else{
logger.info("player didn't vote: "+jsonNode);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Document getVotes(String season){
Document ret = new Document();
try {
MongoCollection<Document> configCollection;
configCollection = getCollection("Scores");
Bson filter = eq("season",season);
FindIterable<Document> result = configCollection.find(filter);
if(result!=null){
for(Document d:result){
ret.put(d.getString("date"), d);
}
return ret;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Document getVotes(String season, String date){
try {
MongoCollection<Document> configCollection;
configCollection = getCollection("Scores");
Bson filter = and(eq("season",season), eq("date",date));
FindIterable<Document> result = configCollection.find(filter);
if(result!=null && result.first()!=null){
return (Document) result.first();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void createScore(Document data){
try {
MongoCollection<Document> configCollection;
configCollection = getCollection("Scores");
configCollection.insertOne(data);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Boolean addPunctuation(String voter, String voted, Long dateL, String season){
String date = formatter.format(new Date(dateL));
try {
MongoCollection<Document> configCollection;
configCollection = getCollection("Scores");
Bson filter = and(eq("season",season), eq("date",date));
Document s = new Document();
s.put("voter", voter);
s.put("voted", voted);
UpdateResult res = configCollection.updateOne(filter, new Document("$push", new Document("scoresMVP", s)));
if(res.getModifiedCount()==1){ return true; }
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
| |
/*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package com.pivotal.gemfirexd.internal.engine.store;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.TreeSet;
import com.gemstone.gemfire.DataSerializer;
import com.gemstone.gemfire.internal.offheap.OffHeapHelper;
import com.gemstone.gemfire.internal.offheap.UnsafeMemoryChunk;
import com.gemstone.gemfire.internal.offheap.annotations.Released;
import com.gemstone.gemfire.internal.offheap.annotations.Unretained;
import com.pivotal.gemfirexd.internal.engine.GfxdConstants;
import com.pivotal.gemfirexd.internal.engine.GfxdDataSerializable;
import com.pivotal.gemfirexd.internal.engine.distributed.metadata.RegionAndKey;
import com.pivotal.gemfirexd.internal.engine.jdbc.GemFireXDRuntimeException;
import com.pivotal.gemfirexd.internal.engine.store.offheap.OffHeapByteSource;
import com.pivotal.gemfirexd.internal.engine.store.offheap.OffHeapRow;
import com.pivotal.gemfirexd.internal.engine.store.offheap.OffHeapRowWithLobs;
import com.pivotal.gemfirexd.internal.iapi.error.StandardException;
import com.pivotal.gemfirexd.internal.iapi.services.io.FormatableBitSet;
import com.pivotal.gemfirexd.internal.iapi.sql.execute.ExecRow;
import com.pivotal.gemfirexd.internal.iapi.types.DataValueDescriptor;
import com.pivotal.gemfirexd.internal.shared.common.ResolverUtils;
import org.apache.spark.unsafe.types.UTF8String;
import static com.gemstone.gemfire.internal.offheap.annotations.OffHeapIdentifier.OFFHEAP_COMPACT_EXEC_ROW_SOURCE;
/**
* A compact implementation of Row used to minimize the footprint of a row and
* to defer its expansion.
*
* A row is stored in a GemFire Region using the bytes emitted from an instance
* of this class. An instance of this class is used as a substitute for
* DataValueDescriptor[] so that expansion is deferred.
*
* An instance of this class can represent an entire row of the table or a
* partial row.
*
* The row structure does not store type information or preserve logical column
* ordering so additional type information is required at construction time in
* the form of a ColumnDescriptorList.
*
* @see com.pivotal.gemfirexd.internal.impl.sql.execute.ValueRow
* @see com.pivotal.gemfirexd.internal.engine.store.RowFormatter
*
* @author Eric Zoerner
*/
public final class OffHeapCompactExecRow extends AbstractCompactExecRow {
private static final long serialVersionUID = -8506169648261047433L;
/**
* The row data encoded in bytes. The format of the bytes is completely
* delegated to RowFormatter.
*
* If null, then represents a row of all null values.
*/
@Unretained(OFFHEAP_COMPACT_EXEC_ROW_SOURCE)
private Object source;
////////// Constructors //////////
/** only to be used for deserialization */
public OffHeapCompactExecRow() {
}
/**
* Construct a OffHeapCompactExecRow with the given RowFormatter, and with all
* null values.
*/
OffHeapCompactExecRow(final RowFormatter rf) {
super(rf);
this.source = null; // treated as all null valued fields
assert rf.isTableFormatter() || !rf.hasLobs():
"use a OffHeapCompactExecRowWithLobs instead";
}
/**
* Construct a OffHeapCompactExecRow given a DataValueDescriptor[] and
* RowFormatter. The dvds are assumed to be in the logical ordering.
*
* @param dvds
* the DataValueDescriptor[] form of the row, or null to default to
* all null values
* @param rf
* the RowFormatter for this row
*/
OffHeapCompactExecRow(final DataValueDescriptor[] dvds, final RowFormatter rf)
throws StandardException {
super(rf);
assert rf.isTableFormatter() || !rf.hasLobs():
"use a OffHeapCompactExecRowWithLobs instead";
if (dvds != null) {
this.source = rf.generateBytes(dvds);
}
else {
this.source = null; // treated as all null valued fields
}
}
/**
* Construct a OffHeapCompactExecRow given the storage byte[] and
* RowFormatter.
*
* @param rf
* the RowFormatter for this row
*/
OffHeapCompactExecRow(@Unretained final Object bytes,
final RowFormatter rf) {
super(rf);
this.source = bytes;
assert rf.isTableFormatter() || !rf.hasLobs():
"use a OffHeapCompactExecRowWithLobs instead";
}
OffHeapCompactExecRow(final byte[] bytes, final RowFormatter rf) {
super(rf);
this.source = bytes;
assert rf.isTableFormatter() || !rf.hasLobs():
"use a OffHeapCompactExecRowWithLobs instead";
}
OffHeapCompactExecRow(@Unretained final OffHeapRow bytes,
final RowFormatter rf) {
super(rf);
this.source = bytes;
assert rf.isTableFormatter() || !rf.hasLobs():
"use a OffHeapCompactExecRowWithLobs instead";
}
/**
* Construct a OffHeapCompactExecRow given the storage byte[], RowFormatter
* and initial set of DVDs to cache.
*/
OffHeapCompactExecRow(@Unretained final Object bytes,
final RowFormatter rf, final DataValueDescriptor[] row, final int rowLen,
final boolean doClone) {
super(rf, row, rowLen, doClone);
this.source = bytes;
assert rf.isTableFormatter() || !rf.hasLobs():
"use a OffHeapCompactExecRowWithLobs instead";
}
////////// OffHeapCompactExecRow specific methods //////////
/**
* Return the row as a byte[], or null if this row is full of null values.
*/
@Override
public final byte[] getRowBytes() {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return ((OffHeapRow)source).getRowBytes();
}
else if (cls == byte[].class) {
return (byte[])source;
}
else {
return ((OffHeapRowWithLobs)source).getRowBytes();
}
}
else {
return null;
}
}
@Override
public final byte[] getRowBytes(int logicalPosition) {
return this.getRowBytes();
}
@Override
public final boolean hasByteArrays() {
return false;
}
/**
* Get the raw value of the row
*/
@Override
public final Object getRawRowValue(final boolean doClone) {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return ((OffHeapRow)source).getRowBytes();
}
else if (cls == byte[].class) {
byte[] sourceBytes = (byte[])source;
if (doClone) {
byte[] newBytes = new byte[sourceBytes.length];
System.arraycopy(sourceBytes, 0, newBytes, 0, sourceBytes.length);
return newBytes;
}
else {
return sourceBytes;
}
}
else {
return ((OffHeapRowWithLobs)source).getRowBytes();
}
}
else {
return null;
}
}
////////// Abstract methods from AbstractCompactExecRow //////////
/**
* Get a DataValueDescriptor in a Row by ordinal position (1-based).
*
* @param position
* The ordinal position of the column.
*
* @exception StandardException
* Thrown on failure.
* @return The DataValueDescriptor, null if no such column exists
*/
@Override
protected final DataValueDescriptor basicGetColumn(int position)
throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return this.formatter.getColumn(position, (OffHeapRow)source);
}
else if (cls == byte[].class) {
return this.formatter.getColumn(position, (byte[])source);
}
else {
return this.formatter.getColumn(position, (OffHeapRowWithLobs)source);
}
}
else {
return this.formatter.getColumn(position, (byte[])null);
}
}
/**
* Set DataValueDescriptors in a Row.
*
* @param columns
* which columns from values to set, or null if all the values should
* be set.
* @param values
* a sparse array of the values to set
*/
@Override
protected final void basicSetColumns(FormatableBitSet columns,
DataValueDescriptor[] values) throws StandardException {
if (values.length > 0) {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
this.source = this.formatter.setColumns(columns, values,
(OffHeapRow)source, this.formatter);
}
else if (cls == byte[].class) {
this.source = this.formatter.setColumns(columns, values,
(byte[])source, this.formatter);
}
else {
this.source = this.formatter.setColumns(columns, values,
(OffHeapByteSource)source, this.formatter);
}
}
else {
this.source = this.formatter.setColumns(columns, values, (byte[])null,
this.formatter);
}
}
else {
assert this.formatter.getNumColumns() == 0: "if none of the values are "
+ "set such a condition can happen when DTD is also nothing";
// e.g. select count(*) from TABLE_XXX
}
}
/**
* {@inheritDoc}
*/
@Override
protected void basicSetColumn(int columnIndex, DataValueDescriptor value)
throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
this.source = this.formatter.setColumn(columnIndex, value,
(OffHeapRow)source, this.formatter);
}
else if (cls == byte[].class) {
this.source = this.formatter.setColumn(columnIndex, value,
(byte[])source, this.formatter);
}
else {
this.source = this.formatter.setColumn(columnIndex, value,
(OffHeapByteSource)source, this.formatter);
}
}
else {
this.source = this.formatter.setColumn(columnIndex, value, (byte[])null,
this.formatter);
}
}
/**
* {@inheritDoc}
*/
@Override
protected final void basicSetCompactColumns(FormatableBitSet columns,
DataValueDescriptor[] values) throws StandardException {
this.source = this.formatter.setByteCompactColumns(columns, values);
}
/**
* {@inheritDoc}
*/
@Override
protected final void basicSetColumns(final int nCols,
final DataValueDescriptor[] values) throws StandardException {
if (values.length > 0) {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
this.source = this.formatter.setColumns(nCols, values,
(OffHeapRow)source);
}
else if (cls == byte[].class) {
this.source = this.formatter
.setColumns(nCols, values, (byte[])source);
}
else {
this.source = this.formatter.setColumns(nCols, values,
(OffHeapByteSource)source);
}
}
else {
this.source = this.formatter.setColumns(nCols, values, (byte[])null);
}
}
else {
assert this.formatter.getNumColumns() == 0: "if none of the values are "
+ "set such a condition can happen when DTD is also nothing";
// e.g. select count(*) from TABLE_XXX
}
}
/**
* {@inheritDoc}
*/
@Override
protected final void basicSetColumns(final FormatableBitSet columns,
final AbstractCompactExecRow srcRow, final int[] baseColumnMap)
throws StandardException {
final Object fromSource = srcRow.getByteSource();
if (fromSource != null) {
final Class<?> cls = fromSource.getClass();
if (cls == OffHeapRow.class) {
this.source = this.formatter.setColumns(columns,
(OffHeapRow)fromSource, srcRow.formatter, baseColumnMap);
}
else if (cls == byte[].class) {
this.source = this.formatter.setColumns(columns, (byte[])fromSource,
srcRow.formatter, baseColumnMap);
}
else {
this.source = formatter.setColumns(columns,
(OffHeapByteSource)fromSource, srcRow.formatter, baseColumnMap);
}
}
else {
this.source = this.formatter.setColumns(columns, (byte[])null,
srcRow.formatter, baseColumnMap);
}
}
/**
* {@inheritDoc}
*/
@Override
protected final void basicSetColumns(int[] columns, boolean zeroBased,
AbstractCompactExecRow srcRow) throws StandardException {
final Object fromSource = srcRow.getByteSource();
if (fromSource != null) {
final Class<?> cls = fromSource.getClass();
if (cls == OffHeapRow.class) {
this.source = this.formatter.setColumns(columns, zeroBased,
(OffHeapRow)fromSource, srcRow.formatter);
}
else if (cls == byte[].class) {
this.source = this.formatter.setColumns(columns, zeroBased,
(byte[])fromSource, srcRow.formatter);
}
else {
this.source = this.formatter.setColumns(columns, zeroBased,
(OffHeapByteSource)fromSource, srcRow.formatter);
}
}
else {
this.source = this.formatter.setColumns(columns, zeroBased, (byte[])null,
srcRow.formatter);
}
}
/**
* Set first n-columns from given ExecRow.
*
* @param nCols
* number of columns from the start of ExecRow to be copied
* @param srcRow
* the source row from which to copy the columns
*/
@Override
protected final void basicSetColumns(int nCols, AbstractCompactExecRow srcRow)
throws StandardException {
final Object fromSource = srcRow.getByteSource();
if (fromSource != null) {
final Class<?> cls = fromSource.getClass();
if (cls == OffHeapRow.class) {
this.source = this.formatter.setColumns(nCols, (OffHeapRow)fromSource,
srcRow.formatter);
}
else if (cls == byte[].class) {
this.source = this.formatter.setColumns(nCols, (byte[])fromSource,
srcRow.formatter);
}
else {
this.source = this.formatter.setColumns(nCols,
(OffHeapByteSource)fromSource, srcRow.formatter);
}
}
else {
this.source = this.formatter.setColumns(nCols, (byte[])null,
srcRow.formatter);
}
}
/**
* Reset all the <code>DataValueDescriptor</code>s in the row array to (SQL)
* null values. This method may reuse (and therefore modify) the objects
* currently contained in the row array.
*/
@Override
protected final void basicResetRowArray() {
this.source = null;
if (this.setOfKeys != null) {
this.setOfKeys.clear();
}
}
/**
* Return the array of objects that the store needs.
*/
@Override
protected final DataValueDescriptor[] basicGetRowArray() {
try {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return this.formatter.getAllColumns((OffHeapRow)source);
}
else if (cls == byte[].class) {
return this.formatter.getAllColumns((byte[])source);
}
else {
return this.formatter.getAllColumns((OffHeapRowWithLobs)source);
}
}
else {
return this.formatter.getAllColumns((byte[])null);
}
} catch (final StandardException e) {
throw GemFireXDRuntimeException.newRuntimeException(
"OffHeapCompactExecRow#getRowArray: unexpected exception", e);
}
}
@Override
protected final void basicSetRowArray(final ExecRow otherRow) {
if (otherRow instanceof AbstractCompactExecRow) {
basicSetRowArray((AbstractCompactExecRow)otherRow);
}
else {
throw new UnsupportedOperationException(GfxdConstants.NOT_YET_IMPLEMENTED);
}
}
@Override
protected final void basicSetRowArray(final AbstractCompactExecRow otherRow) {
if (this.formatter != otherRow.formatter) {
this.formatter = otherRow.formatter;
}
// no need to call shallowClone(false) since it always returns this.
this.source = otherRow.getByteSource();
}
/**
* Set the array of objects
*/
@Override
protected final void basicSetRowArray(final byte[] rowArray,
final RowFormatter formatter) {
this.source = rowArray;
if (this.formatter != formatter) {
this.formatter = formatter;
}
}
@Override
protected void basicSetRowArray(byte[][] rowArray, RowFormatter formatter) {
if (this.formatter.container == formatter.container) {
// this can be happen due to ALTER TABLE
basicSetRowArray(rowArray[0], formatter);
}
else {
throw new UnsupportedOperationException(
"OffHeapCompactExecRow does not support byte[][]");
}
}
@Override
protected void basicSetDVDValues(final DataValueDescriptor[] dvds,
final int[] srcColumns, boolean zeroBased) throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
final OffHeapRow ohRow = (OffHeapRow)source;
final int bytesLen = ohRow.getLength();
final long memAddr = ohRow.getUnsafeAddress(0, bytesLen);
super.basicSetDVDValues(dvds, srcColumns, zeroBased,
UnsafeMemoryChunk.getUnsafeWrapper(), memAddr, bytesLen, ohRow,
null);
}
else if (cls == byte[].class) {
super.basicSetDVDValues(dvds, srcColumns, zeroBased, (byte[])source);
}
else {
final OffHeapRowWithLobs ohLobRow = (OffHeapRowWithLobs)source;
final int bytesLen = ohLobRow.getLength();
final long memAddr = ohLobRow.getUnsafeAddress(0, bytesLen);
super.basicSetDVDValues(dvds, srcColumns, zeroBased,
UnsafeMemoryChunk.getUnsafeWrapper(), memAddr, bytesLen, null,
ohLobRow);
}
}
else {
for (DataValueDescriptor dvd : dvds) {
if (dvd != null) {
dvd.restoreToNull();
}
}
}
}
@Override
protected final byte[][] getRowByteArrays() {
throw new UnsupportedOperationException(
"OffHeapCompactExecRow does not support byte[][]");
}
@Override
protected final byte[][] getRowByteArraysIfPresent() {
return null;
}
@Override
public UTF8String getAsUTF8String(int index) throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return this.formatter.getAsUTF8String(index, (OffHeapRow)source);
} else if (cls == byte[].class) {
return this.formatter.getAsUTF8String(index, (byte[])source);
} else {
return this.formatter.getAsUTF8String(index,
(OffHeapRowWithLobs)source);
}
} else {
return null;
}
}
@Override
protected String getString(int position, ResultWasNull wasNull)
throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return this.formatter
.getAsString(position, (OffHeapRow)source, wasNull);
}
else if (cls == byte[].class) {
return this.formatter.getAsString(position, (byte[])source, wasNull);
}
else {
return this.formatter.getAsString(position, (OffHeapRowWithLobs)source,
wasNull);
}
}
else {
return this.formatter.getAsString(position, (byte[])null, wasNull);
}
}
@Override
protected Object getObject(int position, ResultWasNull wasNull)
throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return this.formatter
.getAsObject(position, (OffHeapRow)source, wasNull);
}
else if (cls == byte[].class) {
return this.formatter.getAsObject(position, (byte[])source, wasNull);
}
else {
return this.formatter.getAsObject(position, (OffHeapRowWithLobs)source,
wasNull);
}
}
else {
return this.formatter.getAsObject(position, (byte[])null, wasNull);
}
}
@Override
protected boolean getBoolean(int position, ResultWasNull wasNull)
throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return this.formatter.getAsBoolean(position, (OffHeapRow)source,
wasNull);
}
else if (cls == byte[].class) {
return this.formatter.getAsBoolean(position, (byte[])source, wasNull);
}
else {
return this.formatter.getAsBoolean(position,
(OffHeapRowWithLobs)source, wasNull);
}
}
else {
return this.formatter.getAsBoolean(position, (byte[])null, wasNull);
}
}
@Override
protected byte getByte(int position, ResultWasNull wasNull)
throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return this.formatter.getAsByte(position, (OffHeapRow)source, wasNull);
}
else if (cls == byte[].class) {
return this.formatter.getAsByte(position, (byte[])source, wasNull);
}
else {
return this.formatter.getAsByte(position, (OffHeapRowWithLobs)source,
wasNull);
}
}
else {
return this.formatter.getAsByte(position, (byte[])null, wasNull);
}
}
@Override
protected short getShort(int position, ResultWasNull wasNull)
throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return this.formatter.getAsShort(position, (OffHeapRow)source, wasNull);
}
else if (cls == byte[].class) {
return this.formatter.getAsShort(position, (byte[])source, wasNull);
}
else {
return this.formatter.getAsShort(position, (OffHeapRowWithLobs)source,
wasNull);
}
}
else {
return this.formatter.getAsShort(position, (byte[])null, wasNull);
}
}
@Override
protected int getInt(int position, ResultWasNull wasNull)
throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return this.formatter.getAsInt(position, (OffHeapRow)source, wasNull);
}
else if (cls == byte[].class) {
return this.formatter.getAsInt(position, (byte[])source, wasNull);
}
else {
return this.formatter.getAsInt(position, (OffHeapRowWithLobs)source,
wasNull);
}
}
else {
return this.formatter.getAsInt(position, (byte[])null, wasNull);
}
}
@Override
protected long getLong(int position, ResultWasNull wasNull)
throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return this.formatter.getAsLong(position, (OffHeapRow)source, wasNull);
}
else if (cls == byte[].class) {
return this.formatter.getAsLong(position, (byte[])source, wasNull);
}
else {
return this.formatter.getAsLong(position, (OffHeapRowWithLobs)source,
wasNull);
}
}
else {
return this.formatter.getAsLong(position, (byte[])null, wasNull);
}
}
@Override
protected float getFloat(int position, ResultWasNull wasNull)
throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return this.formatter.getAsFloat(position, (OffHeapRow)source, wasNull);
}
else if (cls == byte[].class) {
return this.formatter.getAsFloat(position, (byte[])source, wasNull);
}
else {
return this.formatter.getAsFloat(position, (OffHeapRowWithLobs)source,
wasNull);
}
}
else {
return this.formatter.getAsFloat(position, (byte[])null, wasNull);
}
}
@Override
protected double getDouble(int position, ResultWasNull wasNull)
throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return this.formatter
.getAsDouble(position, (OffHeapRow)source, wasNull);
}
else if (cls == byte[].class) {
return this.formatter.getAsDouble(position, (byte[])source, wasNull);
}
else {
return this.formatter.getAsDouble(position, (OffHeapRowWithLobs)source,
wasNull);
}
}
else {
return this.formatter.getAsDouble(position, (byte[])null, wasNull);
}
}
@Override
protected byte[] getBytes(int position, ResultWasNull wasNull)
throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return this.formatter.getAsBytes(position, (OffHeapRow)source, wasNull);
}
else if (cls == byte[].class) {
return this.formatter.getAsBytes(position, (byte[])source, wasNull);
}
else {
return this.formatter.getAsBytes(position, (OffHeapRowWithLobs)source,
wasNull);
}
}
else {
return this.formatter.getAsBytes(position, (byte[])null, wasNull);
}
}
@Override
protected BigDecimal getBigDecimal(int position, ResultWasNull wasNull)
throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return this.formatter.getAsBigDecimal(position, (OffHeapRow)source,
wasNull);
}
else if (cls == byte[].class) {
return this.formatter
.getAsBigDecimal(position, (byte[])source, wasNull);
}
else {
return this.formatter.getAsBigDecimal(position,
(OffHeapRowWithLobs)source, wasNull);
}
}
else {
return this.formatter.getAsBigDecimal(position, (byte[])null, wasNull);
}
}
@Override
public long getAsDateMillis(int index, Calendar cal,
ResultWasNull wasNull) throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return this.formatter.getAsDateMillis(index, (OffHeapRow)source, cal,
wasNull);
} else if (cls == byte[].class) {
return this.formatter.getAsDateMillis(index, (byte[])source,
cal, wasNull);
} else {
return this.formatter.getAsDateMillis(index, (OffHeapRowWithLobs)source,
cal, wasNull);
}
} else {
if (wasNull != null) wasNull.setWasNull();
return 0L;
}
}
@Override
protected java.sql.Date getDate(int position, Calendar cal,
ResultWasNull wasNull) throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return this.formatter.getAsDate(position, (OffHeapRow)source, cal,
wasNull);
}
else if (cls == byte[].class) {
return this.formatter.getAsDate(position, (byte[])source, cal, wasNull);
}
else {
return this.formatter.getAsDate(position, (OffHeapRowWithLobs)source,
cal, wasNull);
}
}
else {
return this.formatter.getAsDate(position, (byte[])null, cal, wasNull);
}
}
@Override
protected java.sql.Time getTime(int position, Calendar cal,
ResultWasNull wasNull) throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return this.formatter.getAsTime(position, (OffHeapRow)source, cal,
wasNull);
}
else if (cls == byte[].class) {
return this.formatter.getAsTime(position, (byte[])source, cal, wasNull);
}
else {
return this.formatter.getAsTime(position, (OffHeapRowWithLobs)source,
cal, wasNull);
}
}
else {
return this.formatter.getAsTime(position, (byte[])null, cal, wasNull);
}
}
@Override
public long getAsTimestampMicros(int index, Calendar cal,
ResultWasNull wasNull) throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return this.formatter.getAsTimestampMicros(index, (OffHeapRow)source, cal,
wasNull);
} else if (cls == byte[].class) {
return this.formatter.getAsTimestampMicros(index, (byte[])source, cal,
wasNull);
} else {
return this.formatter.getAsTimestampMicros(index,
(OffHeapRowWithLobs)source, cal, wasNull);
}
} else {
if (wasNull != null) wasNull.setWasNull();
return 0L;
}
}
@Override
protected java.sql.Timestamp getTimestamp(int position, Calendar cal,
ResultWasNull wasNull) throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return this.formatter.getAsTimestamp(position, (OffHeapRow)source, cal,
wasNull);
}
else if (cls == byte[].class) {
return this.formatter.getAsTimestamp(position, (byte[])source, cal,
wasNull);
}
else {
return this.formatter.getAsTimestamp(position,
(OffHeapRowWithLobs)source, cal, wasNull);
}
}
else {
return this.formatter
.getAsTimestamp(position, (byte[])null, cal, wasNull);
}
}
////////// ExecRow methods //////////
public final void setRowArrayClone(final ExecRow otherRow,
final TreeSet<RegionAndKey> allKeys) {
if (otherRow instanceof AbstractCompactExecRow) {
basicSetRowArray((AbstractCompactExecRow)otherRow);
clearCachedRow();
}
else {
setRowArray(otherRow.getRowArray());
}
this.setOfKeys = allKeys;
}
/**
* Clone the Row and its contents.
*
* @return Row A clone of the Row and its contents.
*/
@Override
public final OffHeapCompactExecRow getClone() {
// no need to call shallowClone(false) since it always returns this
// bytes (this.source) are immutable and the formatter does not need to be
// cloned
final OffHeapCompactExecRow row = new OffHeapCompactExecRow(this.source,
this.formatter);
row.setOfKeys = this.setOfKeys;
return row;
}
@Override
public final OffHeapCompactExecRow getShallowClone() {
return getClone();
}
/**
* Get a new row with the same columns type as this one, containing nulls.
*
*/
@Override
public final OffHeapCompactExecRow getNewNullRow() {
return new OffHeapCompactExecRow(this.formatter);
}
@Override
public final int compare(final ExecRow row, final int logicalPosition,
final long thisOffsetWidth, final boolean nullsOrderedLow)
throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return compare(row, (OffHeapRow)source, logicalPosition,
thisOffsetWidth, nullsOrderedLow);
}
else if (cls == byte[].class) {
return compare(row, (byte[])source, logicalPosition, thisOffsetWidth,
nullsOrderedLow);
}
else {
return compare(row, (OffHeapRowWithLobs)source, logicalPosition,
thisOffsetWidth, nullsOrderedLow);
}
}
else {
return compare(row, (byte[])null, logicalPosition, thisOffsetWidth,
nullsOrderedLow);
}
}
@Override
public final int compare(final ExecRow row, final int logicalPosition,
final boolean nullsOrderedLow) throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
@Unretained
final OffHeapRow bytes = (OffHeapRow)source;
return super.compare(row, bytes, logicalPosition,
this.formatter.getOffsetAndWidth(logicalPosition, bytes),
nullsOrderedLow);
}
else if (cls == byte[].class) {
final byte[] bytes = (byte[])source;
return super.compare(row, bytes, logicalPosition,
this.formatter.getOffsetAndWidth(logicalPosition, bytes),
nullsOrderedLow);
}
else {
@Unretained final OffHeapRowWithLobs bytes = (OffHeapRowWithLobs)source;
// this should never lead to LOB comparison
assert !this.formatter.getColumnDescriptor(logicalPosition - 1).isLob:
this.formatter.getColumnDescriptor(logicalPosition - 1).toString();
return super.compare(row, bytes, logicalPosition,
this.formatter.getOffsetAndWidth(logicalPosition, bytes),
nullsOrderedLow);
}
}
else {
return super.compare(row, (byte[])null, logicalPosition,
RowFormatter.OFFSET_AND_WIDTH_IS_NULL, nullsOrderedLow);
}
}
@Override
public final int computeHashCode(final int position, int hash) {
final Object source = this.source;
if (source != null) {
if (source instanceof byte[]) {
return this.formatter.computeHashCode(position, (byte[])source, hash);
}
else {
@Unretained
final OffHeapByteSource bs = (OffHeapByteSource)source;
final int bytesLen = bs.getLength();
final long memAddr = bs.getUnsafeAddress(0, bytesLen);
return this.formatter.computeHashCode(position,
UnsafeMemoryChunk.getUnsafeWrapper(), memAddr, bytesLen, hash);
}
}
else {
return ResolverUtils.addByteToBucketHash((byte)0, hash, this.formatter
.getType(position).getTypeId().getTypeFormatId());
}
}
@Override
public long isNull(final int logicalPosition) throws StandardException {
final Object source = this.source;
if (source != null) {
final Class<?> cls = source.getClass();
if (cls == OffHeapRow.class) {
return this.formatter.getOffsetAndWidth(logicalPosition,
(OffHeapRow)source);
}
else if (cls == byte[].class) {
return this.formatter.getOffsetAndWidth(logicalPosition,
(byte[])source);
}
else {
// this should never lead to LOB column read
assert !this.formatter.getColumnDescriptor(logicalPosition - 1).isLob:
this.formatter.getColumnDescriptor(logicalPosition - 1).toString();
return this.formatter.getOffsetAndWidth(logicalPosition,
(OffHeapRowWithLobs)source);
}
}
else {
return RowFormatter.OFFSET_AND_WIDTH_IS_NULL;
}
}
/*
@Override
public final int compareStringBytes(final byte[] sb1,
final DataValueDescriptor dvd, final int logicalPosition)
throws StandardException {
return compareStringBytes(sb1, dvd, this.bytes, logicalPosition);
}
*/
////////// Serialization related methods //////////
/**
* @see GfxdDataSerializable#getGfxdID()
*/
@Override
public byte getGfxdID() {
throw new UnsupportedOperationException(
"OffHeapCompactExecRow does not support getGfxdID()");
}
@Override
public void toData(final DataOutput out) throws IOException {
throw new UnsupportedOperationException(
"OffHeapCompactExecRow does not support toData");
}
@Override
public void fromData(DataInput in) throws IOException, ClassNotFoundException {
super.fromData(in);
this.source = DataSerializer.readByteArray(in);
}
@Override
@Unretained(OFFHEAP_COMPACT_EXEC_ROW_SOURCE)
public Object getByteSource() {
return this.source;
}
@Override
@Unretained(OFFHEAP_COMPACT_EXEC_ROW_SOURCE)
public Object getByteSource(int offset) {
return this.source;
}
@Override
void basicSetByteSource(
@Unretained(OFFHEAP_COMPACT_EXEC_ROW_SOURCE) Object source) {
this.source = source;
}
@Override
@Released(OFFHEAP_COMPACT_EXEC_ROW_SOURCE)
public void releaseByteSource() {
if (OffHeapHelper.release(this.source)) {
// no longer can safely refer to source
this.source = null;
}
}
@Override
@Unretained(OFFHEAP_COMPACT_EXEC_ROW_SOURCE)
public Object getBaseByteSource() {
return this.source;
}
}
| |
/*
* Requirements mandating inclusion:
*
* 3.2.1.6.3.1 User can specify Game Rules associated with particular Cards.
* 3.2.1.6.3.2 User can create Game Rules by selecting Game Events and adding a Game Action to that event.
* 3.2.1.6.3.3 User can create a Game Flow Sequence by linking Game Rules.
* 3.2.1.3.7.1 Load Event settings.
* 3.2.1.3.7.2 User can view Event actions and rules.
* 3.2.1.3.7.3 User can edit Event actions and rules.
* */
package view.EditorTab;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import model.GameRule;
import model.GameRuleType;
import model.RuleElementLineBlueprint;
import model.RuleElementRectangleBlueprint;
import java.util.ArrayList;
public class RuleElementRectangle extends Rectangle {
private Text name = new Text("");
private GameRule gameRule;
private Paint defaultBorderColor;
private boolean clicked = false;
private ArrayList<RuleElementRectangle> preRules = new ArrayList<>();
private ArrayList<RuleElementRectangle> postRules = new ArrayList<>();
private ArrayList<RuleElementLine> outLines = new ArrayList<>();
private ArrayList<RuleElementLine> inLines = new ArrayList<>();
private GameRuleType ruleType;
private double dragStartX;
private double dragStartY;
public RuleElementRectangle() {
super();
this.setListeners();
}
public RuleElementRectangle(double width, double height) {
super(width, height);
this.setListeners();
}
public RuleElementRectangle(double x, double y, double width, double height) {
super(x, y, width, height);
this.setListeners();
}
public RuleElementRectangle(double width, double height, Paint fill) {
super(width, height, fill);
this.setListeners();
}
/**
* Dynamically center the given name (string) in the rectangle, based on the given rectangle width and height.
*
* @param x Rectangle starting (top-left) x coordinate.
* @param y Rectangle starting (top-left) y coordinate.
* @param width Rectangle width.
* @param height Rectangle height.
* @param name Text (string) that goes inside the rectangle.
*/
public RuleElementRectangle(double x, double y, double width, double height, String name) {
super(x, y, width, height);
Text t = new Text(name);
t.setFont(new Font(15));
t.setWrappingWidth(width-20);
this.name = t;
double textWidth = t.getLayoutBounds().getWidth();
t.setX(x+(width-textWidth)/2);
double textHeight = t.getLayoutBounds().getHeight();
t.setY(y+(height-textHeight)/2);
this.setListeners();
}
/**
* Dynamically center the given Text (object) in the rectangle, based on the given rectangle width and height.
* Does not modify any of the properties in the given Text.
*
* @param x Rectangle starting (top-left) x coordinate.
* @param y Rectangle starting (top-left) y coordinate.
* @param width Rectangle width.
* @param height Rectangle height.
* @param name Text (JavaFX object) that goes inside the rectangle.
*/
public RuleElementRectangle(double x, double y, double width, double height, Text name) {
super(x, y, width, height);
this.name = name;
this.setListeners();
}
/**
* Dynamically generates the rectangle width and height based on (to fit) the given name.
*
* @param x Rectangle starting (top-left) x coordinate.
* @param y Rectangle starting (top-left) y coordinate.
* @param name Text that goes inside the rectangle.
*/
public RuleElementRectangle(double x, double y, String name) {
super(x, y, 150, 75);
Text t = new Text(name);
t.setFont(new Font(15));
this.name = t;
double rectWidth = calculateRectWidth();
double rectHeight = calculateRectHeight();
t.setWrappingWidth(rectWidth-20);
this.setX(x, true);
this.setY(y, true);
this.setWidth(rectWidth);
this.setHeight(rectHeight);
this.setListeners();
}
/**
* Dynamically generates the rectangle width and height based on (to fit) the given name.
* Accepts a ruleType parameter (an event or action), and sets the rectangle border accordingly.
*
* @param x Rectangle starting (top-left) x coordinate.
* @param y Rectangle starting (top-left) y coordinate.
* @param name Text that goes inside the rectangle.
* @param ruleType Either GameRuleType.EVENT or GameRuleType.ACTION. Used to set the rectangle border color.
*/
public RuleElementRectangle(double x, double y, String name, GameRuleType ruleType) {
this(x, y, name);
this.ruleType = ruleType;
this.setFill(Color.WHITE);
this.setStrokeWidth(2);
switch (ruleType) {
case EVENT:
this.setStroke(Color.BLUE);
this.defaultBorderColor = Color.BLUE;
break;
case ACTION:
this.setStroke(Color.RED);
this.defaultBorderColor = Color.RED;
break;
}
}
/**
* Constructs the rectangle from the given blueprint.
*
* @param blueprint A RuleElementRectangleBlueprint that will be used to construct this rectangle.
*/
public RuleElementRectangle(RuleElementRectangleBlueprint blueprint) {
this();
this.constructFromBlueprint(blueprint);
}
/**
* Constructs (sets the fields) of this rectangle given its blueprint.
*
* @param blueprint A RuleElementRectangleBlueprint that will be used to set all the fields of this rectangle.
*/
public void constructFromBlueprint(RuleElementRectangleBlueprint blueprint) {
this.setWidth(blueprint.getWidth());
this.setHeight(blueprint.getHeight());
this.setGameRule(blueprint.getGameRule());
this.setRuleType(blueprint.getRuleType());
this.setDefaultBorderColor(Color.valueOf(blueprint.getDefaultBorderColor()));
Text t = new Text(blueprint.getName());
t.setFont(new Font(15));
this.name = t;
t.setWrappingWidth(blueprint.getWidth()-20);
this.setX(blueprint.getX(), true);
this.setY(blueprint.getY(), true);
this.setFill(Color.WHITE);
this.setStrokeWidth(2);
this.setStroke(this.getDefaultBorderColor());
for (RuleElementRectangleBlueprint preRuleBlueprint : blueprint.getPreRules()) {
this.preRules.add(new RuleElementRectangle(preRuleBlueprint));
}
for (RuleElementRectangleBlueprint postRuleBlueprint : blueprint.getPostRules()) {
this.postRules.add(new RuleElementRectangle(postRuleBlueprint));
}
for (RuleElementLineBlueprint inLineBlueprint : blueprint.getInLines()) {
this.inLines.add(new RuleElementLine(inLineBlueprint));
}
for (RuleElementLineBlueprint outLineBlueprint : blueprint.getOutLines()) {
this.outLines.add(new RuleElementLine(outLineBlueprint));
}
this.setListeners();
}
/**
* Returns the expected/desired width of the rectangle, based on the name inside of it.
*
* @return The proper width of the rectangle.
*/
public double calculateRectWidth() {
double textWidth = name.getLayoutBounds().getWidth();
return textWidth + 40;
}
/**
* Returns the expected/desired height of the rectangle, based on the name inside of it.
*
* @return The proper height of the rectangle.
*/
public double calculateRectHeight() {
double textHeight = name.getLayoutBounds().getHeight();
return textHeight + 40;
}
/**
* Sets the x-coordinate of the Rectangle and sets its name accordingly, if setText is provided (true).
*
* @param x The x-coordinate to which the Rectangle will be set and the name will be levelled with.
* @param setText Boolean that determines whether the Rectangle name position will be adjusted.
*/
public void setX(double x, boolean setText) {
this.setX(x);
if (setText) {this.name.setX(x+20);}
}
/**
* Sets the y-coordinate of the Rectangle and sets its name accordingly, if setText is provided (true).
*
* @param y The y-coordinate to which the Rectangle will be set and the name will be levelled with.
* @param setText Boolean that determines whether the Rectangle name position will be adjusted.
*/
public void setY(double y, boolean setText) {
this.setY(y);
if (setText) {this.name.setY(y+33);}
}
/**
* Sets the x-coordinate of the Rectangle, its name, and lines, if setText and setLines are provided (true).
*
* @param x The x-coordinate to which the Rectangle will be set. The name will be centered inside this Rectangle
* position, and the lines will be centered on its border.
* @param setText Boolean that determines whether the Rectangle name position will be adjusted.
* @param setLines Boolean that determines whether the Rectangle line positions will be adjusted.
*/
public void setX(double x, boolean setText, boolean setLines) {
this.setX(x, setText);
if (setLines) {
if (this.inLines.size() > 0) {
for (RuleElementLine l : this.inLines) {
l.setEndX(this.getCenterX(), true);
}
}
if (this.outLines.size() > 0) {
for (RuleElementLine l : this.outLines) {
l.setStartX(this.getCenterX());
}
}
}
}
/**
* Sets the y-coordinate of the Rectangle, its name, and lines, if setText and setLines are provided (true).
*
* @param y The y-coordinate to which the Rectangle will be set. The name will be centered inside this Rectangle
* position, and the lines will be centered on its border.
* @param setText Boolean that determines whether the Rectangle name position will be adjusted.
* @param setLines Boolean that determines whether the Rectangle line positions will be adjusted.
*/
public void setY(double y, boolean setText, boolean setLines) {
this.setY(y, setText);
if (setLines) {
if (this.inLines.size() > 0) {
for (RuleElementLine l : this.inLines) {
l.setEndY(this.getY(), true);
}
}
if (this.outLines.size() > 0) {
for (RuleElementLine l : this.outLines) {
l.setStartY(this.getEndY());
}
}
}
}
/**
* Returns the x-coordinate of the center of the rectangle.
* Formula: ([rectangle width]/2) + [starting x-coordinate of rectangle]
*
* @return Center x-coordinate of rectangle.
*/
public double getCenterX() {
return this.getX()+(this.getWidth()/2);
}
/**
* Returns the y-coordinate of the center of the rectangle.
* Formula: ([rectangle height]/2) + [starting y-coordinate of rectangle]
*
* @return Center y-coordinate of rectangle.
*/
public double getCenterY() {
return this.getY()+(this.getHeight()/2);
}
/**
* Returns the x-coordinate of the end of the rectangle.
*
* @return End x-coordinate of rectangle.
*/
public double getEndX() {
return this.getX()+(this.getWidth());
}
/**
* Returns the y-coordinate of the end of the rectangle.
*
* @return End y-coordinate of rectangle.
*/
public double getEndY() {
return this.getY()+(this.getHeight());
}
/**
* Returns the x-coordinate of the Rectangle assuming its center at the specified value.
*
* @return The x-coordinate of the Rectangle given its center.
*/
public double getXForCenter(double centerX) {
return centerX-(this.getWidth()/2);
}
/**
* Returns the y-coordinate of the Rectangle assuming its center at the specified value.
*
* @return The y-coordinate of the Rectangle given its center.
*/
public double getYForCenter(double centerY) {
return centerY-(this.getHeight()/2);
}
/**
* Sets the x-coordinate of the center of the rectangle to the specified x value.
*/
public void setCenterX(double centerX) {
double x = this.getXForCenter(centerX);
this.setX(x, true);
}
/**
* Sets the y-coordinate of the center of the rectangle to the specified y value.
*/
public void setCenterY(double centerY) {
double y = this.getYForCenter(centerY);
this.setY(y, true);
}
/**
* Returns the name (string) within the rectangle.
*
* @return Rectangle name (string).
*/
public String getName() {
return this.name.getText();
}
/**
* Sets the name (string) inside the rectangle. No resizing to the rectangle itself.
* The name will automatically wrap within the rectangle if necessary.
*
* @param name New name (string) to update within the rectangle.
*/
public void setName(String name) {
this.name.setText(name);
this.name.setWrappingWidth(0.0);
this.setWidth(calculateRectWidth());
this.setHeight(calculateRectHeight());
this.name.setWrappingWidth(this.getWidth()-20);
this.setX(this.getX(), true, true);
this.setY(this.getY(), true, true);
}
/**
* Returns the Text (JavaFX object) within the rectangle.
*
* @return Rectangle Text (JavaFX object).
*/
public Text getTextObj() {
return this.name;
}
/**
* Sets the Text (JavaFX object) inside the rectangle. No resizing to the rectangle itself.
*
* @param text New Text (JavaFX object) to update within the rectangle.
*/
public void setTextObj(Text text) {
this.name = text;
}
/**
* Returns the Game Rule (GameEvent or GameAction) associated with this rectangle.
*
* @return Game Rule.
*/
public GameRule getGameRule() {
return this.gameRule;
}
/**
* Returns the class name of the Game Rule (GameEvent or GameAction) associated with this rectangle.
*
* @return Game Rule name.
*/
public String getGameRuleClassName() {
return this.gameRule.getClassName();
}
/**
* Sets the Game Rule (GameEvent or GameAction) associated with this rectangle.
*
* @param gameRule String representing a game rule (event or action).
*/
public void setGameRule(GameRule gameRule) {
this.gameRule = gameRule;
}
/**
* Return the Color of this Rectangle's border/stroke.
*
* @return defaultBorderColor (color of this rectangle's border/stroke)
*/
public Paint getDefaultBorderColor() {
return defaultBorderColor;
}
/**
* Set the Color of this Rectangle's border/stroke.
*
* @param defaultBorderColor Color to set the Rectangle border/stroke.
*/
public void setDefaultBorderColor(Paint defaultBorderColor) {
this.defaultBorderColor = defaultBorderColor;
}
/**
* Returns the value of this.clicked. True if the Rectangle is currently clicked (the border is a different color).
*
* @return Returns true if this Rectangle is currently clicked (this.clicked == true).
*/
public boolean isClicked() {
return this.clicked;
}
/**
* Sets the value of this.clicked; i.e., whether this Rectangle is currently clicked or not.
* If it is clicked, the Rectangle border should be a different color.
*/
public void setClicked(boolean clicked) {
this.clicked = clicked;
}
/**
* Returns this.preRules; an ArrayList of Rectangles that immediately precede this Rectangle.
*
* @return ArrayList of Game Rules that immediately precede this Game Rule
*/
public ArrayList<RuleElementRectangle> getPreRules() {
return this.preRules;
}
/**
* Sets this.preRules, given an ArrayList of Rectangles that immediately precede this Rectangle.
*
* @param preRules ArrayList of Rectangles that immediately precede this Rectangle
*/
public void setPreRules(ArrayList<RuleElementRectangle> preRules) {
this.preRules = preRules;
}
/**
* Adds a rectangle to the list of pre-rules - rules that immediately precede this rectangle in the rule tree.
*
* @param preRule A RuleElementRectangle that immediately precedes this rectangle in the rule tree.
*/
public void addPreRule(RuleElementRectangle preRule) {
this.preRules.add(preRule);
}
/**
* Returns this.postRules; an ArrayList of Rectangles that immediately proceed this Rectangle.
*
* @return ArrayList of Game Rules that immediately follow this Game Rule
*/
public ArrayList<RuleElementRectangle> getPostRules() {
return this.postRules;
}
/**
* Sets this.postRules, given an ArrayList of Rectangles that immediately proceed this Rectangle.
*
* @param postRules ArrayList of Rectangles that immediately follow this Rectangle
*/
public void setPostRules(ArrayList<RuleElementRectangle> postRules) {
this.postRules = postRules;
}
/**
* Adds a rectangle to the list of post-rules - rules that immediately proceed this rectangle in the rule tree.
*
* @param postRule A RuleElementRectangle that immediately proceeds this rectangle in the rule tree.
*/
public void addPostRule(RuleElementRectangle postRule) {
this.postRules.add(postRule);
}
/**
* Returns an ArrayList of Lines that are exiting from this Rectangle.
*
* @return this.outLines; ArrayList of Lines that exit from this Rectangle
*/
public ArrayList<RuleElementLine> getOutLines() {
return this.outLines;
}
/**
* Sets this.outLines; an ArrayList of Lines that are exiting from this Rectangle.
*
* @param outLines An ArrayList of Lines that are exiting from this Rectangle.
*/
public void setOutLines(ArrayList<RuleElementLine> outLines) {
this.outLines = outLines;
}
/**
* Returns an ArrayList of Lines that are entering this Rectangle.
*
* @return this.inLines; ArrayList of Lines that enter this Rectangle
*/
public ArrayList<RuleElementLine> getInLines() {
return this.inLines;
}
/**
* Sets this.inLines; an ArrayList of Lines that are entering this Rectangle.
*
* @param inLines An ArrayList of Lines that are entering this Rectangle.
*/
public void setInLines(ArrayList<RuleElementLine> inLines) {
this.inLines = inLines;
}
/**
* Returns the GameRuleType (ACTION or EVENT) associated with this rectangle.
*
* @return The type of game rule (event or action) that this rectangle represents.
*/
public GameRuleType getRuleType() {
return this.ruleType;
}
/**
* Sets this.ruleType; the GameRuleType associated with this rectangle.
*
* @param ruleType The type of game rule (event or action) of this rectangle.
*/
public void setRuleType(GameRuleType ruleType) {
this.ruleType = ruleType;
}
/**
* Listener for the mouse entering the rectangle. Changes the border color, but saves the old (original) one.
*
* @param e MouseEvent
*/
public void onMouseEntered(MouseEvent e) {
if (!this.clicked) {
if (this.defaultBorderColor == null) {
this.defaultBorderColor = this.getStroke();
}
this.setStroke(Color.GAINSBORO);
}
}
/**
* Listener for the mouse exiting the rectangle. Changes the border color back to the original color.
*
* @param e MouseEvent
*/
public void onMouseExited(MouseEvent e) {
if (!this.clicked) {
this.setStroke(this.defaultBorderColor);
}
}
/**
* Listener for the mouse being pressed on this rectangle. Used to log the starting mouse-drag position.
*
* @param e MouseEvent
*/
public void onMousePressed(MouseEvent e) {
this.dragStartX = e.getX();
this.dragStartY = e.getY();
}
/**
* Listener for the mouse being dragged (pressed and moved) while on this rectangle.
* Moves the Rectangle, name, and lines according to the drag movement.
*
* @param e MouseEvent
*/
public void onMouseDragged(MouseEvent e) {
double offsetX = e.getX()-this.dragStartX;
double offsetY = e.getY()-this.dragStartY;
this.setX(this.getX()+offsetX > 0 ? this.getX()+offsetX : 0, true, true);
this.setY(this.getY()+offsetY > 0 ? this.getY()+offsetY : 0, true, true);
this.dragStartX = e.getX();
this.dragStartY = e.getY();
}
/**
* Resets the border (stroke) color of the rectangle to its default (original) one.
*/
public void resetBorder() {
if (this.defaultBorderColor != null) {
this.setStroke(this.defaultBorderColor);
} else {
this.defaultBorderColor = this.getStroke();
}
}
@Override
public int hashCode() {
return super.hashCode() + this.name.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == this) {return true;}
if (obj == null) {return false;}
if (!(obj instanceof RuleElementRectangle)) {return false;}
RuleElementRectangle otherRect = (RuleElementRectangle) obj;
return (this.getX() == otherRect.getX()) &&
(this.getY() == otherRect.getY()) &&
(this.getWidth() == otherRect.getWidth()) &&
(this.getHeight() == otherRect.getHeight()) &&
(this.getName().equals(otherRect.getName())) &&
(this.getRuleType() == otherRect.getRuleType()) &&
(this.getGameRuleClassName().equals(otherRect.getGameRuleClassName()));
}
/**
* Sets listeners for this Rectangle.
*/
public void setListeners() {
this.setOnMouseEntered(this::onMouseEntered);
this.setOnMouseExited(this::onMouseExited);
this.setOnMousePressed(this::onMousePressed);
this.setOnMouseDragged(this::onMouseDragged);
this.name.setOnMouseEntered(this::onMouseEntered);
this.name.setOnMouseExited(this::onMouseExited);
this.name.setOnMousePressed(this::onMousePressed);
this.name.setOnMouseDragged(this::onMouseDragged);
}
}
| |
package net.wigle.wigleandroid;
import java.util.Arrays;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.SingleLineTransformationMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
/**
* configure settings
*/
public final class SettingsActivity extends ActionBarActivity implements DialogListener {
private static final int MENU_RETURN = 12;
private static final int MENU_ERROR_REPORT = 13;
private static final int ZERO_OUT_DIALOG=110;
private static final int MAX_OUT_DIALOG=111;
private static final int DONATE_DIALOG=112;
private static final int ANONYMOUS_DIALOG=113;
/** convenience, just get the darn new string */
public static abstract class SetWatcher implements TextWatcher {
@Override
public void afterTextChanged( final Editable s ) {}
@Override
public void beforeTextChanged( final CharSequence s, final int start, final int count, final int after ) {}
@Override
public void onTextChanged( final CharSequence s, final int start, final int before, final int count ) {
onTextChanged( s.toString() );
}
public abstract void onTextChanged( String s );
}
/** Called when the activity is first created. */
@Override
public void onCreate( final Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
// set language
MainActivity.setLocale( this );
setContentView( R.layout.settings );
// force media volume controls
this.setVolumeControlStream( AudioManager.STREAM_MUSIC );
// don't let the textbox have focus to start with, so we don't see a keyboard right away
final LinearLayout linearLayout = (LinearLayout) findViewById( R.id.linearlayout );
linearLayout.setFocusableInTouchMode(true);
linearLayout.requestFocus();
// get prefs
final SharedPreferences prefs = this.getSharedPreferences( ListFragment.SHARED_PREFS, 0);
final Editor editor = prefs.edit();
// donate
final CheckBox donate = (CheckBox) findViewById(R.id.donate);
final boolean isDonate = prefs.getBoolean( ListFragment.PREF_DONATE, false);
donate.setChecked( isDonate );
if ( isDonate ) {
eraseDonate();
}
donate.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged( final CompoundButton buttonView, final boolean isChecked ) {
if ( isChecked == prefs.getBoolean( ListFragment.PREF_DONATE, false) ) {
// this would cause no change, bail
return;
}
if ( isChecked ) {
// turn off until confirmed
buttonView.setChecked( false );
// confirm
MainActivity.createConfirmation( SettingsActivity.this,
getString(R.string.donate_question) + "\n\n" + getString(R.string.donate_explain), 0, DONATE_DIALOG);
}
else {
editor.putBoolean( ListFragment.PREF_DONATE, isChecked );
editor.commit();
}
}
});
// anonymous
final CheckBox beAnonymous = (CheckBox) findViewById(R.id.be_anonymous);
final EditText user = (EditText) findViewById(R.id.edit_username);
final EditText pass = (EditText) findViewById(R.id.edit_password);
final boolean isAnonymous = prefs.getBoolean( ListFragment.PREF_BE_ANONYMOUS, false);
if ( isAnonymous ) {
user.setEnabled( false );
pass.setEnabled( false );
}
beAnonymous.setChecked( isAnonymous );
beAnonymous.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged( final CompoundButton buttonView, final boolean isChecked ) {
if ( isChecked == prefs.getBoolean(ListFragment.PREF_BE_ANONYMOUS, false) ) {
// this would cause no change, bail
return;
}
if ( isChecked ) {
// turn off until confirmed
buttonView.setChecked( false );
// confirm
MainActivity.createConfirmation( SettingsActivity.this, "Upload anonymously?", 0, ANONYMOUS_DIALOG );
}
else {
// unset anonymous
user.setEnabled( true );
pass.setEnabled( true );
editor.putBoolean( ListFragment.PREF_BE_ANONYMOUS, false );
editor.commit();
// might have to remove or show register link
updateRegister();
}
}
});
// register link
final TextView register = (TextView) findViewById(R.id.register);
register.setText(Html.fromHtml("<a href='http://wigle.net/gps/gps/main/register'>Register</a>"
+ " at <a href='http://wigle.net/gps/gps/main/register'>WiGLE.net</a>"));
register.setMovementMethod(LinkMovementMethod.getInstance());
updateRegister();
user.setText( prefs.getString( ListFragment.PREF_USERNAME, "" ) );
user.addTextChangedListener( new SetWatcher() {
@Override
public void onTextChanged( final String s ) {
// ListActivity.debug("user: " + s);
editor.putString( ListFragment.PREF_USERNAME, s.trim() );
editor.commit();
// might have to remove or show register link
updateRegister();
}
});
final CheckBox showPassword = (CheckBox) findViewById(R.id.showpassword);
showPassword.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged( final CompoundButton buttonView, final boolean isChecked ) {
if ( isChecked ) {
pass.setTransformationMethod(SingleLineTransformationMethod.getInstance());
}
else {
pass.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
}
});
pass.setText( prefs.getString( ListFragment.PREF_PASSWORD, "" ) );
pass.addTextChangedListener( new SetWatcher() {
@Override
public void onTextChanged( final String s ) {
// ListActivity.debug("pass: " + s);
editor.putString( ListFragment.PREF_PASSWORD, s.trim() );
editor.commit();
}
});
final Button button = (Button) findViewById( R.id.speech_button );
button.setOnClickListener( new OnClickListener() {
@Override
public void onClick( final View view ) {
final Intent errorReportIntent = new Intent( SettingsActivity.this, SpeechActivity.class );
SettingsActivity.this.startActivity( errorReportIntent );
}
});
// db marker reset button and text
final TextView tv = (TextView) findViewById( R.id.reset_maxid_text );
tv.setText( getString(R.string.setting_high_up) + " " + prefs.getLong( ListFragment.PREF_DB_MARKER, 0L ) );
final Button resetMaxidButton = (Button) findViewById( R.id.reset_maxid_button );
resetMaxidButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick( final View buttonView ) {
MainActivity.createConfirmation( SettingsActivity.this, getString(R.string.setting_zero_out), 0, ZERO_OUT_DIALOG);
}
});
// db marker maxout button and text
final TextView maxtv = (TextView) findViewById( R.id.maxout_maxid_text );
final long maxDB = prefs.getLong( ListFragment.PREF_MAX_DB, 0L );
maxtv.setText( getString(R.string.setting_max_start) + " " + maxDB );
final Button maxoutMaxidButton = (Button) findViewById( R.id.maxout_maxid_button );
maxoutMaxidButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick( final View buttonView ) {
MainActivity.createConfirmation( SettingsActivity.this, getString(R.string.setting_max_out), 0, MAX_OUT_DIALOG);
}
} );
// period spinners
doScanSpinner( R.id.periodstill_spinner,
ListFragment.PREF_SCAN_PERIOD_STILL, MainActivity.SCAN_STILL_DEFAULT, getString(R.string.nonstop) );
doScanSpinner( R.id.period_spinner,
ListFragment.PREF_SCAN_PERIOD, MainActivity.SCAN_DEFAULT, getString(R.string.nonstop) );
doScanSpinner( R.id.periodfast_spinner,
ListFragment.PREF_SCAN_PERIOD_FAST, MainActivity.SCAN_FAST_DEFAULT, getString(R.string.nonstop) );
doScanSpinner( R.id.gps_spinner,
ListFragment.GPS_SCAN_PERIOD, MainActivity.LOCATION_UPDATE_INTERVAL, getString(R.string.setting_tie_wifi) );
MainActivity.prefBackedCheckBox(this, R.id.edit_showcurrent, ListFragment.PREF_SHOW_CURRENT, true);
MainActivity.prefBackedCheckBox(this, R.id.use_metric, ListFragment.PREF_METRIC, false);
MainActivity.prefBackedCheckBox(this, R.id.found_sound, ListFragment.PREF_FOUND_SOUND, true);
MainActivity.prefBackedCheckBox(this, R.id.found_new_sound, ListFragment.PREF_FOUND_NEW_SOUND, true);
MainActivity.prefBackedCheckBox(this, R.id.circle_size_map, ListFragment.PREF_CIRCLE_SIZE_MAP, false);
MainActivity.prefBackedCheckBox(this, R.id.use_network_location, ListFragment.PREF_USE_NETWORK_LOC, false);
MainActivity.prefBackedCheckBox(this, R.id.use_wigle_tiles, ListFragment.PREF_USE_WIGLE_TILES, false);
MainActivity.prefBackedCheckBox(this, R.id.disable_toast, ListFragment.PREF_DISABLE_TOAST, false);
// speech spinner
Spinner spinner = (Spinner) findViewById( R.id.speak_spinner );
if ( ! TTS.hasTTS() ) {
// no text to speech :(
spinner.setEnabled( false );
final TextView speakText = (TextView) findViewById( R.id.speak_text );
speakText.setText(getString(R.string.no_tts));
}
final String[] languages = new String[]{ "", "en", "ar", "cs", "da", "de", "es", "fi", "fr",
"he", "hi", "it", "ja", "ko", "nl", "no", "pl", "pt", "pt-rBR", "ru", "sv", "tr", "zh" };
final String[] languageName = new String[]{ getString(R.string.auto), getString(R.string.language_en),
getString(R.string.language_ar), getString(R.string.language_cs), getString(R.string.language_da),
getString(R.string.language_de), getString(R.string.language_es), getString(R.string.language_fi),
getString(R.string.language_fr), getString(R.string.language_he), getString(R.string.language_hi),
getString(R.string.language_it), getString(R.string.language_ja), getString(R.string.language_ko),
getString(R.string.language_nl), getString(R.string.language_no), getString(R.string.language_pl),
getString(R.string.language_pt), getString(R.string.language_pt_rBR), getString(R.string.language_ru),
getString(R.string.language_sv), getString(R.string.language_tr), getString(R.string.language_zh),
};
doSpinner( R.id.language_spinner, ListFragment.PREF_LANGUAGE, "", languages, languageName );
final String off = getString(R.string.off);
final String sec = " " + getString(R.string.sec);
final String min = " " + getString(R.string.min);
final Long[] speechPeriods = new Long[]{ 10L,15L,30L,60L,120L,300L,600L,900L,1800L,0L };
final String[] speechName = new String[]{ "10" + sec,"15" + sec,"30" + sec,
"1" + min,"2" + min,"5" + min,"10" + min,"15" + min,"30" + min, off };
doSpinner( R.id.speak_spinner,
ListFragment.PREF_SPEECH_PERIOD, MainActivity.DEFAULT_SPEECH_PERIOD, speechPeriods, speechName );
// battery kill spinner
final Long[] batteryPeriods = new Long[]{ 1L,2L,3L,4L,5L,10L,15L,20L,0L };
final String[] batteryName = new String[]{ "1 %","2 %","3 %","4 %","5 %","10 %","15 %","20 %",off };
doSpinner( R.id.battery_kill_spinner,
ListFragment.PREF_BATTERY_KILL_PERCENT, MainActivity.DEFAULT_BATTERY_KILL_PERCENT, batteryPeriods, batteryName );
// reset wifi spinner
final Long[] resetPeriods = new Long[]{ 15000L,30000L,60000L,90000L,120000L,300000L,600000L,0L };
final String[] resetName = new String[]{ "15" + sec, "30" + sec,"1" + min,"1.5" + min,
"2" + min,"5" + min,"10" + min,off };
doSpinner( R.id.reset_wifi_spinner,
ListFragment.PREF_RESET_WIFI_PERIOD, MainActivity.DEFAULT_RESET_WIFI_PERIOD, resetPeriods, resetName );
}
@Override
public void handleDialog(final int dialogId) {
final SharedPreferences prefs = this.getSharedPreferences( ListFragment.SHARED_PREFS, 0);
final Editor editor = prefs.edit();
switch (dialogId) {
case ZERO_OUT_DIALOG: {
editor.putLong( ListFragment.PREF_DB_MARKER, 0L );
editor.commit();
final TextView tv = (TextView) findViewById( R.id.reset_maxid_text );
tv.setText( getString(R.string.setting_max_id) + " 0" );
break;
}
case MAX_OUT_DIALOG: {
final long maxDB = prefs.getLong( ListFragment.PREF_MAX_DB, 0L );
editor.putLong( ListFragment.PREF_DB_MARKER, maxDB );
editor.commit();
// set the text on the other button
final TextView tv = (TextView) findViewById( R.id.reset_maxid_text );
tv.setText( getString(R.string.setting_max_id) + " " + maxDB );
break;
}
case DONATE_DIALOG: {
editor.putBoolean( ListFragment.PREF_DONATE, true );
editor.commit();
final CheckBox donate = (CheckBox) findViewById(R.id.donate);
donate.setChecked( true );
// poof
eraseDonate();
break;
}
case ANONYMOUS_DIALOG: {
// turn anonymous
final EditText user = (EditText) findViewById(R.id.edit_username);
final EditText pass = (EditText) findViewById(R.id.edit_password);
user.setEnabled( false );
pass.setEnabled( false );
editor.putBoolean( ListFragment.PREF_BE_ANONYMOUS, true );
editor.commit();
final CheckBox be_anonymous = (CheckBox) findViewById(R.id.be_anonymous);
be_anonymous.setChecked( true );
// might have to remove or show register link
updateRegister();
break;
}
default:
MainActivity.warn("Settings unhandled dialogId: " + dialogId);
}
}
@Override
public void onResume() {
MainActivity.info( "resume settings." );
final SharedPreferences prefs = this.getSharedPreferences( ListFragment.SHARED_PREFS, 0);
// donate
final boolean isDonate = prefs.getBoolean( ListFragment.PREF_DONATE, false);
if ( isDonate ) {
eraseDonate();
}
super.onResume();
}
private void updateRegister() {
final TextView register = (TextView) findViewById(R.id.register);
final SharedPreferences prefs = this.getSharedPreferences( ListFragment.SHARED_PREFS, 0);
final String username = prefs.getString( ListFragment.PREF_USERNAME, "" );
final boolean isAnonymous = prefs.getBoolean( ListFragment.PREF_BE_ANONYMOUS, false);
if ( "".equals(username) || isAnonymous ) {
register.setEnabled( true );
register.setVisibility( View.VISIBLE );
}
else {
// poof
register.setEnabled( false );
register.setVisibility( View.GONE );
}
}
private void eraseDonate() {
final CheckBox donate = (CheckBox) findViewById(R.id.donate);
donate.setEnabled(false);
donate.setVisibility(View.GONE);
}
private void doScanSpinner( final int id, final String pref, final long spinDefault, final String zeroName ) {
final String ms = " " + getString(R.string.ms_short);
final String sec = " " + getString(R.string.sec);
final String min = " " + getString(R.string.min);
final Long[] periods = new Long[]{ 0L,50L,250L,500L,750L,1000L,1500L,2000L,3000L,4000L,5000L,10000L,30000L,60000L };
final String[] periodName = new String[]{ zeroName,"50" + ms,"250" + ms,"500" + ms,"750" + ms,
"1" + sec,"1.5" + sec,"2" + sec,
"3" + sec,"4" + sec,"5" + sec,"10" + sec,"30" + sec,"1" + min };
doSpinner(id, pref, spinDefault, periods, periodName);
}
private <V> void doSpinner( final int id, final String pref, final V spinDefault,
final V[] periods, final String[] periodName ) {
if ( periods.length != periodName.length ) {
throw new IllegalArgumentException("lengths don't match, periods: " + Arrays.toString(periods)
+ " periodName: " + Arrays.toString(periodName));
}
final SharedPreferences prefs = this.getSharedPreferences( ListFragment.SHARED_PREFS, 0);
final Editor editor = prefs.edit();
Spinner spinner = (Spinner) findViewById( id );
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item);
Object period = null;
if ( periods instanceof Long[] ) {
period = prefs.getLong( pref, (Long) spinDefault );
}
else if ( periods instanceof String[] ) {
period = prefs.getString( pref, (String) spinDefault );
}
else {
MainActivity.error("unhandled object type array: " + Arrays.toString(periods) + " class: " + periods.getClass());
}
int periodIndex = 0;
for ( int i = 0; i < periods.length; i++ ) {
adapter.add( periodName[i] );
if ( period.equals(periods[i]) ) {
periodIndex = i;
}
}
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
spinner.setAdapter( adapter );
spinner.setSelection( periodIndex );
spinner.setOnItemSelectedListener( new OnItemSelectedListener() {
@Override
public void onItemSelected( final AdapterView<?> parent, final View v, final int position, final long id ) {
// set pref
final V period = periods[position];
MainActivity.info( pref + " setting scan period: " + period );
if ( period instanceof Long ) {
editor.putLong( pref, (Long) period );
}
else if ( period instanceof String ) {
editor.putString( pref, (String) period );
}
else {
MainActivity.error("unhandled object type: " + period + " class: " + period.getClass());
}
editor.commit();
if ( period instanceof String ) {
MainActivity.setLocale( SettingsActivity.this );
}
}
@Override
public void onNothingSelected( final AdapterView<?> arg0 ) {}
});
}
/* Creates the menu items */
@Override
public boolean onCreateOptionsMenu( final Menu menu ) {
MenuItem item = menu.add( 0, MENU_ERROR_REPORT, 0, getString(R.string.menu_error_report) );
item.setIcon( android.R.drawable.ic_menu_report_image );
item = menu.add(0, MENU_RETURN, 0, getString(R.string.menu_return));
item.setIcon( android.R.drawable.ic_media_previous );
return true;
}
/* Handles item selections */
@Override
public boolean onOptionsItemSelected( final MenuItem item ) {
switch ( item.getItemId() ) {
case MENU_RETURN:
finish();
return true;
case MENU_ERROR_REPORT:
final Intent errorReportIntent = new Intent( this, ErrorReportActivity.class );
this.startActivity( errorReportIntent );
break;
}
return false;
}
}
| |
/**
* Copyright 2005 Sakai Foundation Licensed under the
* Educational Community License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.osedu.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.sakaiproject.evaluation.tool.renderers;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.sakaiproject.evaluation.constant.EvalConstants;
import org.sakaiproject.evaluation.logic.EvalAuthoringService;
import org.sakaiproject.evaluation.model.EvalItem;
import org.sakaiproject.evaluation.model.EvalScale;
import org.sakaiproject.evaluation.model.EvalTemplateItem;
import org.sakaiproject.evaluation.tool.EvalToolConstants;
import org.sakaiproject.evaluation.tool.utils.RenderingUtils;
import org.sakaiproject.evaluation.utils.ArrayUtils;
import uk.org.ponder.arrayutil.MapUtil;
import uk.org.ponder.rsf.components.UIBranchContainer;
import uk.org.ponder.rsf.components.UIContainer;
import uk.org.ponder.rsf.components.UIJointContainer;
import uk.org.ponder.rsf.components.UILink;
import uk.org.ponder.rsf.components.UIMessage;
import uk.org.ponder.rsf.components.UIOutput;
import uk.org.ponder.rsf.components.UISelect;
import uk.org.ponder.rsf.components.UISelectChoice;
import uk.org.ponder.rsf.components.UISelectLabel;
import uk.org.ponder.rsf.components.UIVerbatim;
import uk.org.ponder.rsf.components.decorators.DecoratorList;
import uk.org.ponder.rsf.components.decorators.UIDisabledDecorator;
import uk.org.ponder.rsf.components.decorators.UIFreeAttributeDecorator;
import uk.org.ponder.rsf.components.decorators.UIStyleDecorator;
/**
* This handles the rendering of scaled type items
*
* @author Aaron Zeckoski (aaronz@vt.edu)
*/
public class BlockRenderer implements ItemRenderer {
private EvalAuthoringService authoringService;
public void setAuthoringService(EvalAuthoringService authoringService) {
this.authoringService = authoringService;
}
/**
* This identifies the template component associated with this renderer
*/
public static final String COMPONENT_ID = "render-block-item:";
/* (non-Javadoc)
* @see org.sakaiproject.evaluation.tool.renderers.ItemRenderer#renderItem(uk.org.ponder.rsf.components.UIContainer, java.lang.String, org.sakaiproject.evaluation.model.EvalTemplateItem, int, boolean)
*/
@SuppressWarnings("unchecked")
public UIJointContainer renderItem(UIContainer parent, String ID, String[] bindings, EvalTemplateItem templateItem, int displayNumber, boolean disabled, Map<String, Object> renderProperties) {
// check to make sure we are only dealing with block parents
if (templateItem.getBlockParent() == null) {
throw new IllegalArgumentException("Block renderer can only work for block items, this templateItem ("+templateItem.getId()+") has a null block parent");
} else if (! templateItem.getBlockParent() ||
templateItem.getBlockId() != null) {
throw new IllegalArgumentException("Block renderer can only work for block parents, this templateItem ("+templateItem.getId()+") is a block child");
}
List<EvalTemplateItem> childList = templateItem.childTemplateItems;
if (childList == null || childList.isEmpty()) {
// get the list of children the slow way if we have to
childList = authoringService.getBlockChildTemplateItemsForBlockParent(templateItem.getId(), false);
}
// check that the child count matches the bindings count
if ( ! disabled && (childList.size() != bindings.length) ) {
throw new IllegalArgumentException("The bindings array ("+bindings.length+") must match the size of the block child count ("+childList.size()+")");
}
UIJointContainer container = new UIJointContainer(parent, ID, COMPONENT_ID);
if (displayNumber <= 0) displayNumber = 0;
String initValue = null;
if (bindings[0] == null) initValue = "";
EvalScale scale = templateItem.getItem().getScale();
List<String> scaleOptions = scale.getOptions();
int optionCount = scaleOptions.size();
// handle NA
boolean usesNA = templateItem.getUsesNA();
String scaleValues[] = new String[optionCount];
String scaleLabels[] = new String[optionCount];
String scaleDisplaySetting = templateItem.getScaleDisplaySetting();
///////////////
// matrix block
///////////////
if (templateItem.getScaleDisplaySetting().equals(EvalConstants.ITEM_SCALE_DISPLAY_MATRIX) ||
templateItem.getScaleDisplaySetting().equals(EvalConstants.ITEM_SCALE_DISPLAY_MATRIX_COLORED)) {
for (int count = 1; count <= optionCount; count++) {
scaleValues[optionCount - count] = Integer.toString(optionCount - count);
scaleLabels[optionCount - count] = scaleOptions.get(count-1);
}
if (usesNA) {
scaleValues = ArrayUtils.appendArray(scaleValues, EvalConstants.NA_VALUE.toString());
scaleLabels = ArrayUtils.appendArray(scaleLabels, "");
}
UIBranchContainer matrixGroup = UIBranchContainer.make(container, "matrixGroupDisplay:");
if (usesNA) {
matrixGroup.decorate( new UIStyleDecorator("use-na") );
UIMessage.make(matrixGroup,"response-scale-label-na", "viewitem.na.desc");
}
// display header labels
List<String> headerLabels = RenderingUtils.getMatrixLabels(scaleOptions);
UIOutput.make(matrixGroup, "label-start", headerLabels.get(0));
UIOutput.make(matrixGroup, "label-end", headerLabels.get(1));
if (headerLabels.size() == 3) {
UIOutput.make(matrixGroup, "label-middle", headerLabels.get(2));
}
UIOutput.make(matrixGroup,"label-na", "NA");
UIVerbatim.make(matrixGroup, "matrixGroupTitle", templateItem.getItem().getItemText());
// display number labels
for (int i = 0; i < optionCount; i++) {
UIOutput.make(matrixGroup, "response-scale-label:", (i + 1) + "");
}
// iterate through each question in the block
for (int j = 0; j < childList.size(); j++) {
// build the question row container and apply decorations
UIBranchContainer matrix = UIBranchContainer.make(matrixGroup, "matrixDisplay:", j+"");
if (usesNA) {
matrix.decorate( new UIStyleDecorator("use-na") );
}
// get the child item
EvalTemplateItem childTemplateItem = (EvalTemplateItem) childList.get(j);
EvalItem childItem = childTemplateItem.getItem();
Map<String, Object> childRenderProperties = (Map<String, Object>) renderProperties.get("child-" + childTemplateItem.getId());
if (childRenderProperties.containsKey(ItemRenderer.EVAL_PROP_RENDER_INVALID)) {
matrix.decorate( new UIStyleDecorator("validFail") ); // must match the existing CSS class
} else if ( childRenderProperties.containsKey(ItemRenderer.EVAL_PROP_ANSWER_REQUIRED) ) {
matrix.decorate( new UIStyleDecorator("compulsory") ); // must match the existing CSS class
}
// display question text
UIOutput.make(matrix, "itemNum", Integer.toString(displayNumber + j) ); //$NON-NLS-2$
UIVerbatim.make(matrix, "itemText", childItem.getItemText());
UIBranchContainer rowBranch = UIBranchContainer.make(matrix, "response-list:");
// Bind the answers to a list of answers in evaluation bean (if enabled)
String childBinding = null;
if (! disabled && bindings != null) {
childBinding = bindings[j];
}
UISelect childRadios = UISelect.make(rowBranch, "childRadio", scaleValues, scaleLabels, childBinding, initValue);
String selectID = childRadios.getFullID();
if (disabled) {
childRadios.selection.willinput = false;
childRadios.selection.fossilize = false;
}
int scaleLength = scaleValues.length;
int limit = usesNA ? scaleLength - 1: scaleLength; // skip the NA value at the end
for (int k = 0; k < limit; ++k) {
UIBranchContainer radioBranchSecond = UIBranchContainer.make(rowBranch, "scaleOption:", k+"");
UISelectChoice.make(radioBranchSecond, "radioValue", selectID, k);
// scaleLabels are in reverse order, indexed from (end - 1) to 0. If usesNA,
// an empty label is appended; ignore that one too
int labelIndex = scaleLabels.length - k - (usesNA ? 2 : 1);
UIVerbatim.make(radioBranchSecond, "radioValueLabel", scaleLabels[labelIndex]);
}
// display the N/A radio button always; use CSS to hide if not needed (via the "use-na" class (above)
UIBranchContainer labelContainer = UIBranchContainer.make(rowBranch, "na-input-label:");
UISelectChoice naChoice = UISelectChoice.make(labelContainer, "na-input", selectID, scaleLength - 1);
if (!usesNA) {
naChoice.decorate( new UIDisabledDecorator());
}
UIMessage.make(rowBranch, "radioValueLabelNa", "viewitem.na.desc");
}
////////////////
// stepped block
////////////////
} else {
UIBranchContainer blockStepped = UIBranchContainer.make(container, "blockStepped:");
blockStepped.decorate( new UIStyleDecorator("options-"+optionCount) );
// setup simple variables to make code more clear
boolean colored = EvalConstants.ITEM_SCALE_DISPLAY_STEPPED_COLORED.equals(scaleDisplaySetting) ||
EvalConstants.ITEM_SCALE_DISPLAY_MATRIX_COLORED.equals(scaleDisplaySetting);
for (int count = 1; count <= optionCount; count++) {
scaleValues[optionCount - count] = Integer.toString(optionCount - count);
scaleLabels[optionCount - count] = scaleOptions.get(count-1);
}
// handle ideal coloring
String idealImage = "";
if (colored) {
String ideal = scale.getIdeal();
// Get the scale ideal value (none, low, mid, high )
if (ideal == null || "*NULL*".equals(ideal)) {
// When no ideal is specified then just plain blue for both start and end
idealImage = EvalToolConstants.COLORED_IMAGE_URLS[0];
} else if (EvalConstants.SCALE_IDEAL_LOW.equals(ideal)) {
idealImage = EvalToolConstants.COLORED_IMAGE_URLS[1];
} else if (EvalConstants.SCALE_IDEAL_MID.equals(ideal)) {
idealImage = EvalToolConstants.COLORED_IMAGE_URLS[2];
} else if (EvalConstants.SCALE_IDEAL_HIGH.equals(ideal)) {
idealImage = EvalToolConstants.COLORED_IMAGE_URLS[3];
} else if (EvalConstants.SCALE_IDEAL_OUTSIDE.equals(ideal)) {
idealImage = EvalToolConstants.COLORED_IMAGE_URLS[4];
} else {
// use no decorators
}
}
// Radio Buttons
UISelect radioLabel = UISelect.make(blockStepped, "radioLabel", scaleValues, scaleLabels, null, false);
String selectIDLabel = radioLabel.getFullID();
if (usesNA) {
scaleValues = ArrayUtils.appendArray(scaleValues, EvalConstants.NA_VALUE.toString());
scaleLabels = ArrayUtils.appendArray(scaleLabels, "");
UIMessage.make(blockStepped, "na-desc", "viewitem.na.desc");
}
// render the stepped labels and images
int scaleLength = scaleValues.length;
int limit = usesNA ? scaleLength - 1: scaleLength; // skip the NA value at the end
for (int j = 0; j < limit; ++j) {
UIBranchContainer rowBranch = UIBranchContainer.make(blockStepped, "blockRowBranch:", j+"");
// put in the block header text (only once)
if (j == 0) {
UIVerbatim headerText = UIVerbatim.make(rowBranch, "itemText", templateItem.getItem().getItemText());
headerText.decorators =
new DecoratorList(new UIFreeAttributeDecorator( MapUtil.make("rowspan", (optionCount + 1) + "") ));
// add render markers if they are set for this block parent
if ( renderProperties.containsKey(ItemRenderer.EVAL_PROP_RENDER_INVALID) ) {
rowBranch.decorate( new UIStyleDecorator("validFail") ); // must match the existing CSS class
} else if ( renderProperties.containsKey(ItemRenderer.EVAL_PROP_ANSWER_REQUIRED) ) {
rowBranch.decorate( new UIStyleDecorator("compulsory") ); // must match the existing CSS class
}
}
// Actual label
UISelectLabel.make(rowBranch, "topLabel", selectIDLabel, j);
// Corner Image
UILink.make(rowBranch, "cornerImage", EvalToolConstants.STEPPED_IMAGE_URLS[0]);
// This branch container is created to help in creating the middle images after the LABEL
for (int k = 0; k < j; ++k) {
UIBranchContainer afterTopLabelBranch = UIBranchContainer.make(rowBranch, "blockAfterTopLabelBranch:", k+"");
UILink.make(afterTopLabelBranch, "middleImage", EvalToolConstants.STEPPED_IMAGE_URLS[1]);
}
// the down arrow images
UIBranchContainer bottomLabelBranch = UIBranchContainer.make(blockStepped, "blockBottomLabelBranch:", j+"");
UILink.make(bottomLabelBranch, "bottomImage", EvalToolConstants.STEPPED_IMAGE_URLS[2]);
}
// the child items rendering loop
for (int j = 0; j < childList.size(); j++) {
// get the child item
EvalTemplateItem childTemplateItem = (EvalTemplateItem) childList.get(j);
EvalItem childItem = childTemplateItem.getItem();
// get mapping props for the child
Map<String, Object> childRenderProps = (Map<String, Object>) renderProperties.get("child-"+childTemplateItem.getId());
if (childRenderProps == null) {
childRenderProps = new HashMap<>(0);
}
// For the radio buttons
UIBranchContainer childRow = UIBranchContainer.make(blockStepped, "childRow:", j+"" );
if ( childRenderProps.containsKey(ItemRenderer.EVAL_PROP_RENDER_INVALID) ) {
childRow.decorate( new UIStyleDecorator("validFail") ); // must match the existing CSS class
} else if ( childRenderProps.containsKey(ItemRenderer.EVAL_PROP_ANSWER_REQUIRED) ) {
childRow.decorate( new UIStyleDecorator("compulsory") ); // must match the existing CSS class
}
if (colored) {
UILink.make(childRow, "idealImage", idealImage);
}
// put in the item information (number and text)
UIOutput.make(childRow, "childNum", Integer.toString(displayNumber + j) );
UIVerbatim.make(childRow, "childText", childItem.getItemText());
// Bind the answers to a list of answers in evaluation bean (if enabled)
String childBinding = null;
if (! disabled && bindings != null) {
childBinding = bindings[j];
}
UISelect childRadios = UISelect.make(childRow, "childRadio", scaleValues, scaleLabels, childBinding, initValue);
String selectID = childRadios.getFullID();
if (disabled) {
childRadios.selection.willinput = false;
childRadios.selection.fossilize = false;
}
if (usesNA) {
UIBranchContainer na = UIBranchContainer.make(childRow, "na-parent:");
UISelectChoice.make(childRow, "na-input", selectID, scaleLength - 1);
}
// render child radio choices
for (int k = 0; k < limit; ++k) {
if (colored) {
UIBranchContainer radioBranchFirst = UIBranchContainer.make(childRow, "scaleOptionColored:", k+"");
UISelectChoice.make(radioBranchFirst, "radioValueColored", selectID, k);
// this is confusing but this is now the one underneath
UIBranchContainer radioBranchSecond = UIBranchContainer.make(childRow, "scaleOption:", k+"");
UIOutput.make(radioBranchSecond, "radioValue");
} else {
UIBranchContainer radioBranchSecond = UIBranchContainer.make(childRow, "scaleOption:", k+"");
UISelectChoice.make(radioBranchSecond, "radioValue", selectID, k);
}
}
}
}
return container;
}
/* (non-Javadoc)
* @see org.sakaiproject.evaluation.tool.renderers.ItemRenderer#getRenderType()
*/
public String getRenderType() {
return EvalConstants.ITEM_TYPE_BLOCK_PARENT;
}
}
| |
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package javax.swing;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.*;
import java.beans.Transient;
import java.util.Vector;
import java.util.Enumeration;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import javax.swing.event.*;
import javax.swing.border.Border;
import javax.swing.plaf.*;
import javax.accessibility.*;
/**
* An implementation of a menu bar. You add <code>JMenu</code> objects to the
* menu bar to construct a menu. When the user selects a <code>JMenu</code>
* object, its associated <code>JPopupMenu</code> is displayed, allowing the
* user to select one of the <code>JMenuItems</code> on it.
* <p>
* For information and examples of using menu bars see
* <a
href="https://docs.oracle.com/javase/tutorial/uiswing/components/menu.html">How to Use Menus</a>,
* a section in <em>The Java Tutorial.</em>
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans™
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
* <p>
* <strong>Warning:</strong>
* By default, pressing the Tab key does not transfer focus from a <code>
* JMenuBar</code> which is added to a container together with other Swing
* components, because the <code>focusTraversalKeysEnabled</code> property
* of <code>JMenuBar</code> is set to <code>false</code>. To resolve this,
* you should call the <code>JMenuBar.setFocusTraversalKeysEnabled(true)</code>
* method.
* @beaninfo
* attribute: isContainer true
* description: A container for holding and displaying menus.
*
* @author Georges Saab
* @author David Karlton
* @author Arnaud Weber
* @see JMenu
* @see JPopupMenu
* @see JMenuItem
*/
@SuppressWarnings("serial")
public class JMenuBar extends JComponent implements Accessible,MenuElement
{
/**
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "MenuBarUI";
/*
* Model for the selected subcontrol.
*/
private transient SingleSelectionModel selectionModel;
private boolean paintBorder = true;
private Insets margin = null;
/* diagnostic aids -- should be false for production builds. */
private static final boolean TRACE = false; // trace creates and disposes
private static final boolean VERBOSE = false; // show reuse hits/misses
private static final boolean DEBUG = false; // show bad params, misc.
/**
* Creates a new menu bar.
*/
public JMenuBar() {
super();
setFocusTraversalKeysEnabled(false);
setSelectionModel(new DefaultSingleSelectionModel());
updateUI();
}
/**
* Returns the menubar's current UI.
* @see #setUI
*/
public MenuBarUI getUI() {
return (MenuBarUI)ui;
}
/**
* Sets the L&F object that renders this component.
*
* @param ui the new MenuBarUI L&F object
* @see UIDefaults#getUI
* @beaninfo
* bound: true
* hidden: true
* attribute: visualUpdate true
* description: The UI object that implements the Component's LookAndFeel.
*/
public void setUI(MenuBarUI ui) {
super.setUI(ui);
}
/**
* Resets the UI property with a value from the current look and feel.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((MenuBarUI)UIManager.getUI(this));
}
/**
* Returns the name of the L&F class that renders this component.
*
* @return the string "MenuBarUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/**
* Returns the model object that handles single selections.
*
* @return the <code>SingleSelectionModel</code> property
* @see SingleSelectionModel
*/
public SingleSelectionModel getSelectionModel() {
return selectionModel;
}
/**
* Sets the model object to handle single selections.
*
* @param model the <code>SingleSelectionModel</code> to use
* @see SingleSelectionModel
* @beaninfo
* bound: true
* description: The selection model, recording which child is selected.
*/
public void setSelectionModel(SingleSelectionModel model) {
SingleSelectionModel oldValue = selectionModel;
this.selectionModel = model;
firePropertyChange("selectionModel", oldValue, selectionModel);
}
/**
* Appends the specified menu to the end of the menu bar.
*
* @param c the <code>JMenu</code> component to add
* @return the menu component
*/
public JMenu add(JMenu c) {
super.add(c);
return c;
}
/**
* Returns the menu at the specified position in the menu bar.
*
* @param index an integer giving the position in the menu bar, where
* 0 is the first position
* @return the <code>JMenu</code> at that position, or <code>null</code> if
* if there is no <code>JMenu</code> at that position (ie. if
* it is a <code>JMenuItem</code>)
*/
public JMenu getMenu(int index) {
Component c = getComponentAtIndex(index);
if (c instanceof JMenu)
return (JMenu) c;
return null;
}
/**
* Returns the number of items in the menu bar.
*
* @return the number of items in the menu bar
*/
public int getMenuCount() {
return getComponentCount();
}
/**
* Sets the help menu that appears when the user selects the
* "help" option in the menu bar. This method is not yet implemented
* and will throw an exception.
*
* @param menu the JMenu that delivers help to the user
*/
public void setHelpMenu(JMenu menu) {
throw new Error("setHelpMenu() not yet implemented.");
}
/**
* Gets the help menu for the menu bar. This method is not yet
* implemented and will throw an exception.
*
* @return the <code>JMenu</code> that delivers help to the user
*/
@Transient
public JMenu getHelpMenu() {
throw new Error("getHelpMenu() not yet implemented.");
}
/**
* Returns the component at the specified index.
*
* @param i an integer specifying the position, where 0 is first
* @return the <code>Component</code> at the position,
* or <code>null</code> for an invalid index
* @deprecated replaced by <code>getComponent(int i)</code>
*/
@Deprecated
public Component getComponentAtIndex(int i) {
if(i < 0 || i >= getComponentCount()) {
return null;
}
return getComponent(i);
}
/**
* Returns the index of the specified component.
*
* @param c the <code>Component</code> to find
* @return an integer giving the component's position, where 0 is first;
* or -1 if it can't be found
*/
public int getComponentIndex(Component c) {
int ncomponents = this.getComponentCount();
Component[] component = this.getComponents();
for (int i = 0 ; i < ncomponents ; i++) {
Component comp = component[i];
if (comp == c)
return i;
}
return -1;
}
/**
* Sets the currently selected component, producing a
* a change to the selection model.
*
* @param sel the <code>Component</code> to select
*/
public void setSelected(Component sel) {
SingleSelectionModel model = getSelectionModel();
int index = getComponentIndex(sel);
model.setSelectedIndex(index);
}
/**
* Returns true if the menu bar currently has a component selected.
*
* @return true if a selection has been made, else false
*/
public boolean isSelected() {
return selectionModel.isSelected();
}
/**
* Returns true if the menu bars border should be painted.
*
* @return true if the border should be painted, else false
*/
public boolean isBorderPainted() {
return paintBorder;
}
/**
* Sets whether the border should be painted.
*
* @param b if true and border property is not <code>null</code>,
* the border is painted.
* @see #isBorderPainted
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: Whether the border should be painted.
*/
public void setBorderPainted(boolean b) {
boolean oldValue = paintBorder;
paintBorder = b;
firePropertyChange("borderPainted", oldValue, paintBorder);
if (b != oldValue) {
revalidate();
repaint();
}
}
/**
* Paints the menubar's border if <code>BorderPainted</code>
* property is true.
*
* @param g the <code>Graphics</code> context to use for painting
* @see JComponent#paint
* @see JComponent#setBorder
*/
protected void paintBorder(Graphics g) {
if (isBorderPainted()) {
super.paintBorder(g);
}
}
/**
* Sets the margin between the menubar's border and
* its menus. Setting to <code>null</code> will cause the menubar to
* use the default margins.
*
* @param m an Insets object containing the margin values
* @see Insets
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The space between the menubar's border and its contents
*/
public void setMargin(Insets m) {
Insets old = margin;
this.margin = m;
firePropertyChange("margin", old, m);
if (old == null || !old.equals(m)) {
revalidate();
repaint();
}
}
/**
* Returns the margin between the menubar's border and
* its menus. If there is no previous margin, it will create
* a default margin with zero size.
*
* @return an <code>Insets</code> object containing the margin values
* @see Insets
*/
public Insets getMargin() {
if(margin == null) {
return new Insets(0,0,0,0);
} else {
return margin;
}
}
/**
* Implemented to be a <code>MenuElement</code> -- does nothing.
*
* @see #getSubElements
*/
public void processMouseEvent(MouseEvent event,MenuElement path[],MenuSelectionManager manager) {
}
/**
* Implemented to be a <code>MenuElement</code> -- does nothing.
*
* @see #getSubElements
*/
public void processKeyEvent(KeyEvent e,MenuElement path[],MenuSelectionManager manager) {
}
/**
* Implemented to be a <code>MenuElement</code> -- does nothing.
*
* @see #getSubElements
*/
public void menuSelectionChanged(boolean isIncluded) {
}
/**
* Implemented to be a <code>MenuElement</code> -- returns the
* menus in this menu bar.
* This is the reason for implementing the <code>MenuElement</code>
* interface -- so that the menu bar can be treated the same as
* other menu elements.
* @return an array of menu items in the menu bar.
*/
public MenuElement[] getSubElements() {
MenuElement result[];
Vector<MenuElement> tmp = new Vector<MenuElement>();
int c = getComponentCount();
int i;
Component m;
for(i=0 ; i < c ; i++) {
m = getComponent(i);
if(m instanceof MenuElement)
tmp.addElement((MenuElement) m);
}
result = new MenuElement[tmp.size()];
for(i=0,c=tmp.size() ; i < c ; i++)
result[i] = tmp.elementAt(i);
return result;
}
/**
* Implemented to be a <code>MenuElement</code>. Returns this object.
*
* @return the current <code>Component</code> (this)
* @see #getSubElements
*/
public Component getComponent() {
return this;
}
/**
* Returns a string representation of this <code>JMenuBar</code>.
* This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this <code>JMenuBar</code>
*/
protected String paramString() {
String paintBorderString = (paintBorder ?
"true" : "false");
String marginString = (margin != null ?
margin.toString() : "");
return super.paramString() +
",margin=" + marginString +
",paintBorder=" + paintBorderString;
}
/////////////////
// Accessibility support
////////////////
/**
* Gets the AccessibleContext associated with this JMenuBar.
* For JMenuBars, the AccessibleContext takes the form of an
* AccessibleJMenuBar.
* A new AccessibleJMenuBar instance is created if necessary.
*
* @return an AccessibleJMenuBar that serves as the
* AccessibleContext of this JMenuBar
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJMenuBar();
}
return accessibleContext;
}
/**
* This class implements accessibility support for the
* <code>JMenuBar</code> class. It provides an implementation of the
* Java Accessibility API appropriate to menu bar user-interface
* elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans™
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
@SuppressWarnings("serial")
protected class AccessibleJMenuBar extends AccessibleJComponent
implements AccessibleSelection {
/**
* Get the accessible state set of this object.
*
* @return an instance of AccessibleState containing the current state
* of the object
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
return states;
}
/**
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.MENU_BAR;
}
/**
* Get the AccessibleSelection associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleSelection interface on behalf of itself.
*
* @return this object
*/
public AccessibleSelection getAccessibleSelection() {
return this;
}
/**
* Returns 1 if a menu is currently selected in this menu bar.
*
* @return 1 if a menu is currently selected, else 0
*/
public int getAccessibleSelectionCount() {
if (isSelected()) {
return 1;
} else {
return 0;
}
}
/**
* Returns the currently selected menu if one is selected,
* otherwise null.
*/
public Accessible getAccessibleSelection(int i) {
if (isSelected()) {
if (i != 0) { // single selection model for JMenuBar
return null;
}
int j = getSelectionModel().getSelectedIndex();
if (getComponentAtIndex(j) instanceof Accessible) {
return (Accessible) getComponentAtIndex(j);
}
}
return null;
}
/**
* Returns true if the current child of this object is selected.
*
* @param i the zero-based index of the child in this Accessible
* object.
* @see AccessibleContext#getAccessibleChild
*/
public boolean isAccessibleChildSelected(int i) {
return (i == getSelectionModel().getSelectedIndex());
}
/**
* Selects the nth menu in the menu bar, forcing it to
* pop up. If another menu is popped up, this will force
* it to close. If the nth menu is already selected, this
* method has no effect.
*
* @param i the zero-based index of selectable items
* @see #getAccessibleStateSet
*/
public void addAccessibleSelection(int i) {
// first close up any open menu
int j = getSelectionModel().getSelectedIndex();
if (i == j) {
return;
}
if (j >= 0 && j < getMenuCount()) {
JMenu menu = getMenu(j);
if (menu != null) {
MenuSelectionManager.defaultManager().setSelectedPath(null);
// menu.setPopupMenuVisible(false);
}
}
// now popup the new menu
getSelectionModel().setSelectedIndex(i);
JMenu menu = getMenu(i);
if (menu != null) {
MenuElement me[] = new MenuElement[3];
me[0] = JMenuBar.this;
me[1] = menu;
me[2] = menu.getPopupMenu();
MenuSelectionManager.defaultManager().setSelectedPath(me);
// menu.setPopupMenuVisible(true);
}
}
/**
* Removes the nth selected item in the object from the object's
* selection. If the nth item isn't currently selected, this
* method has no effect. Otherwise, it closes the popup menu.
*
* @param i the zero-based index of selectable items
*/
public void removeAccessibleSelection(int i) {
if (i >= 0 && i < getMenuCount()) {
JMenu menu = getMenu(i);
if (menu != null) {
MenuSelectionManager.defaultManager().setSelectedPath(null);
// menu.setPopupMenuVisible(false);
}
getSelectionModel().setSelectedIndex(-1);
}
}
/**
* Clears the selection in the object, so that nothing in the
* object is selected. This will close any open menu.
*/
public void clearAccessibleSelection() {
int i = getSelectionModel().getSelectedIndex();
if (i >= 0 && i < getMenuCount()) {
JMenu menu = getMenu(i);
if (menu != null) {
MenuSelectionManager.defaultManager().setSelectedPath(null);
// menu.setPopupMenuVisible(false);
}
}
getSelectionModel().setSelectedIndex(-1);
}
/**
* Normally causes every selected item in the object to be selected
* if the object supports multiple selections. This method
* makes no sense in a menu bar, and so does nothing.
*/
public void selectAllAccessibleSelection() {
}
} // internal class AccessibleJMenuBar
/**
* Subclassed to check all the child menus.
* @since 1.3
*/
protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,
int condition, boolean pressed) {
// See if we have a local binding.
boolean retValue = super.processKeyBinding(ks, e, condition, pressed);
if (!retValue) {
MenuElement[] subElements = getSubElements();
for (MenuElement subElement : subElements) {
if (processBindingForKeyStrokeRecursive(
subElement, ks, e, condition, pressed)) {
return true;
}
}
}
return retValue;
}
static boolean processBindingForKeyStrokeRecursive(MenuElement elem,
KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
if (elem == null) {
return false;
}
Component c = elem.getComponent();
if ( !(c.isVisible() || (c instanceof JPopupMenu)) || !c.isEnabled() ) {
return false;
}
if (c != null && c instanceof JComponent &&
((JComponent)c).processKeyBinding(ks, e, condition, pressed)) {
return true;
}
MenuElement[] subElements = elem.getSubElements();
for (MenuElement subElement : subElements) {
if (processBindingForKeyStrokeRecursive(subElement, ks, e, condition, pressed)) {
return true;
// We don't, pass along to children JMenu's
}
}
return false;
}
/**
* Overrides <code>JComponent.addNotify</code> to register this
* menu bar with the current keyboard manager.
*/
public void addNotify() {
super.addNotify();
KeyboardManager.getCurrentManager().registerMenuBar(this);
}
/**
* Overrides <code>JComponent.removeNotify</code> to unregister this
* menu bar with the current keyboard manager.
*/
public void removeNotify() {
super.removeNotify();
KeyboardManager.getCurrentManager().unregisterMenuBar(this);
}
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
Object[] kvData = new Object[4];
int n = 0;
if (selectionModel instanceof Serializable) {
kvData[n++] = "selectionModel";
kvData[n++] = selectionModel;
}
s.writeObject(kvData);
}
/**
* See JComponent.readObject() for information about serialization
* in Swing.
*/
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException
{
s.defaultReadObject();
Object[] kvData = (Object[])(s.readObject());
for(int i = 0; i < kvData.length; i += 2) {
if (kvData[i] == null) {
break;
}
else if (kvData[i].equals("selectionModel")) {
selectionModel = (SingleSelectionModel)kvData[i + 1];
}
}
}
}
| |
package com.oy.u911.function.dribbble.model;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* Author : xiaoyu
* Date : 2017/10/2 12:40
* Describe :
*/
public class ShotJson implements Serializable {
@SerializedName("id")
private int mId;
@SerializedName("title")
private String mTitle;
@SerializedName("width")
private int mWidth;
@SerializedName("height")
private int mHeight;
@SerializedName("images")
private ImageJson mImages;
@SerializedName("views_count")
private int mViewCount;
@SerializedName("likes_count")
private int mLikeCount;
@SerializedName("comments_count")
private int mCommentCount;
@SerializedName("attachments_count")
private int mAttachmentCount;
@SerializedName("rebounds_count")
private int mReboundCount;
@SerializedName("buckets_count")
private int mBucketCount;
@SerializedName("created_at")
private Date mCreatedTime;
@SerializedName("updated_at")
private Date mUpdatedTime;
@SerializedName("html_url")
private String mHtmlUrl;
@SerializedName("attachments_url")
private String mAttachmentUrl;
@SerializedName("buckets_url")
private String mBucketUrl;
@SerializedName("comments_url")
private String mCommentUrl;
@SerializedName("likes_url")
private String mLikeUrl;
@SerializedName("projects_url")
private String mProjectUrl;
@SerializedName("rebounds_url")
private String mReboundUrl;
@SerializedName("animated")
private boolean mAnimated;
@SerializedName("tags")
private List<String> mTags;
@SerializedName("user")
private UserJson mUserJson;
@SerializedName("team")
private TeamJson mTeamJson;
public int getId() {
return mId;
}
public String getTitle() {
return mTitle;
}
public int getWidth() {
return mWidth;
}
public int getHeight() {
return mHeight;
}
public ImageJson getImages() {
return mImages;
}
public int getViewCount() {
return mViewCount;
}
public int getLikeCount() {
return mLikeCount;
}
public int getCommentCount() {
return mCommentCount;
}
public int getAttachmentCount() {
return mAttachmentCount;
}
public int getReboundCount() {
return mReboundCount;
}
public int getBucketCount() {
return mBucketCount;
}
public Date getCreatedTime() {
return mCreatedTime;
}
public Date getUpdatedTime() {
return mUpdatedTime;
}
public String getHtmlUrl() {
return mHtmlUrl;
}
public String getAttachmentUrl() {
return mAttachmentUrl;
}
public String getBucketUrl() {
return mBucketUrl;
}
public String getCommentUrl() {
return mCommentUrl;
}
public String getLikeUrl() {
return mLikeUrl;
}
public String getProjectUrl() {
return mProjectUrl;
}
public String getReboundUrl() {
return mReboundUrl;
}
public boolean isAnimated() {
return mAnimated;
}
public List<String> getTags() {
return mTags;
}
public UserJson getUserJson() {
return mUserJson;
}
public TeamJson getTeamJson() {
return mTeamJson;
}
@Override
public String toString() {
return "ShotJson{" +
"mId=" + mId +
", mTitle='" + mTitle + '\'' +
", mWidth=" + mWidth +
", mHeight=" + mHeight +
", mImages=" + mImages +
", mViewCount=" + mViewCount +
", mLikeCount=" + mLikeCount +
", mCommentCount=" + mCommentCount +
", mAttachmentCount=" + mAttachmentCount +
", mReboundCount=" + mReboundCount +
", mBucketCount=" + mBucketCount +
", mCreatedTime=" + mCreatedTime +
", mUpdatedTime=" + mUpdatedTime +
", mHtmlUrl='" + mHtmlUrl + '\'' +
", mAttachmentUrl='" + mAttachmentUrl + '\'' +
", mBucketUrl='" + mBucketUrl + '\'' +
", mCommentUrl='" + mCommentUrl + '\'' +
", mLikeUrl='" + mLikeUrl + '\'' +
", mProjectUrl='" + mProjectUrl + '\'' +
", mReboundUrl='" + mReboundUrl + '\'' +
", mAnimated=" + mAnimated +
", mTags=" + mTags +
", mUserJson=" + mUserJson +
", mTeamJson=" + mTeamJson +
'}';
}
}
| |
/*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.server.ft.journal;
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 alluxio.AlluxioTestDirectory;
import alluxio.AlluxioURI;
import alluxio.ClientContext;
import alluxio.ConfigurationRule;
import alluxio.Constants;
import alluxio.client.block.BlockMasterClient;
import alluxio.client.block.RetryHandlingBlockMasterClient;
import alluxio.client.file.FileSystem;
import alluxio.client.file.FileSystemTestUtils;
import alluxio.client.file.URIStatus;
import alluxio.client.meta.MetaMasterClient;
import alluxio.client.meta.RetryHandlingMetaMasterClient;
import alluxio.conf.PropertyKey;
import alluxio.conf.ServerConfiguration;
import alluxio.exception.BackupAbortedException;
import alluxio.exception.status.FailedPreconditionException;
import alluxio.grpc.BackupPOptions;
import alluxio.grpc.BackupPRequest;
import alluxio.grpc.BackupState;
import alluxio.grpc.CreateDirectoryPOptions;
import alluxio.grpc.CreateFilePOptions;
import alluxio.grpc.DeletePOptions;
import alluxio.grpc.ListStatusPOptions;
import alluxio.grpc.LoadMetadataPType;
import alluxio.grpc.WritePType;
import alluxio.master.MasterClientContext;
import alluxio.master.journal.JournalType;
import alluxio.multi.process.MultiProcessCluster;
import alluxio.multi.process.PortCoordination;
import alluxio.testutils.AlluxioOperationThread;
import alluxio.testutils.BaseIntegrationTest;
import alluxio.util.CommonUtils;
import alluxio.util.WaitForOptions;
import org.junit.After;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
/**
* Integration test for backing up and restoring alluxio master.
*/
public final class JournalBackupIntegrationTest extends BaseIntegrationTest {
public MultiProcessCluster mCluster;
private static final int GET_PRIMARY_INDEX_TIMEOUT_MS = 30000;
private static final int PRIMARY_KILL_TIMEOUT_MS = 30000;
private static final int WAIT_NODES_REGISTERED_MS = 30000;
@Rule
public ConfigurationRule mConf = new ConfigurationRule(new HashMap<PropertyKey, String>() {
{
put(PropertyKey.USER_METRICS_COLLECTION_ENABLED, "false");
}
}, ServerConfiguration.global());
@After
public void after() throws Exception {
if (mCluster != null) {
mCluster.destroy();
}
}
// This test needs to stop and start master many times, so it can take up to a minute to complete.
@Test
public void backupRestoreZk() throws Exception {
mCluster = MultiProcessCluster.newBuilder(PortCoordination.BACKUP_RESTORE_ZK)
.setClusterName("backupRestoreZk")
.setNumMasters(3)
.addProperty(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.UFS.toString())
// Masters become primary faster
.addProperty(PropertyKey.ZOOKEEPER_SESSION_TIMEOUT, "3sec")
.build();
backupRestoreTest(true);
}
@Test
public void backupRestoreMetastore_Heap() throws Exception {
mCluster = MultiProcessCluster.newBuilder(PortCoordination.BACKUP_RESTORE_METASSTORE_HEAP)
.setClusterName("backupRestoreMetastore_Heap")
.setNumMasters(1)
.setNumWorkers(1)
.addProperty(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.UFS.toString())
// Masters become primary faster
.addProperty(PropertyKey.ZOOKEEPER_SESSION_TIMEOUT, "1sec")
.addProperty(PropertyKey.MASTER_METASTORE, "HEAP")
.build();
backupRestoreMetaStoreTest();
}
@Test
public void backupRestoreMetastore_Rocks() throws Exception {
mCluster = MultiProcessCluster.newBuilder(PortCoordination.BACKUP_RESTORE_METASSTORE_ROCKS)
.setClusterName("backupRestoreMetastore_Rocks")
.setNumMasters(1)
.setNumWorkers(1)
.addProperty(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.UFS.toString())
// Masters become primary faster
.addProperty(PropertyKey.ZOOKEEPER_SESSION_TIMEOUT, "1sec")
.addProperty(PropertyKey.MASTER_METASTORE, "ROCKS")
.build();
backupRestoreMetaStoreTest();
}
// This test needs to stop and start master many times, so it can take up to a minute to complete.
@Test
public void backupRestoreEmbedded() throws Exception {
mCluster = MultiProcessCluster.newBuilder(PortCoordination.BACKUP_RESTORE_EMBEDDED)
.setClusterName("backupRestoreEmbedded")
.setNumMasters(3)
.addProperty(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.EMBEDDED.toString())
.build();
backupRestoreTest(true);
}
@Test
public void backupRestoreSingleMaster() throws Exception {
mCluster = MultiProcessCluster.newBuilder(PortCoordination.BACKUP_RESTORE_SINGLE)
.setClusterName("backupRestoreSingle")
.setNumMasters(1)
.addProperty(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.UFS.toString())
.build();
backupRestoreTest(false);
}
// Tests various protocols and configurations for backup delegation.
@Test
public void backupDelegationProtocol() throws Exception {
mCluster = MultiProcessCluster.newBuilder(PortCoordination.BACKUP_DELEGATION_PROTOCOL)
.setClusterName("backupDelegationProtocol")
.setNumMasters(3)
.addProperty(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.UFS.toString())
// Masters become primary faster
.addProperty(PropertyKey.ZOOKEEPER_SESSION_TIMEOUT, "1sec")
// For faster backup role handshake.
.addProperty(PropertyKey.MASTER_BACKUP_CONNECT_INTERVAL_MIN, "100ms")
.addProperty(PropertyKey.MASTER_BACKUP_CONNECT_INTERVAL_MAX, "100ms")
// Enable backup delegation
.addProperty(PropertyKey.MASTER_BACKUP_DELEGATION_ENABLED, "true")
.build();
File backups = AlluxioTestDirectory.createTemporaryDirectory("backups");
mCluster.start();
// Validate backup works with delegation.
waitForBackup(BackupPRequest.newBuilder().setTargetDirectory(backups.getAbsolutePath())
.setOptions(BackupPOptions.newBuilder().setLocalFileSystem(false)).build());
// Kill the primary.
int primaryIdx = mCluster.getPrimaryMasterIndex(GET_PRIMARY_INDEX_TIMEOUT_MS);
mCluster.waitForAndKillPrimaryMaster(PRIMARY_KILL_TIMEOUT_MS);
// Validate backup works again after leader fail-over.
waitForBackup(BackupPRequest.newBuilder().setTargetDirectory(backups.getAbsolutePath())
.setOptions(BackupPOptions.newBuilder().setLocalFileSystem(false)).build());
// Continue testing with 2 masters...
// Find standby master index.
int newPrimaryIdx = mCluster.getPrimaryMasterIndex(GET_PRIMARY_INDEX_TIMEOUT_MS);
int followerIdx = (newPrimaryIdx + 1) % 2;
if (followerIdx == primaryIdx) {
followerIdx = (followerIdx + 1) % 2;
}
// Kill the follower. (only leader remains).
mCluster.stopMaster(followerIdx);
// Wait for a second for process to terminate properly.
// This is so that backup request don't get delegated to follower before termination.
Thread.sleep(1000);
// Validate backup delegation fails.
try {
mCluster.getMetaMasterClient()
.backup(BackupPRequest.newBuilder().setTargetDirectory(backups.getAbsolutePath())
.setOptions(BackupPOptions.newBuilder().setLocalFileSystem(false)).build());
Assert.fail("Cannot delegate backup with no followers.");
} catch (FailedPreconditionException e) {
// Expected to fail since there is only single master.
}
// Should work with "AllowLeader" backup.
mCluster.getMetaMasterClient()
.backup(BackupPRequest.newBuilder().setTargetDirectory(backups.getAbsolutePath())
.setOptions(BackupPOptions.newBuilder().setLocalFileSystem(false).setAllowLeader(true))
.build());
// Restart the follower. (1 leader 1 follower remains).
mCluster.startMaster(followerIdx);
// Validate backup works again.
waitForBackup(BackupPRequest.newBuilder().setTargetDirectory(backups.getAbsolutePath())
.setOptions(BackupPOptions.newBuilder().setLocalFileSystem(false)).build());
// Schedule async backup.
UUID backupId = mCluster.getMetaMasterClient()
.backup(BackupPRequest.newBuilder().setTargetDirectory(backups.getAbsolutePath())
.setOptions(BackupPOptions.newBuilder().setLocalFileSystem(false).setRunAsync(true))
.build())
.getBackupId();
// Wait until backup is complete.
CommonUtils.waitFor("Backup completed.", () -> {
try {
return mCluster.getMetaMasterClient().getBackupStatus(backupId).getState()
.equals(BackupState.Completed);
} catch (Exception e) {
throw new RuntimeException(
String.format("Unexpected error while getting backup status: %s", e.toString()));
}
});
// Schedule a local backup to overwrite latest backup Id in the current leader.
mCluster.getMetaMasterClient()
.backup(BackupPRequest.newBuilder().setTargetDirectory(backups.getAbsolutePath())
.setOptions(BackupPOptions.newBuilder().setLocalFileSystem(false).setAllowLeader(true))
.build());
// Validate old backup can still be queried.
mCluster.getMetaMasterClient().getBackupStatus(backupId);
mCluster.notifySuccess();
}
// Tests various protocols and configurations for backup delegation during fail-overs.
@Test
public void backupDelegationFailoverProtocol() throws Exception {
mCluster = MultiProcessCluster.newBuilder(PortCoordination.BACKUP_DELEGATION_FAILOVER_PROTOCOL)
.setClusterName("backupDelegationFailoverProtocol")
.setNumMasters(2)
.addProperty(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.UFS.toString())
// Masters become primary faster
.addProperty(PropertyKey.ZOOKEEPER_SESSION_TIMEOUT, "1sec")
// For faster backup role handshake.
.addProperty(PropertyKey.MASTER_BACKUP_CONNECT_INTERVAL_MIN, "100ms")
.addProperty(PropertyKey.MASTER_BACKUP_CONNECT_INTERVAL_MAX, "100ms")
// Enable backup delegation
.addProperty(PropertyKey.MASTER_BACKUP_DELEGATION_ENABLED, "true")
// Set backup timeout to be shorter
.addProperty(PropertyKey.MASTER_BACKUP_ABANDON_TIMEOUT, "3sec")
.build();
File backups = AlluxioTestDirectory.createTemporaryDirectory("backups");
mCluster.start();
// Validate backup works with delegation.
waitForBackup(BackupPRequest.newBuilder().setTargetDirectory(backups.getAbsolutePath())
.setOptions(BackupPOptions.newBuilder().setLocalFileSystem(false)).build());
// Find standby master index.
int primaryIdx = mCluster.getPrimaryMasterIndex(GET_PRIMARY_INDEX_TIMEOUT_MS);
int followerIdx = (primaryIdx + 1) % 2;
// Schedule async backup.
UUID backupId = mCluster.getMetaMasterClient()
.backup(BackupPRequest.newBuilder().setTargetDirectory(backups.getAbsolutePath())
.setOptions(BackupPOptions.newBuilder().setLocalFileSystem(false).setRunAsync(true))
.build())
.getBackupId();
// Kill follower immediately before it sends the next heartbeat to leader.
mCluster.stopMaster(followerIdx);
// Wait until backup is abandoned.
CommonUtils.waitForResult("Backup abandoned.", () -> {
try {
return mCluster.getMetaMasterClient().getBackupStatus(backupId);
} catch (Exception e) {
throw new RuntimeException(
String.format("Unexpected error while getting backup status: %s", e.toString()));
}
}, (backupStatus) -> backupStatus.getError() instanceof BackupAbortedException);
// Restart follower to restore HA.
mCluster.startMaster(followerIdx);
// Validate delegated backup works again.
waitForBackup(BackupPRequest.newBuilder().setTargetDirectory(backups.getAbsolutePath())
.setOptions(BackupPOptions.newBuilder().setLocalFileSystem(false)).build());
// Schedule async backup.
mCluster.getMetaMasterClient()
.backup(BackupPRequest.newBuilder().setTargetDirectory(backups.getAbsolutePath())
.setOptions(BackupPOptions.newBuilder().setLocalFileSystem(false).setRunAsync(true))
.build())
.getBackupId();
// Kill leader immediately before it receives the next heartbeat from backup-worker.
mCluster.waitForAndKillPrimaryMaster(PRIMARY_KILL_TIMEOUT_MS);
// Wait until follower steps up.
assertEquals(mCluster.getPrimaryMasterIndex(GET_PRIMARY_INDEX_TIMEOUT_MS), followerIdx);
// Follower should step-up without problem and accept backup requests.
mCluster.getMetaMasterClient()
.backup(BackupPRequest.newBuilder().setTargetDirectory(backups.getAbsolutePath())
.setOptions(BackupPOptions.newBuilder().setLocalFileSystem(false).setAllowLeader(true))
.build());
mCluster.notifySuccess();
}
@Test
public void backupDelegationZk() throws Exception {
MultiProcessCluster.Builder clusterBuilder = MultiProcessCluster
.newBuilder(PortCoordination.BACKUP_DELEGATION_ZK)
.setClusterName("backupDelegationZk")
.setNumMasters(2)
.addProperty(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.UFS.toString())
// Masters become primary faster
.addProperty(PropertyKey.ZOOKEEPER_SESSION_TIMEOUT, "1sec")
// Enable backup delegation
.addProperty(PropertyKey.MASTER_BACKUP_DELEGATION_ENABLED, "true")
// For faster backup role handshake.
.addProperty(PropertyKey.MASTER_BACKUP_CONNECT_INTERVAL_MIN, "100ms")
.addProperty(PropertyKey.MASTER_BACKUP_CONNECT_INTERVAL_MAX, "100ms");
backupDelegationTest(clusterBuilder);
}
@Test
public void backupDelegationEmbedded() throws Exception {
MultiProcessCluster.Builder clusterBuilder =
MultiProcessCluster.newBuilder(PortCoordination.BACKUP_DELEGATION_EMBEDDED)
.setClusterName("backupDelegationEmbedded")
.setNumMasters(2)
.addProperty(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.EMBEDDED.toString())
// Enable backup delegation
.addProperty(PropertyKey.MASTER_BACKUP_DELEGATION_ENABLED, "true")
// For faster backup role handshake.
.addProperty(PropertyKey.MASTER_BACKUP_CONNECT_INTERVAL_MIN, "100ms")
.addProperty(PropertyKey.MASTER_BACKUP_CONNECT_INTERVAL_MAX, "100ms");
backupDelegationTest(clusterBuilder);
}
/**
* Used to wait until successful backup.
*
* It tolerates {@link FailedPreconditionException} that could be thrown when backup-workers have
* not established connection with the backup-leader yet.
*
* @param backupRequest the backup request
* @return backup uri
*/
private AlluxioURI waitForBackup(BackupPRequest backupRequest) throws Exception {
AtomicReference<AlluxioURI> backupUriRef = new AtomicReference<>(null);
CommonUtils.waitFor("Backup delegation to succeed.", () -> {
try {
backupUriRef.set(mCluster.getMetaMasterClient().backup(backupRequest).getBackupUri());
return true;
} catch (FailedPreconditionException e1) {
// Expected to fail with this until backup-workers connect with backup-leader.
return false;
} catch (Exception e2) {
throw new RuntimeException(
String.format("Backup failed with unexpected error: %s", e2.toString()));
}
}, WaitForOptions.defaults());
return backupUriRef.get();
}
private void backupRestoreTest(boolean testFailover) throws Exception {
File backups = AlluxioTestDirectory.createTemporaryDirectory("backups");
mCluster.start();
List<Thread> opThreads = new ArrayList<>();
// Run background threads to perform metadata operations while the journal backups and restores
// are happening.
for (int i = 0; i < 10; i++) {
AlluxioOperationThread thread = new AlluxioOperationThread(mCluster.getFileSystemClient());
thread.start();
opThreads.add(thread);
}
try {
FileSystem fs = mCluster.getFileSystemClient();
MetaMasterClient metaClient = getMetaClient(mCluster);
AlluxioURI dir1 = new AlluxioURI("/dir1");
fs.createDirectory(dir1,
CreateDirectoryPOptions.newBuilder().setWriteType(WritePType.MUST_CACHE).build());
AlluxioURI backup1 = metaClient
.backup(BackupPRequest.newBuilder().setTargetDirectory(backups.getAbsolutePath())
.setOptions(BackupPOptions.newBuilder().setLocalFileSystem(false)).build())
.getBackupUri();
AlluxioURI dir2 = new AlluxioURI("/dir2");
fs.createDirectory(dir2,
CreateDirectoryPOptions.newBuilder().setWriteType(WritePType.MUST_CACHE).build());
AlluxioURI backup2 = metaClient
.backup(BackupPRequest.newBuilder().setTargetDirectory(backups.getAbsolutePath())
.setOptions(BackupPOptions.newBuilder().setLocalFileSystem(false)).build())
.getBackupUri();
restartMastersFromBackup(backup2);
assertTrue(fs.exists(dir1));
assertTrue(fs.exists(dir2));
restartMastersFromBackup(backup1);
assertTrue(fs.exists(dir1));
assertFalse(fs.exists(dir2));
// Restart normally and make sure we remember the state from backup 1.
mCluster.stopMasters();
mCluster.startMasters();
assertTrue(fs.exists(dir1));
assertFalse(fs.exists(dir2));
if (testFailover) {
// Verify that failover works correctly.
mCluster.waitForAndKillPrimaryMaster(30 * Constants.SECOND_MS);
assertTrue(fs.exists(dir1));
assertFalse(fs.exists(dir2));
}
mCluster.notifySuccess();
} finally {
opThreads.forEach(Thread::interrupt);
}
}
private void backupDelegationTest(MultiProcessCluster.Builder clusterBuilder) throws Exception {
// Update configuration for each master to backup to a specific folder.
Map<Integer, Map<PropertyKey, String>> masterProps = new HashMap<>();
File backupsParent0 = AlluxioTestDirectory.createTemporaryDirectory("backups0");
File backupsParent1 = AlluxioTestDirectory.createTemporaryDirectory("backups1");
Map<PropertyKey, String> master0Props = new HashMap<>();
master0Props.put(PropertyKey.MASTER_BACKUP_DIRECTORY, backupsParent0.getAbsolutePath());
Map<PropertyKey, String> master1Props = new HashMap<>();
master1Props.put(PropertyKey.MASTER_BACKUP_DIRECTORY, backupsParent1.getAbsolutePath());
masterProps.put(0, master0Props);
masterProps.put(1, master1Props);
clusterBuilder.setMasterProperties(masterProps);
// Start cluster.
mCluster = clusterBuilder.build();
mCluster.start();
// Delegation test can work with 2 masters only.
assertEquals(2, mCluster.getMasterAddresses().size());
FileSystem fs = mCluster.getFileSystemClient();
AlluxioURI dir1 = new AlluxioURI("/dir1");
mCluster.getFileSystemClient().createDirectory(dir1,
CreateDirectoryPOptions.newBuilder().setWriteType(WritePType.MUST_CACHE).build());
AlluxioURI backupUri = waitForBackup(BackupPRequest.newBuilder()
.setOptions(BackupPOptions.newBuilder().setLocalFileSystem(true)).build());
int primaryIndex = mCluster.getPrimaryMasterIndex(GET_PRIMARY_INDEX_TIMEOUT_MS);
int followerIndex = (primaryIndex + 1) % 2;
// Validate backup is taken on follower's local path.
assertTrue(backupUri.toString()
.contains(masterProps.get(followerIndex).get(PropertyKey.MASTER_BACKUP_DIRECTORY)));
// Validate backup is valid.
restartMastersFromBackup(backupUri);
assertTrue(fs.exists(dir1));
mCluster.notifySuccess();
}
private void backupRestoreMetaStoreTest() throws Exception {
// Directory for backups.
File backups = AlluxioTestDirectory.createTemporaryDirectory("backups");
mCluster.start();
// Needs workers to be up before the test.
mCluster.waitForAllNodesRegistered(WAIT_NODES_REGISTERED_MS);
// Acquire clients.
FileSystem fs = mCluster.getFileSystemClient();
MetaMasterClient metaClient = getMetaClient(mCluster);
BlockMasterClient blockClient = getBlockClient(mCluster);
// Create single test file.
String testFilePath = "/file";
AlluxioURI testFileUri = new AlluxioURI(testFilePath);
// Create file THROUGH.
FileSystemTestUtils.createByteFile(fs, testFilePath, 100,
CreateFilePOptions.newBuilder().setWriteType(WritePType.THROUGH).build());
// Delete it from Alluxio namespace.
fs.delete(testFileUri, DeletePOptions.newBuilder().setAlluxioOnly(true).build());
// List status on root to bring the file's meta back.
fs.listStatus(new AlluxioURI("/"), ListStatusPOptions.newBuilder().setRecursive(true)
.setLoadMetadataType(LoadMetadataPType.ONCE).build());
// Verify that file's meta is in Alluxio.
assertNotNull(fs.getStatus(testFileUri));
// Take a backup.
AlluxioURI backup1 = metaClient
.backup(BackupPRequest.newBuilder().setTargetDirectory(backups.getAbsolutePath())
.setOptions(BackupPOptions.newBuilder().setLocalFileSystem(false)).build())
.getBackupUri();
// Restart with backup.
restartMastersFromBackup(backup1);
// Verify that file and its blocks are in Alluxio after restore.
URIStatus fileStatus = fs.getStatus(testFileUri);
assertNotNull(fileStatus);
for (long blockId : fileStatus.getBlockIds()) {
assertNotNull(blockClient.getBlockInfo(blockId));
}
}
private void restartMastersFromBackup(AlluxioURI backup) throws IOException {
mCluster.stopMasters();
mCluster.formatJournal();
mCluster.updateMasterConf(PropertyKey.MASTER_JOURNAL_INIT_FROM_BACKUP, backup.toString());
mCluster.startMasters();
mCluster.updateMasterConf(PropertyKey.MASTER_JOURNAL_INIT_FROM_BACKUP, null);
}
private MetaMasterClient getMetaClient(MultiProcessCluster cluster) {
return new RetryHandlingMetaMasterClient(
MasterClientContext.newBuilder(ClientContext.create(ServerConfiguration.global()))
.setMasterInquireClient(cluster.getMasterInquireClient())
.build());
}
private BlockMasterClient getBlockClient(MultiProcessCluster cluster) {
return new RetryHandlingBlockMasterClient(
MasterClientContext.newBuilder(ClientContext.create(ServerConfiguration.global()))
.setMasterInquireClient(cluster.getMasterInquireClient()).build());
}
}
| |
/*
* Copyright 2012 The Netty Project
*
* The Netty Project 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 io.netty.handler.logging;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufHolder;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.util.internal.StringUtil;
import io.netty.util.internal.logging.InternalLogLevel;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.net.SocketAddress;
/**
* A {@link ChannelHandler} that logs all events using a logging framework.
* By default, all events are logged at <tt>DEBUG</tt> level.
*/
@Sharable
@SuppressWarnings("StringBufferReplaceableByString")
public class LoggingHandler extends ChannelHandlerAdapter {
private static final LogLevel DEFAULT_LEVEL = LogLevel.DEBUG;
private static final String NEWLINE = StringUtil.NEWLINE;
private static final String[] BYTE2HEX = new String[256];
private static final String[] HEXPADDING = new String[16];
private static final String[] BYTEPADDING = new String[16];
private static final char[] BYTE2CHAR = new char[256];
private static final String[] HEXDUMP_ROWPREFIXES = new String[65536 >>> 4];
static {
int i;
// Generate the lookup table for byte-to-hex-dump conversion
for (i = 0; i < BYTE2HEX.length; i ++) {
BYTE2HEX[i] = ' ' + StringUtil.byteToHexStringPadded(i);
}
// Generate the lookup table for hex dump paddings
for (i = 0; i < HEXPADDING.length; i ++) {
int padding = HEXPADDING.length - i;
StringBuilder buf = new StringBuilder(padding * 3);
for (int j = 0; j < padding; j ++) {
buf.append(" ");
}
HEXPADDING[i] = buf.toString();
}
// Generate the lookup table for byte dump paddings
for (i = 0; i < BYTEPADDING.length; i ++) {
int padding = BYTEPADDING.length - i;
StringBuilder buf = new StringBuilder(padding);
for (int j = 0; j < padding; j ++) {
buf.append(' ');
}
BYTEPADDING[i] = buf.toString();
}
// Generate the lookup table for byte-to-char conversion
for (i = 0; i < BYTE2CHAR.length; i ++) {
if (i <= 0x1f || i >= 0x7f) {
BYTE2CHAR[i] = '.';
} else {
BYTE2CHAR[i] = (char) i;
}
}
// Generate the lookup table for the start-offset header in each row (up to 64KiB).
for (i = 0; i < HEXDUMP_ROWPREFIXES.length; i ++) {
StringBuilder buf = new StringBuilder(12);
buf.append(NEWLINE);
buf.append(Long.toHexString(i << 4 & 0xFFFFFFFFL | 0x100000000L));
buf.setCharAt(buf.length() - 9, '|');
buf.append('|');
HEXDUMP_ROWPREFIXES[i] = buf.toString();
}
}
protected final InternalLogger logger;
protected final InternalLogLevel internalLevel;
private final LogLevel level;
/**
* Creates a new instance whose logger name is the fully qualified class
* name of the instance with hex dump enabled.
*/
public LoggingHandler() {
this(DEFAULT_LEVEL);
}
/**
* Creates a new instance whose logger name is the fully qualified class
* name of the instance.
*
* @param level the log level
*/
public LoggingHandler(LogLevel level) {
if (level == null) {
throw new NullPointerException("level");
}
logger = InternalLoggerFactory.getInstance(getClass());
this.level = level;
internalLevel = level.toInternalLevel();
}
/**
* Creates a new instance with the specified logger name and with hex dump
* enabled.
*
* @param clazz the class type to generate the logger for
*/
public LoggingHandler(Class<?> clazz) {
this(clazz, DEFAULT_LEVEL);
}
/**
* Creates a new instance with the specified logger name.
*
* @param clazz the class type to generate the logger for
* @param level the log level
*/
public LoggingHandler(Class<?> clazz, LogLevel level) {
if (clazz == null) {
throw new NullPointerException("clazz");
}
if (level == null) {
throw new NullPointerException("level");
}
logger = InternalLoggerFactory.getInstance(clazz);
this.level = level;
internalLevel = level.toInternalLevel();
}
/**
* Creates a new instance with the specified logger name using the default log level.
*
* @param name the name of the class to use for the logger
*/
public LoggingHandler(String name) {
this(name, DEFAULT_LEVEL);
}
/**
* Creates a new instance with the specified logger name.
*
* @param name the name of the class to use for the logger
* @param level the log level
*/
public LoggingHandler(String name, LogLevel level) {
if (name == null) {
throw new NullPointerException("name");
}
if (level == null) {
throw new NullPointerException("level");
}
logger = InternalLoggerFactory.getInstance(name);
this.level = level;
internalLevel = level.toInternalLevel();
}
/**
* Returns the {@link LogLevel} that this handler uses to log
*/
public LogLevel level() {
return level;
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
if (logger.isEnabled(internalLevel)) {
logger.log(internalLevel, format(ctx, "REGISTERED"));
}
ctx.fireChannelRegistered();
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
if (logger.isEnabled(internalLevel)) {
logger.log(internalLevel, format(ctx, "UNREGISTERED"));
}
ctx.fireChannelUnregistered();
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
if (logger.isEnabled(internalLevel)) {
logger.log(internalLevel, format(ctx, "ACTIVE"));
}
ctx.fireChannelActive();
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
if (logger.isEnabled(internalLevel)) {
logger.log(internalLevel, format(ctx, "INACTIVE"));
}
ctx.fireChannelInactive();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (logger.isEnabled(internalLevel)) {
logger.log(internalLevel, format(ctx, "EXCEPTION", cause), cause);
}
ctx.fireExceptionCaught(cause);
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (logger.isEnabled(internalLevel)) {
logger.log(internalLevel, format(ctx, "USER_EVENT", evt));
}
ctx.fireUserEventTriggered(evt);
}
@Override
public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) throws Exception {
if (logger.isEnabled(internalLevel)) {
logger.log(internalLevel, format(ctx, "BIND", localAddress));
}
ctx.bind(localAddress, promise);
}
@Override
public void connect(
ChannelHandlerContext ctx,
SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) throws Exception {
if (logger.isEnabled(internalLevel)) {
logger.log(internalLevel, format(ctx, "CONNECT", remoteAddress, localAddress));
}
ctx.connect(remoteAddress, localAddress, promise);
}
@Override
public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
if (logger.isEnabled(internalLevel)) {
logger.log(internalLevel, format(ctx, "DISCONNECT"));
}
ctx.disconnect(promise);
}
@Override
public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
if (logger.isEnabled(internalLevel)) {
logger.log(internalLevel, format(ctx, "CLOSE"));
}
ctx.close(promise);
}
@Override
public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
if (logger.isEnabled(internalLevel)) {
logger.log(internalLevel, format(ctx, "DEREGISTER"));
}
ctx.deregister(promise);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (logger.isEnabled(internalLevel)) {
logger.log(internalLevel, format(ctx, "RECEIVED", msg));
}
ctx.fireChannelRead(msg);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (logger.isEnabled(internalLevel)) {
logger.log(internalLevel, format(ctx, "WRITE", msg));
}
ctx.write(msg, promise);
}
@Override
public void flush(ChannelHandlerContext ctx) throws Exception {
if (logger.isEnabled(internalLevel)) {
logger.log(internalLevel, format(ctx, "FLUSH"));
}
ctx.flush();
}
/**
* Formats an event and returns the formatted message.
*
* @param eventName the name of the event
*/
protected String format(ChannelHandlerContext ctx, String eventName) {
String chStr = ctx.channel().toString();
return new StringBuilder(chStr.length() + 1 + eventName.length())
.append(chStr)
.append(' ')
.append(eventName)
.toString();
}
/**
* Formats an event and returns the formatted message.
*
* @param eventName the name of the event
* @param arg the argument of the event
*/
protected String format(ChannelHandlerContext ctx, String eventName, Object arg) {
if (arg instanceof ByteBuf) {
return formatByteBuf(ctx, eventName, (ByteBuf) arg);
} else if (arg instanceof ByteBufHolder) {
return formatByteBufHolder(ctx, eventName, (ByteBufHolder) arg);
} else {
return formatSimple(ctx, eventName, arg);
}
}
/**
* Formats an event and returns the formatted message. This method is currently only used for formatting
* {@link ChannelHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)}.
*
* @param eventName the name of the event
* @param firstArg the first argument of the event
* @param secondArg the second argument of the event
*/
protected String format(ChannelHandlerContext ctx, String eventName, Object firstArg, Object secondArg) {
if (secondArg == null) {
return formatSimple(ctx, eventName, firstArg);
}
String chStr = ctx.channel().toString();
String arg1Str = String.valueOf(firstArg);
String arg2Str = secondArg.toString();
StringBuilder buf = new StringBuilder(
chStr.length() + 1 + eventName + 2 + arg1Str.length() + 2 + arg2Str.length());
buf.append(chStr).append(' ').append(eventName).append(": ").append(arg1Str).append(", ").append(arg2Str);
return buf.toString();
}
/**
* Generates the default log message of the specified event whose argument is a {@link ByteBuf}.
*/
private static String formatByteBuf(ChannelHandlerContext ctx, String eventName, ByteBuf msg) {
String chStr = ctx.channel().toString();
int length = msg.readableBytes();
if (length == 0) {
StringBuilder buf = new StringBuilder(chStr.length() + 1 + eventName.length() + 4);
buf.append(chStr).append(' ').append(eventName).append(": 0B");
return buf.toString();
} else {
int rows = length / 16 + (length % 15 == 0? 0 : 1) + 4;
StringBuilder buf = new StringBuilder(chStr.length() + 1 + eventName.length() + 2 + 10 + 1 + 2 + rows * 80);
buf.append(chStr).append(' ').append(eventName).append(": ").append(length).append('B');
appendHexDump(buf, msg);
return buf.toString();
}
}
/**
* Generates the default log message of the specified event whose argument is a {@link ByteBufHolder}.
*/
private static String formatByteBufHolder(ChannelHandlerContext ctx, String eventName, ByteBufHolder msg) {
String chStr = ctx.channel().toString();
String msgStr = msg.toString();
ByteBuf content = msg.content();
int length = content.readableBytes();
if (length == 0) {
StringBuilder buf = new StringBuilder(chStr.length() + 1 + eventName.length() + 2 + msgStr.length() + 4);
buf.append(chStr).append(' ').append(eventName).append(", ").append(msgStr).append(", 0B");
return buf.toString();
} else {
int rows = length / 16 + (length % 15 == 0? 0 : 1) + 4;
StringBuilder buf = new StringBuilder(
chStr.length() + 1 + eventName.length() + 2 + msgStr.length() + 2 + 10 + 1 + 2 + rows * 80);
buf.append(chStr).append(' ').append(eventName).append(": ")
.append(msgStr).append(", ").append(length).append('B');
appendHexDump(buf, content);
return buf.toString();
}
}
/**
* Appends the prettifies multi-line hexadecimal dump of the specified {@link ByteBuf} to the specified
* {@link StringBuilder}.
*/
protected static void appendHexDump(StringBuilder dump, ByteBuf buf) {
dump.append(
NEWLINE + " +-------------------------------------------------+" +
NEWLINE + " | 0 1 2 3 4 5 6 7 8 9 a b c d e f |" +
NEWLINE + "+--------+-------------------------------------------------+----------------+");
final int startIndex = buf.readerIndex();
final int endIndex = buf.writerIndex();
final int length = endIndex - startIndex;
final int fullRows = length >>> 4;
final int remainder = length & 0xF;
// Dump the rows which have 16 bytes.
for (int row = 0; row < fullRows; row ++) {
int rowStartIndex = row << 4;
// Per-row prefix.
appendHexDumpRowPrefix(dump, row, rowStartIndex);
// Hex dump
int rowEndIndex = rowStartIndex + 16;
for (int j = rowStartIndex; j < rowEndIndex; j ++) {
dump.append(BYTE2HEX[buf.getUnsignedByte(j)]);
}
dump.append(" |");
// ASCII dump
for (int j = rowStartIndex; j < rowEndIndex; j ++) {
dump.append(BYTE2CHAR[buf.getUnsignedByte(j)]);
}
dump.append('|');
}
// Dump the last row which has less than 16 bytes.
if (remainder != 0) {
int rowStartIndex = fullRows << 4;
appendHexDumpRowPrefix(dump, fullRows, rowStartIndex);
// Hex dump
int rowEndIndex = rowStartIndex + remainder;
for (int j = rowStartIndex; j < rowEndIndex; j ++) {
dump.append(BYTE2HEX[buf.getUnsignedByte(j)]);
}
dump.append(HEXPADDING[remainder]);
dump.append(" |");
// Ascii dump
for (int j = rowStartIndex; j < rowEndIndex; j ++) {
dump.append(BYTE2CHAR[buf.getUnsignedByte(j)]);
}
dump.append(BYTEPADDING[remainder]);
dump.append('|');
}
dump.append(NEWLINE + "+--------+-------------------------------------------------+----------------+");
}
/**
* Appends the prefix of each hex dump row. Uses the look-up table for the buffer <= 64 KiB.
*/
private static void appendHexDumpRowPrefix(StringBuilder dump, int row, int rowStartIndex) {
if (row < HEXDUMP_ROWPREFIXES.length) {
dump.append(HEXDUMP_ROWPREFIXES[row]);
} else {
dump.append(NEWLINE);
dump.append(Long.toHexString(rowStartIndex & 0xFFFFFFFFL | 0x100000000L));
dump.setCharAt(dump.length() - 9, '|');
dump.append('|');
}
}
/**
* Generates the default log message of the specified event whose argument is an arbitrary object.
*/
private static String formatSimple(ChannelHandlerContext ctx, String eventName, Object msg) {
String chStr = ctx.channel().toString();
String msgStr = String.valueOf(msg);
StringBuilder buf = new StringBuilder(chStr.length() + 1 + eventName.length() + 2 + msgStr.length());
return buf.append(chStr).append(' ').append(eventName).append(": ").append(msgStr).toString();
}
}
| |
/**
* 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.mrql;
import org.apache.mrql.gen.*;
import java.io.*;
import java.util.Random;
import java.util.ArrayList;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.SequenceFile.Sorter;
/** A physical plan (a superclass for both MapReduce, BSP, and Spark plans) */
public class Plan {
public static Configuration conf;
static ArrayList<String> temporary_paths = new ArrayList<String>();
private static Random random_generator = new Random();
final static int max_input_files = 100;
/** generate a new path name in HDFS to store intermediate results */
public static String new_path ( Configuration conf ) throws IOException {
String dir = (Config.local_mode)
? ((Config.tmpDirectory == null) ? "/tmp/mrql" : Config.tmpDirectory)
: "mrql";
Path p;
do {
p = new Path(dir+"/mrql"+random_generator.nextInt(1000000));
} while (p.getFileSystem(conf).exists(p));
String path = p.toString();
temporary_paths.add(path);
DataSource.dataSourceDirectory.distribute(conf);
return path;
}
/** remove all temporary files */
public static void clean () throws IOException {
for (String p: temporary_paths)
try {
Path path = new Path(p);
path.getFileSystem(conf).delete(path,true);
} catch (Exception ex) {
FileSystem.getLocal(conf).delete(new Path(p),true);
};
temporary_paths.clear();
DataSource.dataSourceDirectory.clear();
}
/** return the data set size in bytes */
public final static long size ( DataSet s ) {
return s.size(conf);
}
/** the cache that holds all local data in memory */
static Tuple cache;
/** return the cache element at location loc */
public static synchronized MRData getCache ( int loc ) {
return cache.get(loc);
}
/** set the cache element at location loc to value and return ret */
public static synchronized MRData setCache ( int loc, MRData value, MRData ret ) {
if (value instanceof Bag)
((Bag)value).materialize();
cache.set(loc,value);
return ret;
}
/** put the jar file that contains the compiled MR functional parameters into the TaskTracker classpath */
final static void distribute_compiled_arguments ( Configuration conf ) {
try {
if (!Config.compile_functional_arguments)
return;
Path local_path = new Path("file://"+Compiler.jar_path);
if (Config.flink_mode)
conf.set("mrql.jar.path",Compiler.jar_path);
else if (Config.spark_mode)
conf.set("mrql.jar.path",local_path.toString());
else {
// distribute the jar file with the compiled arguments to all clients
Path hdfs_path = new Path("mrql-tmp/class"+random_generator.nextInt(1000000)+".jar");
FileSystem fs = hdfs_path.getFileSystem(conf);
fs.copyFromLocalFile(false,true,local_path,hdfs_path);
temporary_paths.add(hdfs_path.toString());
conf.set("mrql.jar.path",hdfs_path.toString());
}
} catch (Exception ex) {
throw new Error(ex);
}
}
/** retrieve the compiled functional argument of code */
final static Function functional_argument ( Configuration conf, Tree code ) {
Node n = (Node)code;
if (n.name().equals("compiled"))
try {
// if the clent has not received the jar file with the compiled arguments, copy the file from HDFS
if (Compiler.jar_path == null) {
Path hdfs_path = new Path(conf.get("mrql.jar.path"));
String local_path = Compiler.tmp_dir+"/mrql_args_"+random_generator.nextInt(1000000)+".jar";
FileSystem fs = hdfs_path.getFileSystem(conf);
fs.copyToLocalFile(false,hdfs_path,new Path("file://"+local_path));
Compiler.jar_path = local_path;
};
return Compiler.compiled(conf.getClassLoader(),n.children().nth(0).toString());
} catch (Exception ex) {
System.err.println("*** Warning: Unable to retrieve the compiled lambda: "+code);
return ((Lambda) Interpreter.evalE(n.children().nth(1))).lambda();
}
else if (code.equals(Interpreter.identity_mapper))
return new Function () {
public MRData eval ( final MRData x ) { return new Bag(x); }
};
else return ((Lambda) Interpreter.evalE(code)).lambda();
}
/** comparator for MRData keys */
public final static class MRContainerKeyComparator implements RawComparator<MRContainer> {
int[] container_size;
public MRContainerKeyComparator () {
container_size = new int[1];
}
final public int compare ( byte[] x, int xs, int xl, byte[] y, int ys, int yl ) {
return MRContainer.compare(x,xs,xl,y,ys,yl,container_size);
}
final public int compare ( MRContainer x, MRContainer y ) {
return x.compareTo(y);
}
}
/** The source physical operator for binary files */
public final static DataSet binarySource ( int source_num, String file ) {
return new DataSet(new BinaryDataSource(source_num,file,conf),0,0);
}
/** The source physical operator for binary files */
public final static DataSet binarySource ( String file ) {
return new DataSet(new BinaryDataSource(-1,file,conf),0,0);
}
/** splits the range min..max into multiple ranges, one for each mapper */
public final static DataSet generator ( int source_num, long min, long max, long split_length ) throws Exception {
if (min > max)
throw new Error("Wrong range: "+min+"..."+max);
if (split_length < 1)
if (Config.bsp_mode)
split_length = (max-min)/Config.nodes+1;
else split_length = Config.range_split_size;
DataSet ds = new DataSet(0,0);
long i = min;
while (i+split_length <= max) {
String file = new_path(conf);
Path path = new Path(file);
SequenceFile.Writer writer
= SequenceFile.createWriter(path.getFileSystem(conf),conf,path,
MRContainer.class,MRContainer.class,
SequenceFile.CompressionType.NONE);
writer.append(new MRContainer(new MR_long(i)),
new MRContainer(new Tuple(new MR_long(i),new MR_long(split_length))));
writer.close();
ds.source.add(new GeneratorDataSource(source_num,file,conf));
i += split_length;
};
if (i <= max) {
String file = new_path(conf);
Path path = new Path(file);
SequenceFile.Writer writer
= SequenceFile.createWriter(path.getFileSystem(conf),conf,path,
MRContainer.class,MRContainer.class,
SequenceFile.CompressionType.NONE);
writer.append(new MRContainer(new MR_long(i)),
new MRContainer(new Tuple(new MR_long(i),new MR_long(max-i+1))));
writer.close();
ds.source.add(new GeneratorDataSource(source_num,file,conf));
};
return ds;
}
/** splits the range min..max into multiple ranges, one for each mapper */
public final static DataSet generator ( long min, long max, long split_length ) throws Exception {
return generator(-1,min,max,split_length);
}
/** The source physical operator for parsing text files */
public final static DataSet parsedSource ( int source_num, Class<? extends Parser> parser, String file, Trees args ) {
return new DataSet(new ParsedDataSource(source_num,file,parser,args,conf),0,0);
}
/** The source physical operator for parsing text files */
public final static DataSet parsedSource ( Class<? extends Parser> parser, String file, Trees args ) {
return new DataSet(new ParsedDataSource(file,parser,args,conf),0,0);
}
/** merge the sorted files of the data source */
public final static Bag merge ( final DataSource s ) throws Exception {
Path path = new Path(s.path);
final FileSystem fs = path.getFileSystem(conf);
final FileStatus[] ds
= fs.listStatus(path,
new PathFilter () {
public boolean accept ( Path path ) {
return !path.getName().startsWith("_");
}
});
int dl = ds.length;
if (dl == 0)
return new Bag();
Path[] paths = new Path[dl];
for ( int i = 0; i < dl; i++ )
paths[i] = ds[i].getPath();
if (dl > Config.max_merged_streams) {
if (Config.trace)
System.out.println("Merging "+dl+" files");
Path out_path = new Path(new_path(conf));
SequenceFile.Sorter sorter
= new SequenceFile.Sorter(fs,new MRContainerKeyComparator(),
MRContainer.class,MRContainer.class,conf);
sorter.merge(paths,out_path);
paths = new Path[1];
paths[0] = out_path;
};
final int n = paths.length;
SequenceFile.Reader[] sreaders = new SequenceFile.Reader[n];
for ( int i = 0; i < n; i++ )
sreaders[i] = new SequenceFile.Reader(fs,paths[i],conf);
final SequenceFile.Reader[] readers = sreaders;
final MRContainer[] keys_ = new MRContainer[n];
final MRContainer[] values_ = new MRContainer[n];
for ( int i = 0; i < n; i++ ) {
keys_[i] = new MRContainer();
values_[i] = new MRContainer();
};
return new Bag(new BagIterator () {
int min = 0;
boolean first = true;
final MRContainer[] keys = keys_;
final MRContainer[] values = values_;
final MRContainer key = new MRContainer();
final MRContainer value = new MRContainer();
public boolean hasNext () {
if (first)
try {
first = false;
for ( int i = 0; i < n; i++ )
if (readers[i].next(key,value)) {
keys[i].set(key.data());
values[i].set(value.data());
} else {
keys[i] = null;
readers[i].close();
}
} catch (IOException e) {
throw new Error("Cannot merge values from an intermediate result");
};
min = -1;
for ( int i = 0; i < n; i++ )
if (keys[i] != null && min < 0)
min = i;
else if (keys[i] != null && keys[i].compareTo(keys[min]) < 0)
min = i;
return min >= 0;
}
public MRData next () {
try {
MRData res = values[min].data();
if (readers[min].next(key,value)) {
keys[min].set(key.data());
values[min].set(value.data());
} else {
keys[min] = null;
readers[min].close();
};
return res;
} catch (IOException e) {
throw new Error("Cannot merge values from an intermediate result");
}
}
});
}
/** The collect physical operator */
public final static Bag collect ( final DataSet x, boolean strip ) throws Exception {
return Evaluator.evaluator.parsedInputFormat().newInstance().collect(x,strip);
}
/** The collect physical operator */
public final static Bag collect ( final DataSet x ) throws Exception {
return collect(x,true);
}
/** the DataSet union physical operator */
public final static DataSet merge ( final DataSet x, final DataSet y ) throws IOException {
DataSet res = x;
res.source.addAll(y.source);
return res;
}
final static MR_long counter_key = new MR_long(0);
final static MRContainer counter_container = new MRContainer(counter_key);
final static MRContainer value_container = new MRContainer(new MR_int(0));
/** The cache operator that dumps a bag into an HDFS file */
public final static DataSet fileCache ( Bag s ) throws IOException {
String newpath = new_path(conf);
Path path = new Path(newpath);
FileSystem fs = path.getFileSystem(conf);
SequenceFile.Writer writer
= new SequenceFile.Writer(fs,conf,path,
MRContainer.class,MRContainer.class);
long i = 0;
for ( MRData e: s ) {
counter_key.set(i++);
value_container.set(e);
writer.append(counter_container,value_container);
};
writer.close();
return new DataSet(new BinaryDataSource(0,newpath,conf),0,0);
}
/** create a new PrintStream from the file */
final static PrintStream print_stream ( String file ) throws Exception {
Path path = new Path(file);
FileSystem fs = path.getFileSystem(conf);
return new PrintStream(fs.create(path));
}
}
| |
/**
* Copyright (C) 2004-2011 Jive Software. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.spark.roar.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import org.jivesoftware.spark.component.VerticalFlowLayout;
import org.jivesoftware.spark.roar.RoarProperties;
import org.jivesoftware.spark.roar.RoarResources;
import org.jivesoftware.spark.roar.displaytype.RoarDisplayType;
import org.jivesoftware.spark.util.ColorPick;
/**
* Super Awesome Preference Panel
*
* @author wolf.posdorfer
*
*/
public class RoarPreferencePanel extends JPanel {
private static final long serialVersionUID = -5334936099931215962L;
// private Image _backgroundimage;
private JTextField _duration;
private JTextField _amount;
private JCheckBox _enabledCheckbox;
private JComboBox<String> _typelist;
private JList<ColorTypes> _singleColorlist;
private ColorPick _singleColorpicker;
private HashMap<ColorTypes, Color> _colormap;
private HashMap<String, Object> _components;
private Insets INSETS = new Insets(5, 5, 5, 5);
public RoarPreferencePanel() {
_components = new HashMap<>();
_colormap = new HashMap<>();
for (ColorTypes e : ColorTypes.values()) {
_colormap.put(e, Color.BLACK);
}
this.setLayout(new BorderLayout());
// ClassLoader cl = getClass().getClassLoader();
// _backgroundimage = new ImageIcon(cl.getResource("background2.png")).getImage();
_duration = new JTextField();
_amount = new JTextField();
_enabledCheckbox = new JCheckBox(RoarResources.getString("roar.enabled"));
_singleColorpicker = new ColorPick(false);
_singleColorpicker.addChangeListener( e -> stateChangedSingleColorPicker(e) );
DefaultListModel<ColorTypes> listModel = new DefaultListModel<>();
listModel.addElement(ColorTypes.BACKGROUNDCOLOR);
listModel.addElement(ColorTypes.HEADERCOLOR);
listModel.addElement(ColorTypes.TEXTCOLOR);
_singleColorlist = new JList<>(listModel);
List<RoarDisplayType> roarDisplayTypes = RoarProperties.getInstance().getDisplayTypes();
String[] _typelistdata = new String[ roarDisplayTypes.size() ];
for (int i = 0; i < roarDisplayTypes.size(); i++) {
_typelistdata[i] = roarDisplayTypes.get(i).getLocalizedName();
}
_typelist = new JComboBox<>( _typelistdata );
_typelist.addActionListener( e -> updateWarningLabel(getDisplayTypeClass().getWarningMessage()) );
add(makeGeneralSettingsPanel());
_singleColorlist.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
colorListMouseClicked(e);
}
});
}
private JComponent makeGeneralSettingsPanel() {
JPanel generalPanel = new JPanel();
generalPanel.setLayout(new GridBagLayout());
generalPanel.setBorder(BorderFactory.createTitledBorder(RoarResources.getString("roar.settings")));
int rowcount = 0;
generalPanel.add(_enabledCheckbox,
new GridBagConstraints(0, rowcount, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, INSETS, 0, 0));
rowcount++;
generalPanel.add(new JLabel(RoarResources.getString("roar.amount")),
new GridBagConstraints(0, rowcount, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, INSETS, 0, 0));
generalPanel.add(_amount,
new GridBagConstraints(1, rowcount, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, INSETS, 0, 0));
rowcount++;
generalPanel.add(new JLabel(RoarResources.getString("roar.location")),
new GridBagConstraints(0, rowcount, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, INSETS, 0, 0));
generalPanel.add(_typelist,
new GridBagConstraints(1, rowcount, 1, 1, 0.8, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, INSETS, 0, 0));
rowcount++;
JLabel warningLabel = new JLabel("<html>placeholder :-)</html>");
//warningLabel.setForeground(Color.RED);
generalPanel.add(warningLabel,
new GridBagConstraints(1, rowcount, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, INSETS, 0, 0));
_components.put("label.warning", warningLabel);
JPanel panel = new JPanel(new VerticalFlowLayout());
panel.add(generalPanel);
panel.add(makeSinglePanel());
panel.add(makeGroupChatPanel());
panel.add(makeKeyWordPanel());
JScrollPane scroll = new JScrollPane(panel);
return scroll;
}
private JPanel makeSinglePanel() {
JPanel singlePanel = new JPanel();
singlePanel.setLayout(new GridBagLayout());
singlePanel.setBorder(BorderFactory.createTitledBorder(RoarResources.getString("roar.single")));
JCheckBox disableSingle = new JCheckBox(RoarResources.getString("roar.single.disable"));
// row
int rowcount = 0;
singlePanel.add(_singleColorlist,
new GridBagConstraints(0, rowcount, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, INSETS, 0, 0));
singlePanel.add(_singleColorpicker,
new GridBagConstraints(1, rowcount, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, INSETS, 0, 0));
rowcount++;
singlePanel.add(new JLabel(RoarResources.getString("roar.duration")),
new GridBagConstraints(0, rowcount, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, INSETS, 0, 0));
singlePanel.add(_duration,
new GridBagConstraints(1, rowcount, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, INSETS, 0, 0));
rowcount++;
singlePanel.add(disableSingle,
new GridBagConstraints(0, rowcount, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, INSETS, 0, 0));
_components.put("roar.disable.single", disableSingle);
return singlePanel;
}
private JPanel makeGroupChatPanel() {
JPanel groupPanel = new JPanel();
groupPanel.setLayout(new GridBagLayout());
groupPanel.setBorder(BorderFactory.createTitledBorder(RoarResources.getString("roar.group")));
final JCheckBox enableDifferentGroup = new JCheckBox(RoarResources.getString("roar.group.different"));
JCheckBox disableGroup = new JCheckBox(RoarResources.getString("roar.group.disable"));
JTextField durationGroup = new JTextField();
enableDifferentGroup.addActionListener( e -> toggleDifferentSettingsForGroup(enableDifferentGroup.isSelected()) );
int rowcount = 0;
groupPanel.add(enableDifferentGroup,
new GridBagConstraints(0, rowcount, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, INSETS, 0, 0));
rowcount++;
groupPanel.add(new JLabel(RoarResources.getString("roar.duration")),
new GridBagConstraints(0, rowcount, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, INSETS, 0, 0));
groupPanel.add(durationGroup,
new GridBagConstraints(1, rowcount, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, INSETS, 0, 0));
rowcount++;
groupPanel.add(disableGroup,
new GridBagConstraints(0, rowcount, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, INSETS, 0, 0));
_components.put("group.different.enabled", enableDifferentGroup);
_components.put("group.duration", durationGroup);
_components.put("group.disable", disableGroup);
return groupPanel;
}
private JPanel makeKeyWordPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.setBorder(BorderFactory.createTitledBorder(RoarResources.getString("roar.keyword")));
final JCheckBox differentKeyword = new JCheckBox(RoarResources.getString("roar.keyword.different"));
differentKeyword.addActionListener( e -> toggleDifferentSettingsForKeyword(differentKeyword.isSelected()) );
JTextField durationKeyword = new JTextField();
JTextField keywords = new JTextField();
int rowcount = 0;
panel.add(differentKeyword,
new GridBagConstraints(0, rowcount, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, INSETS, 0, 0));
rowcount++;
panel.add(new JLabel(RoarResources.getString("roar.duration")),
new GridBagConstraints(0, rowcount, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, INSETS, 0, 0));
panel.add(durationKeyword,
new GridBagConstraints(1, rowcount, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, INSETS, 0, 0));
rowcount++;
panel.add(new JLabel(RoarResources.getString("roar.keyword.keyword")),
new GridBagConstraints(0, rowcount, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, INSETS, 0, 0));
panel.add(keywords, new GridBagConstraints(1, rowcount, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, INSETS, 0, 0));
_components.put("keyword.different.enabled", differentKeyword);
_components.put("keyword.duration", durationKeyword);
_components.put("keywords", keywords);
return panel;
}
public void initializeValues() {
RoarProperties props = RoarProperties.getInstance();
_enabledCheckbox.setSelected(props.getShowingPopups());
_amount.setText("" + props.getMaximumPopups());
setDisplayType(props.getDisplayType());
setColor(ColorTypes.BACKGROUNDCOLOR, props.getBackgroundColor());
setColor(ColorTypes.BACKGROUNDCOLOR_GROUP, props.getColor(RoarProperties.BACKGROUNDCOLOR_GROUP, props.getBackgroundColor()));
setColor(ColorTypes.BACKGROUNDCOLOR_KEYWORD, props.getColor(RoarProperties.BACKGROUNDCOLOR_KEYWORD, props.getBackgroundColor()));
setColor(ColorTypes.HEADERCOLOR, props.getHeaderColor());
setColor(ColorTypes.HEADERCOLOR_GROUP, props.getColor(RoarProperties.HEADERCOLOR_GROUP, props.getHeaderColor()));
setColor(ColorTypes.HEADERCOLOR_KEYWORD, props.getColor(RoarProperties.HEADERCOLOR_KEYWORD, props.getHeaderColor()));
setColor(ColorTypes.TEXTCOLOR, props.getTextColor());
setColor(ColorTypes.TEXTCOLOR_GROUP, props.getColor(RoarProperties.TEXTCOLOR_GROUP, props.getTextColor()));
setColor(ColorTypes.TEXTCOLOR_KEYWORD, props.getColor(RoarProperties.TEXTCOLOR_KEYWORD, props.getTextColor()));
retrieveComponent("roar.disable.single", JCheckBox.class).setSelected(props.getBoolean("roar.disable.single", false));
_duration.setText("" + props.getDuration());
retrieveComponent("keyword.duration", JTextField.class).setText("" + props.getInt("keyword.duration"));
retrieveComponent("group.duration", JTextField.class).setText("" + props.getInt("group.duration"));
retrieveComponent("keywords", JTextField.class).setText(props.getProperty("keywords"));
retrieveComponent("group.disable", JCheckBox.class).setSelected(props.getBoolean("group.disable", false));
boolean group_different_enabled = props.getBoolean("group.different.enabled", false);
retrieveComponent("group.different.enabled", JCheckBox.class).setSelected(group_different_enabled);
toggleDifferentSettingsForGroup(group_different_enabled);
boolean keyword_different_enabled = props.getBoolean("keyword.different.enabled", false);
retrieveComponent("keyword.different.enabled", JCheckBox.class).setSelected(keyword_different_enabled);
toggleDifferentSettingsForKeyword(keyword_different_enabled);
}
public void storeValues() {
RoarProperties props = RoarProperties.getInstance();
props.setShowingPopups(_enabledCheckbox.isSelected());
props.setDisplayType(this.getDisplayType());
props.setMaximumPopups(this.getAmount());
props.setDuration(this.getDuration());
props.setInt("group.duration", getIntFromTextField("group.duration"));
props.setInt("keyword.duration", getIntFromTextField("keyword.duration"));
props.setKeywords(retrieveComponent("keywords", JTextField.class).getText());
props.setBackgroundColor(getColor(ColorTypes.BACKGROUNDCOLOR));
props.setColor(RoarProperties.BACKGROUNDCOLOR_GROUP, getColor(ColorTypes.BACKGROUNDCOLOR_GROUP));
props.setColor(RoarProperties.BACKGROUNDCOLOR_KEYWORD, getColor(ColorTypes.BACKGROUNDCOLOR_KEYWORD));
props.setTextColor(getColor(ColorTypes.TEXTCOLOR));
props.setColor(RoarProperties.TEXTCOLOR_GROUP, getColor(ColorTypes.TEXTCOLOR_GROUP));
props.setColor(RoarProperties.TEXTCOLOR_KEYWORD, getColor(ColorTypes.TEXTCOLOR_KEYWORD));
props.setHeaderColor(getColor(ColorTypes.HEADERCOLOR));
props.setColor(RoarProperties.HEADERCOLOR_GROUP, getColor(ColorTypes.HEADERCOLOR_GROUP));
props.setColor(RoarProperties.HEADERCOLOR_KEYWORD, getColor(ColorTypes.HEADERCOLOR_KEYWORD));
props.setBoolean("roar.disable.single", retrieveComponent("roar.disable.single", JCheckBox.class).isSelected());
props.setBoolean("group.different.enabled", retrieveComponent("group.different.enabled", JCheckBox.class).isSelected());
props.setBoolean("keyword.different.enabled", retrieveComponent("keyword.different.enabled", JCheckBox.class).isSelected());
props.setBoolean("group.disable", retrieveComponent("group.disable", JCheckBox.class).isSelected());
props.save();
}
@SuppressWarnings("unchecked")
private <K> K retrieveComponent(String key, Class<K> classs) {
return (K) _components.get(key);
}
private int getIntFromTextField(String key) {
JTextField field = retrieveComponent(key, JTextField.class);
try {
return Integer.parseInt(field.getText());
} catch (Exception e) {
return 3000;
}
}
/**
* returns the popup duration
*
* @return int
*/
public int getDuration() {
try {
return Integer.parseInt(_duration.getText());
} catch (Exception e) {
return 3000;
}
}
/**
* Amount of Windows on Screen
*
* @return int
*/
public int getAmount() {
return Integer.parseInt(_amount.getText());
}
public Color getColor(ColorTypes type) {
return _colormap.get(type);
}
public void setColor(ColorTypes type, Color color) {
_colormap.put(type, color);
}
private void colorListMouseClicked(MouseEvent e) {
if (e.getSource() == _singleColorlist) {
ColorTypes key = _singleColorlist.getSelectedValue();
_singleColorpicker.setColor(_colormap.get(key));
}
}
public void setDisplayType(String t) {
for (RoarDisplayType type : RoarProperties.getInstance().getDisplayTypes()) {
if (type.getName().equals(t)) {
_typelist.setSelectedItem(type.getLocalizedName());
updateWarningLabel(type.getWarningMessage());
return;
}
}
}
public void updateWarningLabel(String text) {
retrieveComponent("label.warning", JLabel.class).setText("<html>" + text + "</html>");
}
public RoarDisplayType getDisplayTypeClass() {
String o = (String) _typelist.getSelectedItem();
for (RoarDisplayType type : RoarProperties.getInstance().getDisplayTypes()) {
if (type.getLocalizedName().equals(o)) {
return type;
}
}
return RoarProperties.getInstance().getDisplayTypes().get(0);
// topright is default
}
public String getDisplayType() {
return getDisplayTypeClass().getName();
}
private void toggleDifferentSettingsForKeyword(boolean isSelected) {
DefaultListModel<ColorTypes> model = (DefaultListModel<ColorTypes>) _singleColorlist.getModel();
JTextField duration = retrieveComponent("keyword.duration", JTextField.class);
if (isSelected) {
if (!model.contains(ColorTypes.BACKGROUNDCOLOR_KEYWORD)) {
model.addElement(ColorTypes.BACKGROUNDCOLOR_KEYWORD);
model.addElement(ColorTypes.HEADERCOLOR_KEYWORD);
model.addElement(ColorTypes.TEXTCOLOR_KEYWORD);
}
duration.setEnabled(true);
} else {
model.removeElement(ColorTypes.BACKGROUNDCOLOR_KEYWORD);
model.removeElement(ColorTypes.HEADERCOLOR_KEYWORD);
model.removeElement(ColorTypes.TEXTCOLOR_KEYWORD);
duration.setEnabled(false);
duration.setText(_duration.getText());
}
}
private void toggleDifferentSettingsForGroup(boolean isSelected) {
DefaultListModel<ColorTypes> model = (DefaultListModel<ColorTypes>) _singleColorlist.getModel();
JTextField duration = retrieveComponent("group.duration", JTextField.class);
if (isSelected) {
if (!model.contains(ColorTypes.BACKGROUNDCOLOR_GROUP)) {
model.addElement(ColorTypes.BACKGROUNDCOLOR_GROUP);
model.addElement(ColorTypes.HEADERCOLOR_GROUP);
model.addElement(ColorTypes.TEXTCOLOR_GROUP);
}
duration.setEnabled(true);
} else {
model.removeElement(ColorTypes.BACKGROUNDCOLOR_GROUP);
model.removeElement(ColorTypes.HEADERCOLOR_GROUP);
model.removeElement(ColorTypes.TEXTCOLOR_GROUP);
duration.setEnabled(false);
duration.setText(_duration.getText());
}
}
private void stateChangedSingleColorPicker(ChangeEvent e) {
if (e.getSource() instanceof JSlider) {
_colormap.put( _singleColorlist.getSelectedValue(), _singleColorpicker.getColor());
}
}
// ============================================================================================================
// ============================================================================================================
// ============================================================================================================
// public void paintComponent(Graphics g) {
// CENTER LOGO
// int imgwi = _backgroundimage.getWidth(null);
// int imghe = _backgroundimage.getHeight(null);
// int x = this.getSize().width;
// x = (x/2)-(imgwi/2) < 0 ? 0 : (x/2)-(imgwi/2) ;
//
// int y = this.getSize().height;
// y = (y/2) -(imghe/2)< 0 ? 0 : y/2-(imghe/2) ;
//
// LOGO in bottom right corner
//
// int x = this.getSize().width - _backgroundimage.getWidth(null);
// int y = this.getSize().height - _backgroundimage.getHeight(null);
//
// super.paintComponent(g);
// g.drawImage(_backgroundimage, x, y, this);
// }
// ============================================================================================================
// ============================================================================================================
// ============================================================================================================
public enum ColorTypes {
BACKGROUNDCOLOR(RoarResources.getString("roar.background")),
HEADERCOLOR(RoarResources.getString("roar.header")),
TEXTCOLOR(RoarResources.getString("roar.text")),
BACKGROUNDCOLOR_GROUP(RoarResources.getString("roar.background.group")),
HEADERCOLOR_GROUP(RoarResources.getString("roar.header.group")),
TEXTCOLOR_GROUP(RoarResources.getString("roar.text.group")),
BACKGROUNDCOLOR_KEYWORD(RoarResources.getString("roar.background.keyword")),
HEADERCOLOR_KEYWORD(RoarResources.getString("roar.header.keyword")),
TEXTCOLOR_KEYWORD(RoarResources.getString("roar.text.keyword"));
private String string;
private ColorTypes(String c) {
string = c;
}
public String toString() {
return string;
}
}
}
| |
package com.nirima.jenkins.plugins.docker;
import com.cloudbees.jenkins.plugins.sshcredentials.SSHAuthenticator;
import com.cloudbees.jenkins.plugins.sshcredentials.SSHUserListBoxModel;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Strings;
import com.nirima.docker.client.DockerException;
import com.nirima.docker.client.DockerClient;
import com.nirima.docker.client.model.*;
import com.trilead.ssh2.Connection;
import hudson.Extension;
import hudson.Util;
import hudson.model.*;
import hudson.model.labels.LabelAtom;
import hudson.plugins.sshslaves.SSHLauncher;
import hudson.security.ACL;
import hudson.slaves.ComputerLauncher;
import hudson.slaves.NodeProperty;
import hudson.slaves.RetentionStrategy;
import hudson.util.ListBoxModel;
import hudson.util.StreamTaskListener;
import jenkins.model.Jenkins;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import java.io.IOException;
import java.io.PrintStream;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jenkinsci.plugins.durabletask.executors.OnceRetentionStrategy;
public class DockerTemplate extends DockerTemplateBase implements Describable<DockerTemplate> {
private static final Logger LOGGER = Logger.getLogger(DockerTemplate.class.getName());
public final String labelString;
// SSH settings
/**
* The id of the credentials to use.
*/
public final String credentialsId;
/**
* Minutes before terminating an idle slave
*/
public final String idleTerminationMinutes;
/**
* Minutes before SSHLauncher times out on launch
*/
public final String sshLaunchTimeoutMinutes;
/**
* Field jvmOptions.
*/
public final String jvmOptions;
/**
* Field javaPath.
*/
public final String javaPath;
/**
* Field prefixStartSlaveCmd.
*/
public final String prefixStartSlaveCmd;
/**
* Field suffixStartSlaveCmd.
*/
public final String suffixStartSlaveCmd;
/**
* Field remoteFSMapping.
*/
public final String remoteFsMapping;
public final String remoteFs; // = "/home/jenkins";
public final int instanceCap;
private transient /*almost final*/ Set<LabelAtom> labelSet;
public transient DockerCloud parent;
@DataBoundConstructor
public DockerTemplate(String image, String labelString,
String remoteFs,
String remoteFsMapping,
String credentialsId, String idleTerminationMinutes,
String sshLaunchTimeoutMinutes,
String jvmOptions, String javaPath,
String prefixStartSlaveCmd, String suffixStartSlaveCmd,
String instanceCapStr, String dnsString,
String dockerCommand,
String volumesString, String volumesFrom,
String environmentsString,
String lxcConfString,
String hostname,
String bindPorts,
boolean bindAllPorts,
boolean privileged
) {
super(image, dnsString,dockerCommand,volumesString,volumesFrom,environmentsString,lxcConfString,hostname,
Objects.firstNonNull(bindPorts, "0.0.0.0:22"), bindAllPorts,
privileged);
this.labelString = Util.fixNull(labelString);
this.credentialsId = credentialsId;
this.idleTerminationMinutes = idleTerminationMinutes;
this.sshLaunchTimeoutMinutes = sshLaunchTimeoutMinutes;
this.jvmOptions = jvmOptions;
this.javaPath = javaPath;
this.prefixStartSlaveCmd = prefixStartSlaveCmd;
this.suffixStartSlaveCmd = suffixStartSlaveCmd;
this.remoteFs = Strings.isNullOrEmpty(remoteFs)?"/home/jenkins":remoteFs;
this.remoteFsMapping = remoteFsMapping;
if (instanceCapStr.equals("")) {
this.instanceCap = Integer.MAX_VALUE;
} else {
this.instanceCap = Integer.parseInt(instanceCapStr);
}
readResolve();
}
private String[] splitAndFilterEmpty(String s) {
List<String> temp = new ArrayList<String>();
for (String item : s.split(" ")) {
if (!item.isEmpty())
temp.add(item);
}
return temp.toArray(new String[temp.size()]);
}
public String getInstanceCapStr() {
if (instanceCap==Integer.MAX_VALUE) {
return "";
} else {
return String.valueOf(instanceCap);
}
}
public String getDnsString() {
return Joiner.on(" ").join(dnsHosts);
}
public String getVolumesString() {
return Joiner.on(" ").join(volumes);
}
public String getVolumesFrom() {
return volumesFrom;
}
public String getRemoteFsMapping() {
return remoteFsMapping;
}
public Descriptor<DockerTemplate> getDescriptor() {
return Jenkins.getInstance().getDescriptor(getClass());
}
public Set<LabelAtom> getLabelSet(){
return labelSet;
}
public int getSSHLaunchTimeoutMinutes() {
if (sshLaunchTimeoutMinutes == null || sshLaunchTimeoutMinutes.trim().isEmpty()) {
return 1;
} else {
try {
return Integer.parseInt(sshLaunchTimeoutMinutes);
} catch (NumberFormatException nfe) {
LOGGER.log(Level.INFO, "Malformed SSH Launch Timeout value: {0}", sshLaunchTimeoutMinutes);
return 1;
}
}
}
/**
* Initializes data structure that we don't persist.
*/
protected Object readResolve() {
super.readResolve();
labelSet = Label.parse(labelString);
return this;
}
public String getDisplayName() {
return "Image of " + image;
}
public DockerCloud getParent() {
return parent;
}
private int idleTerminationMinutes() {
if (idleTerminationMinutes == null || idleTerminationMinutes.trim().isEmpty()) {
return 0;
} else {
try {
return Integer.parseInt(idleTerminationMinutes);
} catch (NumberFormatException nfe) {
LOGGER.log(Level.INFO, "Malformed idleTermination value: {0}", idleTerminationMinutes);
return 30;
}
}
}
public DockerSlave provision(StreamTaskListener listener) throws IOException, Descriptor.FormException, DockerException {
PrintStream logger = listener.getLogger();
logger.println("Launching " + image );
int numExecutors = 1;
Node.Mode mode = Node.Mode.NORMAL;
RetentionStrategy retentionStrategy = new OnceRetentionStrategy(idleTerminationMinutes());
List<? extends NodeProperty<?>> nodeProperties = new ArrayList();
ContainerInspectResponse containerInspectResponse = provisionNew();
String containerId = containerInspectResponse.getId();
ComputerLauncher launcher = new DockerComputerLauncher(this, containerInspectResponse);
// Build a description up:
String nodeDescription = "Docker Node [" + image + " on ";
try {
nodeDescription += getParent().getDisplayName();
} catch(Exception ex)
{
nodeDescription += "???";
}
nodeDescription += "]";
String slaveName = containerId.substring(0,12);
try
{
slaveName = slaveName + "@" + getParent().getDisplayName();
}
catch(Exception ex) {
LOGGER.warning("Error fetching name of cloud");
}
return new DockerSlave(this, containerId,
slaveName,
nodeDescription,
remoteFs, numExecutors, mode, labelString,
launcher, retentionStrategy, nodeProperties);
}
public ContainerInspectResponse provisionNew() throws DockerException {
DockerClient dockerClient = getParent().connect();
return provisionNew(dockerClient);
}
public int getNumExecutors() {
return 1;
}
@Override
protected String[] getDockerCommandArray() {
String[] cmd = super.getDockerCommandArray();
if( cmd.length == 0 ) {
//default value to preserve comptability
cmd = new String[]{"/usr/sbin/sshd", "-D"};
}
return cmd;
}
@Override
/**
* Provide a sensible default - templates are for slaves, and you're mostly going
* to want port 22 exposed.
*/
protected Iterable<PortMapping> getPortMappings() {
if(Strings.isNullOrEmpty(bindPorts) ) {
return PortMapping.parse("0.0.0.0::22");
}
return super.getPortMappings();
}
@Extension
public static final class DescriptorImpl extends Descriptor<DockerTemplate> {
@Override
public String getDisplayName() {
return "Docker Template";
}
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context) {
return new SSHUserListBoxModel().withMatching(SSHAuthenticator.matcher(Connection.class),
CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, context,
ACL.SYSTEM, SSHLauncher.SSH_SCHEME));
}
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("image", image)
.add("parent", parent)
.toString();
}
}
| |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002, 2014 Oracle and/or its affiliates. All rights reserved.
*
*/
package com.sleepycat.je.rep.txn;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import com.sleepycat.je.CommitToken;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Durability.ReplicaAckPolicy;
import com.sleepycat.je.EnvironmentFailureException;
import com.sleepycat.je.LockConflictException;
import com.sleepycat.je.LockNotAvailableException;
import com.sleepycat.je.ThreadInterruptedException;
import com.sleepycat.je.TransactionConfig;
import com.sleepycat.je.dbi.DatabaseImpl;
import com.sleepycat.je.dbi.EnvironmentImpl;
import com.sleepycat.je.log.LogItem;
import com.sleepycat.je.log.ReplicationContext;
import com.sleepycat.je.rep.InsufficientAcksException;
import com.sleepycat.je.rep.ReplicaWriteException;
import com.sleepycat.je.rep.ReplicatedEnvironment;
import com.sleepycat.je.rep.UnknownMasterException;
import com.sleepycat.je.rep.impl.RepImpl;
import com.sleepycat.je.rep.impl.node.NameIdPair;
import com.sleepycat.je.rep.impl.node.Replay;
import com.sleepycat.je.rep.impl.node.Replica;
import com.sleepycat.je.txn.LockResult;
import com.sleepycat.je.txn.LockType;
import com.sleepycat.je.txn.Txn;
import com.sleepycat.je.txn.TxnManager;
import com.sleepycat.je.txn.WriteLockInfo;
import com.sleepycat.je.utilint.DbLsn;
import com.sleepycat.je.utilint.LoggerUtils;
import com.sleepycat.je.utilint.TestHook;
import com.sleepycat.je.utilint.TestHookExecute;
import com.sleepycat.je.utilint.VLSN;
/**
* A MasterTxn represents a user initiated Txn executed on the Master node.
* This class uses the hooks defined by Txn to support the durability
* requirements of a replicated transaction on the Master.
*/
public class MasterTxn extends Txn {
/* Holds the commit VLSN after a successful commit. */
private VLSN commitVLSN = VLSN.NULL_VLSN;
private final NameIdPair nameIdPair;
/* The number of acks required by this txn commit. */
private int requiredAckCount = -1;
/*
* Used to measure replicated transaction commit performance. All deltas
* are measured relative to the start time, to minimize storage overhead.
*/
/* The time the transaction was started. */
private final long startMs = System.currentTimeMillis();
/* The start relative delta time when the commit pre hook exited. */
private int preLogCommitEndDeltaMs = 0;
/*
* The start relative delta time when the commit message was written to
* the rep stream.
*/
private int repWriteStartDeltaMs = 0;
/**
* Flag to keep track of whether this transaction has taken the read lock
* that protects access to the blocking latch used by Master Transfer.
*/
private boolean locked;
/**
* Flag to prevent any change to the txn's contents. Used in
* master->replica transition. Intentionally volatile, so it can be
* interleaved with use of the MasterTxn mutex.
*/
private volatile boolean freeze;
/* For unit testing */
private TestHook<Integer> convertHook;
/* The default factory used to create MasterTxns */
private static final MasterTxnFactory DEFAULT_FACTORY =
new MasterTxnFactory() {
@Override
public MasterTxn create(EnvironmentImpl envImpl,
TransactionConfig config,
NameIdPair nameIdPair) {
return new MasterTxn(envImpl, config, nameIdPair);
}
};
/* The current Txn Factory. */
private static MasterTxnFactory factory = DEFAULT_FACTORY;
public MasterTxn(EnvironmentImpl envImpl,
TransactionConfig config,
NameIdPair nameIdPair)
throws DatabaseException {
super(envImpl, config, ReplicationContext.MASTER);
this.nameIdPair = nameIdPair;
}
/**
* Returns the transaction commit token used to identify the transaction.
*
* @see com.sleepycat.je.txn.Txn#getCommitToken()
*/
@Override
public CommitToken getCommitToken() {
if (commitVLSN.isNull()) {
return null;
}
RepImpl repImpl = (RepImpl) envImpl;
return new CommitToken(repImpl.getUUID(), commitVLSN.getSequence());
}
public VLSN getCommitVLSN() {
return commitVLSN;
}
/**
* MasterTxns use txn ids from a reserved negative space. So override
* the default generation of ids.
*/
@Override
protected long generateId(TxnManager txnManager,
long ignore /* mandatedId */) {
assert(ignore == 0);
return txnManager.getNextReplicatedTxnId();
}
/**
* Causes the transaction to wait until we have sufficient replicas to
* acknowledge the commit.
*/
@Override
@SuppressWarnings("unused")
protected void txnBeginHook(TransactionConfig config)
throws DatabaseException {
RepImpl repImpl = (RepImpl) envImpl;
try {
repImpl.txnBeginHook(this);
} catch (InterruptedException e) {
throw new ThreadInterruptedException(envImpl, e);
}
}
@Override
protected void preLogCommitHook()
throws DatabaseException {
RepImpl repImpl = (RepImpl) envImpl;
ReplicaAckPolicy ackPolicy = getCommitDurability().getReplicaAck();
requiredAckCount =
repImpl.getRepNode().getDurabilityQuorum().
getCurrentRequiredAckCount(ackPolicy);
/*
* TODO: An optimization we'd like to do is to identify transactions
* that only modify non-replicated databases, so they can avoid waiting
* for Replica commit acks and avoid checks like the one that requires
* that the node be a master before proceeding with the transaction.
*/
repImpl.preLogCommitHook(this);
preLogCommitEndDeltaMs = (int) (System.currentTimeMillis() - startMs);
}
@Override
protected void postLogCommitHook(LogItem commitItem)
throws DatabaseException {
commitVLSN = commitItem.getHeader().getVLSN();
try {
RepImpl repImpl = (RepImpl) envImpl;
repImpl.postLogCommitHook(this);
} catch (InterruptedException e) {
throw new ThreadInterruptedException(envImpl, e);
}
}
@Override
protected void preLogAbortHook()
throws DatabaseException {
RepImpl repImpl = (RepImpl) envImpl;
repImpl.preLogAbortHook(this);
}
@Override
protected void postLogCommitAbortHook() {
RepImpl repImpl = (RepImpl) envImpl;
repImpl.postLogCommitAbortHook(this);
}
@Override
protected void postLogAbortHook() {
RepImpl repImpl = (RepImpl)envImpl;
repImpl.postLogAbortHook(this);
}
/**
* Prevent this MasterTxn from taking locks if the node becomes a
* replica. The application has a reference to this Txn, and may
* attempt to use it well after the node has transitioned from master
* to replica.
*/
@Override
public LockResult lockInternal(long lsn,
LockType lockType,
boolean noWait,
boolean jumpAheadOfWaiters,
DatabaseImpl database)
throws LockNotAvailableException, LockConflictException,
DatabaseException {
ReplicatedEnvironment.State nodeState = ((RepImpl)envImpl).getState();
if (nodeState.isMaster()) {
return super.lockInternal
(lsn, lockType, noWait, jumpAheadOfWaiters, database);
}
throwNotMaster(nodeState);
return null; /* not reached */
}
private void throwNotMaster(ReplicatedEnvironment.State nodeState) {
if (nodeState.isReplica()) {
throw new ReplicaWriteException
(this, ((RepImpl)envImpl).getStateChangeEvent());
}
throw new UnknownMasterException
("Transaction " + getId() +
" cannot execute write operations because this node is" +
" no longer a master");
}
/**
* If logging occurs before locking, we must screen out write locks here.
*/
@Override
public synchronized void preLogWithoutLock(DatabaseImpl database) {
ReplicatedEnvironment.State nodeState = ((RepImpl)envImpl).getState();
if (nodeState.isMaster()) {
super.preLogWithoutLock(database);
return;
}
throwNotMaster(nodeState);
}
/**
* Determines whether we should lock the block-latch lock.
* <p>
* We acquire the lock during pre-log hook, and release it during post-log
* hook. Specifically, there are the following cases:
* <ol>
* <li>
* For a normal commit, we acquire it in {@code preLogCommitHook()} and
* release it in {@code postLogCommitHook()}
* <li>
* For a normal abort (invoked by the application on the {@code
* Txn.abort()} API), we acquire the lock in {@code preLogAbortHook()} and
* release it in {@code postLogAbortHook()}.
* <li>
* When a commit fails in such a way as to call {@code
* Txn.throwPreCommitException()}, we go through the abort path as well.
* In this case:
* <ul>
* <li>we will of course already have called {@code preLogCommitHook()};
* <li>the abort path calls {@code preLogAbortHook()} and {@code
* postLogAbortHook()} as always;
* <li>finally we call {@code postLogCommitAbortHook()}
* </ul>
* Fortunately we can avoid the complexity of dealing with a second
* (recursive) lock acquisition here, because by the time either post-hook
* is called we've done any writing of VLSNs. Thus, when we want to
* take the lock, we take it if it hasn't already been taken, and do
* nothing if it has; when releasing, we release it if we have it, and do
* nothing if we don't.
* </ol>
* <p>
* See additional javadoc at {@code RepImpl.blockLatchLock}
*/
public boolean lockOnce() {
if (locked) {
return false;
}
locked = true;
return true;
}
/**
* Determines whether we should unlock the block-latch lock.
*
* @see #lockOnce
*/
public boolean unlockOnce() {
if (locked) {
locked = false;
return true;
}
return false;
}
public int getRequiredAckCount() {
return requiredAckCount;
}
public void resetRequiredAckCount() {
requiredAckCount = 0;
}
/** A masterTxn always writes its own id into the commit or abort. */
@Override
protected int getReplicatorNodeId() {
return nameIdPair.getId();
}
public long getStartMs() {
return startMs;
}
public void stampRepWriteTime() {
this.repWriteStartDeltaMs =
(int)(System.currentTimeMillis() - startMs);
}
/**
* Returns the amount of time it took to copy the commit record from the
* log buffer to the rep stream. It's measured as the time interval
* starting with the time the preCommit hook completed, to the time the
* message write to the replication stream was initiated.
*/
public long messageTransferMs() {
return repWriteStartDeltaMs > 0 ?
(repWriteStartDeltaMs - preLogCommitEndDeltaMs) :
/*
* The message was invoked before the post commit hook fired.
*/
0;
}
@Override
protected boolean
propagatePostCommitException(DatabaseException postCommitException) {
return (postCommitException instanceof InsufficientAcksException) ?
true :
super.propagatePostCommitException(postCommitException);
}
/* The Txn factory interface. */
public interface MasterTxnFactory {
MasterTxn create(EnvironmentImpl envImpl,
TransactionConfig config,
NameIdPair nameIdPair);
}
/* The method used to create user Master Txns via the factory. */
public static MasterTxn create(EnvironmentImpl envImpl,
TransactionConfig config,
NameIdPair nameIdPair) {
return factory.create(envImpl, config, nameIdPair);
}
/**
* Method used for unit testing.
*
* Sets the factory to the one supplied. If the argument is null it
* restores the factory to the original default value.
*/
public static void setFactory(MasterTxnFactory factory) {
MasterTxn.factory = (factory == null) ? DEFAULT_FACTORY : factory;
}
@Override
public boolean isReplicationDefined() {
return true;
}
/**
* Convert a MasterTxn that has any write locks into a ReplayTxn, and close
* the MasterTxn after it is disemboweled. A MasterTxn that only has read
* locks is unchanged and is still usable by the application. To be clear,
* the application can never use a MasterTxn to obtain a lock if the node
* is in Replica mode, but may indeed be able to use a read-lock-only
* MasterTxn if the node cycles back into Master status.
*
* For converted MasterTxns, all write locks are transferred to a replay
* transaction, read locks are released, and the txn is closed. Used when a
* node is transitioning from master to replica mode without recovery,
* which may happen for an explicit master transfer request, or merely for
* a network partition/election of new
* master.
*
* The newly created replay transaction will need to be in the appropriate
* state, holding all write locks, so that the node in replica form can
* execute the proper syncups. Note that the resulting replay txn will
* only be aborted, and will never be committed, because the txn originated
* on this node, which is transitioning from master -> replica.
*
* We only transfer write locks. We need not transfer read locks, because
* replays only operate on writes, and are never required to obtain read
* locks. Read locks are released though, because (a) this txn is now only
* abortable, and (b) although the Replay can preempt any read locks held
* by the MasterTxn, such preemption will add delay.
*
* @return a ReplayTxn, if there were locks in this transaction, and
* there's a need to create a ReplayTxn.
*/
public ReplayTxn convertToReplayTxnAndClose(Logger logger,
Replay replay) {
/* Assertion */
if (!freeze) {
throw EnvironmentFailureException.unexpectedState
(envImpl,
"Txn " + getId() +
" should be frozen when converting to replay txn");
}
/*
* This is an important and relatively rare operation, and worth
* logging.
*/
LoggerUtils.info(logger, envImpl,
"Transforming txn " + getId() +
" from MasterTxn to ReplayTxn");
int hookCount = 0;
ReplayTxn replayTxn = null;
boolean needToClose = true;
try {
synchronized (this) {
if (isClosed()) {
LoggerUtils.info(logger, envImpl,
"Txn " + getId() +
" is closed, no tranform needed");
needToClose = false;
return null;
}
/*
* Get the list of write locks, and process them in lsn order,
* so we properly maintain the lastLoggedLsn and firstLoggedLSN
* fields of the newly created ReplayTxn.
*/
final Set<Long> lockedLSNs = getWriteLockIds();
/*
* This transaction may not actually have any write locks. In
* that case, we permit it to live on.
*/
if (lockedLSNs.size() == 0) {
LoggerUtils.info(logger, envImpl, "Txn " + getId() +
" had no write locks, didn't create" +
" ReplayTxn");
needToClose = false;
return null;
}
/*
* We have write locks. Make sure that this txn can now
* only be aborted. Otherwise, there could be this window
* in this method:
* t1: locks stolen, no locks left in this txn
* t2: txn unfrozen, commits and aborts possible
* -- at this point, another thread could sneak in and
* -- try to commit. The txn would commmit successfully,
* -- because a commit w/no write locks is a no-op.
* -- but that would convey the false impression that the
* -- txn's write operations had commmitted.
* t3: txn is closed
*/
setOnlyAbortable(new UnknownMasterException
(envImpl.getNodeName() +
" is no longer a master"));
replayTxn = replay.getReplayTxn(getId(), false);
/*
* Order the lsns, so that the locks are taken in the proper
* order, and the txn's firstLoggedLsn and lastLoggedLsn fields
* are properly set.
*/
List<Long> sortedLsns = new ArrayList<Long>(lockedLSNs);
Collections.sort(sortedLsns);
LoggerUtils.info(logger, envImpl,
"Txn " + getId() + " has " +
lockedLSNs.size() + " locks to transform");
/*
* Transfer each lock. Note that ultimately, since mastership
* is changing, and replicated commits will only be executed
* when a txn has originated on that node, the target ReplayTxn
* can never be committed, and will only be aborted.
*/
for (Long lsn: sortedLsns) {
LoggerUtils.info(logger, envImpl,
"Txn " + getId() +
" is transferring lock " + lsn);
/*
* Use a special method to steal the lock. Another approach
* might have been to have the replayTxn merely attempt a
* lock(); as an importunate txn, the replayTxn would
* preempt the MasterTxn's lock. However, that path doesn't
* work because lock() requires having a databaseImpl in
* hand, and that's not available here.
*/
replayTxn.stealLockFromMasterTxn(lsn);
/*
* Copy all the lock's info into the Replay and remove it
* from the master. Normally, undo clears write locks, but
* this MasterTxn will not be executing undo.
*/
WriteLockInfo replayWLI = replayTxn.getWriteLockInfo(lsn);
WriteLockInfo masterWLI = getWriteLockInfo(lsn);
replayWLI.copyAllInfo(masterWLI);
removeLock(lsn);
}
/*
* Txns have collections of undoDatabases and deletedDatabases.
* Undo databases are normally incrementally added to the txn
* as locks are obtained Unlike normal locking or recovery
* locking, in this case we don't have a reference to the
* databaseImpl that goes with this lock, so we copy the undo
* collection in one fell swoop.
*/
replayTxn.copyDatabasesForConversion(this);
/*
* This txn is no longer responsible for databaseImpl
* cleanup, as that issue now lies with the ReplayTxn, so
* remove the collection.
*/
deletedDatabases = null;
/*
* All locks have been removed from this transaction. Clear
* the firstLoggedLsn and lastLoggedLsn so there's no danger
* of attempting to undo anything; this txn is no longer
* responsible for any records.
*/
lastLoggedLsn = DbLsn.NULL_LSN;
firstLoggedLsn = DbLsn.NULL_LSN;
/* If this txn also had read locks, clear them */
clearReadLocks();
}
} finally {
assert TestHookExecute.doHookIfSet(convertHook, hookCount++);
unfreeze();
assert TestHookExecute.doHookIfSet(convertHook, hookCount++);
/*
* We need to abort the txn, but we can't call abort() because that
* method checks whether we are the master! Instead, call the
* internal method, close(), in order to end this transaction and
* unregister it from the transactionManager. Must be called
* outside the synchronization block.
*/
if (needToClose) {
LoggerUtils.info(logger, envImpl, "About to close txn " +
getId() + " state=" + getState());
close(false /*isCommit */);
LoggerUtils.info(logger, envImpl, "Closed txn " + getId() +
" state=" + getState());
}
assert TestHookExecute.doHookIfSet(convertHook, hookCount++);
}
return replayTxn;
}
public void freeze() {
freeze = true;
}
private void unfreeze() {
freeze = false;
}
/**
* Used to hold the transaction stable while it is being cloned as a
* ReplayTxn, during master->replica transitions. Essentially, there
* are two parties that now have a reference to this transaction -- the
* originating application thread, and the RepNode thread that is
* trying to set up internal state so it can begin to act as a replica.
*
* The transaction will throw UnknownMasterException or
* ReplicaWriteException if the transaction is frozen, so that the
* application knows that the transaction is no longer viable, but it
* doesn't attempt to do most of the follow-on cleanup and release of locks
* that failed aborts and commits normally attempt. One aspect of
* transaction cleanup can't be skipped though. It is necessary to do the
* post log hooks to free up the block txn latch lock so that the
* transaction can be closed by the RepNode thread. For example:
* - application thread starts transaction
* - application takes the block txn latch lock and attempts commit or
* abort, but is stopped because the txn is frozen by master transfer.
* - the application must release the block txn latch lock.
* @see Replica#replicaTransitionCleanup
*/
@Override
protected void checkIfFrozen(boolean isCommit) {
if (freeze) {
try {
((RepImpl) envImpl).checkIfMaster(this);
} catch (DatabaseException e) {
if (isCommit) {
postLogCommitAbortHook();
} else {
postLogAbortHook();
}
throw e;
}
}
}
/* For unit testing */
public void setConvertHook(TestHook<Integer> hook) {
convertHook = hook;
}
@Override
public boolean isMasterTxn() {
return true;
}
}
| |
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Carlos Andres Jimenez <apps@carlosandresjimenez.co>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package co.carlosandresjimenez.gotit.backend.controller;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
import javax.jdo.JDOException;
import javax.jdo.JDOObjectNotFoundException;
import javax.servlet.http.HttpServletRequest;
import co.carlosandresjimenez.gotit.backend.Utility;
import co.carlosandresjimenez.gotit.backend.beans.Answer;
import co.carlosandresjimenez.gotit.backend.beans.Checkin;
import co.carlosandresjimenez.gotit.backend.beans.Following;
import co.carlosandresjimenez.gotit.backend.beans.Question;
import co.carlosandresjimenez.gotit.backend.beans.User;
import co.carlosandresjimenez.gotit.backend.beans.UserPrivacy;
import co.carlosandresjimenez.gotit.backend.repository.AnswerRepository;
import co.carlosandresjimenez.gotit.backend.repository.CheckinRepository;
import co.carlosandresjimenez.gotit.backend.repository.FollowingRepository;
import co.carlosandresjimenez.gotit.backend.repository.QuestionRepository;
import co.carlosandresjimenez.gotit.backend.repository.UserPrivacyRepository;
import co.carlosandresjimenez.gotit.backend.repository.UserRepository;
// Tell Spring that this class is a Controller that should
// handle certain HTTP requests for the DispatcherServlet
@Controller
public class GotItSvc implements GotItSvcApi {
@Autowired
private UserRepository userRepository;
@Autowired
private QuestionRepository questionRepository;
@Autowired
private AnswerRepository answerRepository;
@Autowired
private CheckinRepository checkinRepository;
@Autowired
private FollowingRepository followingRepository;
@Autowired
private UserPrivacyRepository userPrivacyRepository;
@RequestMapping(value = USER_PATH, method = RequestMethod.GET)
public
@ResponseBody
User getUserDetails(@RequestParam(ID_PARAMETER) String email,
HttpServletRequest request) {
String sessionEmail = (String) request.getAttribute("email");
if (email == null || email.isEmpty()) {
return null; //RESPONSE_STATUS_AUTH_REQUIRED;
}
if (sessionEmail == null || sessionEmail.isEmpty()) {
return null; //RESPONSE_STATUS_AUTH_REQUIRED;
}
boolean isPublic = true;
if (sessionEmail.equals(email)) {
isPublic = false;
}
return findUser(email, isPublic);
}
public User findUser(String email, boolean isPublic) {
User user = null;
try {
user = userRepository.findByEmail(email);
} catch (JDOObjectNotFoundException e) {
System.out.println(USER_PATH + " getUserDetails: User " + email + " not found.");
}
if (user == null)
return null;
UserPrivacy userPrivacy = null;
try {
userPrivacy = userPrivacyRepository.findOne(UserPrivacy.getKey(email));
} catch (JDOObjectNotFoundException e) {
System.out.println(USER_PATH + " getUserDetails: User Privacy not found for " + email);
}
if (isPublic) {
user = user.copy();
if (userPrivacy != null) {
if (!userPrivacy.isShareAvatar())
user.setAvatarUrl(null);
if (!userPrivacy.isShareBirthDate())
user.setBirthDate(null);
if (!userPrivacy.isShareMedical())
user.setMedicalRecNum(null);
if (!userPrivacy.isShareTelephoneNumber())
user.setTelephoneNumber(null);
} else {
user.setBirthDate(null);
user.setMedicalRecNum(null);
user.setTelephoneNumber(null);
}
} else {
if (userPrivacy == null)
user.setUserPrivacy(new UserPrivacy(email,
UserPrivacy.DEFAULT_SHARE_MEDICAL,
UserPrivacy.DEFAULT_SHARE_BIRTH_DATE,
UserPrivacy.DEFAULT_SHARE_AVATAR,
UserPrivacy.DEFAULT_SHARE_LOCATION,
UserPrivacy.DEFAULT_SHARE_TELEPHONE,
UserPrivacy.DEFAULT_SHARE_FEEDBACK));
else
user.setUserPrivacy(userPrivacy);
}
return user;
}
@RequestMapping(value = REGISTER_PATH, method = RequestMethod.POST)
public
@ResponseBody
String registerUser(@RequestBody User user) {
if (user == null)
return null;
User result = null;
try {
result = userRepository.save(user);
} catch (JDOException e) {
e.printStackTrace();
}
UserPrivacy userPrivacy = user.getUserPrivacy();
try {
if (userPrivacy != null)
userPrivacy.setPrivacyId(userPrivacy.getEmail());
else
userPrivacy = new UserPrivacy(user.getEmail(),
UserPrivacy.DEFAULT_SHARE_MEDICAL,
UserPrivacy.DEFAULT_SHARE_BIRTH_DATE,
UserPrivacy.DEFAULT_SHARE_AVATAR,
UserPrivacy.DEFAULT_SHARE_LOCATION,
UserPrivacy.DEFAULT_SHARE_TELEPHONE,
UserPrivacy.DEFAULT_SHARE_FEEDBACK);
userPrivacyRepository.save(userPrivacy);
} catch (JDOException e) {
e.printStackTrace();
}
return result != null ? result.getUserId() : null;
}
@RequestMapping(value = QUESTION_PATH, method = RequestMethod.GET)
public
@ResponseBody
ArrayList<Question> getAllQuestions() {
ArrayList<Question> questions = Lists.newArrayList(questionRepository.findAll());
questions.add(new Question(
null,
questions.size() + 1,
"Share this check-in?",
"singe choice",
"checkbox",
null,
false));
return Lists.newArrayList(questions);
}
@RequestMapping(value = LOAD_QUESTION_PATH, method = RequestMethod.POST)
public
@ResponseBody
String saveQuestion(@RequestBody Question question) {
Question result = null;
try {
result = questionRepository.save(question);
} catch (JDOException e) {
e.printStackTrace();
}
return result != null ? result.getQuestionId() : null;
}
@RequestMapping(value = ANSWER_PATH, method = RequestMethod.POST)
public
@ResponseBody
int saveAnswers(@RequestBody ArrayList<Answer> answers, HttpServletRequest request) {
if (answers == null || answers.isEmpty()) {
return RESPONSE_STATUS_NOT_SAVED;
}
Checkin checkin;
String email = (String) request.getAttribute("email");
if (email == null || email.isEmpty()) {
return RESPONSE_STATUS_AUTH_REQUIRED;
}
int lastAnswerPosition = answers.size() - 1;
Answer lastAnswer = answers.get(lastAnswerPosition);
try {
checkin = checkinRepository.save(new Checkin(null,
email,
Utility.getDatetime(),
Boolean.parseBoolean(lastAnswer.getValue())));
} catch (JDOException e) {
e.printStackTrace();
return RESPONSE_STATUS_NOT_SAVED;
}
answers.remove(lastAnswerPosition);
for (Answer answer : answers) {
answer.setCheckinId(checkin.getCheckinId());
}
ArrayList<Answer> result;
try {
result = (ArrayList<Answer>) answerRepository.save(answers);
} catch (JDOException e) {
e.printStackTrace();
return RESPONSE_STATUS_NOT_SAVED;
}
if (result == null || result.isEmpty()) {
return RESPONSE_STATUS_NOT_SAVED;
}
if (result.size() != answers.size()) {
return RESPONSE_STATUS_NOT_SAVED;
}
return RESPONSE_STATUS_OK;
}
@RequestMapping(value = CHECKIN_HISTORY_PATH, method = RequestMethod.GET)
public
@ResponseBody
ArrayList<Checkin> getCheckinHistory(HttpServletRequest request) {
String email = (String) request.getAttribute("email");
if (email == null || email.isEmpty()) {
return null; //RESPONSE_STATUS_AUTH_REQUIRED;
}
return Lists.newArrayList(checkinRepository.findByEmail(email));
}
@RequestMapping(value = CHECKIN_BASE_PATH, method = RequestMethod.GET)
public
@ResponseBody
ArrayList<Question> getCheckinAnswers(
@RequestParam(ID_PARAMETER) String checkinId) {
if (checkinId == null || checkinId.isEmpty())
return null;
Answer answer;
ArrayList<Question> questions = Lists.newArrayList(questionRepository.findAll());
for (Question question : questions) {
if (question != null && !question.getQuestionId().isEmpty())
answer = answerRepository.findByCheckinAndQuestionId(checkinId, question.getQuestionId());
else
answer = null;
question.setAnswer(answer);
}
return questions;
}
@RequestMapping(value = FOLLOW_BASE_PATH, method = RequestMethod.GET)
public
@ResponseBody
int follow(@RequestParam(ID_PARAMETER) String followEmail,
HttpServletRequest request) {
String userEmail = (String) request.getAttribute("email");
if (userEmail == null || userEmail.isEmpty()) {
return RESPONSE_STATUS_AUTH_REQUIRED;
}
return followUser(userEmail, followEmail, Following.PENDING);
}
@RequestMapping(value = FOLLOW_APPROVE_PATH, method = RequestMethod.GET)
public
@ResponseBody
int changeFollowerStatus(@RequestParam(ID_PARAMETER) String followerEmail,
@RequestParam(APPROVE_PARAMETER) boolean approve,
@RequestParam(FOLLOWBACK_PARAMETER) boolean followBack,
HttpServletRequest request) {
String userEmail = (String) request.getAttribute("email");
if (userEmail == null || userEmail.isEmpty()) {
return RESPONSE_STATUS_AUTH_REQUIRED;
}
int resultCode;
try {
if (approve) {
// Save approved
resultCode = followUser(followerEmail, userEmail, Following.APPROVED);
if (resultCode == RESPONSE_STATUS_OK && followBack) {
// Save follow back
resultCode = followUser(userEmail, followerEmail, Following.PENDING);
}
} else {
// Save rejected
resultCode = followUser(followerEmail, userEmail, Following.REJECTED);
}
} catch (JDOException e) {
e.printStackTrace();
return RESPONSE_STATUS_NOT_SAVED;
}
return resultCode;
}
int followUser(String userEmail, String followUserEmail, int approvedStatus) {
if (userEmail.equals(followUserEmail))
return RESPONSE_STATUS_CANNOT_FOLLOW_ITSELF;
try {
if (approvedStatus == Following.PENDING &&
followingRepository.exists(Following.getKey(userEmail, followUserEmail))) {
System.out.println("ERROR " + RESPONSE_STATUS_PK_VIOLATED + ". Primary Key violated, relation " + userEmail + " to " + followUserEmail + " exists.");
return RESPONSE_STATUS_PK_VIOLATED;
}
} catch (JDOObjectNotFoundException e) {
// This is thrown if the relationship is not found, in that case we can continue.
}
User user;
try {
user = userRepository.findByEmail(followUserEmail);
} catch (JDOObjectNotFoundException e) {
return RESPONSE_STATUS_NOT_FOUND;
}
if (user == null)
return RESPONSE_STATUS_NOT_FOUND;
if (user.getUserType().equals(User.USER_TYPE_FOLLOWER)) {
return RESPONSE_STATUS_CANNOT_FOLLOW;
}
Following following;
try {
following = followingRepository.save(new Following(userEmail, followUserEmail, approvedStatus));
} catch (JDOException e) {
e.printStackTrace();
return RESPONSE_STATUS_NOT_SAVED;
}
if (following == null)
return RESPONSE_STATUS_NOT_SAVED;
return RESPONSE_STATUS_OK;
}
@RequestMapping(value = FOLLOWING_LIST_PATH, method = RequestMethod.GET)
public
@ResponseBody
ArrayList<User> getFollowingList(HttpServletRequest request) {
String userEmail = (String) request.getAttribute("email");
if (userEmail == null || userEmail.isEmpty()) {
return null; // RESPONSE_STATUS_AUTH_REQUIRED;
}
List<Following> followingList = followingRepository.findFollowingUsers(userEmail, Following.APPROVED);
ArrayList<User> users = Lists.newArrayList();
for (Following following : followingList)
users.add(findUser(following.getFollowingUserEmail(), true));
if (users.isEmpty())
return null;
return users;
}
@RequestMapping(value = FOLLOW_REQUESTS_PATH, method = RequestMethod.GET)
public
@ResponseBody
ArrayList<User> getFollowRequestsList(HttpServletRequest request) {
String userEmail = (String) request.getAttribute("email");
if (userEmail == null || userEmail.isEmpty()) {
return null; // RESPONSE_STATUS_AUTH_REQUIRED;
}
List<Following> followingList = followingRepository.findFollowRequest(userEmail, Following.PENDING);
ArrayList<User> users = Lists.newArrayList();
for (Following following : followingList)
users.add(findUser(following.getUserEmail(), true));
if (users.isEmpty())
return null;
return users;
}
@RequestMapping(value = FOLLOWING_TIMELINE_PATH, method = RequestMethod.GET)
public
@ResponseBody
ArrayList<Checkin> getFollowingTimeline(HttpServletRequest request) {
String userEmail = (String) request.getAttribute("email");
if (userEmail == null || userEmail.isEmpty()) {
return null; // RESPONSE_STATUS_AUTH_REQUIRED;
}
ArrayList<String> followingUsers = Lists.newArrayList(followingRepository.findFollowingUsersEmails(userEmail));
if (followingUsers.isEmpty())
return null;
return Lists.newArrayList(checkinRepository.findByListOfEmails(followingUsers));
}
@RequestMapping(value = CHECKIN_GRAPH_PATH, method = RequestMethod.GET)
public
@ResponseBody
ArrayList<Answer> getGraphData(@RequestParam(ID_PARAMETER) String email,
HttpServletRequest request) {
String sessionEmail = (String) request.getAttribute("email");
if (email == null || email.isEmpty()) {
return null; //RESPONSE_STATUS_AUTH_REQUIRED;
}
if (sessionEmail == null || sessionEmail.isEmpty()) {
return null; //RESPONSE_STATUS_AUTH_REQUIRED;
}
boolean isPublic = true;
if (sessionEmail.equals(email)) {
isPublic = false;
}
if (isPublic) {
UserPrivacy userPrivacy = null;
try {
userPrivacy = userPrivacyRepository.findOne(UserPrivacy.getKey(email));
} catch (JDOObjectNotFoundException e) {
System.out.println(USER_PATH + " getUserDetails: User Privacy not found for " + email);
}
if (userPrivacy == null || !userPrivacy.isShareFeedback())
return null;
}
Question question;
try {
question = questionRepository.findFirstGraphAvailableQuestion();
} catch (JDOException e) {
e.printStackTrace();
return null;
}
if (question == null || question.getQuestionId() == null || question.getQuestionId().isEmpty())
return null;
return Lists.newArrayList(answerRepository.findByEmailAndQuestionId(email, question.getQuestionId()));
}
}
| |
/*
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* 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.drools.workbench.screens.guided.dtable.client.widget.table.model.synchronizers.impl;
import java.util.ArrayList;
import java.util.Collections;
import org.drools.workbench.models.guided.dtable.shared.model.BRLConditionVariableColumn;
import org.drools.workbench.models.guided.dtable.shared.model.CompositeColumn;
import org.drools.workbench.models.guided.dtable.shared.model.LimitedEntryBRLConditionColumn;
import org.drools.workbench.screens.guided.dtable.client.widget.table.columns.BaseMultipleDOMElementUiColumn;
import org.drools.workbench.screens.guided.dtable.client.widget.table.columns.BooleanUiColumn;
import org.drools.workbench.screens.guided.dtable.client.widget.table.model.synchronizers.ModelSynchronizer.VetoException;
import org.junit.Test;
import org.uberfire.ext.wires.core.grids.client.model.GridColumn;
import org.uberfire.ext.wires.core.grids.client.model.impl.BaseGridCellValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class LimitedEntryBRLConditionColumnSynchronizerTest extends BaseSynchronizerTest {
@Test
public void testAppend() throws VetoException {
final LimitedEntryBRLConditionColumn column = new LimitedEntryBRLConditionColumn();
column.setHeader("col1");
modelSynchronizer.appendColumn(column);
assertEquals(1,
model.getConditions().size());
assertEquals(4,
uiModel.getColumns().size());
assertTrue(uiModel.getColumns().get(3) instanceof BooleanUiColumn);
assertEquals(true,
((BaseMultipleDOMElementUiColumn) uiModel.getColumns().get(3)).isEditable());
}
@Test
public void testUpdate() throws VetoException {
final LimitedEntryBRLConditionColumn column = new LimitedEntryBRLConditionColumn();
column.setHeader("col1");
modelSynchronizer.appendColumn(column);
final LimitedEntryBRLConditionColumn edited = new LimitedEntryBRLConditionColumn();
edited.setHideColumn(true);
edited.setHeader("updated");
modelSynchronizer.updateColumn(column,
edited);
assertEquals(1,
model.getConditions().size());
assertEquals(4,
uiModel.getColumns().size());
assertTrue(uiModel.getColumns().get(3) instanceof BooleanUiColumn);
assertEquals("updated",
uiModel.getColumns().get(3).getHeaderMetaData().get(0).getTitle());
assertEquals(false,
uiModel.getColumns().get(3).isVisible());
}
@Test
public void testDelete() throws VetoException {
final LimitedEntryBRLConditionColumn column = new LimitedEntryBRLConditionColumn();
column.setHeader("col1");
modelSynchronizer.appendColumn(column);
assertEquals(1,
model.getConditions().size());
assertEquals(4,
uiModel.getColumns().size());
modelSynchronizer.deleteColumn(column);
assertEquals(0,
model.getConditions().size());
assertEquals(3,
uiModel.getColumns().size());
}
@Test
public void testMoveColumnTo_MoveLeft() throws VetoException {
final CompositeColumn<BRLConditionVariableColumn> column1 = new LimitedEntryBRLConditionColumn();
column1.setHeader("age");
final CompositeColumn<BRLConditionVariableColumn> column2 = new LimitedEntryBRLConditionColumn();
column2.setHeader("name");
modelSynchronizer.appendColumn(column1);
modelSynchronizer.appendColumn(column2);
modelSynchronizer.appendRow();
uiModel.setCellValue(0,
3,
new BaseGridCellValue<Boolean>(true));
uiModel.setCellValue(0,
4,
new BaseGridCellValue<Boolean>(false));
assertEquals(2,
model.getConditions().size());
assertEquals(column1,
model.getConditions().get(0));
assertEquals(column2,
model.getConditions().get(1));
assertEquals(true,
model.getData().get(0).get(3).getBooleanValue());
assertEquals(false,
model.getData().get(0).get(4).getBooleanValue());
assertEquals(5,
uiModel.getColumns().size());
final GridColumn<?> uiModelColumn1_1 = uiModel.getColumns().get(3);
final GridColumn<?> uiModelColumn2_1 = uiModel.getColumns().get(4);
assertEquals("age",
uiModelColumn1_1.getHeaderMetaData().get(0).getTitle());
assertEquals("name",
uiModelColumn2_1.getHeaderMetaData().get(0).getTitle());
assertTrue(uiModelColumn1_1 instanceof BooleanUiColumn);
assertTrue(uiModelColumn2_1 instanceof BooleanUiColumn);
assertEquals(3,
uiModelColumn1_1.getIndex());
assertEquals(4,
uiModelColumn2_1.getIndex());
assertEquals(true,
uiModel.getRow(0).getCells().get(uiModelColumn1_1.getIndex()).getValue().getValue());
assertEquals(false,
uiModel.getRow(0).getCells().get(uiModelColumn2_1.getIndex()).getValue().getValue());
uiModel.moveColumnTo(3,
uiModelColumn2_1);
assertEquals(2,
model.getConditions().size());
assertEquals(column2,
model.getConditions().get(0));
assertEquals(column1,
model.getConditions().get(1));
assertEquals(false,
model.getData().get(0).get(3).getBooleanValue());
assertEquals(true,
model.getData().get(0).get(4).getBooleanValue());
assertEquals(5,
uiModel.getColumns().size());
final GridColumn<?> uiModelColumn1_2 = uiModel.getColumns().get(3);
final GridColumn<?> uiModelColumn2_2 = uiModel.getColumns().get(4);
assertEquals("name",
uiModelColumn1_2.getHeaderMetaData().get(0).getTitle());
assertEquals("age",
uiModelColumn2_2.getHeaderMetaData().get(0).getTitle());
assertTrue(uiModelColumn1_2 instanceof BooleanUiColumn);
assertTrue(uiModelColumn2_2 instanceof BooleanUiColumn);
assertEquals(4,
uiModelColumn1_2.getIndex());
assertEquals(3,
uiModelColumn2_2.getIndex());
assertEquals(false,
uiModel.getRow(0).getCells().get(uiModelColumn1_2.getIndex()).getValue().getValue());
assertEquals(true,
uiModel.getRow(0).getCells().get(uiModelColumn2_2.getIndex()).getValue().getValue());
}
@Test
public void testMoveColumnTo_MoveRight() throws VetoException {
final CompositeColumn<BRLConditionVariableColumn> column1 = new LimitedEntryBRLConditionColumn();
column1.setHeader("age");
final CompositeColumn<BRLConditionVariableColumn> column2 = new LimitedEntryBRLConditionColumn();
column2.setHeader("name");
modelSynchronizer.appendColumn(column1);
modelSynchronizer.appendColumn(column2);
modelSynchronizer.appendRow();
uiModel.setCellValue(0,
3,
new BaseGridCellValue<Boolean>(true));
uiModel.setCellValue(0,
4,
new BaseGridCellValue<Boolean>(false));
assertEquals(2,
model.getConditions().size());
assertEquals(column1,
model.getConditions().get(0));
assertEquals(column2,
model.getConditions().get(1));
assertEquals(true,
model.getData().get(0).get(3).getBooleanValue());
assertEquals(false,
model.getData().get(0).get(4).getBooleanValue());
assertEquals(5,
uiModel.getColumns().size());
final GridColumn<?> uiModelColumn1_1 = uiModel.getColumns().get(3);
final GridColumn<?> uiModelColumn2_1 = uiModel.getColumns().get(4);
assertEquals("age",
uiModelColumn1_1.getHeaderMetaData().get(0).getTitle());
assertEquals("name",
uiModelColumn2_1.getHeaderMetaData().get(0).getTitle());
assertTrue(uiModelColumn1_1 instanceof BooleanUiColumn);
assertTrue(uiModelColumn2_1 instanceof BooleanUiColumn);
assertEquals(3,
uiModelColumn1_1.getIndex());
assertEquals(4,
uiModelColumn2_1.getIndex());
assertEquals(true,
uiModel.getRow(0).getCells().get(uiModelColumn1_1.getIndex()).getValue().getValue());
assertEquals(false,
uiModel.getRow(0).getCells().get(uiModelColumn2_1.getIndex()).getValue().getValue());
uiModel.moveColumnTo(4,
uiModelColumn1_1);
assertEquals(2,
model.getConditions().size());
assertEquals(column2,
model.getConditions().get(0));
assertEquals(column1,
model.getConditions().get(1));
assertEquals(false,
model.getData().get(0).get(3).getBooleanValue());
assertEquals(true,
model.getData().get(0).get(4).getBooleanValue());
assertEquals(5,
uiModel.getColumns().size());
final GridColumn<?> uiModelColumn1_2 = uiModel.getColumns().get(3);
final GridColumn<?> uiModelColumn2_2 = uiModel.getColumns().get(4);
assertEquals("name",
uiModelColumn1_2.getHeaderMetaData().get(0).getTitle());
assertEquals("age",
uiModelColumn2_2.getHeaderMetaData().get(0).getTitle());
assertTrue(uiModelColumn1_2 instanceof BooleanUiColumn);
assertTrue(uiModelColumn2_2 instanceof BooleanUiColumn);
assertEquals(4,
uiModelColumn1_2.getIndex());
assertEquals(3,
uiModelColumn2_2.getIndex());
assertEquals(false,
uiModel.getRow(0).getCells().get(uiModelColumn1_2.getIndex()).getValue().getValue());
assertEquals(true,
uiModel.getRow(0).getCells().get(uiModelColumn2_2.getIndex()).getValue().getValue());
}
@Test
public void testMoveColumnTo_OutOfBounds() throws VetoException {
final CompositeColumn<BRLConditionVariableColumn> column1 = new LimitedEntryBRLConditionColumn();
column1.setHeader("age");
final CompositeColumn<BRLConditionVariableColumn> column2 = new LimitedEntryBRLConditionColumn();
column2.setHeader("name");
modelSynchronizer.appendColumn(column1);
modelSynchronizer.appendColumn(column2);
modelSynchronizer.appendRow();
uiModel.setCellValue(0,
3,
new BaseGridCellValue<Boolean>(true));
uiModel.setCellValue(0,
4,
new BaseGridCellValue<Boolean>(false));
assertEquals(2,
model.getConditions().size());
assertEquals(column1,
model.getConditions().get(0));
assertEquals(column2,
model.getConditions().get(1));
assertEquals(true,
model.getData().get(0).get(3).getBooleanValue());
assertEquals(false,
model.getData().get(0).get(4).getBooleanValue());
assertEquals(5,
uiModel.getColumns().size());
final GridColumn<?> uiModelColumn1_1 = uiModel.getColumns().get(3);
final GridColumn<?> uiModelColumn2_1 = uiModel.getColumns().get(4);
assertEquals("age",
uiModelColumn1_1.getHeaderMetaData().get(0).getTitle());
assertEquals("name",
uiModelColumn2_1.getHeaderMetaData().get(0).getTitle());
assertTrue(uiModelColumn1_1 instanceof BooleanUiColumn);
assertTrue(uiModelColumn2_1 instanceof BooleanUiColumn);
assertEquals(3,
uiModelColumn1_1.getIndex());
assertEquals(4,
uiModelColumn2_1.getIndex());
assertEquals(true,
uiModel.getRow(0).getCells().get(uiModelColumn1_1.getIndex()).getValue().getValue());
assertEquals(false,
uiModel.getRow(0).getCells().get(uiModelColumn2_1.getIndex()).getValue().getValue());
uiModel.moveColumnTo(1,
uiModelColumn1_1);
assertEquals(2,
model.getConditions().size());
assertEquals(column1,
model.getConditions().get(0));
assertEquals(column2,
model.getConditions().get(1));
assertEquals(true,
model.getData().get(0).get(3).getBooleanValue());
assertEquals(false,
model.getData().get(0).get(4).getBooleanValue());
assertEquals(5,
uiModel.getColumns().size());
final GridColumn<?> uiModelColumn1_2 = uiModel.getColumns().get(3);
final GridColumn<?> uiModelColumn2_2 = uiModel.getColumns().get(4);
assertEquals("age",
uiModelColumn1_2.getHeaderMetaData().get(0).getTitle());
assertEquals("name",
uiModelColumn2_2.getHeaderMetaData().get(0).getTitle());
assertTrue(uiModelColumn1_2 instanceof BooleanUiColumn);
assertTrue(uiModelColumn2_2 instanceof BooleanUiColumn);
assertEquals(3,
uiModelColumn1_2.getIndex());
assertEquals(4,
uiModelColumn2_2.getIndex());
assertEquals(true,
uiModel.getRow(0).getCells().get(uiModelColumn1_2.getIndex()).getValue().getValue());
assertEquals(false,
uiModel.getRow(0).getCells().get(uiModelColumn2_2.getIndex()).getValue().getValue());
}
@Test
public void checkHandlesMoveColumnsToWithEmptyMetadata() throws VetoException {
final LimitedEntryBRLConditionColumnSynchronizer synchronizer = new LimitedEntryBRLConditionColumnSynchronizer();
assertFalse(synchronizer.handlesMoveColumnsTo(Collections.emptyList()));
}
@Test
public void checkHandlesMoveColumnsToWithMultipleMetadata() throws VetoException {
final BaseSynchronizer.MoveColumnToMetaData md0 = mock(BaseSynchronizer.MoveColumnToMetaData.class);
final BaseSynchronizer.MoveColumnToMetaData md1 = mock(BaseSynchronizer.MoveColumnToMetaData.class);
final LimitedEntryBRLConditionColumnSynchronizer synchronizer = new LimitedEntryBRLConditionColumnSynchronizer();
when(md0.getColumn()).thenReturn(mock(LimitedEntryBRLConditionColumn.class));
when(md1.getColumn()).thenReturn(mock(LimitedEntryBRLConditionColumn.class));
assertFalse(synchronizer.handlesMoveColumnsTo(new ArrayList<BaseSynchronizer.MoveColumnToMetaData>() {{
add(md0);
add(md1);
}}));
}
@Test
public void checkHandlesMoveColumnsToWithSingleMetadata() throws VetoException {
final BaseSynchronizer.MoveColumnToMetaData md0 = mock(BaseSynchronizer.MoveColumnToMetaData.class);
final LimitedEntryBRLConditionColumnSynchronizer synchronizer = new LimitedEntryBRLConditionColumnSynchronizer();
when(md0.getColumn()).thenReturn(mock(LimitedEntryBRLConditionColumn.class));
assertTrue(synchronizer.handlesMoveColumnsTo(Collections.singletonList(md0)));
}
}
| |
/*
* Copyright 2012-2016 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.boot.autoconfigure.security;
import java.util.EnumSet;
import javax.servlet.DispatcherType;
import org.junit.After;
import org.junit.Test;
import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.autoconfigure.TestAutoConfigurationPackage;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.test.City;
import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration;
import org.springframework.boot.test.util.EnvironmentTestUtils;
import org.springframework.boot.web.servlet.DelegatingFilterProxyRegistrationBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.mock.web.MockServletContext;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.event.AbstractAuthenticationEvent;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
/**
* Tests for {@link SecurityAutoConfiguration}.
*
* @author Dave Syer
* @author Rob Winch
* @author Andy Wilkinson
*/
public class SecurityAutoConfigurationTests {
private AnnotationConfigWebApplicationContext context;
@After
public void close() {
if (this.context != null) {
this.context.close();
}
}
@Test
public void testWebConfiguration() throws Exception {
this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext());
this.context.register(SecurityAutoConfiguration.class,
ServerPropertiesAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context.refresh();
assertThat(this.context.getBean(AuthenticationManagerBuilder.class)).isNotNull();
// 4 for static resources and one for the rest
assertThat(this.context.getBean(FilterChainProxy.class).getFilterChains())
.hasSize(5);
}
@Test
public void testDefaultFilterOrderWithSecurityAdapter() throws Exception {
this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext());
this.context.register(WebSecurity.class, SecurityAutoConfiguration.class,
SecurityFilterAutoConfiguration.class,
ServerPropertiesAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context.refresh();
assertThat(this.context.getBean("securityFilterChainRegistration",
DelegatingFilterProxyRegistrationBean.class).getOrder()).isEqualTo(
FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100);
}
@Test
public void testFilterIsNotRegisteredInNonWeb() throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(SecurityAutoConfiguration.class,
SecurityFilterAutoConfiguration.class,
ServerPropertiesAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
try {
context.refresh();
assertThat(context.containsBean("securityFilterChainRegistration")).isFalse();
}
finally {
context.close();
}
}
@Test
public void testDefaultFilterOrder() throws Exception {
this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext());
this.context.register(SecurityAutoConfiguration.class,
SecurityFilterAutoConfiguration.class,
ServerPropertiesAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context.refresh();
assertThat(this.context.getBean("securityFilterChainRegistration",
DelegatingFilterProxyRegistrationBean.class).getOrder()).isEqualTo(
FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100);
}
@Test
public void testCustomFilterOrder() throws Exception {
this.context = new AnnotationConfigWebApplicationContext();
EnvironmentTestUtils.addEnvironment(this.context, "security.filter-order:12345");
this.context.setServletContext(new MockServletContext());
this.context.register(SecurityAutoConfiguration.class,
SecurityFilterAutoConfiguration.class,
ServerPropertiesAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context.refresh();
assertThat(this.context.getBean("securityFilterChainRegistration",
DelegatingFilterProxyRegistrationBean.class).getOrder()).isEqualTo(12345);
}
@Test
public void testDisableIgnoredStaticApplicationPaths() throws Exception {
this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext());
this.context.register(SecurityAutoConfiguration.class,
ServerPropertiesAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
EnvironmentTestUtils.addEnvironment(this.context, "security.ignored:none");
this.context.refresh();
// Just the application endpoints now
assertThat(this.context.getBean(FilterChainProxy.class).getFilterChains())
.hasSize(1);
}
@Test
public void testDisableBasicAuthOnApplicationPaths() throws Exception {
this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext());
this.context.register(SecurityAutoConfiguration.class,
ServerPropertiesAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
EnvironmentTestUtils.addEnvironment(this.context, "security.basic.enabled:false");
this.context.refresh();
// Ignores and the "matches-none" filter only
assertThat(this.context.getBeanNamesForType(FilterChainProxy.class).length)
.isEqualTo(1);
}
@Test
public void testAuthenticationManagerCreated() throws Exception {
this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext());
this.context.register(SecurityAutoConfiguration.class,
ServerPropertiesAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context.refresh();
assertThat(this.context.getBean(AuthenticationManager.class)).isNotNull();
}
@Test
public void testEventPublisherInjected() throws Exception {
testAuthenticationManagerCreated();
pingAuthenticationListener();
}
private void pingAuthenticationListener() {
AuthenticationListener listener = new AuthenticationListener();
this.context.addApplicationListener(listener);
AuthenticationManager manager = this.context.getBean(AuthenticationManager.class);
try {
manager.authenticate(new UsernamePasswordAuthenticationToken("foo", "wrong"));
fail("Expected BadCredentialsException");
}
catch (BadCredentialsException e) {
// expected
}
assertThat(listener.event)
.isInstanceOf(AuthenticationFailureBadCredentialsEvent.class);
}
@Test
public void testOverrideAuthenticationManager() throws Exception {
this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext());
this.context.register(TestAuthenticationConfiguration.class,
SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context.refresh();
assertThat(this.context.getBean(AuthenticationManager.class))
.isEqualTo(this.context.getBean(
TestAuthenticationConfiguration.class).authenticationManager);
}
@Test
public void testDefaultAuthenticationManagerMakesUserDetailsAvailable()
throws Exception {
this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext());
this.context.register(UserDetailsSecurityCustomizer.class,
SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context.refresh();
assertThat(this.context.getBean(UserDetailsSecurityCustomizer.class)
.getUserDetails().loadUserByUsername("user")).isNotNull();
}
@Test
public void testOverrideAuthenticationManagerAndInjectIntoSecurityFilter()
throws Exception {
this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext());
this.context.register(TestAuthenticationConfiguration.class,
SecurityCustomizer.class, SecurityAutoConfiguration.class,
ServerPropertiesAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context.refresh();
assertThat(this.context.getBean(AuthenticationManager.class))
.isEqualTo(this.context.getBean(
TestAuthenticationConfiguration.class).authenticationManager);
}
@Test
public void testOverrideAuthenticationManagerWithBuilderAndInjectIntoSecurityFilter()
throws Exception {
this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext());
this.context.register(AuthenticationManagerCustomizer.class,
SecurityCustomizer.class, SecurityAutoConfiguration.class,
ServerPropertiesAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context.refresh();
UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken(
"foo", "bar",
AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
assertThat(this.context.getBean(AuthenticationManager.class).authenticate(user))
.isNotNull();
pingAuthenticationListener();
}
@Test
public void testOverrideAuthenticationManagerWithBuilderAndInjectBuilderIntoSecurityFilter()
throws Exception {
this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext());
this.context.register(AuthenticationManagerCustomizer.class,
WorkaroundSecurityCustomizer.class, SecurityAutoConfiguration.class,
ServerPropertiesAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context.refresh();
UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken(
"foo", "bar",
AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
assertThat(this.context.getBean(AuthenticationManager.class).authenticate(user))
.isNotNull();
}
@Test
public void testJpaCoexistsHappily() throws Exception {
this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext());
EnvironmentTestUtils.addEnvironment(this.context,
"spring.datasource.url:jdbc:hsqldb:mem:testsecdb");
EnvironmentTestUtils.addEnvironment(this.context,
"spring.datasource.initialize:false");
this.context.register(EntityConfiguration.class,
PropertyPlaceholderAutoConfiguration.class,
DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class,
SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class);
// This can fail if security @Conditionals force early instantiation of the
// HibernateJpaAutoConfiguration (e.g. the EntityManagerFactory is not found)
this.context.refresh();
assertThat(this.context.getBean(JpaTransactionManager.class)).isNotNull();
}
@Test
public void testDefaultUsernamePassword() throws Exception {
this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext());
this.context.register(SecurityAutoConfiguration.class,
ServerPropertiesAutoConfiguration.class);
this.context.refresh();
SecurityProperties security = this.context.getBean(SecurityProperties.class);
AuthenticationManager manager = this.context.getBean(AuthenticationManager.class);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
security.getUser().getName(), security.getUser().getPassword());
assertThat(manager.authenticate(token)).isNotNull();
}
@Test
public void testCustomAuthenticationDoesNotAuthenticateWithBootSecurityUser()
throws Exception {
this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext());
this.context.register(AuthenticationManagerCustomizer.class,
SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class);
this.context.refresh();
SecurityProperties security = this.context.getBean(SecurityProperties.class);
AuthenticationManager manager = this.context.getBean(AuthenticationManager.class);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
security.getUser().getName(), security.getUser().getPassword());
try {
manager.authenticate(token);
fail("Expected Exception");
}
catch (AuthenticationException success) {
// Expected
}
token = new UsernamePasswordAuthenticationToken("foo", "bar");
assertThat(manager.authenticate(token)).isNotNull();
}
@Test
public void testSecurityEvaluationContextExtensionSupport() {
this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext());
this.context.register(AuthenticationManagerCustomizer.class,
SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class);
this.context.refresh();
assertThat(this.context.getBean(SecurityEvaluationContextExtension.class))
.isNotNull();
}
@Test
public void defaultFilterDispatcherTypes() {
this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext());
this.context.register(SecurityAutoConfiguration.class,
SecurityFilterAutoConfiguration.class,
ServerPropertiesAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context.refresh();
DelegatingFilterProxyRegistrationBean bean = this.context.getBean(
"securityFilterChainRegistration",
DelegatingFilterProxyRegistrationBean.class);
@SuppressWarnings("unchecked")
EnumSet<DispatcherType> dispatcherTypes = (EnumSet<DispatcherType>) ReflectionTestUtils
.getField(bean, "dispatcherTypes");
assertThat(dispatcherTypes).isNull();
}
@Test
public void customFilterDispatcherTypes() {
this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext());
this.context.register(SecurityAutoConfiguration.class,
SecurityFilterAutoConfiguration.class,
ServerPropertiesAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
EnvironmentTestUtils.addEnvironment(this.context,
"security.filter-dispatcher-types:INCLUDE,ERROR");
this.context.refresh();
DelegatingFilterProxyRegistrationBean bean = this.context.getBean(
"securityFilterChainRegistration",
DelegatingFilterProxyRegistrationBean.class);
@SuppressWarnings("unchecked")
EnumSet<DispatcherType> dispatcherTypes = (EnumSet<DispatcherType>) ReflectionTestUtils
.getField(bean, "dispatcherTypes");
assertThat(dispatcherTypes).containsOnly(DispatcherType.INCLUDE,
DispatcherType.ERROR);
}
private static final class AuthenticationListener
implements ApplicationListener<AbstractAuthenticationEvent> {
private ApplicationEvent event;
@Override
public void onApplicationEvent(AbstractAuthenticationEvent event) {
this.event = event;
}
}
@Configuration
@TestAutoConfigurationPackage(City.class)
protected static class EntityConfiguration {
}
@Configuration
protected static class TestAuthenticationConfiguration {
private AuthenticationManager authenticationManager;
@Bean
public AuthenticationManager myAuthenticationManager() {
this.authenticationManager = new AuthenticationManager() {
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
return new TestingAuthenticationToken("foo", "bar");
}
};
return this.authenticationManager;
}
}
@Configuration
protected static class SecurityCustomizer extends WebSecurityConfigurerAdapter {
final AuthenticationManager authenticationManager;
protected SecurityCustomizer(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
}
@Configuration
protected static class WorkaroundSecurityCustomizer
extends WebSecurityConfigurerAdapter {
private final AuthenticationManagerBuilder builder;
@SuppressWarnings("unused")
private AuthenticationManager authenticationManager;
protected WorkaroundSecurityCustomizer(AuthenticationManagerBuilder builder) {
this.builder = builder;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
this.authenticationManager = new AuthenticationManager() {
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
return WorkaroundSecurityCustomizer.this.builder.getOrBuild()
.authenticate(authentication);
}
};
}
}
@Configuration
@Order(-1)
protected static class AuthenticationManagerCustomizer
extends GlobalAuthenticationConfigurerAdapter {
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("foo").password("bar").roles("USER");
}
}
@Configuration
protected static class UserDetailsSecurityCustomizer
extends WebSecurityConfigurerAdapter {
private UserDetailsService userDetails;
@Override
protected void configure(HttpSecurity http) throws Exception {
this.userDetails = http.getSharedObject(UserDetailsService.class);
}
public UserDetailsService getUserDetails() {
return this.userDetails;
}
}
@Configuration
@EnableWebSecurity
static class WebSecurity extends WebSecurityConfigurerAdapter {
}
}
| |
/**
* Copyright 2013 Technische Universitat Wien (TUW), Distributed Systems Group
* E184
*
* This work was partially supported by the European Commission in terms of the
* CELAR FP7 project (FP7-ICT-2011-8 \#317790)
*
* 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 at.ac.tuwien.dsg.mela.common.elasticityAnalysis.concepts.elasticityPathway;
import at.ac.tuwien.dsg.mela.common.elasticityAnalysis.concepts.elasticityPathway.som.Neuron;
import at.ac.tuwien.dsg.mela.common.elasticityAnalysis.concepts.elasticityPathway.som.SOM2;
import at.ac.tuwien.dsg.mela.common.elasticityAnalysis.concepts.elasticityPathway.som.SimpleSOMStrategy;
import at.ac.tuwien.dsg.mela.common.monitoringConcepts.Metric;
import at.ac.tuwien.dsg.mela.common.monitoringConcepts.MetricValue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
/**
* Author: Daniel Moldovan E-Mail: d.moldovan@dsg.tuwien.ac.at *
*
*/
public class InMemoryEncounterRateElasticityPathway {
int cellsSize = 10;
int upperNormalizationValue = 100;
public List<InMemoryEncounterRateElasticityPathway.SignatureEntry> getElasticitySignature(Map<Metric, List<MetricValue>> dataToClassify) {
SOM2 som = new SOM2(cellsSize, dataToClassify.keySet().size(), 0, upperNormalizationValue, new SimpleSOMStrategy());
List<SignatureEntry> mapped = new ArrayList<SignatureEntry>();
//classify all monitoring data
//need to go trough all monitoring data, and push the classified items, such that I respect the monitored sequence.
if (dataToClassify.values().isEmpty()) {
Logger.getLogger(this.getClass()).log(Level.ERROR, "Empty data to classify as elasticity pathway");
return null;
}
int maxIndex = dataToClassify.values().iterator().next().size();
for (int i = 0; i < maxIndex; i++) {
SignatureEntry signatureEntry = new SignatureEntry();
for (Metric metric : dataToClassify.keySet()) {
List<MetricValue> values = dataToClassify.get(metric);
//maybe we have diff value count for different metrics. Not sure when his might happen though.
if (values.size() <= i) {
Logger.getLogger(this.getClass()).log(Level.ERROR, "Less values for metric " + mapped);
break;
}
signatureEntry.addEntry(metric, values.get(i));
}
mapped.add(signatureEntry);
}
//train map completely pathway entries
for (SignatureEntry signatureEntry : mapped) {
//build the mappedNeuron used to classify the situation
ArrayList<Double> values = new ArrayList<Double>();
//for each metric column, get value from measurement row
for (MetricValue value : signatureEntry.classifiedSituation.values()) {
//avoid using non-numeric values. Although a non-numeric value should not happen
if (value.getValueType() == MetricValue.ValueType.NUMERIC) {
values.add(Double.parseDouble(value.getValueRepresentation()));
} else {
Logger.getLogger(this.getClass()).log(Level.ERROR, "Elasticity Pathway can't be applied on non-numeric metric value " + value);
}
}
Neuron neuron = som.updateMap(new Neuron(values));
}
//computes neuron usage statistics per entire map
som.updateMapUsage();
//classify all entries
for (SignatureEntry signatureEntry : mapped) {
//build the mappedNeuron used to classify the situation
ArrayList<Double> values = new ArrayList<Double>();
//for each metric column, get value from measurement row
for (MetricValue value : signatureEntry.classifiedSituation.values()) {
//avoid using non-numeric values. Although a non-numeric value should not happen
if (value.getValueType() == MetricValue.ValueType.NUMERIC) {
values.add(Double.parseDouble(value.getValueRepresentation()));
} else {
Logger.getLogger(this.getClass()).log(Level.ERROR, "Elasticity Pathway can;t be applied on non-numeric metric value " + value);
}
}
Neuron neuron = som.classifySituation(new Neuron(values));
signatureEntry.mappedNeuron = neuron;
}
//classify entries by encounterRate? Nooo? Yes? Who Knows? I mean, we need to be carefull not to lose monitoring information
//we might need two things to do: 1 to say in 1 chart this metric point is usual, this not
//the second to say ok in usual case the metric value combinations are ..
//currently we go with the second, for which we did not need storing the order of the monitoring data in the entries, but it might be useful later
// Map<NeuronUsageLevel, List<SignatureEntry>> pathway = new LinkedHashMap<NeuronUsageLevel, List<SignatureEntry>>();
// List<SignatureEntry> rare = new ArrayList<SignatureEntry>();
// List<SignatureEntry> neutral = new ArrayList<SignatureEntry>();
// List<SignatureEntry> dominant = new ArrayList<SignatureEntry>();
//
// pathway.put(NeuronUsageLevel.DOMINANT, rare);
// pathway.put(NeuronUsageLevel.NEUTRAL, neutral);
// pathway.put(NeuronUsageLevel.RARE, dominant);
//
// for (SignatureEntry signatureEntry : mapped) {
// switch (signatureEntry.getMappedNeuron().getUsageLevel()) {
// case RARE:
// rare.add(signatureEntry);
// break;
// case NEUTRAL:
// neutral.add(signatureEntry);
// break;
// case DOMINANT:
// dominant.add(signatureEntry);
// break;
// }
// }
//returning all, such that I can sort them after occurrence and say this pair of values has been encountered 70%
return mapped;
}
public List<Neuron> getSituationGroups(Map<Metric, List<MetricValue>> dataToClassify) {
SOM2 som = new SOM2(cellsSize, dataToClassify.keySet().size(), 0, upperNormalizationValue, new SimpleSOMStrategy());
List<SignatureEntry> mapped = new ArrayList<SignatureEntry>();
//classify all monitoring data
//need to go trough all monitoring data, and push the classified items, such that I respect the monitored sequence.
if (dataToClassify.values().size() == 0) {
Logger.getLogger(this.getClass()).log(Level.ERROR, "Empty data to classify as elasticity pathway");
return null;
}
int maxIndex = dataToClassify.values().iterator().next().size();
for (int i = 0; i < maxIndex; i++) {
SignatureEntry signatureEntry = new SignatureEntry();
for (Metric metric : dataToClassify.keySet()) {
List<MetricValue> values = dataToClassify.get(metric);
//maybe we have diff value count for different metrics. Not sure when his might happen though.
if (values.size() <= i) {
Logger.getLogger(this.getClass()).log(Level.ERROR, "Less values for metric " + mapped);
break;
}
signatureEntry.addEntry(metric, values.get(i));
}
mapped.add(signatureEntry);
}
//train map completely pathway entries
for (SignatureEntry signatureEntry : mapped) {
//build the mappedNeuron used to classify the situation
ArrayList<Double> values = new ArrayList<Double>();
//for each metric column, get value from measurement row
for (MetricValue value : signatureEntry.classifiedSituation.values()) {
//avoid using non-numeric values. Although a non-numeric value should not happen
if (value.getValueType() == MetricValue.ValueType.NUMERIC) {
values.add(Double.parseDouble(value.getValueRepresentation()));
} else {
Logger.getLogger(this.getClass()).log(Level.ERROR, "Elasticity Pathway can't be applied on non-numeric metric value " + value);
}
}
Neuron neuron = som.updateMap(new Neuron(values));
}
//computes neuron usage statistics per entire map
som.updateMapUsage();
//classify all entries
for (SignatureEntry signatureEntry : mapped) {
//build the mappedNeuron used to classify the situation
ArrayList<Double> values = new ArrayList<Double>();
//for each metric column, get value from measurement row
for (MetricValue value : signatureEntry.classifiedSituation.values()) {
//avoid using non-numeric values. Although a non-numeric value should not happen
if (value.getValueType() == MetricValue.ValueType.NUMERIC) {
values.add(Double.parseDouble(value.getValueRepresentation()));
} else {
Logger.getLogger(this.getClass()).log(Level.ERROR, "Elasticity Pathway can;t be applied on non-numeric metric value " + value);
}
}
Neuron neuron = som.classifySituation(new Neuron(values));
signatureEntry.mappedNeuron = neuron;
}
//returning all, such that I can sort them after occurrence and say this pair of values has been encountered 70%
List<Neuron> neurons = new ArrayList<Neuron>();
for (Neuron neuron : som) {
if (neuron.getMappedWeights() > 0) {
neurons.add(neuron);
}
}
//sort the list by occurence
Collections.sort(neurons, new Comparator<Neuron>() {
public int compare(Neuron o1, Neuron o2) {
return o1.getUsagePercentage().compareTo(o2.getUsagePercentage());
}
});
return neurons;
}
public class SignatureEntry {
private Neuron mappedNeuron;
private Map<Metric, MetricValue> classifiedSituation;
{
classifiedSituation = new LinkedHashMap<Metric, MetricValue>();
}
public Neuron getMappedNeuron() {
return mappedNeuron;
}
public Map<Metric, MetricValue> getClassifiedSituation() {
return classifiedSituation;
}
private void addEntry(Metric metric, MetricValue value) {
classifiedSituation.put(metric, value.clone());
}
}
public InMemoryEncounterRateElasticityPathway withCellsSize(final int cellsSize) {
this.cellsSize = cellsSize;
return this;
}
public InMemoryEncounterRateElasticityPathway withUpperNormalizationValue(final int upperNormalizationValue) {
this.upperNormalizationValue = upperNormalizationValue;
return this;
}
}
| |
/*
* 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.flink.client.deployment.application;
import org.apache.flink.annotation.Internal;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.client.ClientUtils;
import org.apache.flink.client.cli.ClientOptions;
import org.apache.flink.client.deployment.application.executors.EmbeddedExecutor;
import org.apache.flink.client.deployment.application.executors.EmbeddedExecutorServiceLoader;
import org.apache.flink.client.program.PackagedProgram;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.DeploymentOptions;
import org.apache.flink.configuration.PipelineOptionsInternal;
import org.apache.flink.core.execution.PipelineExecutorServiceLoader;
import org.apache.flink.runtime.client.DuplicateJobSubmissionException;
import org.apache.flink.runtime.clusterframework.ApplicationStatus;
import org.apache.flink.runtime.dispatcher.DispatcherBootstrap;
import org.apache.flink.runtime.dispatcher.DispatcherGateway;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.jobmanager.HighAvailabilityMode;
import org.apache.flink.runtime.jobmaster.JobResult;
import org.apache.flink.runtime.messages.Acknowledge;
import org.apache.flink.runtime.messages.FlinkJobNotFoundException;
import org.apache.flink.runtime.rpc.FatalErrorHandler;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.concurrent.FutureUtils;
import org.apache.flink.util.concurrent.ScheduledExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.apache.flink.util.Preconditions.checkNotNull;
/**
* A {@link DispatcherBootstrap} used for running the user's {@code main()} in "Application Mode"
* (see FLIP-85).
*
* <p>This dispatcher bootstrap submits the recovered {@link JobGraph job graphs} for re-execution
* (in case of recovery from a failure), and then submits the remaining jobs of the application for
* execution.
*
* <p>To achieve this, it works in conjunction with the {@link EmbeddedExecutor EmbeddedExecutor}
* which decides if it should submit a job for execution (in case of a new job) or the job was
* already recovered and is running.
*/
@Internal
public class ApplicationDispatcherBootstrap implements DispatcherBootstrap {
public static final JobID ZERO_JOB_ID = new JobID(0, 0);
@VisibleForTesting static final String FAILED_JOB_NAME = "(application driver)";
private static final Logger LOG = LoggerFactory.getLogger(ApplicationDispatcherBootstrap.class);
private static boolean isCanceledOrFailed(ApplicationStatus applicationStatus) {
return applicationStatus == ApplicationStatus.CANCELED
|| applicationStatus == ApplicationStatus.FAILED;
}
private final PackagedProgram application;
private final Collection<JobID> recoveredJobIds;
private final Configuration configuration;
private final FatalErrorHandler errorHandler;
private final CompletableFuture<Void> applicationCompletionFuture;
private final CompletableFuture<Acknowledge> bootstrapCompletionFuture;
private ScheduledFuture<?> applicationExecutionTask;
public ApplicationDispatcherBootstrap(
final PackagedProgram application,
final Collection<JobID> recoveredJobIds,
final Configuration configuration,
final DispatcherGateway dispatcherGateway,
final ScheduledExecutor scheduledExecutor,
final FatalErrorHandler errorHandler) {
this.configuration = checkNotNull(configuration);
this.recoveredJobIds = checkNotNull(recoveredJobIds);
this.application = checkNotNull(application);
this.errorHandler = checkNotNull(errorHandler);
this.applicationCompletionFuture =
fixJobIdAndRunApplicationAsync(dispatcherGateway, scheduledExecutor);
this.bootstrapCompletionFuture = finishBootstrapTasks(dispatcherGateway);
}
@Override
public void stop() {
if (applicationExecutionTask != null) {
applicationExecutionTask.cancel(true);
}
if (applicationCompletionFuture != null) {
applicationCompletionFuture.cancel(true);
}
}
@VisibleForTesting
ScheduledFuture<?> getApplicationExecutionFuture() {
return applicationExecutionTask;
}
@VisibleForTesting
CompletableFuture<Void> getApplicationCompletionFuture() {
return applicationCompletionFuture;
}
@VisibleForTesting
CompletableFuture<Acknowledge> getBootstrapCompletionFuture() {
return bootstrapCompletionFuture;
}
/**
* Logs final application status and invokes error handler in case of unexpected failures.
* Optionally shuts down the given dispatcherGateway when the application completes (either
* successfully or in case of failure), depending on the corresponding config option.
*/
private CompletableFuture<Acknowledge> finishBootstrapTasks(
final DispatcherGateway dispatcherGateway) {
final CompletableFuture<Acknowledge> shutdownFuture =
applicationCompletionFuture
.handle(
(ignored, t) -> {
if (t == null) {
LOG.info("Application completed SUCCESSFULLY");
return finish(
dispatcherGateway, ApplicationStatus.SUCCEEDED);
}
final Optional<ApplicationStatus> maybeApplicationStatus =
extractApplicationStatus(t);
if (maybeApplicationStatus.isPresent()
&& isCanceledOrFailed(maybeApplicationStatus.get())) {
final ApplicationStatus applicationStatus =
maybeApplicationStatus.get();
LOG.info("Application {}: ", applicationStatus, t);
return finish(dispatcherGateway, applicationStatus);
}
if (t instanceof CancellationException) {
LOG.warn(
"Application has been cancelled because the {} is being stopped.",
ApplicationDispatcherBootstrap.class
.getSimpleName());
return CompletableFuture.completedFuture(Acknowledge.get());
}
LOG.warn("Application failed unexpectedly: ", t);
return FutureUtils.<Acknowledge>completedExceptionally(t);
})
.thenCompose(Function.identity());
FutureUtils.handleUncaughtException(shutdownFuture, (t, e) -> errorHandler.onFatalError(e));
return shutdownFuture;
}
private CompletableFuture<Acknowledge> finish(
DispatcherGateway dispatcherGateway, ApplicationStatus applicationStatus) {
boolean shouldShutDownOnFinish =
configuration.getBoolean(DeploymentOptions.SHUTDOWN_ON_APPLICATION_FINISH);
return shouldShutDownOnFinish
? dispatcherGateway.shutDownCluster(applicationStatus)
: CompletableFuture.completedFuture(Acknowledge.get());
}
private Optional<ApplicationStatus> extractApplicationStatus(Throwable t) {
final Optional<UnsuccessfulExecutionException> maybeException =
ExceptionUtils.findThrowable(t, UnsuccessfulExecutionException.class);
return maybeException.map(UnsuccessfulExecutionException::getStatus);
}
private CompletableFuture<Void> fixJobIdAndRunApplicationAsync(
final DispatcherGateway dispatcherGateway, final ScheduledExecutor scheduledExecutor) {
final Optional<String> configuredJobId =
configuration.getOptional(PipelineOptionsInternal.PIPELINE_FIXED_JOB_ID);
final boolean submitFailedJobOnApplicationError =
configuration.getBoolean(DeploymentOptions.SUBMIT_FAILED_JOB_ON_APPLICATION_ERROR);
if (!HighAvailabilityMode.isHighAvailabilityModeActivated(configuration)
&& !configuredJobId.isPresent()) {
return runApplicationAsync(
dispatcherGateway, scheduledExecutor, false, submitFailedJobOnApplicationError);
}
if (!configuredJobId.isPresent()) {
configuration.set(
PipelineOptionsInternal.PIPELINE_FIXED_JOB_ID, ZERO_JOB_ID.toHexString());
}
return runApplicationAsync(
dispatcherGateway, scheduledExecutor, true, submitFailedJobOnApplicationError);
}
/**
* Runs the user program entrypoint by scheduling a task on the given {@code scheduledExecutor}.
* The returned {@link CompletableFuture} completes when all jobs of the user application
* succeeded. if any of them fails, or if job submission fails.
*/
private CompletableFuture<Void> runApplicationAsync(
final DispatcherGateway dispatcherGateway,
final ScheduledExecutor scheduledExecutor,
final boolean enforceSingleJobExecution,
final boolean submitFailedJobOnApplicationError) {
final CompletableFuture<List<JobID>> applicationExecutionFuture = new CompletableFuture<>();
final Set<JobID> tolerateMissingResult = Collections.synchronizedSet(new HashSet<>());
// we need to hand in a future as return value because we need to get those JobIs out
// from the scheduled task that executes the user program
applicationExecutionTask =
scheduledExecutor.schedule(
() ->
runApplicationEntryPoint(
applicationExecutionFuture,
tolerateMissingResult,
dispatcherGateway,
scheduledExecutor,
enforceSingleJobExecution,
submitFailedJobOnApplicationError),
0L,
TimeUnit.MILLISECONDS);
return applicationExecutionFuture.thenCompose(
jobIds ->
getApplicationResult(
dispatcherGateway,
jobIds,
tolerateMissingResult,
scheduledExecutor));
}
/**
* Runs the user program entrypoint and completes the given {@code jobIdsFuture} with the {@link
* JobID JobIDs} of the submitted jobs.
*
* <p>This should be executed in a separate thread (or task).
*/
private void runApplicationEntryPoint(
final CompletableFuture<List<JobID>> jobIdsFuture,
final Set<JobID> tolerateMissingResult,
final DispatcherGateway dispatcherGateway,
final ScheduledExecutor scheduledExecutor,
final boolean enforceSingleJobExecution,
final boolean submitFailedJobOnApplicationError) {
if (submitFailedJobOnApplicationError && !enforceSingleJobExecution) {
jobIdsFuture.completeExceptionally(
new ApplicationExecutionException(
String.format(
"Submission of failed job in case of an application error ('%s') is not supported in non-HA setups.",
DeploymentOptions.SUBMIT_FAILED_JOB_ON_APPLICATION_ERROR
.key())));
return;
}
final List<JobID> applicationJobIds = new ArrayList<>(recoveredJobIds);
try {
final PipelineExecutorServiceLoader executorServiceLoader =
new EmbeddedExecutorServiceLoader(
applicationJobIds, dispatcherGateway, scheduledExecutor);
ClientUtils.executeProgram(
executorServiceLoader,
configuration,
application,
enforceSingleJobExecution,
true /* suppress sysout */);
if (applicationJobIds.isEmpty()) {
jobIdsFuture.completeExceptionally(
new ApplicationExecutionException(
"The application contains no execute() calls."));
} else {
jobIdsFuture.complete(applicationJobIds);
}
} catch (Throwable t) {
// If we're running in a single job execution mode, it's safe to consider re-submission
// of an already finished a success.
final Optional<DuplicateJobSubmissionException> maybeDuplicate =
ExceptionUtils.findThrowable(t, DuplicateJobSubmissionException.class);
if (enforceSingleJobExecution
&& maybeDuplicate.isPresent()
&& maybeDuplicate.get().isGloballyTerminated()) {
final JobID jobId = maybeDuplicate.get().getJobID();
tolerateMissingResult.add(jobId);
jobIdsFuture.complete(Collections.singletonList(jobId));
} else if (submitFailedJobOnApplicationError && applicationJobIds.isEmpty()) {
final JobID failedJobId =
JobID.fromHexString(
configuration.get(PipelineOptionsInternal.PIPELINE_FIXED_JOB_ID));
dispatcherGateway.submitFailedJob(failedJobId, FAILED_JOB_NAME, t);
jobIdsFuture.complete(Collections.singletonList(failedJobId));
} else {
jobIdsFuture.completeExceptionally(
new ApplicationExecutionException("Could not execute application.", t));
}
}
}
private CompletableFuture<Void> getApplicationResult(
final DispatcherGateway dispatcherGateway,
final Collection<JobID> applicationJobIds,
final Set<JobID> tolerateMissingResult,
final ScheduledExecutor executor) {
final List<CompletableFuture<?>> jobResultFutures =
applicationJobIds.stream()
.map(
jobId ->
unwrapJobResultException(
getJobResult(
dispatcherGateway,
jobId,
executor,
tolerateMissingResult.contains(jobId))))
.collect(Collectors.toList());
return FutureUtils.waitForAll(jobResultFutures);
}
private CompletableFuture<JobResult> getJobResult(
final DispatcherGateway dispatcherGateway,
final JobID jobId,
final ScheduledExecutor scheduledExecutor,
final boolean tolerateMissingResult) {
final Time timeout =
Time.milliseconds(configuration.get(ClientOptions.CLIENT_TIMEOUT).toMillis());
final Time retryPeriod =
Time.milliseconds(configuration.get(ClientOptions.CLIENT_RETRY_PERIOD).toMillis());
final CompletableFuture<JobResult> jobResultFuture =
JobStatusPollingUtils.getJobResult(
dispatcherGateway, jobId, scheduledExecutor, timeout, retryPeriod);
if (tolerateMissingResult) {
// Return "unknown" job result if dispatcher no longer knows the actual result.
return FutureUtils.handleException(
jobResultFuture,
FlinkJobNotFoundException.class,
exception ->
new JobResult.Builder()
.jobId(jobId)
.applicationStatus(ApplicationStatus.UNKNOWN)
.netRuntime(Long.MAX_VALUE)
.build());
}
return jobResultFuture;
}
/**
* If the given {@link JobResult} indicates success, this passes through the {@link JobResult}.
* Otherwise, this returns a future that is finished exceptionally (potentially with an
* exception from the {@link JobResult}).
*/
private CompletableFuture<JobResult> unwrapJobResultException(
final CompletableFuture<JobResult> jobResult) {
return jobResult.thenApply(
result -> {
if (result.isSuccess()) {
return result;
}
throw new CompletionException(
UnsuccessfulExecutionException.fromJobResult(
result, application.getUserCodeClassLoader()));
});
}
}
| |
/*******************************************************************************
* Copyright (c) 2016 AT&T Intellectual Property. All rights reserved.
*******************************************************************************/
package com.att.cadi.dme2;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import javax.servlet.http.HttpServletResponse;
import com.att.aft.dme2.api.DME2Client;
import com.att.aft.dme2.api.DME2Exception;
import com.att.aft.dme2.api.DME2Manager;
import com.att.aft.dme2.handler.DME2RestfulHandler;
import com.att.aft.dme2.handler.DME2RestfulHandler.ResponseInfo;
import com.att.cadi.CadiException;
import com.att.cadi.SecuritySetter;
import com.att.cadi.client.EClient;
import com.att.cadi.client.Future;
import com.att.cadi.client.Rcli;
import com.att.inno.env.APIException;
import com.att.inno.env.Data;
import com.att.rosetta.env.RosettaDF;
public class DEClient implements EClient<DME2Client> {
private DME2Client client;
private DME2RestfulHandler replyHandler;
private EClient.Transfer payload;
private boolean isProxy;
private SecuritySetter<DME2Client> ss;
public DEClient(DME2Manager manager, SecuritySetter<DME2Client> ss, URI uri, long timeout) throws DME2Exception, CadiException {
client = new DME2Client(manager,uri,timeout);
client.setAllowAllHttpReturnCodes(true);
this.ss = ss;
ss.setSecurity(client);
replyHandler = new DME2RestfulHandler(Rcli.BLANK);
client.setReplyHandler(replyHandler);
}
@Override
public void setMethod(String meth) {
client.setMethod(meth);
}
/**
* DME2 can't handle having QueryParams on the URL line, but it is the most natural way, so...
*
* Also, DME2 can't handle "/proxy" as part of Context in the main URI line, so we add it when we see authz-gw to "isProxy"
*/
public void setPathInfo(String pathinfo) {
int qp = pathinfo.indexOf('?');
if(qp<0) {
client.setContext(isProxy?("/proxy"+pathinfo):pathinfo);
} else {
client.setContext(isProxy?("/proxy"+pathinfo.substring(0,qp)):pathinfo.substring(0,qp));
client.setQueryParams(pathinfo.substring(qp+1));
}
}
@Override
public void setPayload(EClient.Transfer transfer) {
payload = transfer;
}
@Override
public void addHeader(String tag, String value) {
client.addHeader(tag, value);
}
@Override
public void setQueryParams(String q) {
client.setQueryParams(q);
}
@Override
public void setFragment(String f) {
// DME2 does not implement this
}
@Override
public void send() throws APIException {
try {
if(payload!=null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
payload.transfer(baos);
client.setPayload(new String(baos.toByteArray()));
} else {
client.setPayload("");
}
client.send();
} catch (DME2Exception e) {
throw new APIException(e);
} catch (IOException e) {
throw new APIException(e);
}
}
public class DFuture<T> extends Future<T> {
protected final DME2RestfulHandler reply;
protected ResponseInfo info;
public DFuture(DME2RestfulHandler reply) {
this.reply = reply;
}
protected boolean evalInfo() throws APIException{
//return info.getCode()==200;
return true;
};
public final boolean get(int timeout) throws CadiException {
try {
info = reply.getResponse(timeout);
ss.setLastResponse(info.getCode());
return evalInfo();
} catch (Exception e) {
throw new CadiException(e);
}
}
@Override
public int code() {
return info.getCode();
}
@Override
public String body() {
return info.getBody();
}
@Override
public String header(String tag) {
return info.header(tag);
}
}
@Override
public <T> Future<T> futureCreate(Class<T> t) {
return new DFuture<T>(replyHandler) {
public boolean evalInfo() throws APIException {
return info.getCode()==201;
}
};
}
@Override
public Future<String> futureReadString() {
return new DFuture<String>(replyHandler) {
public boolean evalInfo() throws APIException {
if(info.getCode()==200) {
value = info.getBody();
return true;
}
return false;
}
};
}
@Override
public<T> Future<T> futureRead(final RosettaDF<T> df, final Data.TYPE type) {
return new DFuture<T>(replyHandler) {
public boolean evalInfo() throws APIException {
if(info.getCode()==200) {
value = df.newData().in(type).load(info.getBody()).asObject();
return true;
}
return false;
}
};
}
@Override
public <T> Future<T> future(final T t) {
return new DFuture<T>(replyHandler) {
public boolean evalInfo() {
if(info.getCode()==200) {
value = t;
return true;
}
return false;
}
};
}
@Override
public Future<Void> future(HttpServletResponse resp,int expected) throws APIException {
// TODO Auto-generated method stub
return null;
}
public void setProxy(boolean isProxy) {
this.isProxy=isProxy;
}
}
| |
/*
* This file is part of "lunisolar-magma".
*
* (C) Copyright 2014-2022 Lunisolar (http://lunisolar.eu/).
*
* 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 eu.lunisolar.magma.func.consumer.primitives.obj;
import eu.lunisolar.magma.func.*; // NOSONAR
import javax.annotation.Nonnull; // NOSONAR
import javax.annotation.Nullable; // NOSONAR
import java.util.Objects;// NOSONAR
import eu.lunisolar.magma.basics.meta.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR
import eu.lunisolar.magma.func.action.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.bi.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.obj.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.tri.*; // NOSONAR
import eu.lunisolar.magma.func.function.*; // NOSONAR
import eu.lunisolar.magma.func.function.conversion.*; // NOSONAR
import eu.lunisolar.magma.func.function.from.*; // NOSONAR
import eu.lunisolar.magma.func.function.to.*; // NOSONAR
import eu.lunisolar.magma.func.operator.binary.*; // NOSONAR
import eu.lunisolar.magma.func.operator.ternary.*; // NOSONAR
import eu.lunisolar.magma.func.operator.unary.*; // NOSONAR
import eu.lunisolar.magma.func.predicate.*; // NOSONAR
import eu.lunisolar.magma.func.supplier.*; // NOSONAR
import org.testng.Assert;
import org.testng.annotations.*; //NOSONAR
import java.util.regex.Pattern; //NOSONAR
import java.text.ParseException; //NOSONAR
import eu.lunisolar.magma.basics.*; //NOSONAR
import eu.lunisolar.magma.basics.exceptions.*; //NOSONAR
import java.util.concurrent.atomic.AtomicInteger; //NOSONAR
import eu.lunisolar.magma.func.tuple.*; // NOSONAR
import java.util.function.*; // NOSONAR
/** The test obviously concentrate on the interface methods the function it self is very simple. */
public class LTieLongConsumerTest<T> {
private static final String ORIGINAL_MESSAGE = "Original message";
private static final String EXCEPTION_WAS_WRAPPED = "Exception was wrapped.";
private static final String NO_EXCEPTION_WERE_THROWN = "No exception were thrown.";
private LTieLongConsumer<Integer> sut = new LTieLongConsumer<Integer>(){
public void acceptX(Integer a1,int a2,long a3) {
LTieLongConsumer.doNothing(a1,a2,a3);
}
};
private LTieLongConsumer<Integer> sutAlwaysThrowing = LTieLongConsumer.tieLongCons((a1,a2,a3) -> {
throw new ParseException(ORIGINAL_MESSAGE, 0);
});
private LTieLongConsumer<Integer> sutAlwaysThrowingUnchecked = LTieLongConsumer.tieLongCons((a1,a2,a3) -> {
throw new IndexOutOfBoundsException(ORIGINAL_MESSAGE);
});
@Test
public void testTupleCall() throws Throwable {
LObjIntLongTriple<Integer> domainObject = Tuple4U.objIntLongTriple(100,100,100L);
Object result = sut.tupleAccept(domainObject);
Assert.assertSame(result, LTuple.Void.INSTANCE);
}
@Test
public void testNestingAcceptUnchecked() throws Throwable {
// then
try {
sutAlwaysThrowingUnchecked.nestingAccept(100,100,100L);
Assert.fail(NO_EXCEPTION_WERE_THROWN);
} catch (Exception e) {
Assert.assertEquals(e.getClass(), IndexOutOfBoundsException.class);
Assert.assertNull(e.getCause());
Assert.assertEquals(e.getMessage(), ORIGINAL_MESSAGE);
}
}
@Test
public void testShovingAcceptUnchecked() throws Throwable {
// then
try {
sutAlwaysThrowingUnchecked.shovingAccept(100,100,100L);
Assert.fail(NO_EXCEPTION_WERE_THROWN);
} catch (Exception e) {
Assert.assertEquals(e.getClass(), IndexOutOfBoundsException.class);
Assert.assertNull(e.getCause());
Assert.assertEquals(e.getMessage(), ORIGINAL_MESSAGE);
}
}
@Test
public void testFunctionalInterfaceDescription() throws Throwable {
Assert.assertEquals(sut.functionalInterfaceDescription(), "LTieLongConsumer: void accept(T a1,int a2,long a3)");
}
@Test
public void testTieLongConsMethod() throws Throwable {
Assert.assertTrue(LTieLongConsumer.tieLongCons(LTieLongConsumer::doNothing) instanceof LTieLongConsumer);
}
// <editor-fold desc="compose (functional)">
@Test
public void testCompose() throws Throwable {
final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
final AtomicInteger beforeCalls = new AtomicInteger(0);
//given (+ some assertions)
LTieLongConsumer<Integer> sutO = (a1,a2,a3) -> {
mainFunctionCalled.set(true);
Assert.assertEquals(a1, (Object) 90);
Assert.assertEquals(a2, (Object) 91);
Assert.assertEquals(a3, (Object) 92L);
};
LFunction<Integer,Integer> before1 = p0 -> {
Assert.assertEquals(p0, (Object) 80);
beforeCalls.incrementAndGet();
return 90;
};
LIntUnaryOperator before2 = p1 -> {
Assert.assertEquals(p1, (Object) 81);
beforeCalls.incrementAndGet();
return 91;
};
LLongUnaryOperator before3 = p2 -> {
Assert.assertEquals(p2, (Object) 82L);
beforeCalls.incrementAndGet();
return 92L;
};
//when
LTieLongConsumer<Integer> function = sutO.compose(before1,before2,before3);
function.accept(80,81,82L);
//then - finals
Assert.assertTrue(mainFunctionCalled.get());
Assert.assertEquals(beforeCalls.get(), 3);
}
@Test
public void testTieLongConsCompose() throws Throwable {
final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
final AtomicInteger beforeCalls = new AtomicInteger(0);
//given (+ some assertions)
LTieLongConsumer<Integer> sutO = (a1,a2,a3) -> {
mainFunctionCalled.set(true);
Assert.assertEquals(a1, (Object) 90);
Assert.assertEquals(a2, (Object) 91);
Assert.assertEquals(a3, (Object) 92L);
};
LFunction<Integer,Integer> before1 = p0 -> {
Assert.assertEquals(p0, (Object) 80);
beforeCalls.incrementAndGet();
return 90;
};
LToIntFunction<Integer> before2 = p1 -> {
Assert.assertEquals(p1, (Object) 81);
beforeCalls.incrementAndGet();
return 91;
};
LToLongFunction<Integer> before3 = p2 -> {
Assert.assertEquals(p2, (Object) 82);
beforeCalls.incrementAndGet();
return 92L;
};
//when
LTriConsumer<Integer,Integer,Integer> function = sutO.tieLongConsCompose(before1,before2,before3);
function.accept(80,81,82);
//then - finals
Assert.assertTrue(mainFunctionCalled.get());
Assert.assertEquals(beforeCalls.get(), 3);
}
// </editor-fold>
@Test
public void testAndThen() throws Throwable {
final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);
//given (+ some assertions)
LTieLongConsumer<Integer> sutO = (a1,a2,a3) -> {
mainFunctionCalled.set(true);
Assert.assertEquals((Object)a1, (Object) 80);
Assert.assertEquals((Object)a2, (Object) 81);
Assert.assertEquals((Object)a3, (Object) 82L);
};
LTieLongConsumer<Integer> thenFunction = (a1,a2,a3) -> {
thenFunctionCalled.set(true);
Assert.assertEquals((Object)a1, (Object) 80);
Assert.assertEquals((Object)a2, (Object) 81);
Assert.assertEquals((Object)a3, (Object) 82L);
};
//when
LTieLongConsumer<Integer> function = sutO.andThen(thenFunction);
function.accept(80,81,82L);
//then - finals
Assert.assertTrue(mainFunctionCalled.get());
Assert.assertTrue(thenFunctionCalled.get());
}
@Test(expectedExceptions = RuntimeException.class)
public void testShove() {
// given
LTieLongConsumer<Integer> sutThrowing = LTieLongConsumer.tieLongCons((a1,a2,a3) -> {
throw new UnsupportedOperationException();
});
// when
sutThrowing.shovingAccept(100,100,100L);
}
@Test
public void testToString() throws Throwable {
Assert.assertTrue(sut.toString().startsWith(this.getClass().getName()+"$"));
Assert.assertTrue(String.format("%s", sut).contains("LTieLongConsumer: void accept(T a1,int a2,long a3)"));
}
@Test
public void isThrowing() {
Assert.assertFalse(sut.isThrowing());
}
//<editor-fold desc="Variants">
private void variantLObjLongIntCons(Integer a1,long a3,int a2) {
}
@Test
public void compilerSubstituteVariantLObjLongIntCons() {
LTieLongConsumer lambda = LTieLongConsumer./*<T>*/objLongIntCons(this::variantLObjLongIntCons);
Assert.assertTrue(lambda instanceof LTieLongConsumer.LObjLongIntCons);
}
private void variantLIntObjLongCons(int a2,Integer a1,long a3) {
}
@Test
public void compilerSubstituteVariantLIntObjLongCons() {
LTieLongConsumer lambda = LTieLongConsumer./*<T>*/intObjLongCons(this::variantLIntObjLongCons);
Assert.assertTrue(lambda instanceof LTieLongConsumer.LIntObjLongCons);
}
private void variantLIntLongObjCons(int a2,long a3,Integer a1) {
}
@Test
public void compilerSubstituteVariantLIntLongObjCons() {
LTieLongConsumer lambda = LTieLongConsumer./*<T>*/intLongObjCons(this::variantLIntLongObjCons);
Assert.assertTrue(lambda instanceof LTieLongConsumer.LIntLongObjCons);
}
private void variantLLongObjIntCons(long a3,Integer a1,int a2) {
}
@Test
public void compilerSubstituteVariantLLongObjIntCons() {
LTieLongConsumer lambda = LTieLongConsumer./*<T>*/longObjIntCons(this::variantLLongObjIntCons);
Assert.assertTrue(lambda instanceof LTieLongConsumer.LLongObjIntCons);
}
private void variantLLongIntObjCons(long a3,int a2,Integer a1) {
}
@Test
public void compilerSubstituteVariantLLongIntObjCons() {
LTieLongConsumer lambda = LTieLongConsumer./*<T>*/longIntObjCons(this::variantLLongIntObjCons);
Assert.assertTrue(lambda instanceof LTieLongConsumer.LLongIntObjCons);
}
//</editor-fold>
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.