repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
avranju/qpid-jms | qpid-jms-client/src/test/java/org/apache/qpid/jms/message/JmsMapMessageTest.java | 35216 | /**
* 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.qpid.jms.message;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import javax.jms.JMSException;
import javax.jms.MessageFormatException;
import javax.jms.MessageNotWriteableException;
import org.apache.qpid.jms.message.facade.JmsMapMessageFacade;
import org.apache.qpid.jms.message.facade.test.JmsTestMapMessageFacade;
import org.apache.qpid.jms.message.facade.test.JmsTestMessageFactory;
import org.junit.Test;
/**
* Test that the JMS level JmsMapMessage using a simple default message facade follows
* the JMS spec.
*/
public class JmsMapMessageTest {
private final JmsMessageFactory factory = new JmsTestMessageFactory();
// ======= general =========
@Test
public void testToString() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
assertTrue(mapMessage.toString().startsWith("JmsMapMessage"));
}
@Test
public void testGetMapNamesWithNewMessageToSendReturnsEmptyEnumeration() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
Enumeration<?> names = mapMessage.getMapNames();
assertFalse("Expected new message to have no map names", names.hasMoreElements());
}
/**
* Test that we are able to retrieve the names and values of map entries on a received
* message
*/
@Test
public void testGetMapNamesUsingReceivedMessageReturnsExpectedEnumeration() throws Exception {
JmsMapMessageFacade facade = new JmsTestMapMessageFacade();
String myKey1 = "key1";
String myKey2 = "key2";
facade.put(myKey1, "value1");
facade.put(myKey2, "value2");
JmsMapMessage mapMessage = new JmsMapMessage(facade);
Enumeration<?> names = mapMessage.getMapNames();
int count = 0;
List<Object> elements = new ArrayList<Object>();
while (names.hasMoreElements()) {
count++;
elements.add(names.nextElement());
}
assertEquals("expected 2 map keys in enumeration", 2, count);
assertTrue("expected key was not found: " + myKey1, elements.contains(myKey1));
assertTrue("expected key was not found: " + myKey2, elements.contains(myKey2));
}
/**
* Test that we enforce the requirement that map message key names not be null or the empty
* string.
*/
@Test
public void testSetObjectWithNullOrEmptyKeyNameThrowsIAE() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
try {
mapMessage.setObject(null, "value");
fail("Expected exception not thrown");
} catch (IllegalArgumentException iae) {
// expected
}
try {
mapMessage.setObject("", "value");
fail("Expected exception not thrown");
} catch (IllegalArgumentException iae) {
// expected
}
}
/**
* Test that we are not able to write to a received message without calling
* {@link JmsMapMessage#clearBody()}
*/
@Test
public void testReceivedMessageIsReadOnlyAndThrowsMNWE() throws Exception {
JmsMapMessageFacade facade = new JmsTestMapMessageFacade();
String myKey1 = "key1";
facade.put(myKey1, "value1");
JmsMapMessage mapMessage = new JmsMapMessage(facade);
mapMessage.onDispatch();
try {
mapMessage.setObject("name", "value");
fail("expected exception to be thrown");
} catch (MessageNotWriteableException mnwe) {
// expected
}
}
/**
* Test that calling {@link JmsMapMessage#clearBody()} makes a received message writable
*/
@Test
public void testClearBodyMakesReceivedMessageWritable() throws Exception {
JmsMapMessageFacade facade = new JmsTestMapMessageFacade();
String myKey1 = "key1";
facade.put(myKey1, "value1");
JmsMapMessage mapMessage = new JmsMapMessage(facade);
mapMessage.onDispatch();
assertTrue("expected message to be read-only", mapMessage.isReadOnlyBody());
mapMessage.clearBody();
assertFalse("expected message to be writable", mapMessage.isReadOnlyBody());
mapMessage.setObject("name", "value");
}
/**
* Test that calling {@link JmsMapMessage#clearBody()} clears the underlying message body
* map.
*/
@Test
public void testClearBodyClearsUnderlyingMessageMap() throws Exception {
JmsMapMessageFacade facade = new JmsTestMapMessageFacade();
String myKey1 = "key1";
facade.put(myKey1, "value1");
JmsMapMessage mapMessage = new JmsMapMessage(facade);
assertTrue("key should exist: " + myKey1, mapMessage.itemExists(myKey1));
mapMessage.clearBody();
assertFalse("key should not exist", mapMessage.itemExists(myKey1));
}
/**
* When a map entry is not set, the behaviour of JMS specifies that it is equivalent to a
* null value, and the accessors should either return null, throw NPE, or behave in the same
* fashion as <primitive>.valueOf(String).
*
* Test that this is the case.
*/
@Test
public void testGetMissingMapEntryResultsInExpectedBehaviour() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "does_not_exist";
// expect null
assertNull(mapMessage.getBytes(name));
assertNull(mapMessage.getString(name));
// expect false from Boolean.valueOf(null).
assertFalse(mapMessage.getBoolean(name));
// expect an NFE from the primitive integral <type>.valueOf(null) conversions
assertGetMapEntryThrowsNumberFormatException(mapMessage, name, Byte.class);
assertGetMapEntryThrowsNumberFormatException(mapMessage, name, Short.class);
assertGetMapEntryThrowsNumberFormatException(mapMessage, name, Integer.class);
assertGetMapEntryThrowsNumberFormatException(mapMessage, name, Long.class);
// expect an NPE from the primitive float, double, and char <type>.valuleOf(null)
// conversions
assertGetMapEntryThrowsNullPointerException(mapMessage, name, Float.class);
assertGetMapEntryThrowsNullPointerException(mapMessage, name, Double.class);
assertGetMapEntryThrowsNullPointerException(mapMessage, name, Character.class);
}
// ======= object =========
/**
* Test that the {@link JmsMapMessage#setObject(String, Object)} method rejects Objects of
* unexpected types
*/
@Test(expected=MessageFormatException.class)
public void testSetObjectWithIllegalTypeThrowsMFE() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
mapMessage.setObject("myPKey", new Exception());
}
@Test
public void testSetGetObject() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String keyName = "myProperty";
Object entryValue = null;
mapMessage.setObject(keyName, entryValue);
assertEquals(entryValue, mapMessage.getObject(keyName));
entryValue = Boolean.valueOf(false);
mapMessage.setObject(keyName, entryValue);
assertEquals(entryValue, mapMessage.getObject(keyName));
entryValue = Byte.valueOf((byte) 1);
mapMessage.setObject(keyName, entryValue);
assertEquals(entryValue, mapMessage.getObject(keyName));
entryValue = Short.valueOf((short) 2);
mapMessage.setObject(keyName, entryValue);
assertEquals(entryValue, mapMessage.getObject(keyName));
entryValue = Integer.valueOf(3);
mapMessage.setObject(keyName, entryValue);
assertEquals(entryValue, mapMessage.getObject(keyName));
entryValue = Long.valueOf(4);
mapMessage.setObject(keyName, entryValue);
assertEquals(entryValue, mapMessage.getObject(keyName));
entryValue = Float.valueOf(5.01F);
mapMessage.setObject(keyName, entryValue);
assertEquals(entryValue, mapMessage.getObject(keyName));
entryValue = Double.valueOf(6.01);
mapMessage.setObject(keyName, entryValue);
assertEquals(entryValue, mapMessage.getObject(keyName));
entryValue = "string";
mapMessage.setObject(keyName, entryValue);
assertEquals(entryValue, mapMessage.getObject(keyName));
entryValue = Character.valueOf('c');
mapMessage.setObject(keyName, entryValue);
assertEquals(entryValue, mapMessage.getObject(keyName));
byte[] bytes = new byte[] { (byte) 1, (byte) 0, (byte) 1 };
mapMessage.setObject(keyName, bytes);
Object retrieved = mapMessage.getObject(keyName);
assertTrue(retrieved instanceof byte[]);
assertTrue(Arrays.equals(bytes, (byte[]) retrieved));
}
// ======= Strings =========
@Test
public void testSetGetString() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
// null value
String name = "myNullString";
String value = null;
assertFalse(mapMessage.itemExists(name));
mapMessage.setString(name, value);
assertTrue(mapMessage.itemExists(name));
assertEquals(value, mapMessage.getString(name));
// non-null value
name = "myName";
value = "myValue";
assertFalse(mapMessage.itemExists(name));
mapMessage.setString(name, value);
assertTrue(mapMessage.itemExists(name));
assertEquals(value, mapMessage.getString(name));
}
/**
* Set a String, then retrieve it as all of the legal type combinations to verify it is
* parsed correctly
*/
@Test
public void testSetStringGetLegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myStringName";
String value;
// boolean
value = "true";
mapMessage.setString(name, value);
assertGetMapEntryEquals(mapMessage, name, Boolean.valueOf(value), Boolean.class);
// byte
value = String.valueOf(Byte.MAX_VALUE);
mapMessage.setString(name, value);
assertGetMapEntryEquals(mapMessage, name, Byte.valueOf(value), Byte.class);
// short
value = String.valueOf(Short.MAX_VALUE);
mapMessage.setString(name, value);
assertGetMapEntryEquals(mapMessage, name, Short.valueOf(value), Short.class);
// int
value = String.valueOf(Integer.MAX_VALUE);
mapMessage.setString(name, value);
assertGetMapEntryEquals(mapMessage, name, Integer.valueOf(value), Integer.class);
// long
value = String.valueOf(Long.MAX_VALUE);
mapMessage.setString(name, value);
assertGetMapEntryEquals(mapMessage, name, Long.valueOf(value), Long.class);
// float
value = String.valueOf(Float.MAX_VALUE);
mapMessage.setString(name, value);
assertGetMapEntryEquals(mapMessage, name, Float.valueOf(value), Float.class);
// double
value = String.valueOf(Double.MAX_VALUE);
mapMessage.setString(name, value);
assertGetMapEntryEquals(mapMessage, name, Double.valueOf(value), Double.class);
}
/**
* Set a String, then retrieve it as all of the illegal type combinations to verify it fails
* as expected
*/
@Test
public void testSetStringGetIllegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
String value = "myStringValue";
mapMessage.setString(name, value);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, byte[].class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Character.class);
}
// ======= boolean =========
/**
* Set a boolean, then retrieve it as all of the legal type combinations to verify it is
* parsed correctly
*/
@Test
public void testSetBooleanGetLegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
boolean value = true;
mapMessage.setBoolean(name, value);
assertEquals("value not as expected", value, mapMessage.getBoolean(name));
assertGetMapEntryEquals(mapMessage, name, String.valueOf(value), String.class);
mapMessage.setBoolean(name, !value);
assertEquals("value not as expected", !value, mapMessage.getBoolean(name));
assertGetMapEntryEquals(mapMessage, name, String.valueOf(!value), String.class);
}
/**
* Set a boolean, then retrieve it as all of the illegal type combinations to verify it
* fails as expected
*/
@Test
public void testSetBooleanGetIllegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
boolean value = true;
mapMessage.setBoolean(name, value);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, byte[].class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Character.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Byte.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Short.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Integer.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Long.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Float.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Double.class);
}
// ======= byte =========
/**
* Set a byte, then retrieve it as all of the legal type combinations to verify it is parsed
* correctly
*/
@Test
public void testSetByteGetLegalProperty() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
byte value = (byte) 1;
mapMessage.setByte(name, value);
assertEquals(value, mapMessage.getByte(name));
assertGetMapEntryEquals(mapMessage, name, String.valueOf(value), String.class);
assertGetMapEntryEquals(mapMessage, name, Short.valueOf(value), Short.class);
assertGetMapEntryEquals(mapMessage, name, Integer.valueOf(value), Integer.class);
assertGetMapEntryEquals(mapMessage, name, Long.valueOf(value), Long.class);
}
/**
* Set a byte, then retrieve it as all of the illegal type combinations to verify it is
* fails as expected
*/
@Test
public void testSetByteGetIllegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
byte value = (byte) 1;
mapMessage.setByte(name, value);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, byte[].class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Character.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Boolean.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Float.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Double.class);
}
// ======= short =========
/**
* Set a short, then retrieve it as all of the legal type combinations to verify it is
* parsed correctly
*/
@Test
public void testSetShortGetLegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
short value = (short) 1;
mapMessage.setShort(name, value);
assertEquals(value, mapMessage.getShort(name));
assertGetMapEntryEquals(mapMessage, name, String.valueOf(value), String.class);
assertGetMapEntryEquals(mapMessage, name, Integer.valueOf(value), Integer.class);
assertGetMapEntryEquals(mapMessage, name, Long.valueOf(value), Long.class);
}
/**
* Set a short, then retrieve it as all of the illegal type combinations to verify it fails
* as expected
*/
@Test
public void testSetShortGetIllegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
short value = (short) 1;
mapMessage.setShort(name, value);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, byte[].class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Character.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Boolean.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Byte.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Float.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Double.class);
}
// ======= int =========
/**
* Set an int, then retrieve it as all of the legal type combinations to verify it is parsed
* correctly
*/
@Test
public void testSetIntGetLegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
int value = 1;
mapMessage.setInt(name, value);
assertEquals(value, mapMessage.getInt(name));
assertGetMapEntryEquals(mapMessage, name, String.valueOf(value), String.class);
assertGetMapEntryEquals(mapMessage, name, Long.valueOf(value), Long.class);
}
/**
* Set an int, then retrieve it as all of the illegal type combinations to verify it fails
* as expected
*/
@Test
public void testSetIntGetIllegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
int value = 1;
mapMessage.setInt(name, value);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, byte[].class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Character.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Boolean.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Byte.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Short.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Float.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Double.class);
}
// ======= long =========
/**
* Set a long, then retrieve it as all of the legal type combinations to verify it is parsed
* correctly
*/
@Test
public void testSetLongGetLegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
long value = Long.MAX_VALUE;
mapMessage.setLong(name, value);
assertEquals(value, mapMessage.getLong(name));
assertGetMapEntryEquals(mapMessage, name, String.valueOf(value), String.class);
}
/**
* Set an long, then retrieve it as all of the illegal type combinations to verify it fails
* as expected
*/
@Test
public void testSetLongGetIllegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
long value = Long.MAX_VALUE;
mapMessage.setLong(name, value);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, byte[].class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Character.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Boolean.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Byte.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Short.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Integer.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Float.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Double.class);
}
// ======= float =========
/**
* Set a float, then retrieve it as all of the legal type combinations to verify it is
* parsed correctly
*/
@Test
public void testSetFloatGetLegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
float value = Float.MAX_VALUE;
mapMessage.setFloat(name, value);
assertEquals(value, mapMessage.getFloat(name), 0.0);
assertGetMapEntryEquals(mapMessage, name, String.valueOf(value), String.class);
assertGetMapEntryEquals(mapMessage, name, Double.valueOf(value), Double.class);
}
/**
* Set a float, then retrieve it as all of the illegal type combinations to verify it fails
* as expected
*/
@Test
public void testSetFloatGetIllegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
float value = Float.MAX_VALUE;
mapMessage.setFloat(name, value);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, byte[].class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Character.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Boolean.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Byte.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Short.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Integer.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Long.class);
}
// ======= double =========
/**
* Set a double, then retrieve it as all of the legal type combinations to verify it is
* parsed correctly
*/
@Test
public void testSetDoubleGetLegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
double value = Double.MAX_VALUE;
mapMessage.setDouble(name, value);
assertEquals(value, mapMessage.getDouble(name), 0.0);
assertGetMapEntryEquals(mapMessage, name, String.valueOf(value), String.class);
}
/**
* Set a double, then retrieve it as all of the illegal type combinations to verify it fails
* as expected
*/
@Test
public void testSetDoubleGetIllegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
double value = Double.MAX_VALUE;
mapMessage.setDouble(name, value);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, byte[].class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Character.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Boolean.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Byte.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Short.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Integer.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Long.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Float.class);
}
// ======= character =========
/**
* Set a char, then retrieve it as all of the legal type combinations to verify it is parsed
* correctly
*/
@Test
public void testSetCharGetLegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
char value = 'c';
mapMessage.setChar(name, value);
assertEquals(value, mapMessage.getChar(name));
assertGetMapEntryEquals(mapMessage, name, String.valueOf(value), String.class);
}
/**
* Set a char, then retrieve it as all of the illegal type combinations to verify it fails
* as expected
*/
@Test
public void testSetCharGetIllegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
char value = 'c';
mapMessage.setChar(name, value);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, byte[].class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Boolean.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Byte.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Short.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Integer.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Long.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Float.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Double.class);
}
// ========= bytes ========
/**
* Set bytes, then retrieve it as all of the legal type combinations to verify it is parsed
* correctly
*/
@Test
public void testSetBytesGetLegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
byte[] value = "myBytes".getBytes();
mapMessage.setBytes(name, value);
assertTrue(Arrays.equals(value, mapMessage.getBytes(name)));
}
/**
* Set bytes, then retrieve it as all of the illegal type combinations to verify it fails as
* expected
*/
@Test
public void testSetBytesGetIllegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
byte[] value = "myBytes".getBytes();
mapMessage.setBytes(name, value);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Character.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, String.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Boolean.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Byte.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Short.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Integer.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Long.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Float.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Double.class);
}
// TODO - This is a test that should be moved to the Facade test for the AMQP message facades.
//
// /**
// * Verify that for a message received with an AmqpValue containing a Map with a Binary entry
// * value, we are able to read it back as a byte[].
// */
// @Test
// public void testReceivedMapWithBinaryEntryReturnsByteArray() throws Exception {
// String myKey1 = "key1";
// String bytesSource = "myBytesAmqpValue";
//
// Map<String, Object> origMap = new HashMap<String, Object>();
// byte[] bytes = bytesSource.getBytes();
// origMap.put(myKey1, new Binary(bytes));
//
// org.apache.qpid.proton.codec.Data payloadData = new DataImpl();
// payloadData.putDescribedType(new AmqpValueDescribedType(origMap));
// Binary b = payloadData.encode();
//
// System.out.println("Using encoded AMQP message payload: " + b);
//
// Message message = Proton.message();
// int decoded = message.decode(b.getArray(), b.getArrayOffset(), b.getLength());
// assertEquals(decoded, b.getLength());
//
// AmqpMapMessage amqpMapMessage = new AmqpMapMessage(message, _mockDelivery, _mockAmqpConnection);
//
// JmsMapMessage mapMessage = new JmsMapMessage(amqpMapMessage, _mockSessionImpl, _mockConnectionImpl, null);
//
// // retrieve the bytes using getBytes, check they match expectation
// byte[] receivedBytes = mapMessage.getBytes(myKey1);
// assertTrue(Arrays.equals(bytes, receivedBytes));
//
// // retrieve the bytes using getObject, check they match expectation
// Object o = mapMessage.getObject(myKey1);
// assertTrue(o instanceof byte[]);
// assertTrue(Arrays.equals(bytes, (byte[]) o));
// }
/**
* Verify that setting bytes takes a copy of the array. Set bytes, then modify them, then
* retrieve the map entry and verify the two differ.
*/
@Test
public void testSetBytesTakesSnapshot() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
byte[] orig = "myBytes".getBytes();
byte[] copy = Arrays.copyOf(orig, orig.length);
// set the original bytes
mapMessage.setBytes(name, orig);
// corrupt the original bytes
orig[0] = (byte) 0;
// verify retrieving the bytes still matches the copy but not the original array
byte[] retrieved = mapMessage.getBytes(name);
assertFalse(Arrays.equals(orig, retrieved));
assertTrue(Arrays.equals(copy, retrieved));
}
/**
* Verify that getting bytes returns a copy of the array. Set bytes, then get them, modify
* the retrieved value, then get them again and verify the two differ.
*/
@Test
public void testGetBytesReturnsSnapshot() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
byte[] orig = "myBytes".getBytes();
// set the original bytes
mapMessage.setBytes(name, orig);
// retrieve them
byte[] retrieved1 = mapMessage.getBytes(name);
;
// corrupt the retrieved bytes
retrieved1[0] = (byte) 0;
// verify retrieving the bytes again still matches the original array, but not the
// previously retrieved (and now corrupted) bytes.
byte[] retrieved2 = mapMessage.getBytes(name);
assertTrue(Arrays.equals(orig, retrieved2));
assertFalse(Arrays.equals(retrieved1, retrieved2));
}
/**
* Verify that setting bytes takes a copy of the array. Set bytes, then modify them, then
* retrieve the map entry and verify the two differ.
*/
@Test
public void testSetBytesWithOffsetAndLength() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
byte[] orig = "myBytesAll".getBytes();
// extract the segment containing 'Bytes'
int offset = 2;
int length = 5;
byte[] segment = Arrays.copyOfRange(orig, offset, offset + length);
// set the same section from the original bytes
mapMessage.setBytes(name, orig, offset, length);
// verify the retrieved bytes from the map match the segment but not the full original
// array
byte[] retrieved = mapMessage.getBytes(name);
assertFalse(Arrays.equals(orig, retrieved));
assertTrue(Arrays.equals(segment, retrieved));
}
@Test
public void testSetBytesWithNull() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
mapMessage.setBytes(name, null);
assertNull(mapMessage.getBytes(name));
}
// ========= utility methods ========
private void assertGetMapEntryEquals(JmsMapMessage testMessage, String name, Object expectedValue, Class<?> clazz) throws JMSException {
Object actualValue = getMapEntryUsingTypeMethod(testMessage, name, clazz);
assertEquals(expectedValue, actualValue);
}
private void assertGetMapEntryThrowsMessageFormatException(JmsMapMessage testMessage, String name, Class<?> clazz) throws JMSException {
try {
getMapEntryUsingTypeMethod(testMessage, name, clazz);
fail("expected exception to be thrown");
} catch (MessageFormatException jmsMFE) {
// expected
}
}
private void assertGetMapEntryThrowsNumberFormatException(JmsMapMessage testMessage, String name, Class<?> clazz) throws JMSException {
try {
getMapEntryUsingTypeMethod(testMessage, name, clazz);
fail("expected exception to be thrown");
} catch (NumberFormatException nfe) {
// expected
}
}
private void assertGetMapEntryThrowsNullPointerException(JmsMapMessage testMessage, String name, Class<?> clazz) throws JMSException {
try {
getMapEntryUsingTypeMethod(testMessage, name, clazz);
fail("expected exception to be thrown");
} catch (NullPointerException npe) {
// expected
}
}
private Object getMapEntryUsingTypeMethod(JmsMapMessage testMessage, String name, Class<?> clazz) throws JMSException {
if (clazz == Boolean.class) {
return testMessage.getBoolean(name);
} else if (clazz == Byte.class) {
return testMessage.getByte(name);
} else if (clazz == Character.class) {
return testMessage.getChar(name);
} else if (clazz == Short.class) {
return testMessage.getShort(name);
} else if (clazz == Integer.class) {
return testMessage.getInt(name);
} else if (clazz == Long.class) {
return testMessage.getLong(name);
} else if (clazz == Float.class) {
return testMessage.getFloat(name);
} else if (clazz == Double.class) {
return testMessage.getDouble(name);
} else if (clazz == String.class) {
return testMessage.getString(name);
} else if (clazz == byte[].class) {
return testMessage.getBytes(name);
} else {
throw new RuntimeException("Unexpected entry type class");
}
}
}
| apache-2.0 |
rithms/riot-api-java | src/main/java/net/rithms/riot/api/endpoints/static_data/constant/MasteryListTags.java | 1040 | /*
* Copyright 2014 Taylor Caldwell
*
* 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 net.rithms.riot.api.endpoints.static_data.constant;
public enum MasteryListTags {
ALL("all"),
IMAGE("image"),
MASTERY_TREE("masteryTree"),
PREREQ("prereq"),
RANKS("ranks"),
SANITIZED_DESCRIPTION("sanitizedDescription"),
TREE("tree");
private String name;
MasteryListTags(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return getName();
}
} | apache-2.0 |
FrantisekGazo/Blade | core-compiler/src/main/java/eu/f3rog/blade/compiler/builder/annotation/WeaveParser.java | 1815 | package eu.f3rog.blade.compiler.builder.annotation;
/**
* Class {@link WeaveParser}
*
* @author FrantisekGazo
*/
public final class WeaveParser {
public static final class Into {
private final WeaveBuilder.MethodWeaveType mMethodWeaveType;
private final WeaveBuilder.WeavePriority mPriority;
private final String mMethodName;
private final String mRename;
private Into(WeaveBuilder.MethodWeaveType methodWeaveType, WeaveBuilder.WeavePriority priority, String methodName, String rename) {
mPriority = priority;
mMethodWeaveType = methodWeaveType;
mMethodName = methodName;
mRename = rename;
}
public WeaveBuilder.MethodWeaveType getMethodWeaveType() {
return mMethodWeaveType;
}
public WeaveBuilder.WeavePriority getPriority() {
return mPriority;
}
public String getMethodName() {
return mMethodName;
}
public boolean shouldRename() {
return mRename != null;
}
public String getRename() {
return mRename;
}
}
public static Into parseInto(final String into) {
int number = Integer.valueOf(into.substring(0, 1));
WeaveBuilder.WeavePriority priority = WeaveBuilder.WeavePriority.from(number);
String type = into.substring(1, 2);
WeaveBuilder.MethodWeaveType weaveType = WeaveBuilder.MethodWeaveType.from(type);
String name = into.substring(2);
String[] names = name.split(WeaveBuilder.RENAME_SEPARATOR);
if (names.length > 1) {
return new Into(weaveType, priority, names[0], names[1]);
} else {
return new Into(weaveType, priority, names[0], null);
}
}
} | apache-2.0 |
littlezhou/hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-core/src/main/java/org/apache/hadoop/yarn/service/impl/pb/client/ClientAMProtocolPBClientImpl.java | 6131 | /**
* 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.yarn.service.impl.pb.client;
import com.google.protobuf.ServiceException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.ipc.ProtobufRpcEngine;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.ipc.RPCUtil;
import org.apache.hadoop.yarn.service.ClientAMProtocol;
import java.io.Closeable;
import java.io.IOException;
import java.net.InetSocketAddress;
import org.apache.hadoop.yarn.proto.ClientAMProtocol.CancelUpgradeRequestProto;
import org.apache.hadoop.yarn.proto.ClientAMProtocol.CancelUpgradeResponseProto;
import org.apache.hadoop.yarn.proto.ClientAMProtocol.CompInstancesUpgradeResponseProto;
import org.apache.hadoop.yarn.proto.ClientAMProtocol.CompInstancesUpgradeRequestProto;
import org.apache.hadoop.yarn.proto.ClientAMProtocol.DecommissionCompInstancesRequestProto;
import org.apache.hadoop.yarn.proto.ClientAMProtocol.DecommissionCompInstancesResponseProto;
import org.apache.hadoop.yarn.proto.ClientAMProtocol.FlexComponentsRequestProto;
import org.apache.hadoop.yarn.proto.ClientAMProtocol.FlexComponentsResponseProto;
import org.apache.hadoop.yarn.proto.ClientAMProtocol.GetCompInstancesRequestProto;
import org.apache.hadoop.yarn.proto.ClientAMProtocol.GetCompInstancesResponseProto;
import org.apache.hadoop.yarn.proto.ClientAMProtocol.GetStatusRequestProto;
import org.apache.hadoop.yarn.proto.ClientAMProtocol.GetStatusResponseProto;
import org.apache.hadoop.yarn.service.impl.pb.service.ClientAMProtocolPB;
import org.apache.hadoop.yarn.proto.ClientAMProtocol.RestartServiceRequestProto;
import org.apache.hadoop.yarn.proto.ClientAMProtocol.RestartServiceResponseProto;
import org.apache.hadoop.yarn.proto.ClientAMProtocol.StopResponseProto;
import org.apache.hadoop.yarn.proto.ClientAMProtocol.StopRequestProto;
import org.apache.hadoop.yarn.proto.ClientAMProtocol.UpgradeServiceRequestProto;
import org.apache.hadoop.yarn.proto.ClientAMProtocol.UpgradeServiceResponseProto;
public class ClientAMProtocolPBClientImpl
implements ClientAMProtocol, Closeable {
private ClientAMProtocolPB proxy;
public ClientAMProtocolPBClientImpl(long clientVersion,
InetSocketAddress addr, Configuration conf) throws IOException {
RPC.setProtocolEngine(conf, ClientAMProtocolPB.class,
ProtobufRpcEngine.class);
proxy = RPC.getProxy(ClientAMProtocolPB.class, clientVersion, addr, conf);
}
@Override public FlexComponentsResponseProto flexComponents(
FlexComponentsRequestProto request) throws IOException, YarnException {
try {
return proxy.flexComponents(null, request);
} catch (ServiceException e) {
RPCUtil.unwrapAndThrowException(e);
}
return null;
}
@Override
public GetStatusResponseProto getStatus(GetStatusRequestProto request)
throws IOException, YarnException {
try {
return proxy.getStatus(null, request);
} catch (ServiceException e) {
RPCUtil.unwrapAndThrowException(e);
}
return null;
}
@Override
public StopResponseProto stop(StopRequestProto requestProto)
throws IOException, YarnException {
try {
return proxy.stop(null, requestProto);
} catch (ServiceException e) {
RPCUtil.unwrapAndThrowException(e);
}
return null;
}
@Override public void close() {
if (this.proxy != null) {
RPC.stopProxy(this.proxy);
}
}
@Override
public UpgradeServiceResponseProto upgrade(
UpgradeServiceRequestProto request) throws IOException, YarnException {
try {
return proxy.upgradeService(null, request);
} catch (ServiceException e) {
RPCUtil.unwrapAndThrowException(e);
}
return null;
}
@Override
public RestartServiceResponseProto restart(RestartServiceRequestProto request)
throws IOException, YarnException {
try {
return proxy.restartService(null, request);
} catch (ServiceException e) {
RPCUtil.unwrapAndThrowException(e);
}
return null;
}
@Override
public CompInstancesUpgradeResponseProto upgrade(
CompInstancesUpgradeRequestProto request)
throws IOException, YarnException {
try {
return proxy.upgrade(null, request);
} catch (ServiceException e) {
RPCUtil.unwrapAndThrowException(e);
}
return null;
}
@Override
public GetCompInstancesResponseProto getCompInstances(
GetCompInstancesRequestProto request) throws IOException, YarnException {
try {
return proxy.getCompInstances(null, request);
} catch (ServiceException e) {
RPCUtil.unwrapAndThrowException(e);
}
return null;
}
@Override
public CancelUpgradeResponseProto cancelUpgrade(
CancelUpgradeRequestProto request) throws IOException, YarnException {
try {
return proxy.cancelUpgrade(null, request);
} catch (ServiceException e) {
RPCUtil.unwrapAndThrowException(e);
}
return null;
}
@Override
public DecommissionCompInstancesResponseProto decommissionCompInstances(
DecommissionCompInstancesRequestProto request)
throws IOException, YarnException {
try {
return proxy.decommissionCompInstances(null, request);
} catch (ServiceException e) {
RPCUtil.unwrapAndThrowException(e);
}
return null;
}
}
| apache-2.0 |
leveyj/ignite | modules/core/src/test/java/org/apache/ignite/internal/util/future/GridFutureAdapterSelfTest.java | 10998 | /*
* 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.util.future;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.IgniteFutureCancelledCheckedException;
import org.apache.ignite.internal.IgniteFutureTimeoutCheckedException;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.cluster.ClusterGroupEmptyCheckedException;
import org.apache.ignite.internal.processors.closure.GridClosureProcessor;
import org.apache.ignite.internal.processors.pool.PoolProcessor;
import org.apache.ignite.internal.util.typedef.CI1;
import org.apache.ignite.internal.util.typedef.CX1;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.GridTestKernalContext;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
/**
* Tests grid future adapter use cases.
*/
public class GridFutureAdapterSelfTest extends GridCommonAbstractTest {
/**
* @throws Exception If failed.
*/
public void testOnDone() throws Exception {
GridFutureAdapter<String> fut = new GridFutureAdapter<>();
fut.onDone();
assertNull(fut.get());
fut = new GridFutureAdapter<>();
fut.onDone("test");
assertEquals("test", fut.get());
fut = new GridFutureAdapter<>();
fut.onDone(new IgniteCheckedException("TestMessage"));
final GridFutureAdapter<String> callFut1 = fut;
GridTestUtils.assertThrows(log, new Callable<Object>() {
@Override public Object call() throws Exception {
return callFut1.get();
}
}, IgniteCheckedException.class, "TestMessage");
fut = new GridFutureAdapter<>();
fut.onDone("test", new IgniteCheckedException("TestMessage"));
final GridFutureAdapter<String> callFut2 = fut;
GridTestUtils.assertThrows(log, new Callable<Object>() {
@Override public Object call() throws Exception {
return callFut2.get();
}
}, IgniteCheckedException.class, "TestMessage");
fut = new GridFutureAdapter<>();
fut.onDone("test");
fut.onCancelled();
assertEquals("test", fut.get());
}
/**
* @throws Exception If failed.
*/
public void testOnCancelled() throws Exception {
GridTestUtils.assertThrows(log, new Callable<Object>() {
@Override public Object call() throws Exception {
GridFutureAdapter<String> fut = new GridFutureAdapter<>();
fut.onCancelled();
return fut.get();
}
}, IgniteFutureCancelledCheckedException.class, null);
GridTestUtils.assertThrows(log, new Callable<Object>() {
@Override public Object call() throws Exception {
GridFutureAdapter<String> fut = new GridFutureAdapter<>();
fut.onCancelled();
fut.onDone();
return fut.get();
}
}, IgniteFutureCancelledCheckedException.class, null);
}
/**
* @throws Exception If failed.
*/
public void testListenSyncNotify() throws Exception {
GridFutureAdapter<String> fut = new GridFutureAdapter<>();
int lsnrCnt = 10;
final CountDownLatch latch = new CountDownLatch(lsnrCnt);
final Thread runThread = Thread.currentThread();
final AtomicReference<Exception> err = new AtomicReference<>();
for (int i = 0; i < lsnrCnt; i++) {
fut.listen(new CI1<IgniteInternalFuture<String>>() {
@Override public void apply(IgniteInternalFuture<String> t) {
if (Thread.currentThread() != runThread)
err.compareAndSet(null, new Exception("Wrong notification thread: " + Thread.currentThread()));
latch.countDown();
}
});
}
fut.onDone();
assertEquals(0, latch.getCount());
if (err.get() != null)
throw err.get();
final AtomicBoolean called = new AtomicBoolean();
err.set(null);
fut.listen(new CI1<IgniteInternalFuture<String>>() {
@Override public void apply(IgniteInternalFuture<String> t) {
if (Thread.currentThread() != runThread)
err.compareAndSet(null, new Exception("Wrong notification thread: " + Thread.currentThread()));
called.set(true);
}
});
assertTrue(called.get());
if (err.get() != null)
throw err.get();
}
/**
* @throws Exception If failed.
*/
public void testListenNotify() throws Exception {
GridTestKernalContext ctx = new GridTestKernalContext(log);
ctx.setExecutorService(Executors.newFixedThreadPool(1));
ctx.setSystemExecutorService(Executors.newFixedThreadPool(1));
ctx.add(new PoolProcessor(ctx));
ctx.add(new GridClosureProcessor(ctx));
ctx.start();
try {
GridFutureAdapter<String> fut = new GridFutureAdapter<>();
int lsnrCnt = 10;
final CountDownLatch latch = new CountDownLatch(lsnrCnt);
final Thread runThread = Thread.currentThread();
for (int i = 0; i < lsnrCnt; i++) {
fut.listen(new CI1<IgniteInternalFuture<String>>() {
@Override public void apply(IgniteInternalFuture<String> t) {
assert Thread.currentThread() == runThread;
latch.countDown();
}
});
}
fut.onDone();
latch.await();
final CountDownLatch doneLatch = new CountDownLatch(1);
fut.listen(new CI1<IgniteInternalFuture<String>>() {
@Override public void apply(IgniteInternalFuture<String> t) {
assert Thread.currentThread() == runThread;
doneLatch.countDown();
}
});
assert doneLatch.getCount() == 0;
doneLatch.await();
}
finally {
ctx.stop(false);
}
}
/**
* Test futures chaining.
*
* @throws Exception In case of any exception.
*/
@SuppressWarnings("ErrorNotRethrown")
public void testChaining() throws Exception {
final CX1<IgniteInternalFuture<Object>, Object> passThrough = new CX1<IgniteInternalFuture<Object>, Object>() {
@Override public Object applyx(IgniteInternalFuture<Object> f) throws IgniteCheckedException {
return f.get();
}
};
final GridTestKernalContext ctx = new GridTestKernalContext(log);
ctx.setExecutorService(Executors.newFixedThreadPool(1));
ctx.setSystemExecutorService(Executors.newFixedThreadPool(1));
ctx.add(new PoolProcessor(ctx));
ctx.add(new GridClosureProcessor(ctx));
ctx.start();
try {
// Test result returned.
GridFutureAdapter<Object> fut = new GridFutureAdapter<>();
IgniteInternalFuture<Object> chain = fut.chain(passThrough);
assertFalse(fut.isDone());
assertFalse(chain.isDone());
try {
chain.get(20);
fail("Expects timeout exception.");
}
catch (IgniteFutureTimeoutCheckedException e) {
info("Expected timeout exception: " + e.getMessage());
}
fut.onDone("result");
assertEquals("result", chain.get(1));
// Test exception re-thrown.
fut = new GridFutureAdapter<>();
chain = fut.chain(passThrough);
fut.onDone(new ClusterGroupEmptyCheckedException("test exception"));
try {
chain.get();
fail("Expects failed with exception.");
}
catch (ClusterGroupEmptyCheckedException e) {
info("Expected exception: " + e.getMessage());
}
// Test error re-thrown.
fut = new GridFutureAdapter<>();
chain = fut.chain(passThrough);
try {
fut.onDone(new StackOverflowError("test error"));
fail("Expects failed with error.");
}
catch (StackOverflowError e) {
info("Expected error: " + e.getMessage());
}
try {
chain.get();
fail("Expects failed with error.");
}
catch (StackOverflowError e) {
info("Expected error: " + e.getMessage());
}
}
finally {
ctx.stop(false);
}
}
/**
* @throws Exception If failed.
*/
public void testGet() throws Exception {
GridFutureAdapter<Object> unfinished = new GridFutureAdapter<>();
GridFutureAdapter<Object> finished = new GridFutureAdapter<>();
GridFutureAdapter<Object> cancelled = new GridFutureAdapter<>();
finished.onDone("Finished");
cancelled.onCancelled();
try {
unfinished.get(50);
assert false;
}
catch (IgniteFutureTimeoutCheckedException e) {
info("Caught expected exception: " + e);
}
Object o = finished.get();
assertEquals("Finished", o);
o = finished.get(1000);
assertEquals("Finished", o);
try {
cancelled.get();
assert false;
}
catch (IgniteFutureCancelledCheckedException e) {
info("Caught expected exception: " + e);
}
try {
cancelled.get(1000);
assert false;
}
catch (IgniteFutureCancelledCheckedException e) {
info("Caught expected exception: " + e);
}
}
} | apache-2.0 |
EvilMcJerkface/atlasdb | timelock-agent/src/test/java/com/palantir/timelock/paxos/DbBoundTimestampCreatorTest.java | 1718 | /*
* (c) Copyright 2020 Palantir Technologies 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.palantir.timelock.paxos;
import static org.assertj.core.api.Assertions.assertThat;
import com.palantir.atlasdb.AtlasDbConstants;
import com.palantir.atlasdb.config.DbTimestampCreationSetting;
import com.palantir.atlasdb.keyvalue.api.TimestampSeries;
import com.palantir.paxos.Client;
import org.junit.Test;
public class DbBoundTimestampCreatorTest {
private static final Client CLIENT_1 = Client.of("tom");
private static final Client CLIENT_2 = Client.of("jeremy");
@Test
public void timestampCreationParametersMaintainClientName() {
assertThat(DbBoundTimestampCreator.getTimestampCreationParameters(CLIENT_1))
.isEqualTo(DbTimestampCreationSetting.of(
AtlasDbConstants.DB_TIMELOCK_TIMESTAMP_TABLE, TimestampSeries.of(CLIENT_1.value())));
assertThat(DbBoundTimestampCreator.getTimestampCreationParameters(CLIENT_2))
.isEqualTo(DbTimestampCreationSetting.of(
AtlasDbConstants.DB_TIMELOCK_TIMESTAMP_TABLE, TimestampSeries.of(CLIENT_2.value())));
}
}
| apache-2.0 |
Fabryprog/camel | components/camel-aws-sdb/src/test/java/org/apache/camel/component/aws/sdb/SdbComponentTest.java | 14426 | /*
* 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.component.aws.sdb;
import java.util.Arrays;
import java.util.List;
import com.amazonaws.services.simpledb.model.Attribute;
import com.amazonaws.services.simpledb.model.DeletableItem;
import com.amazonaws.services.simpledb.model.Item;
import com.amazonaws.services.simpledb.model.ReplaceableAttribute;
import com.amazonaws.services.simpledb.model.ReplaceableItem;
import com.amazonaws.services.simpledb.model.UpdateCondition;
import org.apache.camel.BindToRegistry;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.engine.DefaultProducerTemplate;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
public class SdbComponentTest extends CamelTestSupport {
@BindToRegistry("amazonSDBClient")
private AmazonSDBClientMock amazonSDBClient = new AmazonSDBClientMock();
@Test
public void doesntCreateDomainOnStartIfExists() throws Exception {
assertNull(amazonSDBClient.createDomainRequest);
}
@Test
public void createDomainOnStartIfNotExists() throws Exception {
DefaultProducerTemplate.newInstance(context, "aws-sdb://NonExistingDomain?amazonSDBClient=#amazonSDBClient&operation=GetAttributes");
assertEquals("NonExistingDomain", amazonSDBClient.createDomainRequest.getDomainName());
}
@Test
public void batchDeleteAttributes() {
final List<DeletableItem> deletableItems = Arrays.asList(new DeletableItem[] {
new DeletableItem("ITEM1", null),
new DeletableItem("ITEM2", null)});
template.send("direct:start", new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getIn().setHeader(SdbConstants.OPERATION, SdbOperations.BatchDeleteAttributes);
exchange.getIn().setHeader(SdbConstants.DELETABLE_ITEMS, deletableItems);
}
});
assertEquals("TestDomain", amazonSDBClient.batchDeleteAttributesRequest.getDomainName());
assertEquals(deletableItems, amazonSDBClient.batchDeleteAttributesRequest.getItems());
}
@Test
public void batchPutAttributes() {
final List<ReplaceableItem> replaceableItems = Arrays.asList(new ReplaceableItem[] {
new ReplaceableItem("ITEM1")});
template.send("direct:start", new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getIn().setHeader(SdbConstants.OPERATION, SdbOperations.BatchPutAttributes);
exchange.getIn().setHeader(SdbConstants.REPLACEABLE_ITEMS, replaceableItems);
}
});
assertEquals("TestDomain", amazonSDBClient.batchPutAttributesRequest.getDomainName());
assertEquals(replaceableItems, amazonSDBClient.batchPutAttributesRequest.getItems());
}
@Test
public void deleteAttributes() {
final List<Attribute> attributes = Arrays.asList(new Attribute[] {
new Attribute("NAME1", "VALUE1")});
final UpdateCondition condition = new UpdateCondition("Key1", "Value1", true);
template.send("direct:start", new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getIn().setHeader(SdbConstants.OPERATION, SdbOperations.DeleteAttributes);
exchange.getIn().setHeader(SdbConstants.ATTRIBUTES, attributes);
exchange.getIn().setHeader(SdbConstants.ITEM_NAME, "ITEM1");
exchange.getIn().setHeader(SdbConstants.UPDATE_CONDITION, condition);
}
});
assertEquals("TestDomain", amazonSDBClient.deleteAttributesRequest.getDomainName());
assertEquals("ITEM1", amazonSDBClient.deleteAttributesRequest.getItemName());
assertEquals(condition, amazonSDBClient.deleteAttributesRequest.getExpected());
assertEquals(attributes, amazonSDBClient.deleteAttributesRequest.getAttributes());
}
@Test
public void deleteAttributesItemNameIsRequired() {
final List<Attribute> attributes = Arrays.asList(new Attribute[] {
new Attribute("NAME1", "VALUE1")});
final UpdateCondition condition = new UpdateCondition("Key1", "Value1", true);
Exchange exchange = template.send("direct:start", new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getIn().setHeader(SdbConstants.OPERATION, SdbOperations.DeleteAttributes);
exchange.getIn().setHeader(SdbConstants.ATTRIBUTES, attributes);
exchange.getIn().setHeader(SdbConstants.UPDATE_CONDITION, condition);
}
});
Exception exception = exchange.getException();
assertTrue(exception instanceof IllegalArgumentException);
}
@Test
public void deleteDomain() {
template.send("direct:start", new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getIn().setHeader(SdbConstants.OPERATION, SdbOperations.DeleteDomain);
}
});
assertEquals("TestDomain", amazonSDBClient.deleteDomainRequest.getDomainName());
}
@Test
public void domainMetadata() {
Exchange exchange = template.send("direct:start", new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getIn().setHeader(SdbConstants.OPERATION, SdbOperations.DomainMetadata);
}
});
assertEquals("TestDomain", amazonSDBClient.domainMetadataRequest.getDomainName());
assertEquals(new Integer(10), exchange.getIn().getHeader(SdbConstants.TIMESTAMP));
assertEquals(new Integer(11), exchange.getIn().getHeader(SdbConstants.ITEM_COUNT));
assertEquals(new Integer(12), exchange.getIn().getHeader(SdbConstants.ATTRIBUTE_NAME_COUNT));
assertEquals(new Integer(13), exchange.getIn().getHeader(SdbConstants.ATTRIBUTE_VALUE_COUNT));
assertEquals(new Long(1000000), exchange.getIn().getHeader(SdbConstants.ATTRIBUTE_NAME_SIZE));
assertEquals(new Long(2000000), exchange.getIn().getHeader(SdbConstants.ATTRIBUTE_VALUE_SIZE));
assertEquals(new Long(3000000), exchange.getIn().getHeader(SdbConstants.ITEM_NAME_SIZE));
}
@SuppressWarnings("unchecked")
@Test
public void getAttributes() {
final List<String> attributeNames = Arrays.asList(new String[] {"ATTRIBUTE1"});
Exchange exchange = template.send("direct:start", new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getIn().setHeader(SdbConstants.OPERATION, SdbOperations.GetAttributes);
exchange.getIn().setHeader(SdbConstants.ITEM_NAME, "ITEM1");
exchange.getIn().setHeader(SdbConstants.CONSISTENT_READ, Boolean.TRUE);
exchange.getIn().setHeader(SdbConstants.ATTRIBUTE_NAMES, attributeNames);
}
});
assertEquals("TestDomain", amazonSDBClient.getAttributesRequest.getDomainName());
assertEquals("ITEM1", amazonSDBClient.getAttributesRequest.getItemName());
assertEquals(Boolean.TRUE, amazonSDBClient.getAttributesRequest.getConsistentRead());
assertEquals(attributeNames, amazonSDBClient.getAttributesRequest.getAttributeNames());
List<Attribute> attributes = exchange.getIn().getHeader(SdbConstants.ATTRIBUTES, List.class);
assertEquals(2, attributes.size());
assertEquals("AttributeOne", attributes.get(0).getName());
assertEquals("Value One", attributes.get(0).getValue());
assertEquals("AttributeTwo", attributes.get(1).getName());
assertEquals("Value Two", attributes.get(1).getValue());
}
@Test
public void getAttributesItemNameIsRequired() {
final List<String> attributeNames = Arrays.asList(new String[] {"ATTRIBUTE1"});
Exchange exchange = template.send("direct:start", new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getIn().setHeader(SdbConstants.OPERATION, SdbOperations.GetAttributes);
exchange.getIn().setHeader(SdbConstants.CONSISTENT_READ, Boolean.TRUE);
exchange.getIn().setHeader(SdbConstants.ATTRIBUTE_NAMES, attributeNames);
}
});
Exception exception = exchange.getException();
assertTrue(exception instanceof IllegalArgumentException);
}
@SuppressWarnings({ "unchecked" })
@Test
public void listDomains() {
Exchange exchange = template.send("direct:start", new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getIn().setHeader(SdbConstants.OPERATION, SdbOperations.ListDomains);
exchange.getIn().setHeader(SdbConstants.MAX_NUMBER_OF_DOMAINS, new Integer(5));
exchange.getIn().setHeader(SdbConstants.NEXT_TOKEN, "TOKEN1");
}
});
assertEquals(new Integer(5), amazonSDBClient.listDomainsRequest.getMaxNumberOfDomains());
assertEquals("TOKEN1", amazonSDBClient.listDomainsRequest.getNextToken());
List<String> domains = exchange.getIn().getHeader(SdbConstants.DOMAIN_NAMES, List.class);
assertEquals("TOKEN2", exchange.getIn().getHeader(SdbConstants.NEXT_TOKEN));
assertEquals(2, domains.size());
assertTrue(domains.contains("DOMAIN1"));
assertTrue(domains.contains("DOMAIN2"));
}
@Test
public void putAttributes() {
final List<ReplaceableAttribute> replaceableAttributes = Arrays.asList(new ReplaceableAttribute[] {
new ReplaceableAttribute("NAME1", "VALUE1", true)});
final UpdateCondition updateCondition = new UpdateCondition("NAME1", "VALUE1", true);
template.send("direct:start", new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getIn().setHeader(SdbConstants.OPERATION, SdbOperations.PutAttributes);
exchange.getIn().setHeader(SdbConstants.ITEM_NAME, "ITEM1");
exchange.getIn().setHeader(SdbConstants.UPDATE_CONDITION, updateCondition);
exchange.getIn().setHeader(SdbConstants.REPLACEABLE_ATTRIBUTES, replaceableAttributes);
}
});
assertEquals("TestDomain", amazonSDBClient.putAttributesRequest.getDomainName());
assertEquals("ITEM1", amazonSDBClient.putAttributesRequest.getItemName());
assertEquals(updateCondition, amazonSDBClient.putAttributesRequest.getExpected());
assertEquals(replaceableAttributes, amazonSDBClient.putAttributesRequest.getAttributes());
}
@Test
public void putAttributesItemNameIsRequired() {
final List<ReplaceableAttribute> replaceableAttributes = Arrays.asList(new ReplaceableAttribute[] {
new ReplaceableAttribute("NAME1", "VALUE1", true)});
final UpdateCondition updateCondition = new UpdateCondition("NAME1", "VALUE1", true);
Exchange exchange = template.send("direct:start", new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getIn().setHeader(SdbConstants.OPERATION, SdbOperations.PutAttributes);
exchange.getIn().setHeader(SdbConstants.UPDATE_CONDITION, updateCondition);
exchange.getIn().setHeader(SdbConstants.REPLACEABLE_ATTRIBUTES, replaceableAttributes);
}
});
Exception exception = exchange.getException();
assertTrue(exception instanceof IllegalArgumentException);
}
@SuppressWarnings("unchecked")
@Test
public void select() {
Exchange exchange = template.send("direct:start", new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getIn().setHeader(SdbConstants.OPERATION, SdbOperations.Select);
exchange.getIn().setHeader(SdbConstants.NEXT_TOKEN, "TOKEN1");
exchange.getIn().setHeader(SdbConstants.CONSISTENT_READ, Boolean.TRUE);
exchange.getIn().setHeader(SdbConstants.SELECT_EXPRESSION, "SELECT NAME1 FROM DOMAIN1 WHERE NAME1 LIKE 'VALUE1'");
}
});
assertEquals(Boolean.TRUE, amazonSDBClient.selectRequest.getConsistentRead());
assertEquals("TOKEN1", amazonSDBClient.selectRequest.getNextToken());
assertEquals("SELECT NAME1 FROM DOMAIN1 WHERE NAME1 LIKE 'VALUE1'", amazonSDBClient.selectRequest.getSelectExpression());
List<Item> items = exchange.getIn().getHeader(SdbConstants.ITEMS, List.class);
assertEquals("TOKEN2", exchange.getIn().getHeader(SdbConstants.NEXT_TOKEN));
assertEquals(2, items.size());
assertEquals("ITEM1", items.get(0).getName());
assertEquals("ITEM2", items.get(1).getName());
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start")
.to("aws-sdb://TestDomain?amazonSDBClient=#amazonSDBClient&operation=GetAttributes");
}
};
}
} | apache-2.0 |
ralic/closure-compiler | src/com/google/javascript/jscomp/newtypes/RawNominalType.java | 19463 | /*
* Copyright 2013 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.newtypes;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.javascript.jscomp.NodeUtil;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Represents a class or interface as defined in the code.
* If the raw nominal type has a @template, then many nominal types can be
* created from it by instantiation.
*
* @author blickly@google.com (Ben Lickly)
* @author dimvar@google.com (Dimitris Vardoulakis)
*/
public final class RawNominalType extends Namespace {
// The node (if any) that defines the type. Most times it's a function, in
// rare cases it's a call node.
private final Node defSite;
// If true, we can't add more properties to this type.
private boolean isFinalized;
// Each instance of the class has these properties by default
private PersistentMap<String, Property> classProps = PersistentMap.create();
// The object pointed to by the prototype property of the constructor of
// this class has these properties
private PersistentMap<String, Property> protoProps = PersistentMap.create();
// For @unrestricted, we are less strict about inexistent-prop warnings than
// for @struct. We use this map to remember the names of props added outside
// the constructor and the prototype methods.
private PersistentMap<String, Property> randomProps = PersistentMap.create();
// Consider a generic type A<T> which inherits from a generic type B<T>.
// All instantiated A classes, such as A<number>, A<string>, etc,
// have the same superclass and interfaces fields, because they have the
// same raw type. You need to instantiate these fields to get the correct
// type maps, eg, see NominalType#isSubtypeOf.
private NominalType superClass = null;
private ImmutableSet<NominalType> interfaces = null;
private final Kind kind;
// Used in GlobalTypeInfo to find type mismatches in the inheritance chain.
private ImmutableSet<String> allProps = null;
// In GlobalTypeInfo, we request (wrapped) RawNominalTypes in various
// places. Create them here and cache them to save mem.
private final NominalType wrappedAsNominal;
private final JSType wrappedAsJSType;
private final JSType wrappedAsNullableJSType;
// Empty iff this type is not generic
private final ImmutableList<String> typeParameters;
// Not final b/c interfaces that inherit from IObject mutate this during GTI
private ObjectKind objectKind;
private FunctionType ctorFn;
private enum Kind {
CLASS,
INTERFACE,
RECORD
}
private RawNominalType(
Node defSite, String name, ImmutableList<String> typeParameters,
Kind kind, ObjectKind objectKind) {
Preconditions.checkNotNull(objectKind);
Preconditions.checkState(defSite == null || defSite.isFunction()
|| defSite.isCall(), "Expected function or call but found %s",
Token.name(defSite.getType()));
if (typeParameters == null) {
typeParameters = ImmutableList.of();
}
this.name = name;
this.defSite = defSite;
this.typeParameters = typeParameters;
this.kind = kind;
this.objectKind = isBuiltinHelper(name, "IObject", defSite)
? ObjectKind.UNRESTRICTED : objectKind;
this.wrappedAsNominal = new NominalType(ImmutableMap.<String, JSType>of(), this);
ObjectType objInstance;
if (isBuiltinHelper(name, "Function", defSite)) {
objInstance = ObjectType.fromFunction(FunctionType.TOP_FUNCTION, this.wrappedAsNominal);
} else if (isBuiltinHelper(name, "Object", defSite)) {
// We do this to avoid having two instances of ObjectType that both
// represent the top JS object.
objInstance = ObjectType.TOP_OBJECT;
} else {
objInstance = ObjectType.fromNominalType(this.wrappedAsNominal);
}
this.wrappedAsJSType = JSType.fromObjectType(objInstance);
this.wrappedAsNullableJSType = JSType.join(JSType.NULL, this.wrappedAsJSType);
}
public static RawNominalType makeUnrestrictedClass(
Node defSite, String name, ImmutableList<String> typeParameters) {
return new RawNominalType(
defSite, name, typeParameters, Kind.CLASS, ObjectKind.UNRESTRICTED);
}
public static RawNominalType makeStructClass(
Node defSite, String name, ImmutableList<String> typeParameters) {
return new RawNominalType(
defSite, name, typeParameters, Kind.CLASS, ObjectKind.STRUCT);
}
public static RawNominalType makeDictClass(
Node defSite, String name, ImmutableList<String> typeParameters) {
return new RawNominalType(
defSite, name, typeParameters, Kind.CLASS, ObjectKind.DICT);
}
public static RawNominalType makeNominalInterface(
Node defSite, String name, ImmutableList<String> typeParameters) {
// interfaces are struct by default
return new RawNominalType(
defSite, name, typeParameters, Kind.INTERFACE, ObjectKind.STRUCT);
}
public static RawNominalType makeStructuralInterface(
Node defSite, String name, ImmutableList<String> typeParameters) {
// interfaces are struct by default
return new RawNominalType(
defSite, name, typeParameters, Kind.RECORD, ObjectKind.STRUCT);
}
public Node getDefSite() {
return this.defSite;
}
private static boolean isBuiltinHelper(
String nameToCheck, String builtinName, Node defSite) {
return defSite != null && defSite.isFromExterns()
&& nameToCheck.equals(builtinName);
}
boolean isBuiltinWithName(String s) {
return isBuiltinHelper(this.name, s, this.defSite);
}
public boolean isClass() {
return this.kind == Kind.CLASS;
}
public boolean isInterface() {
return this.kind != Kind.CLASS;
}
boolean isStructuralInterface() {
return this.kind == Kind.RECORD;
}
boolean isGeneric() {
return !typeParameters.isEmpty();
}
public boolean isStruct() {
// The objectKind of interfaces can change during GTI.
Preconditions.checkState(isFinalized() || isClass());
return this.objectKind.isStruct();
}
public boolean isDict() {
return this.objectKind.isDict();
}
public boolean isFinalized() {
return this.isFinalized;
}
ImmutableList<String> getTypeParameters() {
return typeParameters;
}
ObjectKind getObjectKind() {
return this.objectKind;
}
public FunctionType getConstructorFunction() {
return this.ctorFn;
}
public void setCtorFunction(FunctionType ctorFn) {
Preconditions.checkState(!this.isFinalized);
this.ctorFn = ctorFn;
}
boolean hasAncestorClass(RawNominalType ancestor) {
Preconditions.checkState(ancestor.isClass());
if (this == ancestor) {
return true;
} else if (this.superClass == null) {
return false;
} else {
return this.superClass.hasAncestorClass(ancestor);
}
}
/** @return Whether the superclass can be added without creating a cycle. */
public boolean addSuperClass(NominalType superClass) {
Preconditions.checkState(!this.isFinalized);
Preconditions.checkState(this.superClass == null);
if (superClass.hasAncestorClass(this)) {
return false;
}
this.superClass = superClass;
return true;
}
boolean hasAncestorInterface(RawNominalType ancestor) {
Preconditions.checkState(ancestor.isInterface());
if (this == ancestor) {
return true;
} else if (this.interfaces == null) {
return false;
} else {
for (NominalType superInter : interfaces) {
if (superInter.hasAncestorInterface(ancestor)) {
return true;
}
}
return false;
}
}
private boolean inheritsFromIObject() {
Preconditions.checkState(!this.isFinalized);
if (isBuiltinWithName("IObject")) {
return true;
}
if (this.interfaces != null) {
for (NominalType interf : this.interfaces) {
if (interf.getRawNominalType().inheritsFromIObject()) {
return true;
}
}
}
return false;
}
/** @return Whether the interface can be added without creating a cycle. */
public boolean addInterfaces(ImmutableSet<NominalType> interfaces) {
Preconditions.checkState(!this.isFinalized);
Preconditions.checkState(this.interfaces == null);
Preconditions.checkNotNull(interfaces);
if (this.isInterface()) {
for (NominalType interf : interfaces) {
if (interf.hasAncestorInterface(this)) {
this.interfaces = ImmutableSet.of();
return false;
}
}
}
// TODO(dimvar): When a class extends a class that inherits from IObject,
// it should be unrestricted.
for (NominalType interf : interfaces) {
if (interf.getRawNominalType().inheritsFromIObject()) {
this.objectKind = ObjectKind.UNRESTRICTED;
}
}
this.interfaces = interfaces;
return true;
}
public NominalType getSuperClass() {
return superClass;
}
public ImmutableSet<NominalType> getInterfaces() {
return this.interfaces == null ? ImmutableSet.<NominalType>of() : this.interfaces;
}
private Property getOwnProp(String pname) {
Property p = classProps.get(pname);
if (p != null) {
return p;
}
p = randomProps.get(pname);
if (p != null) {
return p;
}
return protoProps.get(pname);
}
public JSType getProtoPropDeclaredType(String pname) {
if (this.protoProps.containsKey(pname)) {
Property p = this.protoProps.get(pname);
Node defSite = p.getDefSite();
if (defSite != null && defSite.isGetProp()) {
JSDocInfo jsdoc = NodeUtil.getBestJSDocInfo(defSite);
JSType declType = p.getDeclaredType();
if (declType != null
// Methods have a "declared" type which represents their arity,
// even when they don't have a jsdoc. Don't include that here.
&& (!declType.isFunctionType() || jsdoc != null)) {
return declType;
}
}
}
return null;
}
private Property getPropFromClass(String pname) {
Preconditions.checkState(isClass());
Property p = getOwnProp(pname);
if (p != null) {
return p;
}
if (superClass != null) {
p = superClass.getProp(pname);
if (p != null) {
return p;
}
}
return null;
}
private Property getPropFromInterface(String pname) {
Preconditions.checkState(isInterface());
Property p = getOwnProp(pname);
if (p != null) {
return p;
}
if (interfaces != null) {
for (NominalType interf : interfaces) {
p = interf.getProp(pname);
if (p != null) {
return p;
}
}
}
return null;
}
Property getProp(String pname) {
if (isInterface()) {
return getPropFromInterface(pname);
}
return getPropFromClass(pname);
}
public boolean mayHaveOwnProp(String pname) {
return getOwnProp(pname) != null;
}
public boolean mayHaveProp(String pname) {
return getProp(pname) != null;
}
public JSType getInstancePropDeclaredType(String pname) {
Property p = getProp(pname);
if (p == null) {
return null;
} else if (p.getDeclaredType() == null && superClass != null) {
return superClass.getPropDeclaredType(pname);
}
return p.getDeclaredType();
}
public Set<String> getAllOwnProps() {
Set<String> ownProps = new LinkedHashSet<>();
ownProps.addAll(classProps.keySet());
ownProps.addAll(protoProps.keySet());
return ownProps;
}
ImmutableSet<String> getAllPropsOfInterface() {
if (!this.isFinalized) {
// During GlobalTypeInfo, we sometimes try to check subtyping between
// structural interfaces, but it's not possible because we may have not
// seen all their properties yet.
return null;
}
if (isClass()) {
Preconditions.checkState(this.name.equals("Object"));
return getAllPropsOfClass();
}
if (this.allProps == null) {
ImmutableSet.Builder<String> builder = ImmutableSet.builder();
if (interfaces != null) {
for (NominalType interf : interfaces) {
builder.addAll(interf.getAllPropsOfInterface());
}
}
this.allProps = builder.addAll(protoProps.keySet()).build();
}
return this.allProps;
}
ImmutableSet<String> getAllPropsOfClass() {
Preconditions.checkState(isClass());
Preconditions.checkState(this.isFinalized);
if (this.allProps == null) {
ImmutableSet.Builder<String> builder = ImmutableSet.builder();
if (superClass != null) {
builder.addAll(superClass.getAllPropsOfClass());
}
this.allProps = builder.addAll(classProps.keySet())
.addAll(protoProps.keySet()).build();
}
return this.allProps;
}
public void addPropertyWhichMayNotBeOnAllInstances(String pname, JSType type) {
Preconditions.checkState(!this.isFinalized);
if (this.classProps.containsKey(pname) || this.protoProps.containsKey(pname)) {
return;
}
if (this.objectKind == ObjectKind.UNRESTRICTED) {
this.randomProps = this.randomProps.with(
pname, Property.make(type == null ? JSType.UNKNOWN : type, type));
}
}
//////////// Class Properties
/** Add a new non-optional declared property to instances of this class */
public void addClassProperty(String pname, Node defSite, JSType type, boolean isConstant) {
Preconditions.checkState(!this.isFinalized);
if (type == null && isConstant) {
type = JSType.UNKNOWN;
}
this.classProps = this.classProps.with(pname, isConstant
? Property.makeConstant(defSite, type, type)
: Property.makeWithDefsite(defSite, type, type));
// Upgrade any proto props to declared, if present
if (this.protoProps.containsKey(pname)) {
addProtoProperty(pname, defSite, type, isConstant);
}
if (this.randomProps.containsKey(pname)) {
this.randomProps = this.randomProps.without(pname);
}
}
/** Add a new undeclared property to instances of this class */
public void addUndeclaredClassProperty(String pname, JSType type, Node defSite) {
Preconditions.checkState(!this.isFinalized);
// Only do so if there isn't a declared prop already.
if (mayHaveProp(pname)) {
return;
}
classProps = classProps.with(pname, Property.makeWithDefsite(defSite, type, null));
}
//////////// Prototype Properties
/** Add a new declared prototype property to this class */
public void addProtoProperty(String pname, Node defSite, JSType type, boolean isConstant) {
Preconditions.checkState(!this.isFinalized);
if (type == null && isConstant) {
type = JSType.UNKNOWN;
}
if (this.classProps.containsKey(pname)
&& this.classProps.get(pname).getDeclaredType() == null) {
this.classProps = this.classProps.without(pname);
}
if (this.randomProps.containsKey(pname)) {
this.randomProps = this.randomProps.without(pname);
}
Property newProp;
if (isConstant) {
newProp = Property.makeConstant(defSite, type, type);
} else if (isStructuralInterface() && type != null
&& !type.isUnknown() && JSType.UNDEFINED.isSubtypeOf(type)) {
// TODO(dimvar): Handle optional properties on @record of unknown type.
// See how we do it in jstypecreatorfromjsdoc.
newProp = Property.makeOptional(defSite, type, type);
} else {
newProp = Property.makeWithDefsite(defSite, type, type);
}
this.protoProps = this.protoProps.with(pname, newProp);
}
/** Add a new undeclared prototype property to this class */
public void addUndeclaredProtoProperty(String pname, Node defSite) {
Preconditions.checkState(!this.isFinalized);
if (!this.protoProps.containsKey(pname)
|| this.protoProps.get(pname).getDeclaredType() == null) {
this.protoProps = this.protoProps.with(pname,
Property.makeWithDefsite(defSite, JSType.UNKNOWN, null));
if (this.randomProps.containsKey(pname)) {
this.randomProps = this.randomProps.without(pname);
}
}
}
//////////// Constructor Properties
public boolean hasCtorProp(String pname) {
return super.hasProp(pname);
}
/** Add a new non-optional declared property to this class's constructor */
public void addCtorProperty(String pname, Node defSite, JSType type, boolean isConstant) {
Preconditions.checkState(!this.isFinalized);
super.addProperty(pname, defSite, type, isConstant);
}
/** Add a new undeclared property to this class's constructor */
public void addUndeclaredCtorProperty(String pname, Node defSite) {
Preconditions.checkState(!this.isFinalized);
super.addUndeclaredProperty(pname, defSite, JSType.UNKNOWN, false);
}
public JSType getCtorPropDeclaredType(String pname) {
return super.getPropDeclaredType(pname);
}
@Override
public void finalize() {
Preconditions.checkState(!this.isFinalized);
Preconditions.checkNotNull(this.ctorFn);
if (this.interfaces == null) {
this.interfaces = ImmutableSet.of();
}
JSType protoObject = JSType.fromObjectType(ObjectType.makeObjectType(
this.superClass, this.protoProps,
null, null, false, ObjectKind.UNRESTRICTED));
addCtorProperty("prototype", null, protoObject, false);
this.isFinalized = true;
}
StringBuilder appendTo(StringBuilder builder) {
builder.append(name);
if (!this.typeParameters.isEmpty()) {
builder.append("<" + Joiner.on(",").join(this.typeParameters) + ">");
}
return builder;
}
@Override
public String toString() {
return appendTo(new StringBuilder()).toString();
}
@Override
protected JSType computeJSType(JSTypes commonTypes) {
Preconditions.checkState(this.isFinalized);
Preconditions.checkState(this.namespaceType == null);
return JSType.fromObjectType(ObjectType.makeObjectType(
commonTypes.getFunctionType(), null, ctorFn,
this, ctorFn.isLoose(), ObjectKind.UNRESTRICTED));
}
public NominalType getAsNominalType() {
return this.wrappedAsNominal;
}
// Don't confuse with the toJSType method, inherited from Namespace.
// The namespace is represented by the constructor, so that method wraps the
// constructor in a JSType, and this method wraps the instance.
public JSType getInstanceAsJSType() {
return wrappedAsJSType;
}
public JSType getInstanceWithNullability(boolean includeNull) {
return includeNull ? wrappedAsNullableJSType : wrappedAsJSType;
}
// equals and hashCode default to reference equality, which is what we want
}
| apache-2.0 |
yihongyuelan/DesignBox | libtreelist/src/main/java/com/seven/treelist/view/AndroidTreeView.java | 10140 | package com.seven.treelist.view;
import android.content.Context;
import android.text.TextUtils;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import com.seven.treelist.R;
import com.seven.treelist.holder.SimpleViewHolder;
import com.seven.treelist.model.TreeNode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class AndroidTreeView {
private static final String NODES_PATH_SEPARATOR = ";";
protected TreeNode mRoot;
private Context mContext;
private boolean applyForRoot;
private int containerStyle = 0;
private Class<? extends TreeNode.BaseNodeViewHolder> defaultViewHolderClass = SimpleViewHolder.class;
private TreeNode.TreeNodeClickListener nodeClickListener;
private TreeNode.TreeNodeLongClickListener nodeLongClickListener;
private boolean mUseDefaultAnimation = false;
private boolean enableAutoToggle = true;
public AndroidTreeView(Context context, TreeNode root) {
mRoot = root;
mContext = context;
}
//Added by Seven for default style
public void setDefaultContainerStyle() {
setDefaultContainerStyle(R.style.TreeNodeStyle, false);
}
public void setDefaultNodeClickListener(TreeNode.TreeNodeClickListener listener) {
nodeClickListener = listener;
}
public void setDefaultNodeLongClickListener(TreeNode.TreeNodeLongClickListener listener) {
nodeLongClickListener = listener;
}
public void setDefaultContainerStyle(int style, boolean applyForRoot) {
containerStyle = style;
this.applyForRoot = applyForRoot;
}
public void collapseAll() {
for (TreeNode n : mRoot.getChildren()) {
collapseNode(n, true);
}
}
public View getView(int style) {
final ViewGroup view;
if (style > 0) {
ContextThemeWrapper newContext = new ContextThemeWrapper(mContext, style);
view = new ScrollView(newContext);
} else {
view = new ScrollView(mContext);
}
Context containerContext = mContext;
if (containerStyle != 0 && applyForRoot) {
containerContext = new ContextThemeWrapper(mContext, containerStyle);
}
final LinearLayout viewTreeItems = new LinearLayout(containerContext, null, containerStyle);
viewTreeItems.setId(R.id.tree_items);
viewTreeItems.setOrientation(LinearLayout.VERTICAL);
view.addView(viewTreeItems);
mRoot.setViewHolder(new TreeNode.BaseNodeViewHolder(mContext) {
@Override
public View createNodeView(TreeNode node, Object value) {
return null;
}
@Override
public ViewGroup getNodeItemsView() {
return viewTreeItems;
}
});
expandNode(mRoot, false);
return view;
}
public View getView() {
return getView(-1);
}
public void expandNode(TreeNode node) {
expandNode(node, false);
}
public String getSaveState() {
final StringBuilder builder = new StringBuilder();
getSaveState(mRoot, builder);
if (builder.length() > 0) {
builder.setLength(builder.length() - 1);
}
return builder.toString();
}
public void restoreState(String saveState) {
if (!TextUtils.isEmpty(saveState)) {
collapseAll();
final String[] openNodesArray = saveState.split(NODES_PATH_SEPARATOR);
final Set<String> openNodes = new HashSet<>(Arrays.asList(openNodesArray));
restoreNodeState(mRoot, openNodes);
}
}
private void restoreNodeState(TreeNode node, Set<String> openNodes) {
for (TreeNode n : node.getChildren()) {
if (openNodes.contains(n.getPath())) {
expandNode(n);
restoreNodeState(n, openNodes);
}
}
}
private void getSaveState(TreeNode root, StringBuilder sBuilder) {
for (TreeNode node : root.getChildren()) {
if (node.isExpanded()) {
sBuilder.append(node.getPath());
sBuilder.append(NODES_PATH_SEPARATOR);
getSaveState(node, sBuilder);
}
}
}
public void toggleNode(TreeNode node) {
if (node.isExpanded()) {
collapseNode(node, false);
} else {
expandNode(node, false);
}
}
private void collapseNode(TreeNode node, final boolean includeSubnodes) {
node.setExpanded(false);
TreeNode.BaseNodeViewHolder nodeViewHolder = getViewHolderForNode(node);
if (mUseDefaultAnimation) {
collapse(nodeViewHolder.getNodeItemsView());
} else {
nodeViewHolder.getNodeItemsView().setVisibility(View.GONE);
}
nodeViewHolder.toggle(false);
if (includeSubnodes) {
for (TreeNode n : node.getChildren()) {
collapseNode(n, includeSubnodes);
}
}
}
private void expandNode(final TreeNode node, boolean includeSubnodes) {
node.setExpanded(true);
final TreeNode.BaseNodeViewHolder parentViewHolder = getViewHolderForNode(node);
parentViewHolder.getNodeItemsView().removeAllViews();
parentViewHolder.toggle(true);
for (final TreeNode n : node.getChildren()) {
addNode(parentViewHolder.getNodeItemsView(), n);
if (n.isExpanded() || includeSubnodes) {
expandNode(n, includeSubnodes);
}
}
if (mUseDefaultAnimation) {
expand(parentViewHolder.getNodeItemsView());
} else {
parentViewHolder.getNodeItemsView().setVisibility(View.VISIBLE);
}
}
private void addNode(ViewGroup container, final TreeNode n) {
final TreeNode.BaseNodeViewHolder viewHolder = getViewHolderForNode(n);
final View nodeView = viewHolder.getView();
container.addView(nodeView);
nodeView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (n.getClickListener() != null) {
n.getClickListener().onClick(n, n.getValue());
} else if (nodeClickListener != null) {
nodeClickListener.onClick(n, n.getValue());
}
if (enableAutoToggle) {
toggleNode(n);
}
}
});
nodeView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
if (n.getLongClickListener() != null) {
return n.getLongClickListener().onLongClick(n, n.getValue());
} else if (nodeLongClickListener != null) {
return nodeLongClickListener.onLongClick(n, n.getValue());
}
if (enableAutoToggle) {
toggleNode(n);
}
return false;
}
});
}
private TreeNode.BaseNodeViewHolder getViewHolderForNode(TreeNode node) {
TreeNode.BaseNodeViewHolder viewHolder = node.getViewHolder();
if (viewHolder == null) {
try {
final Object object = defaultViewHolderClass.getConstructor(Context.class).newInstance(mContext);
viewHolder = (TreeNode.BaseNodeViewHolder) object;
node.setViewHolder(viewHolder);
} catch (Exception e) {
throw new RuntimeException("Could not instantiate class " + defaultViewHolderClass);
}
}
if (viewHolder.getContainerStyle() <= 0) {
viewHolder.setContainerStyle(containerStyle);
}
if (viewHolder.getTreeView() == null) {
viewHolder.setTreeViev(this);
}
return viewHolder;
}
private static void expand(final View v) {
v.measure(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
// final int targetHeight = v.getMeasuredHeight();
//getHeight always return 0
final int targetHeight = v.getHeight();
v.getLayoutParams().height = 0;
v.setVisibility(View.VISIBLE);
Animation a = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
v.getLayoutParams().height = interpolatedTime == 1
? LinearLayout.LayoutParams.WRAP_CONTENT
: (int) (targetHeight * interpolatedTime);
v.requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
};
// 1dp/ms
a.setDuration((int) (targetHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
private static void collapse(final View v) {
final int initialHeight = v.getMeasuredHeight();
Animation a = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if (interpolatedTime == 1) {
v.setVisibility(View.GONE);
} else {
v.getLayoutParams().height = initialHeight - (int) (initialHeight * interpolatedTime);
v.requestLayout();
}
}
@Override
public boolean willChangeBounds() {
return true;
}
};
// 1dp/ms
a.setDuration((int) (initialHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
}
| apache-2.0 |
scottkurz/sample.async.websockets | async-websocket-application/src/main/java/net/wasdev/websocket/EndpointApplicationConfig.java | 3216 | package net.wasdev.websocket;
import java.util.HashSet;
import java.util.Set;
import javax.websocket.Endpoint;
import javax.websocket.server.ServerApplicationConfig;
import javax.websocket.server.ServerEndpointConfig;
/**
* The WebSocket runtime will scan the war for implementations of
* {@link ServerApplicationConfig}. It will register/deploy programmatic Endpoints
* returned from {@link #getEndpointConfigs(Set)}, and annotated Endpoints returned
* from {@link #getAnnotatedEndpointClasses(Set).
* <p>
* The following quotes from the official javadoc, to help with context.
* </p><p>
* If you have no programmatic endpoints, you don't have to provide an instance of this
* this class. You could use this to filter the annotated classes you want to return
* (as an example).
*
* @see ServerEndpointConfig.Builder
* @see ServerEndpointConfig.Configurator
*/
public class EndpointApplicationConfig implements ServerApplicationConfig {
/**
* If you define one of these (which you have to for programmatic
* endpoints), and have a mix of annotated and programmatic endpoints (which
* this example does), make sure you return classes with annotations
* here!
*
* @param scanned
* the set of all the annotated endpoint classes in the archive
* containing the implementation of this interface.
* @return the non-null set of annotated endpoint classes to deploy on the
* server, using the empty set to indicate none.
* @see ServerApplicationConfig#getAnnotatedEndpointClasses(Set)
*/
@Override
public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned) {
System.out.println(scanned);
return scanned;
}
/**
* Create configurations for programmatic endpoints that should be
* deployed.
* <p>
* The string value passed to the {@link ServerEndpointConfig.Builder}
* is the URI relative to your app’s context root, similar to the
* value provided in the @ServerEndpoint annotation, e.g. the context
* root for this example application is <code>websocket</code>, and the string
* provided to build the {@link ServerEndpointConfig} is <code>/ProgrammaticEndpoint</code>,
* which makes the WebSocket URL used to reach the endpoint
* <code>ws://localhost/websocket/ProgrammaticEndpoint</code>.
* </p><p>
* The ServerEndpointConfig can also be used to configure additional
* protocols, and extensions.
* </p>
*
* @param endpointClasses
* the set of all the Endpoint classes in the archive containing
* the implementation of this interface.
* @return the non-null set of ServerEndpointConfigs to deploy on the
* server, using the empty set to indicate none.
* @see ServerApplicationConfig#getEndpointConfigs(Set)
* @see ServerEndpointConfig.Builder#create(Class, String)
*/
@Override
public Set<ServerEndpointConfig> getEndpointConfigs(
Set<Class<? extends Endpoint>> endpointClasses) {
System.out.println(endpointClasses);
HashSet<ServerEndpointConfig> set = new HashSet<ServerEndpointConfig>();
set.add(ServerEndpointConfig.Builder.create(ProgrammaticEndpoint.class,
"/ProgrammaticEndpoint").build());
return set;
}
}
| apache-2.0 |
DuncanDoyle/jbpm | jbpm-bpmn2/src/test/java/org/jbpm/process/audit/command/AuditCommandsTest.java | 6637 | /*
* 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.jbpm.process.audit.command;
import java.util.List;
import org.drools.core.impl.EnvironmentFactory;
import org.jbpm.bpmn2.JbpmBpmn2TestCase;
import org.jbpm.bpmn2.objects.TestWorkItemHandler;
import org.jbpm.process.audit.AuditLogService;
import org.jbpm.process.audit.JPAAuditLogService;
import org.jbpm.process.audit.NodeInstanceLog;
import org.jbpm.process.audit.ProcessInstanceLog;
import org.jbpm.process.audit.VariableInstanceLog;
import org.jbpm.process.instance.impl.demo.SystemOutWorkItemHandler;
import org.junit.BeforeClass;
import org.junit.Test;
import org.kie.api.KieBase;
import org.kie.api.command.Command;
import org.kie.api.runtime.Environment;
import org.kie.api.runtime.EnvironmentName;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.runtime.process.WorkItem;
public class AuditCommandsTest extends JbpmBpmn2TestCase {
public AuditCommandsTest() {
super(true);
}
private static AuditLogService logService;
@BeforeClass
public static void setup() throws Exception {
setUpDataSource();
// clear logs
Environment env = EnvironmentFactory.newEnvironment();
env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf);
logService = new JPAAuditLogService(env);
logService.clear();
}
@Test
public void testFindProcessInstanceCommands() throws Exception {
String processId = "IntermediateCatchEvent";
KieBase kbase = createKnowledgeBase("BPMN2-IntermediateCatchEventSignal.bpmn2");
KieSession ksession = createKnowledgeSession(kbase);
ksession.getWorkItemManager().registerWorkItemHandler("Human Task", new SystemOutWorkItemHandler());
ProcessInstance processInstance = ksession.startProcess(processId);
assertTrue(processInstance.getState() == ProcessInstance.STATE_ACTIVE);
Command<?> cmd = new FindProcessInstancesCommand();
Object result = ksession.execute(cmd);
assertNotNull( "Command result is empty!", result );
assertTrue( result instanceof List );
List<ProcessInstanceLog> logList = (List<ProcessInstanceLog>) result;
assertEquals( "Log list size is incorrect.", 1, logList.size() );
ProcessInstanceLog log = logList.get(0);
assertEquals(log.getProcessInstanceId().longValue(), processInstance.getId());
assertEquals(log.getProcessId(), processInstance.getProcessId());
cmd = new FindActiveProcessInstancesCommand(processId);
result = ksession.execute(cmd);
assertNotNull( "Command result is empty!", result );
assertTrue( result instanceof List );
logList = (List<ProcessInstanceLog>) result;
assertEquals( "Log list size is incorrect.", 1, logList.size() );
log = logList.get(0);
assertEquals("Process instance id", log.getProcessInstanceId().longValue(), processInstance.getId());
assertEquals("Process id", log.getProcessId(), processInstance.getProcessId());
assertEquals("Status", log.getStatus().intValue(), ProcessInstance.STATE_ACTIVE );
cmd = new FindProcessInstanceCommand(processInstance.getId());
result = ksession.execute(cmd);
assertNotNull( "Command result is empty!", result );
assertTrue( result instanceof ProcessInstanceLog );
log = (ProcessInstanceLog) result;
assertEquals(log.getProcessInstanceId().longValue(), processInstance.getId());
assertEquals(log.getProcessId(), processInstance.getProcessId());
// now signal process instance
ksession = restoreSession(ksession, true);
ksession.signalEvent("MyMessage", "SomeValue", processInstance.getId());
assertProcessInstanceCompleted(processInstance.getId(), ksession);
cmd = new ClearHistoryLogsCommand();
result = ksession.execute(cmd);
assertEquals( "There should be no more logs", 0, logService.findProcessInstances().size() );
}
@Test
public void testVarAndNodeInstanceCommands() throws Exception {
KieBase kbase = createKnowledgeBase("BPMN2-SubProcessUserTask.bpmn2");
KieSession ksession = createKnowledgeSession(kbase);
TestWorkItemHandler workItemHandler = new TestWorkItemHandler();
ksession.getWorkItemManager().registerWorkItemHandler("Human Task", workItemHandler);
ProcessInstance processInstance = ksession.startProcess("SubProcess");
assertProcessInstanceActive(processInstance);
Command<?> cmd = new FindNodeInstancesCommand(processInstance.getId());
Object result = ksession.execute(cmd);
assertNotNull( "Command result is empty!", result );
assertTrue( result instanceof List );
List<NodeInstanceLog> nodeLogList = (List<NodeInstanceLog>) result;
assertEquals( "Log list size is incorrect.", 8, nodeLogList.size() );
cmd = new FindNodeInstancesCommand(processInstance.getId(), "UserTask_1");
result = ksession.execute(cmd);
assertNotNull( "Command result is empty!", result );
assertTrue( result instanceof List );
nodeLogList = (List<NodeInstanceLog>) result;
assertEquals( "Log list size is incorrect.", 1, nodeLogList.size() );
cmd = new FindVariableInstancesCommand(processInstance.getId(), "2:x");
result = ksession.execute(cmd);
assertNotNull( "Command result is empty!", result );
assertTrue( result instanceof List );
List<VariableInstanceLog> varLogList = (List<VariableInstanceLog>) result;
assertEquals( "Log list size is incorrect.", 1, varLogList.size() );
WorkItem workItem = workItemHandler.getWorkItem();
assertNotNull(workItem);
ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
assertProcessInstanceFinished(processInstance, ksession);
}
}
| apache-2.0 |
mayonghui2112/helloWorld | sourceCode/apache-tomcat-7.0.82-src/java/org/apache/naming/resources/ConcurrentDateFormat.java | 2907 | /*
* 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.naming.resources;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Queue;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* A thread safe wrapper around {@link SimpleDateFormat} that does not make use
* of ThreadLocal and - broadly - only creates enough SimpleDateFormat objects
* to satisfy the concurrency requirements.
*/
public class ConcurrentDateFormat {
private final String format;
private final Locale locale;
private final TimeZone timezone;
private final Queue<SimpleDateFormat> queue = new ConcurrentLinkedQueue<SimpleDateFormat>();
public static final String RFC1123_DATE = "EEE, dd MMM yyyy HH:mm:ss zzz";
public static final TimeZone GMT = TimeZone.getTimeZone("GMT");
private static final ConcurrentDateFormat FORMAT_RFC1123;
static {
FORMAT_RFC1123 = new ConcurrentDateFormat(RFC1123_DATE, Locale.US, GMT);
}
public static String formatRfc1123(Date date) {
return FORMAT_RFC1123.format(date);
}
public ConcurrentDateFormat(String format, Locale locale,
TimeZone timezone) {
this.format = format;
this.locale = locale;
this.timezone = timezone;
SimpleDateFormat initial = createInstance();
queue.add(initial);
}
public String format(Date date) {
SimpleDateFormat sdf = queue.poll();
if (sdf == null) {
sdf = createInstance();
}
String result = sdf.format(date);
queue.add(sdf);
return result;
}
public Date parse(String source) throws ParseException {
SimpleDateFormat sdf = queue.poll();
if (sdf == null) {
sdf = createInstance();
}
Date result = sdf.parse(source);
queue.add(sdf);
return result;
}
private SimpleDateFormat createInstance() {
SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
sdf.setTimeZone(timezone);
return sdf;
}
}
| apache-2.0 |
JavaMicroService/rapidpm-microservice | modules/core/src/main/java/org/rapidpm/microservice/rest/ddi/PoJoDDIRessourceFactory.java | 3258 | /**
* Copyright © 2013 Sven Ruppert (sven.ruppert@gmail.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 org.rapidpm.microservice.rest.ddi;
import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
import org.jboss.resteasy.spi.ConstructorInjector;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.HttpResponse;
import org.jboss.resteasy.spi.PropertyInjector;
import org.jboss.resteasy.spi.ResourceFactory;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.jboss.resteasy.spi.metadata.ResourceBuilder;
import org.jboss.resteasy.spi.metadata.ResourceClass;
import org.jboss.resteasy.spi.metadata.ResourceConstructor;
import org.rapidpm.ddi.DI;
/**
*
*/
public class PoJoDDIRessourceFactory implements ResourceFactory {
private final Class<?> scannableClass;
private final ResourceClass resourceClass;
private ConstructorInjector constructorInjector;
private PropertyInjector propertyInjector;
public PoJoDDIRessourceFactory(Class<?> scannableClass) {
this.scannableClass = scannableClass;
this.resourceClass = ResourceBuilder.rootResourceFromAnnotations(scannableClass);
}
// public PoJoDDIRessourceFactory(ResourceClass resourceClass) {
// this.scannableClass = resourceClass.getClazz();
// this.resourceClass = resourceClass;
// }
public void registered(ResteasyProviderFactory factory) {
System.out.println("registered - factory = " + factory);
ResourceConstructor constructor = this.resourceClass.getConstructor();
if (constructor == null) {
final Class<?> clazz = this.resourceClass.getClazz();
final Class<?> aClass = DI.getSubTypesWithoutInterfacesAndGeneratedOf(clazz).stream().findFirst().get();
constructor = ResourceBuilder.constructor(aClass);
}
//
if (constructor == null) {
throw new RuntimeException(Messages.MESSAGES.unableToFindPublicConstructorForClass(this.scannableClass.getName()));
} else {
this.constructorInjector = factory.getInjectorFactory().createConstructor(constructor , factory);
this.propertyInjector = factory.getInjectorFactory().createPropertyInjector(this.resourceClass , factory);
}
}
public Object createResource(HttpRequest request , HttpResponse response , ResteasyProviderFactory factory) {
// Object obj = this.constructorInjector.construct(request , response);
// this.propertyInjector.inject(request , response , obj);
// return obj;
return DI.activateDI(scannableClass);
}
public void unregistered() {
}
public Class<?> getScannableClass() {
return this.scannableClass;
}
public void requestFinished(HttpRequest request , HttpResponse response , Object resource) {
}
} | apache-2.0 |
claudiu-stanciu/kylo | services/operational-metadata-service/operational-metadata-integration-service/src/main/java/com/thinkbiganalytics/metadata/jobrepo/nifi/provenance/RetryProvenanceEventRecordHolder.java | 2025 | package com.thinkbiganalytics.metadata.jobrepo.nifi.provenance;
/*-
* #%L
* thinkbig-operational-metadata-integration-service
* %%
* Copyright (C) 2017 ThinkBig Analytics
* %%
* 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.
* #L%
*/
import com.thinkbiganalytics.nifi.provenance.model.ProvenanceEventRecordDTOHolder;
import org.joda.time.DateTime;
/**
* Created by sr186054 on 11/2/17.
*/
public class RetryProvenanceEventRecordHolder extends ProvenanceEventRecordDTOHolder {
private RetryAttempt retryAttempt;
public RetryProvenanceEventRecordHolder(Integer maxRetries) {
super();
retryAttempt = new RetryAttempt(maxRetries);
}
public boolean shouldRetry() {
return this.retryAttempt.shouldRetry();
}
public void incrementRetryAttempt() {
this.retryAttempt.incrementRetryAttempt();
}
public void setLastRetryTime(DateTime lastRetryTime) {
this.retryAttempt.setLastRetryTime(lastRetryTime);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof RetryProvenanceEventRecordHolder)) {
return false;
}
RetryProvenanceEventRecordHolder that = (RetryProvenanceEventRecordHolder) o;
return getBatchId() != null ? getBatchId().equals(that.getBatchId()) : that.getBatchId() == null;
}
@Override
public int hashCode() {
return getBatchId() != null ? getBatchId().hashCode() : 0;
}
}
| apache-2.0 |
WANdisco/gerrit | gerrit-gwtui/src/main/java/com/google/gerrit/client/ui/BranchLink.java | 2739 | // Copyright (C) 2009 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.gerrit.client.ui;
import com.google.gerrit.client.Gerrit;
import com.google.gerrit.client.changes.QueryScreen;
import com.google.gerrit.common.PageLinks;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.client.RefNames;
/** Link to the open changes of a project. */
public class BranchLink extends InlineHyperlink {
private final String query;
public BranchLink(Project.NameKey project, Change.Status status, String branch, String topic) {
this(text(branch, topic), query(project, status, branch, topic));
}
public BranchLink(
String text, Project.NameKey project, Change.Status status, String branch, String topic) {
this(text, query(project, status, branch, topic));
}
private BranchLink(String text, String query) {
super(text, PageLinks.toChangeQuery(query));
this.query = query;
}
@Override
public void go() {
Gerrit.display(getTargetHistoryToken(), createScreen());
}
private Screen createScreen() {
return QueryScreen.forQuery(query);
}
private static String text(String branch, String topic) {
if (topic != null && !topic.isEmpty()) {
return branch + " (" + topic + ")";
}
return branch;
}
public static String query(
Project.NameKey project, Change.Status status, String branch, String topic) {
String query = PageLinks.projectQuery(project, status);
if (branch.startsWith(RefNames.REFS)) {
if (branch.startsWith(RefNames.REFS_HEADS)) {
query +=
" "
+ PageLinks.op(
"branch", //
branch.substring(RefNames.REFS_HEADS.length()));
} else {
query += " " + PageLinks.op("ref", branch);
}
} else {
// Assume it was clipped already by the caller. This
// happens for example inside of the ChangeInfo object.
//
query += " " + PageLinks.op("branch", branch);
}
if (topic != null && !topic.isEmpty()) {
query += " " + PageLinks.op("topic", topic);
}
return query;
}
}
| apache-2.0 |
creaITve/apps-android-tbrc-works | wikipedia/src/main/java/org/wikipedia/page/PageActionsHandler.java | 4096 | package org.wikipedia.page;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import com.squareup.otto.Bus;
import com.squareup.otto.Subscribe;
import org.wikipedia.R;
import org.wikipedia.WikipediaApp;
import org.wikipedia.events.*;
public class PageActionsHandler implements PopupMenu.OnMenuItemClickListener {
private final PopupMenu menu;
private final Bus bus;
private final DrawerLayout navDrawer;
public PageActionsHandler(final Bus bus, final PopupMenu menu, final View trigger, final DrawerLayout navDrawer) {
this.menu = menu;
this.bus = bus;
this.navDrawer = navDrawer;
menu.getMenuInflater().inflate(R.menu.menu_page_actions, menu.getMenu());
menu.setOnMenuItemClickListener(this);
bus.register(this);
trigger.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (navDrawer.isDrawerOpen(Gravity.START)) {
navDrawer.closeDrawer(Gravity.START);
}
menu.show();
}
});
}
public void onDestroy() {
bus.unregister(this);
}
@Subscribe
public void onOverflowMenuChange(OverflowMenuUpdateEvent event) {
switch (event.getState()) {
case PageViewFragment.STATE_NO_FETCH:
case PageViewFragment.STATE_INITIAL_FETCH:
menu.getMenu().findItem(R.id.menu_save_page).setEnabled(false);
menu.getMenu().findItem(R.id.menu_share_page).setEnabled(false);
menu.getMenu().findItem(R.id.menu_other_languages).setEnabled(false);
menu.getMenu().findItem(R.id.menu_find_in_page).setEnabled(false);
menu.getMenu().findItem(R.id.menu_themechooser).setEnabled(false);
break;
case PageViewFragment.STATE_COMPLETE_FETCH:
menu.getMenu().findItem(R.id.menu_save_page).setEnabled(true);
menu.getMenu().findItem(R.id.menu_share_page).setEnabled(true);
menu.getMenu().findItem(R.id.menu_other_languages).setEnabled(true);
menu.getMenu().findItem(R.id.menu_find_in_page).setEnabled(true);
menu.getMenu().findItem(R.id.menu_themechooser).setEnabled(true);
if (event.getSubstate() == PageViewFragment.SUBSTATE_PAGE_SAVED) {
menu.getMenu().findItem(R.id.menu_save_page).setEnabled(false);
menu.getMenu().findItem(R.id.menu_save_page).setTitle(WikipediaApp.getInstance().getString(R.string.menu_page_saved));
} else if (event.getSubstate() == PageViewFragment.SUBSTATE_SAVED_PAGE_LOADED) {
menu.getMenu().findItem(R.id.menu_save_page).setTitle(WikipediaApp.getInstance().getString(R.string.menu_refresh_saved_page));
} else {
menu.getMenu().findItem(R.id.menu_save_page).setTitle(WikipediaApp.getInstance().getString(R.string.menu_save_page));
}
break;
default:
// How can this happen?!
throw new RuntimeException("This can't happen");
}
}
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_save_page:
bus.post(new SavePageEvent());
break;
case R.id.menu_share_page:
bus.post(new SharePageEvent());
break;
case R.id.menu_other_languages:
bus.post(new ShowOtherLanguagesEvent());
break;
case R.id.menu_find_in_page:
bus.post(new FindInPageEvent());
break;
case R.id.menu_themechooser:
bus.post(new ShowThemeChooserEvent());
break;
default:
throw new RuntimeException("Unexpected menu item clicked");
}
return false;
}
}
| apache-2.0 |
apache/juddi | juddi-gui-dsig/src/main/java/org/apache/juddi/gui/dsig/XmlSigApplet2.java | 27503 | /*
* Copyright 2013 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.juddi.gui.dsig;
import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.xml.bind.JAXB;
import netscape.javascript.JSObject;
import org.apache.juddi.v3.client.cryptor.DigSigUtil;
import org.apache.juddi.v3.client.cryptor.XmlUtils;
import org.uddi.api_v3.BindingTemplate;
import org.uddi.api_v3.BusinessEntity;
import org.uddi.api_v3.BusinessService;
import org.uddi.api_v3.TModel;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;
/**
* This is the current Digital Signature Applet used by juddi-gui. It can easily
* be adapted to sign any xml document
*
* @author <a href="mailto:alexoree@apache.org>Alex O'Ree</a>
*/
public class XmlSigApplet2 extends java.applet.Applet {
private static final long serialVersionUID = 1L;
/**
* Initializes the applet XmlSigApplet2
*/
@Override
public void init() {
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
setupCertificates();
}
/**
* this converts a xml document to a string for writing back to the browser
*
* @param doc
* @return string
*/
public String getStringFromDoc(org.w3c.dom.Document doc) {
DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
lsSerializer.getDomConfig().setParameter("xml-declaration", false);
//lsSerializer.getDomConfig().setParameter("xml-declaration", false);
return lsSerializer.writeToString(doc);
}
KeyStore keyStore = null;
KeyStore firefox = null;
private void setupCertificates() {
this.jList1.clearSelection();
this.jList1.removeAll();
Vector<String> certs = new Vector<String>();
String keyStoreError = "";
//covers all modern browsers in windows
if (System.getProperty("os.name").startsWith("Windows")) {
try {
keyStore = KeyStore.getInstance("Windows-MY");
keyStore.load(null, null);
} catch (Exception ex) {
keyStoreError += "Error loading Windows cert store " + ex.getMessage() + "\n";
//ex.printStackTrace();
//JOptionPane.showMessageDialog(this, ex.getMessage());
}
}
//firefox keystore
if (keyStore == null) {
try {
String strCfg = System.getProperty("user.home") + File.separator
+ "jdk6-nss-mozilla.cfg";
// Provider p1 = new sun.security.pkcs11.SunPKCS11(strCfg);
// Security.addProvider(p1);
keyStore = KeyStore.getInstance("PKCS11");
keyStore.load(null, "password".toCharArray());
} catch (Exception ex) {
//JOptionPane.showMessageDialog(this, ex.getMessage());
keyStoreError += "Error loading Firefox cert store " + ex.getMessage() + "\n";
//ex.printStackTrace();
}
}
//MacOS with Safari possibly others
if (keyStore == null) {
try {
keyStore = KeyStore.getInstance("KeychainStore");
keyStore.load(null, null);
} catch (Exception ex) {
//JOptionPane.showMessageDialog(this, ex.getMessage());
//ex.printStackTrace();
keyStoreError += "Error loading MACOS Key chain cert store " + ex.getMessage() + "\n";
}
}
if (keyStore == null) {
System.err.println(keyStoreError);
jTextArea1.setText(keyStoreError);
jTabbedPane1.setSelectedIndex(2);
} else {
try {
Enumeration<String> aliases = keyStore.aliases();
while (aliases.hasMoreElements()) {
String a = aliases.nextElement();
X509Certificate certificate = (X509Certificate) keyStore.getCertificate(a);
//this is needed to test for access
try {
char[] cp = jPasswordField1.getPassword();
if (cp != null && cp.length <= 0) {
cp = null;
}
if (cp != null) {
String s = new String(cp);
s = s.trim();
if ("".equalsIgnoreCase(s)) {
cp = null;
}
}
Key key = keyStore.getKey(a, cp);
certs.add(a);
} catch (Exception x) {
System.out.println("error loading certificate " + a + " " + x.getMessage());
}
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, e.getMessage());
}
}
jList1.setListData(certs);
if (!certs.isEmpty()) {
jList1.setSelectedIndex(0);
}
}
/**
* This method is called from within the init() method to initialize the
* form. WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel3 = new javax.swing.JPanel();
jButton3 = new javax.swing.JButton();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
jButton2 = new javax.swing.JButton();
jLabel5 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
isIncludeSubjectName = new javax.swing.JCheckBox();
isIncludePublicKey = new javax.swing.JCheckBox();
isIncludeIssuer = new javax.swing.JCheckBox();
jLabel2 = new javax.swing.JLabel();
jTextFieldSigMethod = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jTextFieldDigestMethod = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jTextFieldc14n = new javax.swing.JTextField();
jPanel4 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jPanel5 = new javax.swing.JPanel();
jToggleButton1 = new javax.swing.JToggleButton();
jPasswordField1 = new javax.swing.JPasswordField();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jButton3.setText("jButton3");
setLayout(new java.awt.BorderLayout());
jButton1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton1.setText("Digitally Sign");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jScrollPane1.setViewportView(jList1);
jButton2.setText("Show Certificate Details");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jLabel5.setText("Available Certificates");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(70, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(82, 82, 82))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel5)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addContainerGap())
);
jTabbedPane1.addTab("Sign", jPanel1);
jLabel1.setText("Advanced Settings");
isIncludeSubjectName.setSelected(true);
isIncludeSubjectName.setText("Include your certificate's subject name");
isIncludePublicKey.setSelected(true);
isIncludePublicKey.setText("Include your public key in the signature (recommended)");
isIncludeIssuer.setText("Include your certificate's issuer and your certificate's serial");
jLabel2.setText("Signature Method");
jTextFieldSigMethod.setText("http://www.w3.org/2000/09/xmldsig#rsa-sha1");
jLabel3.setText("Digest Method");
jTextFieldDigestMethod.setText("http://www.w3.org/2000/09/xmldsig#sha1");
jTextFieldDigestMethod.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldDigestMethodActionPerformed(evt);
}
});
jLabel4.setText("Canonicalization Method");
jTextFieldc14n.setText("http://www.w3.org/2001/10/xml-exc-c14n#");
jTextFieldc14n.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldc14nActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextFieldDigestMethod)
.addComponent(jTextFieldSigMethod)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(isIncludeIssuer)
.addComponent(isIncludePublicKey)
.addComponent(isIncludeSubjectName)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jTextFieldc14n, javax.swing.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(isIncludePublicKey)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(isIncludeSubjectName)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(isIncludeIssuer)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldSigMethod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldDigestMethod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldc14n, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(127, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Settings", jPanel2);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane2.setViewportView(jTextArea1);
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE)
.addContainerGap())
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 340, Short.MAX_VALUE)
.addContainerGap())
);
jTabbedPane1.addTab("Info", jPanel4);
jToggleButton1.setText("OK");
jToggleButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jToggleButton1MouseClicked(evt);
}
});
jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton1ActionPerformed(evt);
}
});
jLabel6.setText("Password");
jLabel7.setText("<html>For Firefox and certain browser and OS combinations, you may need to specify a password in order to get access to certificates. This is typically used for non-Windows users.</html>");
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(34, 34, 34)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jToggleButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(jLabel6)
.addGap(18, 18, 18)
.addComponent(jPasswordField1, javax.swing.GroupLayout.DEFAULT_SIZE, 182, Short.MAX_VALUE)))
.addGap(100, 100, 100))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jToggleButton1)
.addContainerGap(248, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Key Store", null, jPanel5, "");
add(jTabbedPane1, java.awt.BorderLayout.CENTER);
jTabbedPane1.getAccessibleContext().setAccessibleName("Key Store");
}// </editor-fold>//GEN-END:initComponents
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
//JPopupMenu jp = new JPopupMenu("Certificate Info");
String data = "No certificate selected";
try {
Certificate publickey = keyStore.getCertificate((String) jList1.getSelectedValue());
data = "Issuer: " + ((X509Certificate) publickey).getIssuerDN().getName() + System.getProperty("line.separator");
data += "Subject: " + ((X509Certificate) publickey).getSubjectDN().getName() + System.getProperty("line.separator");
data += "Valid From: " + ((X509Certificate) publickey).getNotBefore().toString() + System.getProperty("line.separator");
data += "Valid Until: " + ((X509Certificate) publickey).getNotAfter().toString() + System.getProperty("line.separator");
data += "Serial Number: " + ((X509Certificate) publickey).getSerialNumber() + System.getProperty("line.separator");
} catch (KeyStoreException ex) {
Logger.getLogger(XmlSigApplet2.class.getName()).log(Level.SEVERE, null, ex);
}
jTextArea1.setText(data);
jPanel4.setVisible(true);
jTabbedPane1.setSelectedIndex(2);
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
boolean error = false;
String signedXml = "error!";
JSObject window = JSObject.getWindow(this);
try {
if (keyStore == null || keyStore.size() == 0) {
error = true;
signedXml = "Unforunately, it looks as if you don't have any certificates to choose from.";
jTextArea1.setText(signedXml);
jTabbedPane1.setSelectedIndex(2);
return;
}
} catch (Exception ex) {
error = true;
signedXml = "Unforunately, it looks as if you don't have any certificates to choose from.";
jTextArea1.setText(signedXml);
jTabbedPane1.setSelectedIndex(2);
}
if (jList1.getSelectedValue() == null) {
error = true;
signedXml = "You must pick a certificate first";
jTextArea1.setText(signedXml);
jTabbedPane1.setSelectedIndex(2);
}
//Object object2 = window.call("getBrowserName", null);
//Object object1 = window.call("getOsName", null);
Object object3 = window.call("getObjectType", null);
//String browserName = (String) object2;
//tring osName = (String) object2;
String objecttype = (String) object3;
//get the xml
String xml = (String) window.call("getXml", new Object[]{});
Object j = null;
if (objecttype.equalsIgnoreCase("business")) {
try {
StringReader sr = new StringReader(xml.trim());
j = (BusinessEntity) XmlUtils.unmarshal(sr, BusinessEntity.class);
} catch (Exception ex) {
}
}
if (objecttype.equalsIgnoreCase("service")) {
try {
StringReader sr = new StringReader(xml.trim());
j = (BusinessService) XmlUtils.unmarshal(sr, BusinessService.class);
} catch (Exception ex) {
}
}
if (objecttype.equalsIgnoreCase("bindingTemplate")) {
try {
StringReader sr = new StringReader(xml.trim());
j = (BindingTemplate) XmlUtils.unmarshal(sr, BindingTemplate.class);
} catch (Exception ex) {
}
}
if (objecttype.equalsIgnoreCase("tmodel")) {
try {
StringReader sr = new StringReader(xml.trim());
j = (TModel) XmlUtils.unmarshal(sr, TModel.class);
} catch (Exception ex) {
}
}
if (j != null) {
try {
//sign it
org.apache.juddi.v3.client.cryptor.DigSigUtil ds = new DigSigUtil();
if (isIncludePublicKey.isSelected()) {
ds.put(DigSigUtil.SIGNATURE_OPTION_CERT_INCLUSION_BASE64, "true");
}
if (isIncludeSubjectName.isSelected()) {
ds.put(DigSigUtil.SIGNATURE_OPTION_CERT_INCLUSION_SUBJECTDN, "true");
}
if (isIncludeIssuer.isSelected()) {
ds.put(DigSigUtil.SIGNATURE_OPTION_CERT_INCLUSION_SERIAL, "true");
}
ds.put(DigSigUtil.SIGNATURE_METHOD, jTextFieldSigMethod.getText());
ds.put(DigSigUtil.SIGNATURE_OPTION_DIGEST_METHOD, jTextFieldDigestMethod.getText());
ds.put(DigSigUtil.CANONICALIZATIONMETHOD, jTextFieldc14n.getText());
char[] cp = jPasswordField1.getPassword();
if (cp != null && cp.length <= 0) {
cp = null;
}
if (cp != null) {
String s = new String(cp);
s = s.trim();
if ("".equalsIgnoreCase(s)) {
cp = null;
}
}
PrivateKey key = (PrivateKey) keyStore.getKey((String) jList1.getSelectedValue(), cp);
Certificate publickey = keyStore.getCertificate((String) jList1.getSelectedValue());
j = ds.signUddiEntity(j, publickey, key);
ds.clear();
StringWriter sw = new StringWriter();
JAXB.marshal(j, sw);
signedXml = sw.toString();
} catch (Exception ex) {
error = true;
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
signedXml = "Sorry I couldn't sign the data. " + ex.getMessage();
}
} else {
error=true;
signedXml = "Unable to determine which type of object that we're signing";
}
/*
try {
signedXml = this.sign(xml);
} catch (Exception ex) {
signedXml = ex.getMessage();
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
}*/
if (error) {
jTextArea1.setText(signedXml);
jTabbedPane1.setSelectedIndex(2);
} else {
//write it back to the web page
window.call("writeXml", new Object[]{signedXml});
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jTextFieldDigestMethodActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldDigestMethodActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextFieldDigestMethodActionPerformed
private void jTextFieldc14nActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldc14nActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextFieldc14nActionPerformed
private void jToggleButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jToggleButton1MouseClicked
// TODO add your handling code here:
}//GEN-LAST:event_jToggleButton1MouseClicked
private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton1ActionPerformed
setupCertificates();
}//GEN-LAST:event_jToggleButton1ActionPerformed
/**
* XML digital signature namespace
*/
public final static String XML_DIGSIG_NS = "http://www.w3.org/2000/09/xmldsig#";
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JCheckBox isIncludeIssuer;
private javax.swing.JCheckBox isIncludePublicKey;
private javax.swing.JCheckBox isIncludeSubjectName;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JList jList1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPasswordField jPasswordField1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextFieldDigestMethod;
private javax.swing.JTextField jTextFieldSigMethod;
private javax.swing.JTextField jTextFieldc14n;
private javax.swing.JToggleButton jToggleButton1;
// End of variables declaration//GEN-END:variables
}
| apache-2.0 |
redkale/redkale-plugins | src/main/java/org/redkalex/source/search/ActionResult.java | 620 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkalex.source.search;
/**
*
* @author zhangjx
*/
public class ActionResult extends BaseBean {
public String _index;
public String _id;
public int _version;
public String result;
public ShardResult _shards;
public int status;
public int _primary_term;
public int successCount() {
return _shards == null ? 0 : _shards.successful;
}
}
| apache-2.0 |
Holden-/Atv_Corporativo | src/main/java/br/edu/ifrn/conta/persistencia/ContaCreditoRepository.java | 869 | /*
* Copyright 2016-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 br.edu.ifrn.conta.persistencia;
import br.edu.ifrn.conta.dominio.ContaCredito;
/**
* Herdando de ContaRepository.
* @author Marcelo Fernandes
*/
public interface ContaCreditoRepository extends ContaRepository<ContaCredito, Long> {
}
| apache-2.0 |
msebire/intellij-community | plugins/InspectionGadgets/testsrc/com/siyeh/ig/logging/LoggingConditionDisagreesWithLogStatementInspectionTest.java | 4065 | /*
* 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.siyeh.ig.logging;
import com.intellij.codeInspection.InspectionProfileEntry;
import com.siyeh.ig.LightInspectionTestCase;
import org.jetbrains.annotations.Nullable;
/**
* @author Bas Leijdekkers
*/
public class LoggingConditionDisagreesWithLogStatementInspectionTest extends LightInspectionTestCase {
@Override
protected String[] getEnvironmentClasses() {
return new String[]{
"package org.slf4j;" +
"public interface Logger { " +
" boolean isInfoEnabled(); " +
" void info(String format, Object... arguments);" +
" void warn(String format, Object... arguments);" +
"}",
"package org.slf4j; " +
"public class LoggerFactory {" +
" public static Logger getLogger(Class clazz) {" +
" return null; " +
" }" +
"}",
"package org.apache.logging.log4j;" +
"public interface Logger {" +
" void warn(String var2);" +
" boolean isInfoEnabled() {" +
" return true;" +
" };" +
"}",
"package org.apache.logging.log4j;" +
"public class LogManager {" +
" public static Logger getLogger() {" +
" return null;" +
" }" +
"}",
"package java.util.logging;" +
"public class Logger {" +
" public static Logger getLogger(String name) {" +
" return null;" +
" }" +
" public void warning(String msg) {}" +
" public boolean isLoggable(Level level) {}" +
"}",
"package java.util.logging;" +
"public class Level {" +
" public static final Level FINE = new Level();" +
" public static final Level WARNING = new Level();" +
"}"
};
}
public void testSlf4j() {
doTest("import org.slf4j.Logger;" +
"import org.slf4j.LoggerFactory;" +
"class X {" +
" private static final Logger LOG = LoggerFactory.getLogger(X.class);" +
" void n() {" +
" if (LOG.isInfoEnabled()) {" +
" LOG.info(\"nothing to report\");" +
" }" +
" if (LOG./*Log condition 'isInfoEnabled()' does not match 'warn()' logging call*/isInfoEnabled/**/()) {" +
" LOG.warn(\"the sky is falling!\");" +
" }" +
" }" +
"}");
}
public void testLog4j2() {
doTest("import org.apache.logging.log4j.*;" +
"class X {" +
" static final Logger LOG = LogManager.getLogger();" +
" void m() {" +
" if (LOG./*Log condition 'isInfoEnabled()' does not match 'warn()' logging call*/isInfoEnabled/**/()) {" +
" LOG.warn(\"hi!\");" +
" }" +
" }" +
"}");
}
public void testJavaUtilLogging() {
doTest("import java.util.logging.*;" +
"class Loggers {" +
" static final Logger LOG = Logger.getLogger(\"\");" +
" public void method() {" +
" if (LOG./*Log condition 'isLoggable()' does not match 'warning()' logging call*/isLoggable/**/(Level.FINE)) {" +
" LOG.warning(\"asdfasdf\");" +
" }" +
" if (LOG.isLoggable(Level.WARNING)) {" +
" LOG.warning(\"oops!\");" +
" }" +
" }" +
"}");
}
@Nullable
@Override
protected InspectionProfileEntry getInspection() {
return new LoggingConditionDisagreesWithLogStatementInspection();
}
} | apache-2.0 |
jabubake/google-cloud-java | google-cloud-datastore/src/test/java/com/google/cloud/datastore/LatLngValueTest.java | 2001 | /*
* 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.cloud.datastore;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class LatLngValueTest {
private static final LatLng CONTENT = new LatLng(37.4, -122.1);
@Test
public void testToBuilder() throws Exception {
LatLngValue value = LatLngValue.of(CONTENT);
assertEquals(value, value.toBuilder().build());
}
@SuppressWarnings("deprecation")
@Test
public void testOf() throws Exception {
LatLngValue value = LatLngValue.of(CONTENT);
assertEquals(CONTENT, value.get());
assertFalse(value.excludeFromIndexes());
}
@SuppressWarnings("deprecation")
@Test
public void testBuilder() throws Exception {
LatLngValue.Builder builder = LatLngValue.newBuilder(CONTENT);
LatLngValue value = builder.setMeaning(1).setExcludeFromIndexes(true).build();
assertEquals(CONTENT, value.get());
assertEquals(1, value.getMeaning());
assertTrue(value.excludeFromIndexes());
}
@Test
public void testBuilderDeprecated() throws Exception {
LatLngValue.Builder builder = LatLngValue.builder(CONTENT);
LatLngValue value = builder.meaning(1).excludeFromIndexes(true).build();
assertEquals(CONTENT, value.get());
assertEquals(1, value.meaning());
assertTrue(value.excludeFromIndexes());
}
}
| apache-2.0 |
flightx31/Bookmark-anator | src/main/java/com/bookmarkanator/ui/interfaces/UIItemInterface.java | 251 | package com.bookmarkanator.ui.interfaces;
public interface UIItemInterface
{
boolean getEditMode();
void setEditMode(boolean editMode);
UIControllerInterface getController();
void setController(UIControllerInterface controller);
}
| apache-2.0 |
roadlabs/alternate-java-bridge-library | src/com/xiledsystems/AlternateJavaBridgelib/components/altbridge/ScrollView.java | 4832 | package com.xiledsystems.AlternateJavaBridgelib.components.altbridge;
import android.content.Context;
import android.view.ViewGroup;
public class ScrollView implements Layout {
private final android.widget.ScrollView layoutManager;
private final Context context;
private final int resourceId;
/**
* Creates a new linear layout.
*
* @param context view context
* @param orientation one of
* {@link ComponentConstants#LAYOUT_ORIENTATION_HORIZONTAL}.
* {@link ComponentConstants#LAYOUT_ORIENTATION_VERTICAL}
*/
ScrollView(Context context, int orientation) {
this(context, orientation, null, null);
}
ScrollView(Context context, int orientation, int resourceId) {
this(context, orientation, null, null, resourceId);
}
ScrollView(Context context, int orientation, Integer null1, Integer null2, int resourceId) {
this.context = context;
this.resourceId = resourceId;
layoutManager = null;
//layoutManager = (android.widget.ScrollView) ((Form)context).findViewById(resourceId);
}
/**
* Creates a new linear layout with a preferred empty width/height.
*
* @param context view context
* @param orientation one of
* {@link ComponentConstants#LAYOUT_ORIENTATION_HORIZONTAL}.
* {@link ComponentConstants#LAYOUT_ORIENTATION_VERTICAL}
* @param preferredEmptyWidth the preferred width of an empty layout
* @param preferredEmptyHeight the preferred height of an empty layout
*/
ScrollView(Context context, int orientation, final Integer preferredEmptyWidth,
final Integer preferredEmptyHeight) {
if (preferredEmptyWidth == null && preferredEmptyHeight != null ||
preferredEmptyWidth != null && preferredEmptyHeight == null) {
throw new IllegalArgumentException("LinearLayout - preferredEmptyWidth and " +
"preferredEmptyHeight must be either both null or both not null");
}
this.context = null;
this.resourceId = -1;
// Create an Android LinearLayout, but override onMeasure so that we can use our preferred
// empty width/height.
layoutManager = new android.widget.ScrollView(context) {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// If there was no preferred empty width/height specified (see constructors above), just
// call super. (This is the case for the Form component.)
if (preferredEmptyWidth == null || preferredEmptyHeight == null) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
// If the layout has any children, just call super.
if (getChildCount() != 0) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
setMeasuredDimension(getSize(widthMeasureSpec, preferredEmptyWidth),
getSize(heightMeasureSpec, preferredEmptyHeight));
}
private int getSize(int measureSpec, int preferredSize) {
int result;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else {
// Use the preferred size.
result = preferredSize;
if (specMode == MeasureSpec.AT_MOST) {
// Respect AT_MOST value if that was what is called for by measureSpec
result = Math.min(result, specSize);
}
}
return result;
}
};
// layoutManager.setOrientation(
// orientation == ComponentConstants.LAYOUT_ORIENTATION_HORIZONTAL ?
// android.widget.LinearLayout.HORIZONTAL : android.widget.LinearLayout.VERTICAL);
}
// Layout implementation
public ViewGroup getLayoutManager() {
if (resourceId!=-1) {
return (android.widget.ScrollView) ((Form)context).findViewById(resourceId);
} else {
return layoutManager;
}
}
public void add(AndroidViewComponent component) {
if (resourceId!=-1) {
((android.widget.ScrollView) ((Form)context).findViewById(resourceId)).addView(component.getView(),
new android.widget.LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, 0f));
} else {
layoutManager.addView(component.getView(), new android.widget.LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, // width
ViewGroup.LayoutParams.WRAP_CONTENT, // height
0f)); // weight
}
}
} | apache-2.0 |
philliprower/cas | support/cas-server-support-radius/src/main/java/org/apereo/cas/adaptors/radius/web/flow/RadiusAccessChallengedMultifactorAuthenticationTrigger.java | 3159 | package org.apereo.cas.adaptors.radius.web.flow;
import org.apereo.cas.authentication.Authentication;
import org.apereo.cas.authentication.AuthenticationException;
import org.apereo.cas.authentication.MultifactorAuthenticationProvider;
import org.apereo.cas.authentication.MultifactorAuthenticationProviderAbsentException;
import org.apereo.cas.authentication.MultifactorAuthenticationProviderResolver;
import org.apereo.cas.authentication.MultifactorAuthenticationTrigger;
import org.apereo.cas.authentication.MultifactorAuthenticationUtils;
import org.apereo.cas.authentication.principal.Service;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.services.RegisteredService;
import org.apereo.cas.util.spring.ApplicationContextProvider;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import net.jradius.dictionary.Attr_ReplyMessage;
import net.jradius.dictionary.Attr_State;
import org.springframework.core.Ordered;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;
/**
* This is {@link RadiusAccessChallengedMultifactorAuthenticationTrigger}.
*
* @author Misagh Moayyed
* @since 6.0.0
*/
@Getter
@Setter
@Slf4j
@RequiredArgsConstructor
public class RadiusAccessChallengedMultifactorAuthenticationTrigger implements MultifactorAuthenticationTrigger {
private final CasConfigurationProperties casProperties;
private final MultifactorAuthenticationProviderResolver multifactorAuthenticationProviderResolver;
private int order = Ordered.LOWEST_PRECEDENCE;
@Override
public Optional<MultifactorAuthenticationProvider> isActivated(final Authentication authentication, final RegisteredService registeredService,
final HttpServletRequest request, final Service service) {
if (authentication == null) {
LOGGER.debug("No authentication or service is available to determine event for principal");
return Optional.empty();
}
val providerMap = MultifactorAuthenticationUtils.getAvailableMultifactorAuthenticationProviders(ApplicationContextProvider.getApplicationContext());
if (providerMap.isEmpty()) {
LOGGER.error("No multifactor authentication providers are available in the application context");
throw new AuthenticationException(new MultifactorAuthenticationProviderAbsentException());
}
val principal = authentication.getPrincipal();
val attributes = principal.getAttributes();
LOGGER.debug("Evaluating principal attributes [{}] for multifactor authentication", attributes.keySet());
if (attributes.containsKey(Attr_ReplyMessage.NAME) && attributes.containsKey(Attr_State.NAME)) {
val id = casProperties.getAuthn().getMfa().getRadius().getId();
LOGGER.debug("Authentication requires multifactor authentication via provider [{}]", id);
return MultifactorAuthenticationUtils.resolveProvider(providerMap, id);
}
return Optional.empty();
}
}
| apache-2.0 |
edlectrico/Pellet4Android | src/org/mindswap/pellet/datatypes/XSDMonth.java | 4529 | // Portions Copyright (c) 2006 - 2008, Clark & Parsia, LLC. <http://www.clarkparsia.com>
// Clark & Parsia, LLC parts of this source code are available under the terms of the Affero General Public License v3.
//
// Please see LICENSE.txt for full license terms, including the availability of proprietary exceptions.
// Questions, comments, or requests for clarification: licensing@clarkparsia.com
package org.mindswap.pellet.datatypes;
import java.math.BigInteger;
import org.mindswap.pellet.utils.ATermUtils;
import org.mindswap.pellet.utils.GenericIntervalList;
import org.mindswap.pellet.utils.Namespaces;
import org.mindswap.pellet.utils.NumberUtils;
import org.relaxng.datatype.DatatypeException;
import aterm.ATermAppl;
import com.sun.msv.datatype.xsd.DatatypeFactory;
import com.sun.msv.datatype.xsd.XSDatatype;
import com.sun.msv.datatype.xsd.datetime.BigDateTimeValueType;
import com.sun.msv.datatype.xsd.datetime.BigTimeDurationValueType;
import com.sun.msv.datatype.xsd.datetime.IDateTimeValueType;
import com.sun.msv.datatype.xsd.datetime.ITimeDurationValueType;
/**
* @author kolovski
*/
@SuppressWarnings("deprecation")
public class XSDMonth extends BaseXSDAtomicType implements AtomicDatatype, XSDAtomicType {
private static XSDatatype dt = null;
private static IDateTimeValueType min = null;
private static IDateTimeValueType max = null;
static {
try {
dt = DatatypeFactory.getTypeByName( "gMonth" );
min = (IDateTimeValueType) dt.createValue( "--01--", null );
max = (IDateTimeValueType) dt.createValue( "--12--", null );
}
catch( DatatypeException e ) {
e.printStackTrace();
}
}
private static final ValueSpace MONTH_VALUE_SPACE = new MonthValueSpace();
private static class MonthValueSpace extends AbstractDateTimeValueSpace implements ValueSpace {
public MonthValueSpace() {
super( min, max, dt );
}
public Object getValue( String value ) {
// xsdlib wrongly expects the gMonth value to be in the format --MM--
// whereas the correct format is --MM. This small hack appends the
// string "--" at the end of valid gMonth values to turn them into
// the format required by xsdlib
value = value + "--";
return dt.createValue( value, null );
}
//return the difference in Months
public int count(Object start, Object end) {
BigDateTimeValueType calendarStart = ((IDateTimeValueType) start).getBigValue();
BigDateTimeValueType calendarEnd = ((IDateTimeValueType) end).getBigValue();
return calendarEnd.getMonth().intValue() - calendarStart.getMonth().intValue() + 1;
}
public Object succ( Object value, int n ) {
BigInteger bigN = new BigInteger( String.valueOf( n ) );
ITimeDurationValueType nMonths =
new BigTimeDurationValueType(
NumberUtils.INTEGER_ZERO, bigN, NumberUtils.INTEGER_ZERO,
NumberUtils.INTEGER_ZERO, NumberUtils.INTEGER_ZERO, NumberUtils.DECIMAL_ZERO );
IDateTimeValueType s = ((IDateTimeValueType)value).add( nMonths );
return s;
}
}
public static XSDMonth instance = new XSDMonth(ATermUtils.makeTermAppl(Namespaces.XSD + "gMonth"));
protected XSDMonth(ATermAppl name) {
super( name, MONTH_VALUE_SPACE );
}
public BaseXSDAtomicType create( GenericIntervalList intervals ) {
XSDMonth type = new XSDMonth( null );
type.values = intervals;
return type;
}
public AtomicDatatype getPrimitiveType() {
return instance;
}
public ATermAppl getValue( int i ) {
Object value = values.get( i );
String lexical = valueSpace.getLexicalForm( value );
// xsdlib wrongly expects the gMonth value to be in the format --MM--
// whereas the correct format is --MM. This small hack removes the
// string "--" from the end of xsdlib generated lexical representation
// to create a valid gMonth value
assert lexical.endsWith( "--" );
assert lexical.length() == 6;
lexical = lexical.substring( 0, 4 );
return ATermUtils.makeTypedLiteral( lexical, getPrimitiveType().getURI() );
}
} | apache-2.0 |
GaneshSPatil/gocd | agent-bootstrapper/src/main/java/com/thoughtworks/go/agent/bootstrapper/DefaultAgentLauncherCreatorImpl.java | 5175 | /*
* Copyright 2021 ThoughtWorks, 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.thoughtworks.go.agent.bootstrapper;
import com.thoughtworks.cruise.agent.common.launcher.AgentLaunchDescriptor;
import com.thoughtworks.cruise.agent.common.launcher.AgentLauncher;
import com.thoughtworks.go.agent.common.util.Downloader;
import com.thoughtworks.go.agent.common.util.JarUtil;
import com.thoughtworks.go.util.FileUtil;
import com.thoughtworks.go.util.SystemUtil;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.function.Predicate;
import java.util.jar.JarEntry;
public class DefaultAgentLauncherCreatorImpl implements AgentLauncherCreator {
private static final Logger LOG = LoggerFactory.getLogger(DefaultAgentLauncherCreatorImpl.class);
private static final String GO_AGENT_LAUNCHER_CLASS = "Go-Agent-Launcher-Class";
private static final String GO_AGENT_LAUNCHER_LIB_DIR = "Go-Agent-Launcher-Lib-Dir";
private static final int DEFAULT_MAX_RETRY_FOR_CLEANUP = 5;
private static final String MAX_RETRY_FOR_LAUNCHER_TEMP_CLEANUP_PROPERTY = "MaxRetryCount.ForLauncher.TempFiles.cleanup";
private final int maxRetryAttempts = SystemUtil.getIntProperty(MAX_RETRY_FOR_LAUNCHER_TEMP_CLEANUP_PROPERTY, DEFAULT_MAX_RETRY_FOR_CLEANUP);
private final File inUseLauncher = new File(FileUtil.TMP_PARENT_DIR, new BigInteger(64, new SecureRandom()).toString(16) + "-" + Downloader.AGENT_LAUNCHER);
private URLClassLoader urlClassLoader;
@Override
public AgentLauncher createLauncher() {
createTempLauncherJar();
try {
String libDir = JarUtil.getManifestKey(inUseLauncher, GO_AGENT_LAUNCHER_LIB_DIR);
String classNameToLoad = JarUtil.getManifestKey(inUseLauncher, GO_AGENT_LAUNCHER_CLASS);
return (AgentLauncher) loadClass(inUseLauncher, GO_AGENT_LAUNCHER_CLASS, libDir, classNameToLoad).getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private Class<?> loadClass(File sourceJar, String classNameManifestKey, String libDir, String classNameToLoad) throws ClassNotFoundException {
Predicate<JarEntry> filter = jarEntry -> jarEntry.getName().startsWith(libDir + "/") && jarEntry.getName().endsWith(".jar");
this.urlClassLoader = JarUtil.getClassLoaderFromJar(sourceJar, filter, getDepsDir(), DefaultAgentLauncherCreatorImpl.class.getClassLoader(), AgentLauncher.class, AgentLaunchDescriptor.class);
LOG.info("Attempting to load {} as specified by manifest key {}", classNameToLoad, classNameManifestKey);
return this.urlClassLoader.loadClass(classNameToLoad);
}
private void createTempLauncherJar() {
try {
inUseLauncher.getParentFile().mkdirs();
Files.copy(new File(Downloader.AGENT_LAUNCHER).toPath(), inUseLauncher.toPath());
} catch (IOException e) {
throw new RuntimeException(e);
}
LauncherTempFileHandler.startTempFileReaper();
}
private void attemptToCleanupMaxRetryTimes() {
boolean shouldRetry;
int retryCount = 0;
do {
forceGCToReleaseAnyReferences();
sleepForAMoment();
LOG.info("Attempt No: {} to cleanup launcher temp files", retryCount + 1);
FileUtils.deleteQuietly(inUseLauncher);
FileUtils.deleteQuietly(getDepsDir());
++retryCount;
shouldRetry = tempFilesExist() && retryCount < maxRetryAttempts;
} while (shouldRetry);
}
private File getDepsDir() {
return new File(FileUtil.TMP_PARENT_DIR, "deps-" + inUseLauncher.getName());
}
private void recordCleanup() {
LauncherTempFileHandler.writeToFile(Collections.singletonList(inUseLauncher.getName()), true);
}
private boolean tempFilesExist() {
return inUseLauncher.exists() || getDepsDir().exists();
}
private void sleepForAMoment() {
int oneSec = 1000;
try {
Thread.sleep(oneSec);
} catch (InterruptedException e) {
}
}
private void forceGCToReleaseAnyReferences() {
System.gc();
}
@Override
public void close() throws Exception {
urlClassLoader.close();
urlClassLoader = null;
recordCleanup();
attemptToCleanupMaxRetryTimes();
}
}
| apache-2.0 |
apetro/uPortal | uportal-war/src/main/java/org/apereo/portal/events/handlers/db/PortalEventDaoQueuingEventHandler.java | 1643 | /**
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo 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 the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apereo.portal.events.handlers.db;
import org.apereo.portal.events.PortalEvent;
import org.apereo.portal.events.handlers.QueueingEventHandler;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Hands off queued portal events for storage by the IPortalEventDao
*
* @author Eric Dalquist
* @version $Revision$
*/
public class PortalEventDaoQueuingEventHandler extends QueueingEventHandler<PortalEvent> {
private IPortalEventDao portalEventDao;
/**
* @param portalEventDao the portalEventDao to set
*/
@Autowired
public void setPortalEventDao(IPortalEventDao portalEventDao) {
this.portalEventDao = portalEventDao;
}
@Override
protected void onApplicationEvents(Iterable<PortalEvent> events) {
this.portalEventDao.storePortalEvents(events);
}
}
| apache-2.0 |
0359xiaodong/YiBo | YiBo/src/com/shejiaomao/weibo/service/adapter/UserTopicStatusListAdapter.java | 3233 | package com.shejiaomao.weibo.service.adapter;
import java.util.ArrayList;
import java.util.List;
import com.cattong.commons.util.ListUtil;
import com.cattong.entity.Status;
import android.app.Activity;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import com.shejiaomao.weibo.db.LocalAccount;
/**
* @author Weiping Ye
* @version 创建时间:2011-8-24 下午12:19:27
**/
public class UserTopicStatusListAdapter extends CacheAdapter<Status> {
private Activity context;
private List<Status> statusList = new ArrayList<Status>();
private String keyword;
public UserTopicStatusListAdapter(Activity context, LocalAccount account, String keyword) {
super(context, account);
this.context = context;
this.account = account;
this.keyword = keyword;
}
@Override
public int getCount() {
return statusList.size();
}
@Override
public Object getItem(int position) {
if (position < 0 || position >= statusList.size()) {
return null;
}
return statusList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Status status = (Status)getItem(position);
if (status == null) {
return null;
}
convertView = StatusUtil.initConvertView(context, convertView, account.getServiceProvider());
StatusUtil.fillConvertView(convertView, status);
StatusHolder holder = (StatusHolder)convertView.getTag();
String text = holder.tvText.getText().toString();
holder.tvText.setText(Html.fromHtml(text.replaceAll(
keyword, "<font color=\"#ff0000\">" + keyword + "</font>")));
return convertView;
}
@Override
public boolean addCacheToFirst(List<Status> list) {
if (ListUtil.isEmpty(list)) {
return false;
}
statusList.addAll(0, list);
this.notifyDataSetChanged();
return true;
}
@Override
public boolean addCacheToDivider(Status status, List<Status> list) {
if (ListUtil.isEmpty(list)) {
return false;
}
statusList.addAll(list);
this.notifyDataSetChanged();
return true;
}
@Override
public boolean addCacheToLast(List<Status> list) {
if (ListUtil.isEmpty(list)) {
return false;
}
statusList.addAll(list);
this.notifyDataSetChanged();
return true;
}
@Override
public Status getMax() {
Status max = null;
if (ListUtil.isNotEmpty(statusList)) {
max = statusList.get(0);
}
return max;
}
@Override
public Status getMin() {
Status min = null;
if (statusList != null && statusList.size() > 0) {
min = statusList.get(statusList.size() - 1);
}
return min;
}
@Override
public boolean remove(int position) {
if (position < 0 || position >= getCount()) {
return false;
}
statusList.remove(position);
this.notifyDataSetChanged();
return true;
}
@Override
public boolean remove(Status status) {
if (status == null) {
return false;
}
statusList.remove(status);
this.notifyDataSetChanged();
return true;
}
@Override
public void clear() {
statusList.clear();
}
}
| apache-2.0 |
jack6215/StreamCQL | streaming/src/test/java/com/huawei/streaming/process/agg/aggregator/sum/AggregateSumTest.java | 4800 | /**
* 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 com.huawei.streaming.process.agg.aggregator.sum;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import org.junit.Assert;
import org.junit.Test;
/**
* <AggregateSumTest>
* <功能详细描述>
*
*/
public class AggregateSumTest
{
private static final double D_ONE = 1d;
private static final double D_TWO = 2d;
private static final double D_THREE = 3d;
private static final float F_ONE = 1f;
private static final float F_TWO = 2f;
private static final float F_THREE = 3f;
private static final long L_ONE = 1L;
private static final long L_TWO = 2L;
private static final long L_THREE = 3L;
private static final int I_ONE = 1;
private static final int I_TWO = 2;
private static final int I_THREE = 3;
private AggregateSum agg = null;
/**
* Test AggregateSum#AggregateSum(java.lang.Class).
*/
@Test
public void testAggregateSum()
{
try
{
agg = new AggregateSum(null);
fail();
}
catch (IllegalArgumentException e)
{
Assert.assertTrue(true);
}
try
{
agg = new AggregateSum(String.class);
fail();
}
catch (IllegalArgumentException e)
{
Assert.assertTrue(true);
}
}
/**
* Test cloneAggregate().
*/
@Test
public void testCloneAggregate()
{
agg = new AggregateSum(Double.class);
assertEquals(Double.class, agg.cloneAggregate().getValueType());
assertEquals(true, agg.cloneAggregate() instanceof AggregateSum);
}
/**
* <testAggregateSumFunction (enter, leave, getValue)>
* <功能详细描述>
*/
@Test
public void testAggregateSumFunction()
{
//Double
agg = new AggregateSum(Double.class);
assertEquals(Double.class, agg.getValueType());
assertNull(agg.getValue());
agg.enter(D_ONE, true);
assertEquals(D_ONE, agg.getValue());
agg.enter(D_TWO, true);
assertEquals(D_THREE, agg.getValue());
agg.leave(D_ONE, true);
assertEquals(D_TWO, agg.getValue());
agg.leave(D_TWO, true);
assertNull(agg.getValue());
//Float
agg = new AggregateSum(Float.class);
assertEquals(Float.class, agg.getValueType());
assertNull(agg.getValue());
agg.enter(F_ONE, true);
assertEquals(F_ONE, agg.getValue());
agg.enter(F_TWO, true);
assertEquals(F_THREE, agg.getValue());
agg.leave(F_ONE, true);
assertEquals(F_TWO, agg.getValue());
agg.leave(F_TWO, true);
assertNull(agg.getValue());
//Integer
agg = new AggregateSum(Integer.class);
assertEquals(Integer.class, agg.getValueType());
assertNull(agg.getValue());
agg.enter(I_ONE, true);
assertEquals(I_ONE, agg.getValue());
agg.enter(I_TWO, true);
assertEquals(I_THREE, agg.getValue());
agg.leave(I_ONE, true);
assertEquals(I_TWO, agg.getValue());
agg.leave(I_TWO, true);
assertNull(agg.getValue());
//Long
agg = new AggregateSum(Long.class);
assertEquals(Long.class, agg.getValueType());
assertNull(agg.getValue());
agg.enter(L_ONE, true);
assertEquals(L_ONE, agg.getValue());
agg.enter(L_TWO, true);
assertEquals(L_THREE, agg.getValue());
agg.leave(L_ONE, true);
assertEquals(L_TWO, agg.getValue());
agg.leave(L_TWO, true);
assertNull(agg.getValue());
}
}
| apache-2.0 |
PennState/SCIMple-Identity | scim-spec/scim-spec-schema/src/main/java/edu/psu/swe/scim/spec/annotation/ScimResourceIdReference.java | 1104 | /*
* 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 edu.psu.swe.scim.spec.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ScimResourceIdReference {
}
| apache-2.0 |
kbachl/brix-cms | brix-core/src/main/java/org/brixcms/web/nodepage/BrixPageLink.java | 2267 | /**
* 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.brixcms.web.nodepage;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.link.AbstractLink;
import org.apache.wicket.model.IModel;
import org.apache.wicket.util.string.Strings;
import org.brixcms.jcr.wrapper.BrixNode;
/**
* A component that links to a page with specified page parameters.
* <p>
* This component is different from {@link PageParametersLink} because it does
* not allow other components to contribute their page parameters to the
* generated url and therefore does not propagate state from one page to the
* next.
* <p>
* TODO expand to support tags other then anchor
*
* @author igor.vaynberg
*/
public class BrixPageLink extends AbstractLink {
// TODO optimize into minimap just like BookmarkablePageLink
private final BrixPageParameters params;
public BrixPageLink(String id, IModel<BrixNode> destination) {
super(id, destination);
this.params = null;
}
public BrixPageLink(String id, IModel<BrixNode> destination, BrixPageParameters params) {
super(id, destination);
this.params = params;
}
@SuppressWarnings("unchecked")
@Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
checkComponentTag(tag, "a");
if (!isEnabledInHierarchy()) {
disableLink(tag);
} else {
BrixPageParameters params = this.params;
if (params == null) {
params = new BrixPageParameters();
}
String url = params.urlFor((IModel<BrixNode>) getDefaultModel());
tag.put("href", Strings.replaceAll(url, "&", "&"));
}
}
}
| apache-2.0 |
Scarabei/Scarabei | scarabei-api/src/com/jfixby/scarabei/api/strings/StringsComponent.java | 910 |
package com.jfixby.scarabei.api.strings;
import com.jfixby.scarabei.api.collections.List;
import com.jfixby.scarabei.api.collections.Map;
import com.jfixby.scarabei.api.collections.Sequence;
import com.jfixby.scarabei.api.java.ByteArray;
public interface StringsComponent {
List<String> split (String input_string, String splitter);
String newString (ByteArray data);
String truncated (String data, int begin_char, int end_char);
String newString (char[] chars);
String newString (byte[] bytes);
String newString (byte[] bytes, String encoding);
String newString (ByteArray bytes, String encoding);
String replaceAll (String input, Map<String, String> termsMapping);
String prefix (String string, int offset);
String wrapSequence (Sequence<String> seq, int size, String bracketLeft, String bracketRight, final String separator);
String padLeft (String value, String pad, int size);
}
| apache-2.0 |
hmmlopez/citrus | modules/citrus-core/src/test/java/com/consol/citrus/actions/PurgeEndpointActionTest.java | 5432 | /*
* Copyright 2006-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.consol.citrus.actions;
import com.consol.citrus.endpoint.Endpoint;
import com.consol.citrus.exceptions.ActionTimeoutException;
import com.consol.citrus.message.DefaultMessage;
import com.consol.citrus.messaging.Consumer;
import com.consol.citrus.messaging.SelectiveConsumer;
import com.consol.citrus.testng.AbstractTestNGUnitTest;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.testng.annotations.Test;
import java.util.*;
import static org.mockito.Mockito.*;
/**
* @author Christoph Deppisch
*/
public class PurgeEndpointActionTest extends AbstractTestNGUnitTest {
@Autowired
@Qualifier(value="mockEndpoint")
private Endpoint mockEndpoint;
private Endpoint emptyEndpoint = Mockito.mock(Endpoint.class);
private Consumer consumer = Mockito.mock(Consumer.class);
private SelectiveConsumer selectiveConsumer = Mockito.mock(SelectiveConsumer.class);
@Test
public void testPurgeWithEndpointNames() throws Exception {
PurgeEndpointAction purgeEndpointAction = new PurgeEndpointAction();
purgeEndpointAction.setBeanFactory(applicationContext);
List<String> endpointNames = new ArrayList<>();
endpointNames.add("mockEndpoint");
purgeEndpointAction.setEndpointNames(endpointNames);
reset(mockEndpoint, consumer, selectiveConsumer);
when(mockEndpoint.getName()).thenReturn("mockEndpoint");
when(mockEndpoint.createConsumer()).thenReturn(consumer);
when(consumer.receive(context, 100L)).thenReturn(new DefaultMessage());
doThrow(new ActionTimeoutException()).when(consumer).receive(context, 100L);
purgeEndpointAction.execute(context);
}
@SuppressWarnings("unchecked")
@Test
public void testPurgeWithEndpointObjects() throws Exception {
PurgeEndpointAction purgeEndpointAction = new PurgeEndpointAction();
purgeEndpointAction.setBeanFactory(applicationContext);
List<Endpoint> endpoints = new ArrayList<>();
endpoints.add(mockEndpoint);
endpoints.add(emptyEndpoint);
purgeEndpointAction.setEndpoints(endpoints);
reset(mockEndpoint, emptyEndpoint, consumer, selectiveConsumer);
when(mockEndpoint.getName()).thenReturn("mockEndpoint");
when(emptyEndpoint.getName()).thenReturn("emptyEndpoint");
when(mockEndpoint.createConsumer()).thenReturn(consumer);
when(emptyEndpoint.createConsumer()).thenReturn(consumer);
when(consumer.receive(context, 100L)).thenReturn(new DefaultMessage());
doThrow(new ActionTimeoutException()).when(consumer).receive(context, 100L);
doThrow(new ActionTimeoutException()).when(consumer).receive(context, 100L);
purgeEndpointAction.execute(context);
}
@Test
public void testPurgeWithMessageSelectorString() throws Exception {
PurgeEndpointAction purgeEndpointAction = new PurgeEndpointAction();
purgeEndpointAction.setBeanFactory(applicationContext);
purgeEndpointAction.setMessageSelectorString("operation = 'sayHello'");
List<Endpoint> endpoints = new ArrayList<>();
endpoints.add(mockEndpoint);
purgeEndpointAction.setEndpoints(endpoints);
reset(mockEndpoint, consumer, selectiveConsumer);
when(mockEndpoint.getName()).thenReturn("mockEndpoint");
when(mockEndpoint.createConsumer()).thenReturn(selectiveConsumer);
when(selectiveConsumer.receive("operation = 'sayHello'", context, 100L)).thenReturn(new DefaultMessage());
doThrow(new ActionTimeoutException()).when(selectiveConsumer).receive("operation = 'sayHello'", context, 100L);
purgeEndpointAction.execute(context);
}
@Test
public void testPurgeWithMessageSelector() throws Exception {
PurgeEndpointAction purgeEndpointAction = new PurgeEndpointAction();
purgeEndpointAction.setBeanFactory(applicationContext);
purgeEndpointAction.setMessageSelector(Collections.<String, Object>singletonMap("operation", "sayHello"));
List<Endpoint> endpoints = new ArrayList<>();
endpoints.add(mockEndpoint);
purgeEndpointAction.setEndpoints(endpoints);
reset(mockEndpoint, consumer, selectiveConsumer);
when(mockEndpoint.getName()).thenReturn("mockEndpoint");
when(mockEndpoint.createConsumer()).thenReturn(selectiveConsumer);
when(selectiveConsumer.receive("operation = 'sayHello'", context, 100L)).thenReturn(new DefaultMessage());
doThrow(new ActionTimeoutException()).when(selectiveConsumer).receive("operation = 'sayHello'", context, 100L);
purgeEndpointAction.execute(context);
}
}
| apache-2.0 |
ptkool/presto | presto-main/src/main/java/com/facebook/presto/metadata/HandleJsonModule.java | 1865 | /*
* 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.metadata;
import com.facebook.presto.index.IndexHandleJacksonModule;
import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Scopes;
import static com.facebook.airlift.json.JsonBinder.jsonBinder;
public class HandleJsonModule
implements Module
{
@Override
public void configure(Binder binder)
{
jsonBinder(binder).addModuleBinding().to(TableHandleJacksonModule.class);
jsonBinder(binder).addModuleBinding().to(TableLayoutHandleJacksonModule.class);
jsonBinder(binder).addModuleBinding().to(ColumnHandleJacksonModule.class);
jsonBinder(binder).addModuleBinding().to(SplitJacksonModule.class);
jsonBinder(binder).addModuleBinding().to(OutputTableHandleJacksonModule.class);
jsonBinder(binder).addModuleBinding().to(InsertTableHandleJacksonModule.class);
jsonBinder(binder).addModuleBinding().to(IndexHandleJacksonModule.class);
jsonBinder(binder).addModuleBinding().to(TransactionHandleJacksonModule.class);
jsonBinder(binder).addModuleBinding().to(PartitioningHandleJacksonModule.class);
jsonBinder(binder).addModuleBinding().to(FunctionHandleJacksonModule.class);
binder.bind(HandleResolver.class).in(Scopes.SINGLETON);
}
}
| apache-2.0 |
apache/cocoon | blocks/cocoon-ojb/cocoon-ojb-mocks/src/main/java/javax/jdo/Query.java | 1942 | /*
* 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.
*/
/*
* Created on 08-oct-2003
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package javax.jdo;
import java.util.Collection;
import java.util.Map;
abstract public interface Query
{
abstract public void close(Object o);
abstract public void closeAll();
abstract public void compile();
abstract public void declareImports(String s);
abstract public void declareParameters(String s);
abstract public void declareVariables(String s);
abstract public Object execute();
abstract public Object execute(Object o);
abstract public Object execute(Object o, Object p);
abstract public Object execute(Object o, Object p, Object q);
abstract public Object executeWithArray(Object[] o);
abstract public Object executeWithMap(Map m);
abstract public boolean getIgnoreCache();
abstract public PersistenceManager getPersistentManager();
abstract public void setIgnoreCandidates(Collection c);
abstract public void setClass(Class c);
abstract public void setFilter(String s);
abstract public void setIgnoreCache(boolean b);
abstract public void setOrdering(String s);
}
| apache-2.0 |
thekingnothing/powermock | core/src/main/java/org/powermock/tests/utils/impl/MockPolicyInitializerImpl.java | 9802 | /*
* Copyright 2011 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.powermock.tests.utils.impl;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map.Entry;
import org.powermock.core.MockRepository;
import org.powermock.core.classloader.MockClassLoader;
import org.powermock.core.classloader.annotations.MockPolicy;
import org.powermock.core.spi.PowerMockPolicy;
import org.powermock.mockpolicies.MockPolicyClassLoadingSettings;
import org.powermock.mockpolicies.MockPolicyInterceptionSettings;
import org.powermock.mockpolicies.impl.MockPolicyClassLoadingSettingsImpl;
import org.powermock.mockpolicies.impl.MockPolicyInterceptionSettingsImpl;
import org.powermock.reflect.Whitebox;
import org.powermock.tests.utils.MockPolicyInitializer;
/**
* The default implementation of the {@link MockPolicyInitializer} interface for
* mock policies.
*/
public class MockPolicyInitializerImpl implements MockPolicyInitializer {
private final PowerMockPolicy[] mockPolicies;
private final Class<? extends PowerMockPolicy>[] mockPolicyTypes;
private final Class<?> testClass;
public MockPolicyInitializerImpl(Class<? extends PowerMockPolicy>[] mockPolicies) {
this(mockPolicies, false);
}
public MockPolicyInitializerImpl(Class<?> testClass) {
this(getMockPolicies(testClass), testClass, false);
}
private MockPolicyInitializerImpl(Class<? extends PowerMockPolicy>[] mockPolicies, boolean internal) {
this(mockPolicies, null, false);
}
private MockPolicyInitializerImpl(Class<? extends PowerMockPolicy>[] mockPolicies, Class<?> testClass, boolean internal) {
this.testClass = testClass;
if (internal) {
mockPolicyTypes = null;
} else {
mockPolicyTypes = mockPolicies;
}
if (mockPolicies == null) {
this.mockPolicies = new PowerMockPolicy[0];
} else {
this.mockPolicies = new PowerMockPolicy[mockPolicies.length];
for (int i = 0; i < mockPolicies.length; i++) {
this.mockPolicies[i] = Whitebox.newInstance(mockPolicies[i]);
}
}
}
@Override
public boolean isPrepared(String fullyQualifiedClassName) {
MockPolicyClassLoadingSettings settings = getClassLoadingSettings();
final boolean foundInSuppressStaticInitializer = Arrays.binarySearch(settings.getStaticInitializersToSuppress(), fullyQualifiedClassName) < 0;
final boolean foundClassesLoadedByMockClassloader = Arrays.binarySearch(settings.getFullyQualifiedNamesOfClassesToLoadByMockClassloader(),
fullyQualifiedClassName) < 0;
return foundInSuppressStaticInitializer || foundClassesLoadedByMockClassloader;
}
@Override
public boolean needsInitialization() {
MockPolicyClassLoadingSettings settings = getClassLoadingSettings();
return settings.getStaticInitializersToSuppress().length > 0 || settings.getFullyQualifiedNamesOfClassesToLoadByMockClassloader().length > 0;
}
/**
* {@inheritDoc}
*/
@Override
public void initialize(ClassLoader classLoader) {
if (classLoader instanceof MockClassLoader) {
initialize((MockClassLoader) classLoader);
}
}
/**
*
* {@inheritDoc}
*/
private void initialize(MockClassLoader classLoader) {
if (mockPolicies.length > 0) {
MockPolicyClassLoadingSettings classLoadingSettings = getClassLoadingSettings();
String[] fullyQualifiedNamesOfClassesToLoadByMockClassloader = classLoadingSettings
.getFullyQualifiedNamesOfClassesToLoadByMockClassloader();
classLoader.addClassesToModify(fullyQualifiedNamesOfClassesToLoadByMockClassloader);
if (testClass == null) {
throw new IllegalStateException("Internal error: testClass should never be null when calling initialize on a mock policy");
}
classLoader.addClassesToModify(testClass.getName());
Class<?>[] classes = testClass.getDeclaredClasses();
for (Class<?> clazz : classes) {
classLoader.addClassesToModify(clazz.getName());
}
Class<?>[] declaredClasses = testClass.getClasses();
for (Class<?> clazz : declaredClasses) {
classLoader.addClassesToModify(clazz.getName());
}
for (String string : classLoadingSettings.getStaticInitializersToSuppress()) {
classLoader.addClassesToModify(string);
MockRepository.addSuppressStaticInitializer(string);
}
invokeInitializeInterceptionSettingsFromClassLoader(classLoader);
}
}
@Override
public void refreshPolicies(ClassLoader classLoader) {
if (classLoader instanceof MockClassLoader) {
invokeInitializeInterceptionSettingsFromClassLoader((MockClassLoader) classLoader);
}
}
private void invokeInitializeInterceptionSettingsFromClassLoader(MockClassLoader classLoader) {
try {
final int sizeOfPolicies = mockPolicyTypes.length;
Object mockPolicies = Array.newInstance(Class.class, sizeOfPolicies);
for (int i = 0; i < sizeOfPolicies; i++) {
final Class<?> policyLoadedByClassLoader = Class.forName(mockPolicyTypes[i].getName(), false, classLoader);
Array.set(mockPolicies, i, policyLoadedByClassLoader);
}
final Class<?> thisTypeLoadedByMockClassLoader = Class.forName(this.getClass().getName(), false, classLoader);
Object mockPolicyHandler = Whitebox.invokeConstructor(thisTypeLoadedByMockClassLoader, mockPolicies, true);
Whitebox.invokeMethod(mockPolicyHandler, "initializeInterceptionSettings");
} catch (InvocationTargetException e) {
final Throwable targetException = e.getTargetException();
if (targetException instanceof RuntimeException) {
throw (RuntimeException) targetException;
} else if (targetException instanceof Error) {
throw (Error) targetException;
} else {
throw new RuntimeException(e);
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("PowerMock internal error: Failed to load class.", e);
}
}
/*
* This method IS used, but it's invoked using reflection from the
* invokeInitializeInterceptionSettingsFromClassLoader method.
*/
@SuppressWarnings("unused")
private void initializeInterceptionSettings() {
MockPolicyInterceptionSettings interceptionSettings = getInterceptionSettings();
for (Method method : interceptionSettings.getMethodsToSuppress()) {
MockRepository.addMethodToSuppress(method);
}
for (Entry<Method, InvocationHandler> entry : interceptionSettings.getProxiedMethods().entrySet()) {
MockRepository.putMethodProxy(entry.getKey(), entry.getValue());
}
for (Entry<Method, Object> entry : interceptionSettings.getStubbedMethods().entrySet()) {
final Method method = entry.getKey();
final Object className = entry.getValue();
MockRepository.putMethodToStub(method, className);
}
for (Field field : interceptionSettings.getFieldsToSuppress()) {
MockRepository.addFieldToSuppress(field);
}
for (String type : interceptionSettings.getFieldTypesToSuppress()) {
MockRepository.addFieldTypeToSuppress(type);
}
}
private MockPolicyInterceptionSettings getInterceptionSettings() {
MockPolicyInterceptionSettings settings = new MockPolicyInterceptionSettingsImpl();
for (PowerMockPolicy mockPolicy : mockPolicies) {
mockPolicy.applyInterceptionPolicy(settings);
}
return settings;
}
private MockPolicyClassLoadingSettings getClassLoadingSettings() {
MockPolicyClassLoadingSettings settings = new MockPolicyClassLoadingSettingsImpl();
for (PowerMockPolicy mockPolicy : mockPolicies) {
mockPolicy.applyClassLoadingPolicy(settings);
}
return settings;
}
/**
* Get the mock policies from a test-class.
*/
@SuppressWarnings("unchecked")
private static Class<? extends PowerMockPolicy>[] getMockPolicies(Class<?> testClass) {
Class<? extends PowerMockPolicy>[] powerMockPolicies = new Class[0];
if (testClass.isAnnotationPresent(MockPolicy.class)) {
MockPolicy annotation = testClass.getAnnotation(MockPolicy.class);
powerMockPolicies = annotation.value();
}
return powerMockPolicies;
}
}
| apache-2.0 |
nakul02/incubator-systemml | src/main/java/org/apache/sysml/hops/estim/EstimatorBasicWorst.java | 2346 | /*
* 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.sysml.hops.estim;
import org.apache.sysml.hops.OptimizerUtils;
import org.apache.sysml.runtime.matrix.MatrixCharacteristics;
import org.apache.sysml.runtime.matrix.data.MatrixBlock;
/**
* Basic average case estimator for matrix sparsity:
* sp = Math.min(1, sp1 * k) * Math.min(1, sp2 * k).
*
* Note: for outer-products (i.e., k=1) this worst-case
* estimate is equivalent to the average case estimate and
* the exact output sparsity.
*/
public class EstimatorBasicWorst extends SparsityEstimator
{
@Override
public double estim(MMNode root) {
//recursive sparsity evaluation of non-leaf nodes
double sp1 = !root.getLeft().isLeaf() ? estim(root.getLeft()) :
OptimizerUtils.getSparsity(root.getLeft().getMatrixCharacteristics());
double sp2 = !root.getRight().isLeaf() ? estim(root.getRight()) :
OptimizerUtils.getSparsity(root.getRight().getMatrixCharacteristics());
return estimIntern(sp1, sp2, root.getRows(), root.getLeft().getCols(), root.getCols());
}
@Override
public double estim(MatrixBlock m1, MatrixBlock m2) {
return estim(m1.getMatrixCharacteristics(), m2.getMatrixCharacteristics());
}
@Override
public double estim(MatrixCharacteristics mc1, MatrixCharacteristics mc2) {
return estimIntern(
OptimizerUtils.getSparsity(mc1), OptimizerUtils.getSparsity(mc2),
mc1.getRows(), mc1.getCols(), mc2.getCols());
}
private double estimIntern(double sp1, double sp2, long m, long k, long n) {
return OptimizerUtils.getMatMultSparsity(sp1, sp2, m, k, n, true);
}
}
| apache-2.0 |
jdeppe-pivotal/geode | geode-core/src/test/java/org/apache/geode/internal/net/ByteBufferVendorTest.java | 6135 | /*
* 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.geode.internal.net;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.CountDownLatch;
import org.junit.Before;
import org.junit.Test;
public class ByteBufferVendorTest {
@FunctionalInterface
private interface Foo {
void run() throws IOException;
}
private ByteBufferVendor sharingVendor;
private BufferPool poolMock;
private CountDownLatch clientHasOpenedResource;
private CountDownLatch clientMayComplete;
@Before
public void before() {
poolMock = mock(BufferPool.class);
sharingVendor =
new ByteBufferVendor(mock(ByteBuffer.class), BufferPool.BufferType.TRACKED_SENDER,
poolMock);
clientHasOpenedResource = new CountDownLatch(1);
clientMayComplete = new CountDownLatch(1);
}
@Test
public void balancedCloseOwnerIsLastReferenceHolder() throws InterruptedException {
resourceOwnerIsLastReferenceHolder("client with balanced close calls", () -> {
try (final ByteBufferSharing _unused = sharingVendor.open()) {
}
});
}
@Test
public void extraCloseOwnerIsLastReferenceHolder() throws InterruptedException {
resourceOwnerIsLastReferenceHolder("client with extra close calls", () -> {
final ByteBufferSharing sharing2 = sharingVendor.open();
sharing2.close();
verify(poolMock, times(0)).releaseBuffer(any(), any());
assertThatThrownBy(sharing2::close).isInstanceOf(IllegalMonitorStateException.class);
verify(poolMock, times(0)).releaseBuffer(any(), any());
});
}
@Test
public void balancedCloseClientIsLastReferenceHolder() throws InterruptedException {
clientIsLastReferenceHolder("client with balanced close calls", () -> {
try (final ByteBufferSharing _unused = sharingVendor.open()) {
clientHasOpenedResource.countDown();
blockClient();
}
});
}
@Test
public void extraCloseClientIsLastReferenceHolder() throws InterruptedException {
clientIsLastReferenceHolder("client with extra close calls", () -> {
final ByteBufferSharing sharing2 = sharingVendor.open();
clientHasOpenedResource.countDown();
blockClient();
sharing2.close();
verify(poolMock, times(1)).releaseBuffer(any(), any());
assertThatThrownBy(sharing2::close).isInstanceOf(IllegalMonitorStateException.class);
});
}
@Test
public void extraCloseDoesNotPrematurelyReturnBufferToPool() throws IOException {
final ByteBufferSharing sharing2 = sharingVendor.open();
sharing2.close();
assertThatThrownBy(sharing2::close).isInstanceOf(IllegalMonitorStateException.class);
verify(poolMock, times(0)).releaseBuffer(any(), any());
sharingVendor.destruct();
verify(poolMock, times(1)).releaseBuffer(any(), any());
}
@Test
public void extraCloseDoesNotDecrementRefCount() throws IOException {
final ByteBufferSharing sharing2 = sharingVendor.open();
sharing2.close();
assertThatThrownBy(sharing2::close).isInstanceOf(IllegalMonitorStateException.class);
final ByteBufferSharing sharing3 = sharingVendor.open();
sharingVendor.destruct();
verify(poolMock, times(0)).releaseBuffer(any(), any());
}
@Test
public void destructIsIdempotent() {
sharingVendor.destruct();
sharingVendor.destruct();
verify(poolMock, times(1)).releaseBuffer(any(), any());
}
private void resourceOwnerIsLastReferenceHolder(final String name, final Foo client)
throws InterruptedException {
/*
* Thread.currentThread() is thread is playing the role of the (ByteBuffer) resource owner
*/
/*
* clientThread thread is playing the role of the client (of the resource owner)
*/
final Thread clientThread = new Thread(asRunnable(client), name);
clientThread.start();
clientThread.join();
verify(poolMock, times(0)).releaseBuffer(any(), any());
sharingVendor.destruct();
verify(poolMock, times(1)).releaseBuffer(any(), any());
}
private void clientIsLastReferenceHolder(final String name, final Foo client)
throws InterruptedException {
/*
* Thread.currentThread() is thread is playing the role of the (ByteBuffer) resource owner
*/
/*
* clientThread thread is playing the role of the client (of the resource owner)
*/
final Thread clientThread = new Thread(asRunnable(client), name);
clientThread.start();
clientHasOpenedResource.await();
sharingVendor.destruct();
verify(poolMock, times(0)).releaseBuffer(any(), any());
clientMayComplete.countDown(); // let client finish
clientThread.join();
verify(poolMock, times(1)).releaseBuffer(any(), any());
}
private void blockClient() {
try {
clientMayComplete.await();
} catch (InterruptedException e) {
fail("test client thread interrupted: " + e);
}
}
private Runnable asRunnable(final Foo client) {
return () -> {
try {
client.run();
} catch (IOException e) {
fail("client thread threw: ", e);
}
};
}
}
| apache-2.0 |
dangi-mukesh/foxtrot | foxtrot-server/src/main/java/com/flipkart/foxtrot/server/resources/FqlResource.java | 1479 | package com.flipkart.foxtrot.server.resources;
import com.flipkart.foxtrot.server.providers.FlatToCsvConverter;
import com.flipkart.foxtrot.server.providers.FoxtrotExtraMediaType;
import com.flipkart.foxtrot.sql.FqlEngine;
import com.flipkart.foxtrot.sql.responseprocessors.model.FlatRepresentation;
import com.google.common.base.Preconditions;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.StreamingOutput;
import java.io.OutputStreamWriter;
@Path("/v1/fql")
public class FqlResource {
private FqlEngine fqlEngine;
public FqlResource(final FqlEngine fqlEngine) {
this.fqlEngine = fqlEngine;
}
@GET
@Produces(FoxtrotExtraMediaType.TEXT_CSV)
@Path("/download")
public StreamingOutput runFqlGet(@QueryParam("q") final String query) throws Exception {
Preconditions.checkNotNull(query);
final FlatRepresentation representation = fqlEngine.parse(query);
return output -> FlatToCsvConverter.convert(representation, new OutputStreamWriter(output));
}
@POST
@Produces({MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON, FoxtrotExtraMediaType.TEXT_CSV})
public FlatRepresentation runFqlPost(final String query) throws Exception {
return fqlEngine.parse(query);
}
String getMessage(Throwable e) {
Throwable root = e;
while (null != root.getCause()) {
root = root.getCause();
}
return root.getMessage();
}
}
| apache-2.0 |
cogroo/cogroo4 | cogroo-eval/BaselineCogrooAE/src/test/java/cogroo/uima/interpreters/FlorestaTagInterpreterTest.java | 6175 | /**
* Copyright (C) 2012 cogroo <cogroo@cogroo.org>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cogroo.uima.interpreters;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
import br.usp.pcs.lta.cogroo.entity.impl.runtime.MorphologicalTag;
import br.usp.pcs.lta.cogroo.tag.TagInterpreterI;
import br.usp.pcs.lta.cogroo.tools.checker.rules.model.TagMask.Class;
import br.usp.pcs.lta.cogroo.tools.checker.rules.model.TagMask.Finiteness;
import br.usp.pcs.lta.cogroo.tools.checker.rules.model.TagMask.Punctuation;
public class FlorestaTagInterpreterTest {
private static Map<String, Class> table = new HashMap<String, Class>();
private TagInterpreterI ti = new FlorestaTagInterpreter();
static {
table.put("-", Class.PUNCTUATION_MARK);
table.put("--", Class.PUNCTUATION_MARK);
table.put(",", Class.PUNCTUATION_MARK);
table.put(";", Class.PUNCTUATION_MARK);
table.put(":", Class.PUNCTUATION_MARK);
table.put("!", Class.PUNCTUATION_MARK);
table.put("?", Class.PUNCTUATION_MARK);
table.put(".", Class.PUNCTUATION_MARK);
table.put("...", Class.PUNCTUATION_MARK);
table.put("'", Class.PUNCTUATION_MARK);
table.put("«", Class.PUNCTUATION_MARK);
table.put("»", Class.PUNCTUATION_MARK);
table.put("(", Class.PUNCTUATION_MARK);
table.put(")", Class.PUNCTUATION_MARK);
table.put("[", Class.PUNCTUATION_MARK);
table.put("]", Class.PUNCTUATION_MARK);
table.put("/", Class.PUNCTUATION_MARK);
table.put("adj", Class.ADJECTIVE);
table.put("adv", Class.ADVERB);
table.put("art", Class.DETERMINER);
table.put("conj-c", Class.COORDINATING_CONJUNCTION);
table.put("conj-s", Class.SUBORDINATING_CONJUNCTION);
table.put("ec", Class.HYPHEN_SEPARATED_PREFIX);
table.put("intj", Class.INTERJECTION);
table.put("n", Class.NOUN);
table.put("n-adj", Class.ADJECTIVE);
table.put("n:", Class.NOUN);
table.put("np", Class.NOUN);
table.put("num", Class.NUMERAL);
table.put("pp", Class.PREPOSITION);
//table.put("pron", Class.PRONOUN); // don't happen, added only for
// compatibility
table.put("pron-det", Class.DETERMINER);
table.put("pron-indp", Class.SPECIFIER);
table.put("pron-pers", Class.PERSONAL_PRONOUN);
table.put("prop", Class.PROPER_NOUN);
table.put("prp", Class.PREPOSITION);
table.put("v-fin", Class.VERB);
table.put("v-ger", Class.VERB);
table.put("v-inf", Class.VERB);
table.put("v-pcp", Class.VERB);
table.put("vp", Class.VERB);
}
@Test
public void testParseMorphologicalTag() {
// class
for (String tag : table.keySet()) {
if (table.get(tag) != null)
assertEquals("Failed to parse class tag: " + tag, table.get(tag), ti
.parseMorphologicalTag(tag).getClazzE());
}
}
@Test
public void testSerializeTag() {
Set<Class> classes = new HashSet<Class>(table.values());
for (Class classTag : classes) {
if (!classTag.equals(Class.PUNCTUATION_MARK) && !classTag.equals(Class.VERB)) {
String value = ti.serialize(classTag);
assertEquals("Failed to parse class tag: " + classTag, classTag,
table.get(value));
}
}
}
@Test
public void testPunctuation() {
MorphologicalTag mt = ti.parseMorphologicalTag(".");
assertEquals(Class.PUNCTUATION_MARK, mt.getClazzE());
assertEquals(Punctuation.ABS, mt.getPunctuation());
mt = ti.parseMorphologicalTag("!");
assertEquals(Class.PUNCTUATION_MARK, mt.getClazzE());
assertEquals(Punctuation.ABS, mt.getPunctuation());
mt = ti.parseMorphologicalTag("?");
assertEquals(Class.PUNCTUATION_MARK, mt.getClazzE());
assertEquals(Punctuation.ABS, mt.getPunctuation());
mt = ti.parseMorphologicalTag(",");
assertEquals(Class.PUNCTUATION_MARK, mt.getClazzE());
assertEquals(Punctuation.NSEP, mt.getPunctuation());
mt = ti.parseMorphologicalTag(";");
assertEquals(Class.PUNCTUATION_MARK, mt.getClazzE());
assertEquals(Punctuation.REL, mt.getPunctuation());
mt = ti.parseMorphologicalTag("(");
assertEquals(Class.PUNCTUATION_MARK, mt.getClazzE());
assertEquals(Punctuation.BIN, mt.getPunctuation());
mt = ti.parseMorphologicalTag("--");
assertEquals(Class.PUNCTUATION_MARK, mt.getClazzE());
assertEquals(Punctuation.BIN, mt.getPunctuation());
mt = ti.parseMorphologicalTag("...");
assertEquals(Class.PUNCTUATION_MARK, mt.getClazzE());
assertEquals(Punctuation.REL, mt.getPunctuation());
mt = ti.parseMorphologicalTag("«");
assertEquals(Class.PUNCTUATION_MARK, mt.getClazzE());
assertEquals(Punctuation.NSEP, mt.getPunctuation());
mt = ti.parseMorphologicalTag("v-pcp");
assertEquals(Class.VERB, mt.getClazzE());
assertEquals(Finiteness.PARTICIPLE, mt.getFinitenessE());
mt = ti.parseMorphologicalTag("v-inf");
assertEquals(Class.VERB, mt.getClazzE());
assertEquals(Finiteness.INFINITIVE, mt.getFinitenessE());
mt = ti.parseMorphologicalTag("v-ger");
assertEquals(Class.VERB, mt.getClazzE());
assertEquals(Finiteness.GERUND, mt.getFinitenessE());
mt = ti.parseMorphologicalTag("v-fin");
assertEquals(Class.VERB, mt.getClazzE());
assertEquals(Finiteness.FINITE, mt.getFinitenessE());
mt = ti.parseMorphologicalTag("n-adj");
assertEquals(Class.ADJECTIVE, mt.getClazzE());
mt = ti.parseMorphologicalTag("intj");
assertEquals(Class.INTERJECTION, mt.getClazzE());
}
}
| apache-2.0 |
permazen/permazen | permazen-kv/src/main/java/io/permazen/kv/util/CloseableForwardingKVStore.java | 3388 |
/*
* Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
*/
package io.permazen.kv.util;
import com.google.common.base.Preconditions;
import io.permazen.kv.CloseableKVStore;
import io.permazen.kv.KVStore;
import java.io.Closeable;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A {@link ForwardingKVStore} also implementing {@link CloseableKVStore}, with some associated
* underlying {@link Closeable} resource to close when {@link #close}'d.
*/
public class CloseableForwardingKVStore extends ForwardingKVStore implements CloseableKVStore {
private static final boolean TRACK_ALLOCATIONS = Boolean.parseBoolean(
System.getProperty(CloseableForwardingKVStore.class.getName() + ".TRACK_ALLOCATIONS", "false"));
private final KVStore kvstore;
private final Closeable closeable;
private final Throwable allocation;
private boolean closed;
/**
* Constructor for a do-nothing {@link #close}.
*
* <p>
* With this constructor, nothing will actually be closed when {@link #close} is invoked.
*
* @param kvstore key/value store for forwarding
* @throws IllegalArgumentException if {@code kvstore} is null
*/
public CloseableForwardingKVStore(KVStore kvstore) {
this(kvstore, null);
}
/**
* Convenience constructor.
*
* @param kvstore key/value store for forwarding; will be closed on {@link #close}
* @throws IllegalArgumentException if {@code kvstore} is null
*/
public CloseableForwardingKVStore(CloseableKVStore kvstore) {
this(kvstore, kvstore);
}
/**
* Primary constructor.
*
* @param kvstore key/value store for forwarding
* @param resource {@link Closeable} resource, or null for none
* @throws IllegalArgumentException if {@code kvstore} is null
*/
public CloseableForwardingKVStore(KVStore kvstore, Closeable resource) {
Preconditions.checkArgument(kvstore != null, "null kvstore");
this.kvstore = kvstore;
this.closeable = resource;
this.allocation = CloseableForwardingKVStore.TRACK_ALLOCATIONS ? new Throwable("allocated here") : null;
}
@Override
protected KVStore delegate() {
return this.kvstore;
}
@Override
public synchronized void close() {
if (this.closed)
return;
try {
if (this.closeable != null)
this.closeable.close();
} catch (IOException e) {
// ignore
}
this.closed = true;
}
/**
* Ensure the associated resource is {@link #close}'d before reclaiming memory.
*/
@Override
protected void finalize() throws Throwable {
try {
final boolean leaked;
synchronized (this) {
leaked = !this.closed;
}
if (leaked) {
final Logger log = LoggerFactory.getLogger(this.getClass());
final String msg = this.getClass().getSimpleName() + "[" + this.closeable + "] leaked without invoking close()";
if (this.allocation != null)
log.warn(msg, this.allocation);
else
log.warn(msg);
this.close();
}
} finally {
super.finalize();
}
}
}
| apache-2.0 |
zjshen/hadoop-YARN-2928-POC | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/event/SchedulerEventType.java | 1299 | /**
* 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.yarn.server.resourcemanager.scheduler.event;
public enum SchedulerEventType {
// Source: Node
NODE_ADDED,
NODE_REMOVED,
NODE_UPDATE,
NODE_RESOURCE_UPDATE,
NODE_LABELS_UPDATE,
// Source: RMApp
APP_ADDED,
APP_REMOVED,
// Source: RMAppAttempt
APP_ATTEMPT_ADDED,
APP_ATTEMPT_REMOVED,
// Source: ContainerAllocationExpirer
CONTAINER_EXPIRED,
// Source: SchedulingEditPolicy
DROP_RESERVATION,
PREEMPT_CONTAINER,
KILL_CONTAINER
}
| apache-2.0 |
luchuangbin/test1 | src/com/mit/dstore/adapter/PromoteInfoAdapter.java | 1839 | package com.mit.dstore.adapter;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.mit.dstore.R;
import com.mit.dstore.entity.PromoteInfoListJson.InvitationInfoJson;
import com.mit.dstore.util.BingContextUtil;
import com.mit.dstore.util.DateformatUtil;
/**"推廣活動"頁面里的adapter*/
public class PromoteInfoAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<InvitationInfoJson> list;
@Override
public int getCount() {
return list == null ? 0 : list.size();
}
public PromoteInfoAdapter(Context mContext) {
super();
inflater = LayoutInflater.from(mContext);
}
public PromoteInfoAdapter(Context mContext,List<InvitationInfoJson> list) {
super();
inflater = LayoutInflater.from(mContext);
this.list = list;
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
InvitationInfoJson data = list.get(position);
if (null == convertView) {
convertView = inflater.inflate(R.layout.person_promote_detail_item, null);
}
((TextView) convertView.findViewById(R.id.user_name)).setText(data.getMobile());
String date = DateformatUtil.formatRoughLine(data.getInvitationTime());
((TextView) convertView.findViewById(R.id.time)).setText(date);
String amount = BingContextUtil.subZeroAndDot(BingContextUtil.formatNum(data.getAmount()));
((TextView) convertView.findViewById(R.id.integration)).setText("+"+amount);
return convertView;
}
}
| apache-2.0 |
Network-of-BioThings/GettinCRAFTy | src/main/resources/gate/plugins/Ontology/src/gate/creole/ontology/impl/LiteralOrONodeIDImpl.java | 2782 | /*
* Copyright (c) 1995-2012, The University of Sheffield. See the file
* COPYRIGHT.txt in the software or at http://gate.ac.uk/gate/COPYRIGHT.txt
*
* This file is part of GATE (see http://gate.ac.uk/), and is free
* software, licenced under the GNU Library General Public License,
* Version 2, June 1991 (in the distribution as file licence.html,
* and also available at http://gate.ac.uk/gate/licence.html).
*
* Johann Petrak 2009-08-20
*
* $Id: LiteralOrONodeIDImpl.java 15334 2012-02-07 13:57:47Z ian_roberts $
*/
package gate.creole.ontology.impl;
import gate.creole.ontology.Literal;
import gate.creole.ontology.LiteralOrONodeID;
import gate.creole.ontology.ONodeID;
import gate.util.GateRuntimeException;
/**
* Wrap either a Literal or a ONodeID object.
* <p>
* TODO: should we implement comparable and equals/hashcode for this?
*
* @author Johann Petrak
*/
public class LiteralOrONodeIDImpl implements LiteralOrONodeID {
protected Object theObject;
protected boolean isLiteral;
public LiteralOrONodeIDImpl(Literal aLiteral) {
theObject = aLiteral;
isLiteral = true;
}
public LiteralOrONodeIDImpl(ONodeID aONodeID) {
theObject = aONodeID;
isLiteral = false;
}
public boolean isLiteral() {
return isLiteral;
}
public boolean isONodeID() {
return !isLiteral;
}
public ONodeID getONodeID() {
if(isLiteral) {
throw new GateRuntimeException(
"Cannot return an ONodeID, have a Literal: "+((Literal)theObject));
}
return (ONodeID)theObject;
}
public Literal getLiteral() {
if(!isLiteral) {
throw new GateRuntimeException(
"Cannot return a Literal, have an ONodeID: "+((ONodeID)theObject));
}
return (Literal)theObject;
}
@Override
public String toString() {
if(isLiteral) {
return ((Literal)theObject).toString();
} else {
return ((ONodeID)theObject).toString();
}
}
public String toTurtle() {
if(isLiteral) {
return ((Literal)theObject).toTurtle();
} else {
return ((ONodeID)theObject).toTurtle();
}
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final LiteralOrONodeIDImpl other = (LiteralOrONodeIDImpl) obj;
if (this.isLiteral != other.isLiteral) {
return false;
}
if(this.isLiteral) {
return ((Literal)this.theObject).equals((Literal)other.theObject);
} else {
return ((ONodeID)this.theObject).equals((ONodeID)other.theObject);
}
}
@Override
public int hashCode() {
if(isLiteral) {
return ((Literal)theObject).hashCode();
} else {
return ((ONodeID)theObject).hashCode();
}
}
}
| apache-2.0 |
cmoen/kuromoji | kuromoji-unidic-neologd/src/main/java/com/atilika/kuromoji/unidic/neologd/compile/TokenInfoDictionaryCompiler.java | 3264 | /**
* Copyright © 2010-2015 Atilika Inc. and contributors (see CONTRIBUTORS.md)
*
* 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 distributed with this work in the LICENSE.md file. You may
* also obtain a copy of the License from
*
* 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.atilika.kuromoji.unidic.neologd.compile;
import com.atilika.kuromoji.compile.TokenInfoDictionaryCompilerBase;
import com.atilika.kuromoji.dict.GenericDictionaryEntry;
import com.atilika.kuromoji.util.DictionaryEntryLineParser;
import java.util.ArrayList;
import java.util.List;
public class TokenInfoDictionaryCompiler extends TokenInfoDictionaryCompilerBase<DictionaryEntry> {
public TokenInfoDictionaryCompiler(String encoding) {
super(encoding);
}
@Override
protected DictionaryEntry parse(String line) {
String[] fields = DictionaryEntryLineParser.parseLine(line);
DictionaryEntry entry = new DictionaryEntry(fields);
return entry;
}
@Override
protected GenericDictionaryEntry makeGenericDictionaryEntry(DictionaryEntry entry) {
List<String> pos = makePartOfSpeechFeatures(entry);
List<String> features = makeOtherFeatures(entry);
return new GenericDictionaryEntry.Builder()
.surface(entry.getSurface())
.leftId(entry.getLeftId())
.rightId(entry.getRightId())
.wordCost(entry.getWordCost())
.partOfSpeech(pos)
.features(features)
.build();
}
public List<String> makePartOfSpeechFeatures(DictionaryEntry entry) {
List<String> posFeatures = new ArrayList<>();
posFeatures.add(entry.getPartOfSpeechLevel1());
posFeatures.add(entry.getPartOfSpeechLevel2());
posFeatures.add(entry.getPartOfSpeechLevel3());
posFeatures.add(entry.getPartOfSpeechLevel4());
posFeatures.add(entry.getConjugationType());
posFeatures.add(entry.getConjugationForm());
return posFeatures;
}
public List<String> makeOtherFeatures(DictionaryEntry entry) {
List<String> otherFeatures = new ArrayList<>();
otherFeatures.add(entry.getLemmaReadingForm());
otherFeatures.add(entry.getLemma());
otherFeatures.add(entry.getWrittenForm());
otherFeatures.add(entry.getPronunciation());
otherFeatures.add(entry.getWrittenBaseForm());
otherFeatures.add(entry.getPronunciationBaseForm());
otherFeatures.add(entry.getLanguageType());
otherFeatures.add(entry.getInitialSoundAlterationType());
otherFeatures.add(entry.getInitialSoundAlterationForm());
otherFeatures.add(entry.getFinalSoundAlterationType());
otherFeatures.add(entry.getFinalSoundAlterationForm());
return otherFeatures;
}
}
| apache-2.0 |
huihoo/olat | olat7.8/src/main/java/org/olat/lms/ims/qti/objects/Matvideo.java | 11337 | /**
* OLAT - Online Learning and Training<br>
* http://www.olat.org
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br>
* University of Zurich, Switzerland.
* <p>
*/
package org.olat.lms.ims.qti.objects;
import org.dom4j.Element;
import org.olat.system.commons.CodeHelper;
/**
* @author rkulow
*/
public class Matvideo implements QTIObject, MatElement {
public static final String VIDEO_TYPE_QUICKTIME = "video/quicktime";
public static final String VIDEO_TYPE_SHOKWAVE = "application/x-shockwave-flash";
public static final String VIDEO_TYPE_REAL = "application/vnd.rn-realmedia";
public static final String VIDEO_TYPE_WMV = "video/x-msvideo";
public static final String VIDEO_TYPE_MPEG = "video/mpeg";
private String id = null;
private String label = null;
private String URI = null;
private String videotype = null;
private String width = null;
private String height = null;
private boolean externalURI = false;
public Matvideo(final String uri) {
id = "" + CodeHelper.getRAMUniqueID();
setURI(uri);
}
/**
*/
@Override
public void addToElement(final Element root) {
if (URI != null) {
final Element matvideo = root.addElement("matvideo");
matvideo.addAttribute("uri", URI);
matvideo.addAttribute("videotype", videotype);
matvideo.addAttribute("width", width);
matvideo.addAttribute("height", height);
}
}
/**
*/
@Override
public String renderAsHtml(final String mediaBaseURL) {
if (getURI() == null) {
return "[ VIDEO: no video selected ]";
} else {
final StringBuilder buffer = new StringBuilder();
final String uri = mediaBaseURL + "/" + getURI();
buffer.append("<object ");
if (width != null) {
buffer.append(" width=\"").append(width).append("\" ");
}
if (height != null) {
buffer.append(" height=\"").append(height).append("\" ");
}
if (videotype.equals("application/x-shockwave-flash")) {
// shockwave
buffer.append("classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0\">");
buffer.append("<param name=\"movie\" value=\"");
buffer.append(uri);
buffer.append("\" />");
if (width != null) {
buffer.append("<param name=\"movie\" value=\"").append(width).append("\" />");
}
if (height != null) {
buffer.append("<param name=\"movie\" value=\"").append(height).append("\" />");
}
buffer.append("<embed type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash\" ");
buffer.append("src=\"");
buffer.append(uri);
buffer.append("\"");
} else if (videotype.equals("video/quicktime")) {
// quicktime
buffer.append("classid=\"clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B\" codebase=\"http://www.apple.com/qtactivex/qtplugin.cab\">");
buffer.append("<param name=\"src\" value=\"");
buffer.append(uri);
buffer.append("\" />");
if (width != null) {
buffer.append("<param name=\"movie\" value=\"").append(width).append("\" />");
}
if (height != null) {
buffer.append("<param name=\"movie\" value=\"").append(height).append("\" />");
}
buffer.append("<param name=\"controller\" value=\"true\"><param name=\"autoplay\" value=\"true\" />");
buffer.append("<embed type=\"video/quicktime\" pluginspage=\"http://www.apple.com/quicktime/download/\"");
buffer.append(" src=\"");
buffer.append(uri);
buffer.append("\" autoplay=\"true\" controller=\"true\"");
} else if (videotype.equals("application/vnd.rn-realmedia")) {
buffer.append("classid=\"clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA\" >").append("<param name=\"src\" value=\"");
buffer.append(uri);
buffer.append("\" />");
if (width != null) {
buffer.append("<param name=\"movie\" value=\"").append(width).append("\" />");
}
if (height != null) {
buffer.append("<param name=\"movie\" value=\"").append(height).append("\" />");
}
buffer.append("<param name=\"autostart\" value=\"true\" />");
buffer.append("<param name=\"controls\" value=\"imagewindow\" />");
buffer.append("<param name=\"console\" value=\"video\" />");
buffer.append("<param name=\"loop\" value=\"false\" />");
buffer.append("<embed type=\"application/vnd.rn-realmedia\" ").append("src=\"");
buffer.append(uri);
buffer.append("\" autostart=\"true\" controls=\"imagewindow\" console=\"video\" loop=\"false\"");
} else if (videotype.equals("video/x-msvideo") || videotype.equals("video/mpeg")) {
// windows media
buffer.append(
"classid=\"CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95\" codebase=\"http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701\" type=\"application/x-oleobject\">")
.append("<param name=\"fileName\" value=\"");
buffer.append(uri);
buffer.append("\" />");
if (width != null) {
buffer.append("<param name=\"movie\" value=\"").append(width).append("\" />");
}
if (height != null) {
buffer.append("<param name=\"movie\" value=\"").append(height).append("\" />");
}
buffer.append("<param name=\"animationatStart\" value=\"true\" />");
buffer.append("<param name=\"transparentatStart\" value=\"true\" />");
buffer.append("<param name=\"autoStart\" value=\"true\" />");
buffer.append("<param name=\"showControls\" value=\"true\" />");
buffer.append("<param name=\"loop\" value=\"false\" />");
buffer.append("<embed type=\"application/x-mplayer2\" pluginspage=\"http://microsoft.com/windows/mediaplayer/en/download/\" ").append("src=\"");
buffer.append(uri);
buffer.append("\" displaysize=\"4\" autosize=\"-1\" bgcolor=\"darkblue\" showcontrols=\"true\" ");
buffer.append("showtracker=\"-1\" showdisplay=\"0\" showstatusbar=\"-1\" videoborder3d=\"-1\" ");
buffer.append("autostart=\"true\" designtimesp=\"5331\" loop=\"false\"");
} else {
buffer.append(" />Not supported.");
return buffer.toString();
}
if (width != null) {
buffer.append(" width=\"").append(width).append("\"");
}
if (height != null) {
buffer.append(" height=\"").append(height).append("\"");
}
buffer.append("></embed></object>");
return buffer.toString();
}
}
/**
*/
@Override
public String renderAsText() {
if (getURI() == null) {
return "[ VIDEO: no video selected ]";
} else {
return "[ VIDEO: " + getURI() + " ]";
}
}
/**
* @return
*/
public String getURI() {
return URI;
}
/**
* @param string
*/
public void setURI(final String string) {
if (string == null) {
return;
}
URI = string;
externalURI = (URI.indexOf("://") == -1) ? false : true;
// extract videotype
String suffix = URI.toLowerCase();
if (suffix.lastIndexOf('.') == -1) {
return;
}
suffix = suffix.substring(suffix.lastIndexOf('.') + 1, suffix.length());
if (suffix.equals("mov")) {
setVideotype(VIDEO_TYPE_QUICKTIME);
}
if (suffix.equals("qt")) {
setVideotype(VIDEO_TYPE_QUICKTIME);
}
if (suffix.equals("rm")) {
setVideotype(VIDEO_TYPE_REAL);
}
if (suffix.equals("swf")) {
setVideotype(VIDEO_TYPE_SHOKWAVE);
}
if (suffix.equals("fla")) {
setVideotype(VIDEO_TYPE_SHOKWAVE);
}
if (suffix.equals("flv")) {
setVideotype(VIDEO_TYPE_SHOKWAVE);
}
if (suffix.equals("wma")) {
setVideotype(VIDEO_TYPE_WMV);
}
if (suffix.equals("wmv")) {
setVideotype(VIDEO_TYPE_WMV);
}
if (suffix.equals("avi")) {
setVideotype(VIDEO_TYPE_WMV);
}
if (suffix.equals("mpeg")) {
setVideotype(VIDEO_TYPE_MPEG);
}
if (suffix.equals("mpg")) {
setVideotype(VIDEO_TYPE_MPEG);
}
if (suffix.equals("mp3")) {
setVideotype(VIDEO_TYPE_MPEG);
}
}
/**
* @return
*/
public boolean isExternalURI() {
return externalURI;
}
/**
* @return
*/
public String getHeight() {
return height;
}
/**
* @return
*/
public String getLabel() {
return label;
}
/**
* @return
*/
public String getVideotype() {
return videotype;
}
/**
* @return
*/
public String getWidth() {
return width;
}
/**
* @param b
*/
public void setExternalURI(final boolean b) {
externalURI = b;
}
/**
* @param string
*/
public void setHeight(final String string) {
height = string;
}
/**
* @param string
*/
public void setLabel(final String string) {
label = string;
}
/**
* @param string
*/
public void setVideotype(final String string) {
videotype = string;
}
/**
* @param string
*/
public void setWidth(final String string) {
width = string;
}
/**
* @return
*/
public String getId() {
return id;
}
/**
* @param string
*/
public void setId(final String string) {
id = string;
}
}
| apache-2.0 |
Scauser/j2ee | upwork-jax-ws-client-new/src/main/java/com/upwork/test/Test.java | 1447 | package com.upwork.test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class Test {
public static void main(String args[]) {
try {
List<String> list = new ArrayList<String>();
list.add("Hello");
list.add(" World!!");
System.out.println(list);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(list);
byte[] text = bos.toByteArray();
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = keygenerator.generateKey();
Cipher desCipher;
desCipher = Cipher.getInstance("DES");
desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
byte[] textEncrypted = desCipher.doFinal(text);
desCipher.init(Cipher.DECRYPT_MODE, myDesKey);
byte[] textDecrypted = desCipher.doFinal(textEncrypted);
ByteArrayInputStream bis = new ByteArrayInputStream(textDecrypted);
ObjectInputStream ois = new ObjectInputStream(bis);
List<String> result = (List<String>) ois.readObject();
System.out.println(result);
} catch(Exception e) {
e.printStackTrace();
}
}
}
| apache-2.0 |
skylot/jadx | jadx-plugins/jadx-java-convert/src/main/java/jadx/plugins/input/javaconvert/D8Converter.java | 1574 | package jadx.plugins.input.javaconvert;
import java.nio.file.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.android.tools.r8.CompilationFailedException;
import com.android.tools.r8.CompilationMode;
import com.android.tools.r8.D8;
import com.android.tools.r8.D8Command;
import com.android.tools.r8.Diagnostic;
import com.android.tools.r8.DiagnosticsHandler;
import com.android.tools.r8.OutputMode;
public class D8Converter {
private static final Logger LOG = LoggerFactory.getLogger(D8Converter.class);
public static void run(Path path, Path tempDirectory, JavaConvertOptions options) throws CompilationFailedException {
D8Command d8Command = D8Command.builder(new LogHandler())
.addProgramFiles(path)
.setOutput(tempDirectory, OutputMode.DexIndexed)
.setMode(CompilationMode.DEBUG)
.setMinApiLevel(30)
.setIntermediate(true)
.setDisableDesugaring(!options.isD8Desugar())
.build();
D8.run(d8Command);
}
private static class LogHandler implements DiagnosticsHandler {
@Override
public void error(Diagnostic diagnostic) {
LOG.error("D8 error: {}", format(diagnostic));
}
@Override
public void warning(Diagnostic diagnostic) {
LOG.warn("D8 warning: {}", format(diagnostic));
}
@Override
public void info(Diagnostic diagnostic) {
LOG.info("D8 info: {}", format(diagnostic));
}
public static String format(Diagnostic diagnostic) {
return diagnostic.getDiagnosticMessage()
+ ", origin: " + diagnostic.getOrigin()
+ ", position: " + diagnostic.getPosition();
}
}
}
| apache-2.0 |
shahramgdz/hibernate-validator | engine/src/test/java/org/hibernate/validator/test/internal/metadata/ChildWithoutAtValid2.java | 491 | /*
* Hibernate Validator, declare and validate application constraints
*
* License: Apache License, Version 2.0
* See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
*/
package org.hibernate.validator.test.internal.metadata;
import javax.validation.constraints.NotNull;
/**
* @author Gunnar Morling
*/
public class ChildWithoutAtValid2 extends ParentWithoutAtValid {
@Override
@NotNull
public Order getOrder() {
return null;
}
}
| apache-2.0 |
mhgrove/Empire | core/test/src/com/clarkparsia/empire/typing/AnotherB.java | 1583 | /*
* Copyright (c) 2009-2010 Clark & Parsia, LLC. <http://www.clarkparsia.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.clarkparsia.empire.typing;
import com.clarkparsia.empire.SupportsRdfId;
import com.clarkparsia.empire.annotation.RdfsClass;
import com.clarkparsia.empire.annotation.RdfProperty;
import com.clarkparsia.empire.annotation.NamedGraph;
import javax.persistence.Entity;
import javax.persistence.MappedSuperclass;
/**
* <p>A class with the same @RdfsClass annotation like B, but not inheriting from A</p>
*
* This class is here merely to be in the classpath and make sure that none of the Empire code
* picks it when needing a class that inherits from A.
*
* @author Blazej Bulka <blazej@clarkparsia.com>
*/
@MappedSuperclass
@Entity
@RdfsClass("urn:clarkparsia.com:empire:test:B")
@NamedGraph(type = NamedGraph.NamedGraphType.Instance)
public abstract class AnotherB implements SupportsRdfId {
@RdfProperty("urn:clarkparsia.com:empire:test:propB")
public abstract String getPropB();
public abstract void setPropB(String b);
}
| apache-2.0 |
papicella/snappy-store | gemfire-core/src/main/java/com/gemstone/gemfire/internal/cache/persistence/soplog/hfile/HFileSortedOplog.java | 22620 | /*
* 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.gemstone.gemfire.internal.cache.persistence.soplog.hfile;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumMap;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import com.gemstone.gemfire.cache.hdfs.HDFSIOException;
import com.gemstone.gemfire.internal.cache.persistence.soplog.AbstractSortedReader;
import com.gemstone.gemfire.internal.cache.persistence.soplog.ComponentLogWriter;
import com.gemstone.gemfire.internal.cache.persistence.soplog.DelegatingSerializedComparator;
import com.gemstone.gemfire.internal.cache.persistence.soplog.ReversingSerializedComparator;
import com.gemstone.gemfire.internal.cache.persistence.soplog.SortedBuffer.BufferIterator;
import com.gemstone.gemfire.internal.cache.persistence.soplog.SortedOplog;
import com.gemstone.gemfire.internal.cache.persistence.soplog.SortedOplogFactory.SortedOplogConfiguration;
import com.gemstone.gemfire.internal.cache.persistence.soplog.SortedReader.Metadata;
import com.gemstone.gemfire.internal.cache.persistence.soplog.SortedReader.SerializedComparator;
import com.gemstone.gemfire.internal.cache.persistence.soplog.SortedReader.SortedIterator;
import com.gemstone.gemfire.internal.cache.persistence.soplog.SortedReader.SortedStatistics;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
import com.gemstone.gemfire.internal.util.Bytes;
import com.gemstone.gemfire.internal.util.Hex;
import com.gemstone.gemfire.internal.util.LogService;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.io.hfile.CacheConfig;
import org.apache.hadoop.hbase.io.hfile.HFile;
import org.apache.hadoop.hbase.io.hfile.HFile.Reader;
import org.apache.hadoop.hbase.io.hfile.HFile.Writer;
import org.apache.hadoop.hbase.io.hfile.HFileContext;
import org.apache.hadoop.hbase.io.hfile.HFileContextBuilder;
import org.apache.hadoop.hbase.io.hfile.HFileScanner;
import org.apache.hadoop.hbase.regionserver.BloomType;
import org.apache.hadoop.hbase.util.BloomFilterFactory;
import org.apache.hadoop.hbase.util.BloomFilterWriter;
import org.apache.hadoop.hbase.util.FSUtils;
/**
* Provides a soplog backed by an HFile.
*
* @author bakera
*/
public class HFileSortedOplog implements SortedOplog {
public static final byte[] MAGIC = new byte[] { 0x53, 0x4F, 0x50 };
public static final byte[] VERSION_1 = new byte[] { 0x1 };
// FileInfo is not visible
private static final byte[] AVG_KEY_LEN = "hfile.AVG_KEY_LEN".getBytes();
private static final byte[] AVG_VALUE_LEN = "hfile.AVG_VALUE_LEN".getBytes();
/** a default bloom filter */
private static final BloomFilter DUMMY_BLOOM = new BloomFilter() {
@Override
public boolean mightContain(byte[] key) {
return true;
}
};
static final Configuration hconf;
private static final FileSystem fs;
static {
// Leave these HBase properties set to defaults for now
//
// hfile.block.cache.size (25% of heap)
// hbase.hash.type (murmur)
// hfile.block.index.cacheonwrite (false)
// hfile.index.block.max.size (128k)
// hfile.format.version (2)
// io.storefile.bloom.block.size (128k)
// hfile.block.bloom.cacheonwrite (false)
// hbase.rs.cacheblocksonwrite (false)
// hbase.offheapcache.minblocksize (64k)
// hbase.offheapcache.percentage (0)
hconf = new Configuration();
hconf.setBoolean("hbase.metrics.showTableName", true);
// [sumedh] should not be required with the new metrics2
// SchemaMetrics.configureGlobally(hconf);
try {
fs = FileSystem.get(hconf);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
private static enum InternalMetadata {
/** identifies the soplog as a gemfire file, required */
GEMFIRE_MAGIC,
/** identifies the soplog version, required */
VERSION,
/** identifies the statistics data */
STATISTICS,
/** identifies the names of embedded comparators */
COMPARATORS;
public byte[] bytes() {
return ("gemfire." + name()).getBytes();
}
}
/** the logger */
private final ComponentLogWriter logger;
/** the configuration */
private final SortedOplogConfiguration sopConfig;
/** the hfile cache config */
private final CacheConfig hcache;
/** the hfile location */
private Path path;
public HFileSortedOplog(File hfile, SortedOplogConfiguration sopConfig) throws IOException {
assert hfile != null;
assert sopConfig != null;
this.sopConfig = sopConfig;
path = fs.makeQualified(new Path(hfile.toString()));
// hcache = new CacheConfig(hconf, sopConfig.getCacheDataBlocksOnRead(), sopConfig.getBlockCache(),
// HFileSortedOplogFactory.convertStatistics(sopConfig.getStatistics(), sopConfig.getStoreStatistics()));
hcache = new CacheConfig(hconf);
logger = ComponentLogWriter.getSoplogLogWriter(sopConfig.getName(), LogService.logger());
}
@Override
public SortedOplogReader createReader() throws IOException {
if (logger.fineEnabled()) {
logger.fine("Creating an HFile reader on " + path);
}
return new HFileSortedOplogReader();
}
@Override
public SortedOplogWriter createWriter() throws IOException {
if (logger.fineEnabled()) {
logger.fine("Creating an HFile writer on " + path);
}
return new HFileSortedOplogWriter();
}
SortedOplogConfiguration getConfiguration() {
return sopConfig;
}
private class HFileSortedOplogReader extends AbstractSortedReader implements SortedOplogReader {
private final Reader reader;
private final BloomFilter bloom;
private final SortedStatistics stats;
private volatile boolean closed;
public HFileSortedOplogReader() throws IOException {
reader = HFile.createReader(fs, path, hcache, hconf);
validate();
stats = new HFileSortedStatistics(reader);
closed = false;
if (reader.getComparator() instanceof DelegatingSerializedComparator) {
loadComparators((DelegatingSerializedComparator) reader.getComparator());
}
DataInput bin = reader.getGeneralBloomFilterMetadata();
if (bin != null) {
final org.apache.hadoop.hbase.util.BloomFilter hbloom = BloomFilterFactory.createFromMeta(bin, reader);
if (reader.getComparator() instanceof DelegatingSerializedComparator) {
loadComparators((DelegatingSerializedComparator) hbloom.getComparator());
}
bloom = new BloomFilter() {
@Override
public boolean mightContain(byte[] key) {
assert key != null;
long start = sopConfig.getStatistics().getBloom().begin();
boolean foundKey = hbloom.contains(key, 0, key.length, null);
sopConfig.getStatistics().getBloom().end(start);
if (logger.finestEnabled()) {
logger.finest(String.format("Bloom check on %s for key %s: %b",
path, Hex.toHex(key), foundKey));
}
return foundKey;
}
};
} else {
bloom = DUMMY_BLOOM;
}
}
@Override
public boolean mightContain(byte[] key) {
return getBloomFilter().mightContain(key);
}
@Override
public ByteBuffer read(byte[] key) throws IOException {
assert key != null;
if (logger.finestEnabled()) {
logger.finest(String.format("Reading key %s from %s", Hex.toHex(key), path));
}
long start = sopConfig.getStatistics().getRead().begin();
try {
HFileScanner seek = reader.getScanner(true, true);
if (seek.seekTo(key) == 0) {
ByteBuffer val = seek.getValue();
sopConfig.getStatistics().getRead().end(val.remaining(), start);
return val;
}
sopConfig.getStatistics().getRead().end(start);
sopConfig.getStatistics().getBloom().falsePositive();
return null;
} catch (IOException e) {
sopConfig.getStatistics().getRead().error(start);
throw (IOException) e.fillInStackTrace();
}
}
@Override
public SortedIterator<ByteBuffer> scan(
byte[] from, boolean fromInclusive,
byte[] to, boolean toInclusive,
boolean ascending,
MetadataFilter filter) throws IOException {
if (filter == null || filter.accept(getMetadata(filter.getName()))) {
SerializedComparator tmp = (SerializedComparator) reader.getComparator();
tmp = ascending ? tmp : ReversingSerializedComparator.reverse(tmp);
// HFileScanner scan = reader.getScanner(true, false, ascending, false);
HFileScanner scan = reader.getScanner(true, false, false);
return new HFileSortedIterator(scan, tmp, from, fromInclusive, to, toInclusive);
}
return new BufferIterator(Collections.<byte[], byte[]>emptyMap().entrySet().iterator());
}
@Override
public SerializedComparator getComparator() {
return (SerializedComparator) reader.getComparator();
}
@Override
public SortedStatistics getStatistics() {
return stats;
}
@Override
public boolean isClosed() {
return closed;
}
@Override
public void close() throws IOException {
if (logger.fineEnabled()) {
logger.fine("Closing reader on " + path);
}
reader.close();
closed = true;
}
@Override
public BloomFilter getBloomFilter() {
return bloom;
}
@Override
public byte[] getMetadata(Metadata name) throws IOException {
assert name != null;
return reader.loadFileInfo().get(name.bytes());
}
@Override
public File getFile() {
return new File(path.toUri());
}
@Override
public String getFileName() {
return path.getName();
}
@Override
public long getModificationTimeStamp() throws IOException {
FileStatus[] stats = FSUtils.listStatus(fs, path, null);
if (stats != null && stats.length == 1) {
return stats[0].getModificationTime();
} else {
return 0;
}
}
@Override
public void rename(String name) throws IOException {
Path parent = path.getParent();
Path newPath = new Path(parent, name);
fs.rename(path, newPath);
// update path to point to the new path
path = newPath;
}
@Override
public void delete() throws IOException {
fs.delete(path, false);
}
@Override
public String toString() {
return path.toString();
}
private byte[] getMetadata(InternalMetadata name) throws IOException {
return reader.loadFileInfo().get(name.bytes());
}
private void validate() throws IOException {
// check magic
byte[] magic = getMetadata(InternalMetadata.GEMFIRE_MAGIC);
if (!Arrays.equals(magic, MAGIC)) {
throw new IOException(LocalizedStrings.Soplog_INVALID_MAGIC.toLocalizedString(Hex.toHex(magic)));
}
// check version compatibility
byte[] ver = getMetadata(InternalMetadata.VERSION);
if (logger.fineEnabled()) {
logger.fine("Soplog version is " + Hex.toHex(ver));
}
if (!Arrays.equals(ver, VERSION_1)) {
throw new IOException(LocalizedStrings.Soplog_UNRECOGNIZED_VERSION.toLocalizedString(Hex.toHex(ver)));
}
}
private void loadComparators(DelegatingSerializedComparator comparator) throws IOException {
byte[] raw = reader.loadFileInfo().get(InternalMetadata.COMPARATORS.bytes());
assert raw != null;
DataInput in = new DataInputStream(new ByteArrayInputStream(raw));
comparator.setComparators(readComparators(in));
}
private SerializedComparator[] readComparators(DataInput in) throws IOException {
try {
SerializedComparator[] comps = new SerializedComparator[in.readInt()];
assert comps.length > 0;
for (int i = 0; i < comps.length; i++) {
comps[i] = (SerializedComparator) Class.forName(in.readUTF()).newInstance();
if (comps[i] instanceof DelegatingSerializedComparator) {
((DelegatingSerializedComparator) comps[i]).setComparators(readComparators(in));
}
}
return comps;
} catch (Exception e) {
throw new IOException(e);
}
}
}
private class HFileSortedOplogWriter implements SortedOplogWriter {
private final Writer writer;
private final BloomFilterWriter bfw;
public HFileSortedOplogWriter() throws IOException {
HFileContext hcontext = new HFileContextBuilder()
.withBlockSize(sopConfig.getBlockSize())
.withBytesPerCheckSum(sopConfig.getBytesPerChecksum())
.withChecksumType(HFileSortedOplogFactory.convertChecksum(
sopConfig.getChecksum()))
.withCompression(HFileSortedOplogFactory.convertCompression(
sopConfig.getCompression()))
.withDataBlockEncoding(HFileSortedOplogFactory.convertEncoding(
sopConfig.getKeyEncoding()).getDataBlockEncoding())
.build();
writer = HFile.getWriterFactory(hconf, hcache)
.withPath(fs, path)
.withFileContext(hcontext)
.withComparator(sopConfig.getComparator())
.create();
bfw = sopConfig.isBloomFilterEnabled() ?
// BloomFilterFactory.createGeneralBloomAtWrite(hconf, hcache, BloomType.ROW,
// 0, writer, sopConfig.getComparator())
BloomFilterFactory.createGeneralBloomAtWrite(hconf, hcache, BloomType.ROW,
0, writer)
: null;
}
@Override
public void append(byte[] key, byte[] value) throws IOException {
assert key != null;
assert value != null;
if (logger.finestEnabled()) {
logger.finest(String.format("Appending key %s to %s", Hex.toHex(key), path));
}
try {
writer.append(key, value);
if (bfw != null) {
bfw.add(key, 0, key.length);
}
} catch (IOException e) {
throw (IOException) e.fillInStackTrace();
}
}
@Override
public void append(ByteBuffer key, ByteBuffer value) throws IOException {
assert key != null;
assert value != null;
if (logger.finestEnabled()) {
logger.finest(String.format("Appending key %s to %s",
Hex.toHex(key.array(), key.arrayOffset(), key.remaining()), path));
}
try {
byte[] keyBytes = key.array();
final int keyOffset = key.arrayOffset();
final int keyLength = key.remaining();
if (keyOffset != 0 || keyLength != keyBytes.length) {
byte[] newKeyBytes = new byte[keyLength];
System.arraycopy(keyBytes, keyOffset, newKeyBytes, 0, keyLength);
keyBytes = newKeyBytes;
}
byte[] valueBytes = value.array();
final int valueOffset = value.arrayOffset();
final int valueLength = value.remaining();
if (valueOffset != 0 || valueLength != valueBytes.length) {
byte[] newValueBytes = new byte[valueLength];
System.arraycopy(valueBytes, valueOffset, newValueBytes, 0,
valueLength);
valueBytes = newValueBytes;
}
writer.append(keyBytes, valueBytes);
if (bfw != null) {
bfw.add(keyBytes, 0, keyLength);
}
} catch (IOException e) {
throw (IOException) e.fillInStackTrace();
}
}
@Override
public void close(EnumMap<Metadata, byte[]> metadata) throws IOException {
if (logger.fineEnabled()) {
logger.fine("Finalizing and closing writer on " + path);
}
if (bfw != null) {
bfw.compactBloom();
writer.addGeneralBloomFilter(bfw);
}
// append system metadata
writer.appendFileInfo(InternalMetadata.GEMFIRE_MAGIC.bytes(), MAGIC);
writer.appendFileInfo(InternalMetadata.VERSION.bytes(), VERSION_1);
// append comparator info
// if (writer.getComparator() instanceof DelegatingSerializedComparator) {
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// DataOutput out = new DataOutputStream(bos);
//
// writecomparatorinfo(out, ((delegatingserializedcomparator) writer.getcomparator()).getcomparators());
// writer.appendFileInfo(InternalMetadata.COMPARATORS.bytes(), bos.toByteArray());
// }
// TODO write statistics data to soplog
// writer.appendFileInfo(Meta.STATISTICS.toBytes(), null);
// append user metadata
if (metadata != null) {
for (Entry<Metadata, byte[]> entry : metadata.entrySet()) {
writer.appendFileInfo(entry.getKey().name().getBytes(), entry.getValue());
}
}
writer.close();
}
@Override
public void closeAndDelete() throws IOException {
if (logger.fineEnabled()) {
logger.fine("Closing writer and deleting " + path);
}
writer.close();
new File(writer.getPath().toUri()).delete();
}
// private void writeComparatorInfo(DataOutput out, SerializedComparator[] comparators) throws IOException {
// out.writeInt(comparators.length);
// for (SerializedComparator sc : comparators) {
// out.writeUTF(sc.getClass().getName());
// if (sc instanceof DelegatingSerializedComparator) {
// writeComparatorInfo(out, ((DelegatingSerializedComparator) sc).getComparators());
// }
// }
// }
}
private class HFileSortedIterator implements SortedIterator<ByteBuffer> {
private final HFileScanner scan;
private final SerializedComparator comparator;
private final byte[] from;
private final boolean fromInclusive;
private final byte[] to;
private final boolean toInclusive;
private final long start;
private long bytes;
private boolean foundNext;
private ByteBuffer key;
private ByteBuffer value;
public HFileSortedIterator(HFileScanner scan, SerializedComparator comparator,
byte[] from, boolean fromInclusive,
byte[] to, boolean toInclusive) throws IOException {
this.scan = scan;
this.comparator = comparator;
this.from = from;
this.fromInclusive = fromInclusive;
this.to = to;
this.toInclusive = toInclusive;
assert from == null
|| to == null
|| comparator.compare(from, 0, from.length, to, 0, to.length) <= 0;
start = sopConfig.getStatistics().getScan().begin();
foundNext = evalFrom();
}
@Override
public ByteBuffer key() {
return key;
}
@Override
public ByteBuffer value() {
return value;
}
@Override
public boolean hasNext() {
if (!foundNext) {
foundNext = step();
}
return foundNext;
}
@Override
public ByteBuffer next() {
long startNext = sopConfig.getStatistics().getScan().beginIteration();
if (!hasNext()) {
throw new NoSuchElementException();
}
foundNext = false;
key = scan.getKey();
value = scan.getValue();
int len = key.remaining() + value.remaining();
bytes += len;
sopConfig.getStatistics().getScan().endIteration(len, startNext);
return key;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public void close() {
sopConfig.getStatistics().getScan().end(bytes, start);
}
private boolean step() {
try {
if (!scan.isSeeked()) {
return false;
} else if (scan.next() && evalTo()) {
return true;
}
} catch (IOException e) {
throw new HDFSIOException("Error from HDFS during iteration", e);
}
return false;
}
private boolean evalFrom() throws IOException {
if (from == null) {
return scan.seekTo() && evalTo();
} else {
int compare = scan.seekTo(from);
if (compare < 0) {
return scan.seekTo() && evalTo();
} else if (compare == 0 && fromInclusive) {
return true;
} else {
return step();
}
}
}
private boolean evalTo() throws IOException {
int compare = -1;
if (to != null) {
ByteBuffer key = scan.getKey();
compare = comparator.compare(
key.array(), key.arrayOffset(), key.remaining(),
to, 0, to.length);
}
return compare < 0 || (compare == 0 && toInclusive);
}
}
private static class HFileSortedStatistics implements SortedStatistics {
private final Reader reader;
private final int keySize;
private final int valueSize;
public HFileSortedStatistics(Reader reader) throws IOException {
this.reader = reader;
byte[] sz = reader.loadFileInfo().get(AVG_KEY_LEN);
keySize = Bytes.toInt(sz[0], sz[1], sz[2], sz[3]);
sz = reader.loadFileInfo().get(AVG_VALUE_LEN);
valueSize = Bytes.toInt(sz[0], sz[1], sz[2], sz[3]);
}
@Override
public long keyCount() {
return reader.getEntries();
}
@Override
public byte[] firstKey() {
return reader.getFirstKey();
}
@Override
public byte[] lastKey() {
return reader.getLastKey();
}
@Override
public double avgKeySize() {
return keySize;
}
@Override
public double avgValueSize() {
return valueSize;
}
@Override
public void close() {
}
}
}
| apache-2.0 |
jbeecham/ovirt-engine | backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/adbroker/ITDSRootDSE.java | 971 | package org.ovirt.engine.core.bll.adbroker;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
public class ITDSRootDSE implements RootDSE {
private String defaultNamingContext;
public ITDSRootDSE() {
}
public ITDSRootDSE(String defaultNamingContext) {
this.defaultNamingContext = defaultNamingContext;
}
public ITDSRootDSE(Attributes rootDseRecords) throws NamingException {
Attribute namingContexts = rootDseRecords.get(ITDSRootDSEAttributes.namingContexts.name());
if ( namingContexts != null ) {
this.defaultNamingContext = namingContexts.get(0).toString();
}
}
@Override
public void setDefaultNamingContext(String defaultNamingContext) {
this.defaultNamingContext = defaultNamingContext;
}
@Override
public String getDefaultNamingContext() {
return defaultNamingContext;
}
}
| apache-2.0 |
nuan-nuan/FanJu | src/com/yuncheng/china/Fanju/db/DBConst.java | 438 | package com.yuncheng.china.Fanju.db;
/**
* Created by agonyice on 14-9-9.
*/
public class DBConst {
public static final String DB_NAME = "fanju";
public static final String TABLE_USER_DATA = "userdata";
public static final String TABLE_USER_IMG="userimg";
public static final String TABLE_USER = "user";
public static final String TABLE_CITY = "city";
public static final String FIRST_PINYIN = "firstPinyin";
}
| apache-2.0 |
wengyanqing/incubator-hawq | pxf/pxf-service/src/test/java/org/apache/hawq/pxf/service/utilities/ProtocolDataTest.java | 17014 | package org.apache.hawq.pxf.service.utilities;
/*
* 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 org.apache.hawq.pxf.api.OutputFormat;
import org.apache.hawq.pxf.api.utilities.ProfileConfException;
import static org.apache.hawq.pxf.api.utilities.ProfileConfException.MessageFormat.NO_PROFILE_DEF;
import org.apache.hawq.pxf.api.utilities.ProfilesConf;
import org.junit.Before;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import org.apache.hadoop.security.UserGroupInformation;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ UserGroupInformation.class, ProfilesConf.class })
public class ProtocolDataTest {
Map<String, String> parameters;
@Test
public void protocolDataCreated() throws Exception {
ProtocolData protocolData = new ProtocolData(parameters);
assertEquals(System.getProperty("greenplum.alignment"), "all");
assertEquals(protocolData.getTotalSegments(), 2);
assertEquals(protocolData.getSegmentId(), -44);
assertEquals(protocolData.outputFormat(), OutputFormat.TEXT);
assertEquals(protocolData.serverName(), "my://bags");
assertEquals(protocolData.serverPort(), -8020);
assertFalse(protocolData.hasFilter());
assertNull(protocolData.getFilterString());
assertEquals(protocolData.getColumns(), 0);
assertEquals(protocolData.getDataFragment(), -1);
assertNull(protocolData.getRecordkeyColumn());
assertEquals(protocolData.getAccessor(), "are");
assertEquals(protocolData.getResolver(), "packed");
assertEquals(protocolData.getDataSource(), "i'm/ready/to/go");
assertEquals(protocolData.getUserProperty("i'm-standing-here"),
"outside-your-door");
assertEquals(protocolData.getParametersMap(), parameters);
assertNull(protocolData.getLogin());
assertNull(protocolData.getSecret());
}
@Test
public void ProtocolDataCopied() throws Exception {
ProtocolData protocolData = new ProtocolData(parameters);
ProtocolData copy = new ProtocolData(protocolData);
assertEquals(copy.getParametersMap(), protocolData.getParametersMap());
}
@Test
public void profileWithDuplicateProperty() throws Exception {
PowerMockito.mockStatic(ProfilesConf.class);
Map<String, String> mockedProfiles = new HashMap<>();
mockedProfiles.put("wHEn you trY yOUR bESt", "but you dont succeed");
mockedProfiles.put("when YOU get WHAT you WANT",
"but not what you need");
mockedProfiles.put("when you feel so tired", "but you cant sleep");
when(ProfilesConf.getProfilePluginsMap("a profile")).thenReturn(
mockedProfiles);
parameters.put("x-gp-profile", "a profile");
parameters.put("when you try your best", "and you do succeed");
parameters.put("WHEN you GET what YOU want", "and what you need");
try {
new ProtocolData(parameters);
fail("Duplicate property should throw IllegalArgumentException");
} catch (IllegalArgumentException iae) {
assertEquals(
"Profile 'a profile' already defines: [when YOU get WHAT you WANT, wHEn you trY yOUR bESt]",
iae.getMessage());
}
}
@Test
public void definedProfile() throws Exception {
parameters.put("X-GP-PROFILE", "HIVE");
parameters.remove("X-GP-ACCESSOR");
parameters.remove("X-GP-RESOLVER");
ProtocolData protocolData = new ProtocolData(parameters);
assertEquals(protocolData.getFragmenter(), "org.apache.hawq.pxf.plugins.hive.HiveDataFragmenter");
assertEquals(protocolData.getAccessor(), "org.apache.hawq.pxf.plugins.hive.HiveAccessor");
assertEquals(protocolData.getResolver(), "org.apache.hawq.pxf.plugins.hive.HiveResolver");
}
@Test
public void undefinedProfile() throws Exception {
parameters.put("X-GP-PROFILE", "THIS_PROFILE_NEVER_EXISTED!");
try {
new ProtocolData(parameters);
fail("Undefined profile should throw ProfileConfException");
} catch (ProfileConfException pce) {
assertEquals(pce.getMsgFormat(), NO_PROFILE_DEF);
}
}
@Test
public void threadSafeTrue() throws Exception {
parameters.put("X-GP-THREAD-SAFE", "TRUE");
ProtocolData protocolData = new ProtocolData(parameters);
assertEquals(protocolData.isThreadSafe(), true);
parameters.put("X-GP-THREAD-SAFE", "true");
protocolData = new ProtocolData(parameters);
assertEquals(protocolData.isThreadSafe(), true);
}
@Test
public void threadSafeFalse() throws Exception {
parameters.put("X-GP-THREAD-SAFE", "False");
ProtocolData protocolData = new ProtocolData(parameters);
assertEquals(protocolData.isThreadSafe(), false);
parameters.put("X-GP-THREAD-SAFE", "falSE");
protocolData = new ProtocolData(parameters);
assertEquals(protocolData.isThreadSafe(), false);
}
@Test
public void threadSafeMaybe() throws Exception {
parameters.put("X-GP-THREAD-SAFE", "maybe");
try {
new ProtocolData(parameters);
fail("illegal THREAD-SAFE value should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertEquals(e.getMessage(),
"Illegal boolean value 'maybe'. Usage: [TRUE|FALSE]");
}
}
@Test
public void threadSafeDefault() throws Exception {
parameters.remove("X-GP-THREAD-SAFE");
ProtocolData protocolData = new ProtocolData(parameters);
assertEquals(protocolData.isThreadSafe(), true);
}
@Test
public void getFragmentMetadata() throws Exception {
ProtocolData protocolData = new ProtocolData(parameters);
byte[] location = protocolData.getFragmentMetadata();
assertEquals(new String(location), "Something in the way");
}
@Test
public void getFragmentMetadataNull() throws Exception {
parameters.remove("X-GP-FRAGMENT-METADATA");
ProtocolData ProtocolData = new ProtocolData(parameters);
assertNull(ProtocolData.getFragmentMetadata());
}
@Test
public void getFragmentMetadataNotBase64() throws Exception {
String badValue = "so b@d";
parameters.put("X-GP-FRAGMENT-METADATA", badValue);
try {
new ProtocolData(parameters);
fail("should fail with bad fragment metadata");
} catch (Exception e) {
assertEquals(e.getMessage(),
"Fragment metadata information must be Base64 encoded."
+ "(Bad value: " + badValue + ")");
}
}
@Test
public void nullTokenThrows() throws Exception {
when(UserGroupInformation.isSecurityEnabled()).thenReturn(true);
try {
new ProtocolData(parameters);
fail("null X-GP-TOKEN should throw");
} catch (IllegalArgumentException e) {
assertEquals(e.getMessage(),
"Internal server error. Property \"TOKEN\" has no value in current request");
}
}
@Test
public void filterUtf8() throws Exception {
parameters.remove("X-GP-HAS-FILTER");
parameters.put("X-GP-HAS-FILTER", "1");
parameters.put("X-GP-FILTER", "UTF8_計算機用語_00000000");
ProtocolData protocolData = new ProtocolData(parameters);
assertTrue(protocolData.hasFilter());
assertEquals("UTF8_計算機用語_00000000", protocolData.getFilterString());
}
@Test
public void noStatsParams() {
ProtocolData protData = new ProtocolData(parameters);
assertEquals(0, protData.getStatsMaxFragments());
assertEquals(0, protData.getStatsSampleRatio(), 0.1);
}
@Test
public void statsParams() {
parameters.put("X-GP-STATS-MAX-FRAGMENTS", "10101");
parameters.put("X-GP-STATS-SAMPLE-RATIO", "0.039");
ProtocolData protData = new ProtocolData(parameters);
assertEquals(10101, protData.getStatsMaxFragments());
assertEquals(0.039, protData.getStatsSampleRatio(), 0.01);
}
@Test
public void statsMissingParams() {
parameters.put("X-GP-STATS-MAX-FRAGMENTS", "13");
try {
new ProtocolData(parameters);
fail("missing X-GP-STATS-SAMPLE-RATIO parameter");
} catch (IllegalArgumentException e) {
assertEquals(
e.getMessage(),
"Missing parameter: STATS-SAMPLE-RATIO and STATS-MAX-FRAGMENTS must be set together");
}
parameters.remove("X-GP-STATS-MAX-FRAGMENTS");
parameters.put("X-GP-STATS-SAMPLE-RATIO", "1");
try {
new ProtocolData(parameters);
fail("missing X-GP-STATS-MAX-FRAGMENTS parameter");
} catch (IllegalArgumentException e) {
assertEquals(
e.getMessage(),
"Missing parameter: STATS-SAMPLE-RATIO and STATS-MAX-FRAGMENTS must be set together");
}
}
@Test
public void statsSampleRatioNegative() {
parameters.put("X-GP-STATS-SAMPLE-RATIO", "101");
try {
new ProtocolData(parameters);
fail("wrong X-GP-STATS-SAMPLE-RATIO value");
} catch (IllegalArgumentException e) {
assertEquals(
e.getMessage(),
"Wrong value '101.0'. "
+ "STATS-SAMPLE-RATIO must be a value between 0.0001 and 1.0");
}
parameters.put("X-GP-STATS-SAMPLE-RATIO", "0");
try {
new ProtocolData(parameters);
fail("wrong X-GP-STATS-SAMPLE-RATIO value");
} catch (IllegalArgumentException e) {
assertEquals(
e.getMessage(),
"Wrong value '0.0'. "
+ "STATS-SAMPLE-RATIO must be a value between 0.0001 and 1.0");
}
parameters.put("X-GP-STATS-SAMPLE-RATIO", "0.00005");
try {
new ProtocolData(parameters);
fail("wrong X-GP-STATS-SAMPLE-RATIO value");
} catch (IllegalArgumentException e) {
assertEquals(
e.getMessage(),
"Wrong value '5.0E-5'. "
+ "STATS-SAMPLE-RATIO must be a value between 0.0001 and 1.0");
}
parameters.put("X-GP-STATS-SAMPLE-RATIO", "a");
try {
new ProtocolData(parameters);
fail("wrong X-GP-STATS-SAMPLE-RATIO value");
} catch (NumberFormatException e) {
assertEquals(e.getMessage(), "For input string: \"a\"");
}
}
@Test
public void statsMaxFragmentsNegative() {
parameters.put("X-GP-STATS-MAX-FRAGMENTS", "10.101");
try {
new ProtocolData(parameters);
fail("wrong X-GP-STATS-MAX-FRAGMENTS value");
} catch (NumberFormatException e) {
assertEquals(e.getMessage(), "For input string: \"10.101\"");
}
parameters.put("X-GP-STATS-MAX-FRAGMENTS", "0");
try {
new ProtocolData(parameters);
fail("wrong X-GP-STATS-MAX-FRAGMENTS value");
} catch (IllegalArgumentException e) {
assertEquals(e.getMessage(), "Wrong value '0'. "
+ "STATS-MAX-FRAGMENTS must be a positive integer");
}
}
@Test
public void typeMods() {
parameters.put("X-GP-ATTRS", "2");
parameters.put("X-GP-ATTR-NAME0", "vc1");
parameters.put("X-GP-ATTR-TYPECODE0", "1043");
parameters.put("X-GP-ATTR-TYPENAME0", "varchar");
parameters.put("X-GP-ATTR-TYPEMOD0-COUNT", "1");
parameters.put("X-GP-ATTR-TYPEMOD0-0", "5");
parameters.put("X-GP-ATTR-NAME1", "dec1");
parameters.put("X-GP-ATTR-TYPECODE1", "1700");
parameters.put("X-GP-ATTR-TYPENAME1", "numeric");
parameters.put("X-GP-ATTR-TYPEMOD1-COUNT", "2");
parameters.put("X-GP-ATTR-TYPEMOD1-0", "10");
parameters.put("X-GP-ATTR-TYPEMOD1-1", "2");
ProtocolData protocolData = new ProtocolData(parameters);
assertArrayEquals(protocolData.getColumn(0).columnTypeModifiers(), new Integer[]{5});
assertArrayEquals(protocolData.getColumn(1).columnTypeModifiers(), new Integer[]{10, 2});
}
@Test
public void typeModsNegative() {
parameters.put("X-GP-ATTRS", "1");
parameters.put("X-GP-ATTR-NAME0", "vc1");
parameters.put("X-GP-ATTR-TYPECODE0", "1043");
parameters.put("X-GP-ATTR-TYPENAME0", "varchar");
parameters.put("X-GP-ATTR-TYPEMOD0-COUNT", "X");
parameters.put("X-GP-ATTR-TYPEMOD0-0", "Y");
try {
ProtocolData protocolData = new ProtocolData(parameters);
fail("should throw IllegalArgumentException when bad value received for X-GP-ATTR-TYPEMOD0-COUNT");
} catch (IllegalArgumentException iae) {
assertEquals(
"ATTR-TYPEMOD0-COUNT must be a positive integer",
iae.getMessage());
}
parameters.put("X-GP-ATTR-TYPEMOD0-COUNT", "-1");
try {
ProtocolData protocolData = new ProtocolData(parameters);
fail("should throw IllegalArgumentException when negative value received for X-GP-ATTR-TYPEMOD0-COUNT");
} catch (IllegalArgumentException iae) {
assertEquals(
"ATTR-TYPEMOD0-COUNT cann't be negative",
iae.getMessage());
}
parameters.put("X-GP-ATTR-TYPEMOD0-COUNT", "1");
try {
ProtocolData protocolData = new ProtocolData(parameters);
fail("should throw IllegalArgumentException when bad value received for X-GP-ATTR-TYPEMOD0-0");
} catch (IllegalArgumentException iae) {
assertEquals(
"ATTR-TYPEMOD0-0 must be a positive integer",
iae.getMessage());
}
parameters.put("X-GP-ATTR-TYPEMOD0-COUNT", "2");
parameters.put("X-GP-ATTR-TYPEMOD0-0", "42");
try {
ProtocolData protocolData = new ProtocolData(parameters);
fail("should throw IllegalArgumentException number of actual type modifiers is less than X-GP-ATTR-TYPEMODX-COUNT");
} catch (IllegalArgumentException iae) {
assertEquals(
"Internal server error. Property \"ATTR-TYPEMOD0-1\" has no value in current request",
iae.getMessage());
}
}
/*
* setUp function called before each test
*/
@Before
public void setUp() {
parameters = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
parameters.put("X-GP-ALIGNMENT", "all");
parameters.put("X-GP-SEGMENT-ID", "-44");
parameters.put("X-GP-SEGMENT-COUNT", "2");
parameters.put("X-GP-HAS-FILTER", "0");
parameters.put("X-GP-FORMAT", "TEXT");
parameters.put("X-GP-URL-HOST", "my://bags");
parameters.put("X-GP-URL-PORT", "-8020");
parameters.put("X-GP-ATTRS", "-1");
parameters.put("X-GP-ACCESSOR", "are");
parameters.put("X-GP-RESOLVER", "packed");
parameters.put("X-GP-DATA-DIR", "i'm/ready/to/go");
parameters.put("X-GP-FRAGMENT-METADATA", "U29tZXRoaW5nIGluIHRoZSB3YXk=");
parameters.put("X-GP-I'M-STANDING-HERE", "outside-your-door");
PowerMockito.mockStatic(UserGroupInformation.class);
}
/*
* tearDown function called after each test
*/
@After
public void tearDown() {
// Cleanup the system property ProtocolData sets
System.clearProperty("greenplum.alignment");
}
}
| apache-2.0 |
haoyanjun21/jstorm | jstorm-core/src/main/java/com/alibaba/jstorm/client/ConfigExtension.java | 48763 | /**
* 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 com.alibaba.jstorm.client;
import backtype.storm.Config;
import backtype.storm.utils.Utils;
import com.alibaba.jstorm.config.DefaultConfigUpdateHandler;
import com.alibaba.jstorm.utils.JStormUtils;
import org.apache.commons.lang.StringUtils;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class ConfigExtension {
/**
* if this configure has been set, the spout or bolt will log all receive tuples
* <p/>
* topology.debug just for logging all sent tuples
*/
protected static final String TOPOLOGY_DEBUG_RECV_TUPLE = "topology.debug.recv.tuple";
public static void setTopologyDebugRecvTuple(Map conf, boolean debug) {
conf.put(TOPOLOGY_DEBUG_RECV_TUPLE, debug);
}
public static Boolean isTopologyDebugRecvTuple(Map conf) {
return JStormUtils.parseBoolean(conf.get(TOPOLOGY_DEBUG_RECV_TUPLE), false);
}
private static final String TOPOLOGY_DEBUG_SAMPLE_RATE = "topology.debug.sample.rate";
public static double getTopologyDebugSampleRate(Map conf) {
double rate = JStormUtils.parseDouble(conf.get(TOPOLOGY_DEBUG_SAMPLE_RATE), 1.0d);
if (!conf.containsKey(TOPOLOGY_DEBUG_SAMPLE_RATE)) {
conf.put(TOPOLOGY_DEBUG_SAMPLE_RATE, rate);
}
return rate;
}
public static void setTopologyDebugSampleRate(Map conf, double rate) {
conf.put(TOPOLOGY_DEBUG_SAMPLE_RATE, rate);
}
private static final String TOPOLOGY_ENABLE_METRIC_DEBUG = "topology.enable.metric.debug";
public static boolean isEnableMetricDebug(Map conf) {
return JStormUtils.parseBoolean(conf.get(TOPOLOGY_ENABLE_METRIC_DEBUG), false);
}
private static final String TOPOLOGY_DEBUG_METRIC_NAMES = "topology.debug.metric.names";
public static String getDebugMetricNames(Map conf) {
String metrics = (String) conf.get(TOPOLOGY_DEBUG_METRIC_NAMES);
if (metrics == null) {
return "";
}
return metrics;
}
/**
* metrics switch, ONLY for performance test, DO NOT set it to false in production
*/
private static final String TOPOLOGY_ENABLE_METRICS = "topology.enable.metrics";
public static boolean isEnableMetrics(Map conf) {
return JStormUtils.parseBoolean(conf.get(TOPOLOGY_ENABLE_METRICS), true);
}
/**
* whether to enable stream metrics, in order to reduce metrics data
*/
public static final String TOPOLOGY_ENABLE_STREAM_METRICS = "topology.enable.stream.metrics";
public static boolean isEnableStreamMetrics(Map conf) {
return JStormUtils.parseBoolean(conf.get(TOPOLOGY_ENABLE_STREAM_METRICS), true);
}
/**
* metric names to be enabled on the fly
*/
private static final String TOPOLOGY_ENABLED_METRIC_NAMES = "topology.enabled.metric.names";
public static String getEnabledMetricNames(Map conf) {
return (String) conf.get(TOPOLOGY_ENABLED_METRIC_NAMES);
}
public static void setEnabledMetricNames(Map conf, String metrics) {
conf.put(TOPOLOGY_ENABLED_METRIC_NAMES, metrics);
}
/**
* metric names to be disabled on the fly
*/
private static final String TOPOLOGY_DISABLED_METRIC_NAMES = "topology.disabled.metric.names";
public static String getDisabledMetricNames(Map conf) {
return (String) conf.get(TOPOLOGY_DISABLED_METRIC_NAMES);
}
public static void setDisabledMetricNames(Map conf, String metrics) {
conf.put(TOPOLOGY_DISABLED_METRIC_NAMES, metrics);
}
/**
* port number of deamon httpserver server
*/
private static final Integer DEFAULT_DEAMON_HTTPSERVER_PORT = 7621;
protected static final String SUPERVISOR_DEAMON_HTTPSERVER_PORT = "supervisor.deamon.logview.port";
public static Integer getSupervisorDeamonHttpserverPort(Map conf) {
return JStormUtils.parseInt(conf.get(SUPERVISOR_DEAMON_HTTPSERVER_PORT), DEFAULT_DEAMON_HTTPSERVER_PORT + 1);
}
protected static final String NIMBUS_DEAMON_HTTPSERVER_PORT = "nimbus.deamon.logview.port";
public static Integer getNimbusDeamonHttpserverPort(Map conf) {
return JStormUtils.parseInt(conf.get(NIMBUS_DEAMON_HTTPSERVER_PORT), DEFAULT_DEAMON_HTTPSERVER_PORT);
}
/**
* Worker gc parameter
*/
protected static final String WORKER_GC_CHILDOPTS = "worker.gc.childopts";
public static void setWorkerGc(Map conf, String gc) {
conf.put(WORKER_GC_CHILDOPTS, gc);
}
public static String getWorkerGc(Map conf) {
return (String) conf.get(WORKER_GC_CHILDOPTS);
}
protected static final String WOREKER_REDIRECT_OUTPUT = "worker.redirect.output";
public static boolean getWorkerRedirectOutput(Map conf) {
Object result = conf.get(WOREKER_REDIRECT_OUTPUT);
if (result == null)
return false;
return (Boolean) result;
}
protected static final String WOREKER_REDIRECT_OUTPUT_FILE = "worker.redirect.output.file";
public static void setWorkerRedirectOutputFile(Map conf, String outputPath) {
conf.put(WOREKER_REDIRECT_OUTPUT_FILE, outputPath);
}
public static String getWorkerRedirectOutputFile(Map conf) {
return (String) conf.get(WOREKER_REDIRECT_OUTPUT_FILE);
}
protected static final String OUTPUT_WOEKER_DUMP = "output.worker.dump";
public static boolean isOutworkerDump(Map conf) {
return JStormUtils.parseBoolean(conf.get(OUTPUT_WOEKER_DUMP), false);
}
/**
* Usually, spout finish prepare before bolt, so spout need wait several seconds so that bolt finish preparation
* <p/>
* By default, the setting is 30 seconds
*/
protected static final String SPOUT_DELAY_RUN = "spout.delay.run";
public static void setSpoutDelayRunSeconds(Map conf, int delay) {
conf.put(SPOUT_DELAY_RUN, delay);
}
public static int getSpoutDelayRunSeconds(Map conf) {
return JStormUtils.parseInt(conf.get(SPOUT_DELAY_RUN), 30);
}
/**
* Default ZMQ Pending queue size
*/
public static final int DEFAULT_ZMQ_MAX_QUEUE_MSG = 1000;
/**
* One task will alloc how many memory slot, the default setting is 1
*/
protected static final String MEM_SLOTS_PER_TASK = "memory.slots.per.task";
@Deprecated
public static void setMemSlotPerTask(Map conf, int slotNum) {
if (slotNum < 1) {
throw new InvalidParameterException();
}
conf.put(MEM_SLOTS_PER_TASK, slotNum);
}
/**
* One task will use cpu slot number, the default setting is 1
*/
protected static final String CPU_SLOTS_PER_TASK = "cpu.slots.per.task";
@Deprecated
public static void setCpuSlotsPerTask(Map conf, int slotNum) {
if (slotNum < 1) {
throw new InvalidParameterException();
}
conf.put(CPU_SLOTS_PER_TASK, slotNum);
}
/**
* * * worker machine minimum available memory (reserved)
*/
protected static final String STORM_MACHINE_RESOURCE_RESERVE_MEM = " storm.machine.resource.reserve.mem";
public static long getStormMachineReserveMem(Map conf) {
Long reserve = JStormUtils.parseLong(conf.get(STORM_MACHINE_RESOURCE_RESERVE_MEM), 1 * 1024 * 1024 * 1024L);
return reserve < 1 * 1024 * 1024 * 1024L ? 1 * 1024 * 1024 * 1024L : reserve;
}
public static void setStormMachineReserveMem(Map conf, long percent) {
conf.put(STORM_MACHINE_RESOURCE_RESERVE_MEM, Long.valueOf(percent));
}
/**
* * * worker machine upper boundary on cpu usage
*/
protected static final String STORM_MACHINE_RESOURCE_RESERVE_CPU_PERCENT = "storm.machine.resource.reserve.cpu.percent";
public static int getStormMachineReserveCpuPercent(Map conf) {
int percent = JStormUtils.parseInt(conf.get(STORM_MACHINE_RESOURCE_RESERVE_CPU_PERCENT), 10);
return percent < 10 ? 10 : percent;
}
public static void setStormMachineReserveCpuPercent(Map conf, int percent) {
conf.put(STORM_MACHINE_RESOURCE_RESERVE_CPU_PERCENT, Integer.valueOf(percent));
}
/**
* if the setting has been set, the component's task must run different node This is conflict with USE_SINGLE_NODE
*/
protected static final String TASK_ON_DIFFERENT_NODE = "task.on.differ.node";
public static void setTaskOnDifferentNode(Map conf, boolean isIsolate) {
conf.put(TASK_ON_DIFFERENT_NODE, isIsolate);
}
public static boolean isTaskOnDifferentNode(Map conf) {
return JStormUtils.parseBoolean(conf.get(TASK_ON_DIFFERENT_NODE), false);
}
protected static final String SUPERVISOR_ENABLE_CGROUP = "supervisor.enable.cgroup";
public static boolean isEnableCgroup(Map conf) {
return JStormUtils.parseBoolean(conf.get(SUPERVISOR_ENABLE_CGROUP), false);
}
/**
* supervisor health check
*/
protected static final String SUPERVISOR_ENABLE_CHECK = "supervisor.enable.check";
public static boolean isEnableCheckSupervisor(Map conf) {
return JStormUtils.parseBoolean(conf.get(SUPERVISOR_ENABLE_CHECK), false);
}
protected static String SUPERVISOR_FREQUENCY_CHECK = "supervisor.frequency.check.secs";
public static int getSupervisorFrequencyCheck(Map conf) {
return JStormUtils.parseInt(conf.get(SUPERVISOR_FREQUENCY_CHECK), 60);
}
protected static final String STORM_HEALTH_CHECK_DIR = "storm.health.check.dir";
public static String getStormHealthCheckDir(Map conf) {
return (String) (conf.get(STORM_HEALTH_CHECK_DIR));
}
protected static final String STORM_MACHINE_RESOURCE_PANIC_CHECK_DIR = "storm.machine.resource.panic.check.dir";
public static String getStormMachineResourcePanicCheckDir(Map conf) {
return (String) (conf.get(STORM_MACHINE_RESOURCE_PANIC_CHECK_DIR));
}
protected static final String STORM_MACHINE_RESOURCE_ERROR_CHECK_DIR = "storm.machine.resource.error.check.dir";
public static String getStormMachineResourceErrorCheckDir(Map conf) {
return (String) (conf.get(STORM_MACHINE_RESOURCE_ERROR_CHECK_DIR));
}
protected static final String STORM_MACHINE_RESOURCE_WARNING_CHECK_DIR = "storm.machine.resource.warning.check.dir";
public static String getStormMachineResourceWarningCheckDir(Map conf) {
return (String) (conf.get(STORM_MACHINE_RESOURCE_WARNING_CHECK_DIR));
}
protected static final String STORM_HEALTH_CHECK_TIMEOUT_MS = "storm.health.check.timeout.ms";
public static long getStormHealthTimeoutMs(Map conf) {
return JStormUtils.parseLong(conf.get(STORM_HEALTH_CHECK_TIMEOUT_MS), 5000);
}
protected static final String STORM_HEALTH_CHECK_MAX_DISK_UTILIZATION_PERCENTAGE =
"storm.health.check.dir.max.disk.utilization.percentage";
public static float getStormHealthCheckMaxDiskUtilizationPercentage(Map conf) {
return (float) (conf.get(STORM_HEALTH_CHECK_MAX_DISK_UTILIZATION_PERCENTAGE));
}
protected static final String STORM_HEALTH_CHECK_MIN_DISK_FREE_SPACE_MB =
"storm.health.check.min.disk.free.space.mb";
public static long getStormHealthCheckMinDiskFreeSpaceMb(Map conf) {
return (long) (conf.get(STORM_HEALTH_CHECK_MIN_DISK_FREE_SPACE_MB));
}
/**
* If component or topology configuration set "use.old.assignment", will try use old assignment firstly
*/
protected static final String USE_OLD_ASSIGNMENT = "use.old.assignment";
public static void setUseOldAssignment(Map conf, boolean useOld) {
conf.put(USE_OLD_ASSIGNMENT, useOld);
}
public static boolean isUseOldAssignment(Map conf) {
return JStormUtils.parseBoolean(conf.get(USE_OLD_ASSIGNMENT), false);
}
/**
* The supervisor's hostname
*/
protected static final String SUPERVISOR_HOSTNAME = "supervisor.hostname";
public static final Object SUPERVISOR_HOSTNAME_SCHEMA = String.class;
public static String getSupervisorHost(Map conf) {
return (String) conf.get(SUPERVISOR_HOSTNAME);
}
protected static final String SUPERVISOR_USE_IP = "supervisor.use.ip";
public static boolean isSupervisorUseIp(Map conf) {
return JStormUtils.parseBoolean(conf.get(SUPERVISOR_USE_IP), false);
}
protected static final String NIMBUS_USE_IP = "nimbus.use.ip";
public static boolean isNimbusUseIp(Map conf) {
return JStormUtils.parseBoolean(conf.get(NIMBUS_USE_IP), true);
}
protected static final String TOPOLOGY_ENABLE_CLASSLOADER = "topology.enable.classloader";
public static boolean isEnableTopologyClassLoader(Map conf) {
return JStormUtils.parseBoolean(conf.get(TOPOLOGY_ENABLE_CLASSLOADER), false);
}
public static void setEnableTopologyClassLoader(Map conf, boolean enable) {
conf.put(TOPOLOGY_ENABLE_CLASSLOADER, enable);
}
protected static String CLASSLOADER_DEBUG = "classloader.debug";
public static boolean isEnableClassloaderDebug(Map conf) {
return JStormUtils.parseBoolean(conf.get(CLASSLOADER_DEBUG), false);
}
public static void setEnableClassloaderDebug(Map conf, boolean enable) {
conf.put(CLASSLOADER_DEBUG, enable);
}
protected static final String CONTAINER_NIMBUS_HEARTBEAT = "container.nimbus.heartbeat";
/**
* Get to know whether nimbus is run under Apsara/Yarn container
*/
public static boolean isEnableContainerNimbus() {
String path = System.getenv(CONTAINER_NIMBUS_HEARTBEAT);
if (StringUtils.isBlank(path)) {
return false;
} else {
return true;
}
}
/**
* Get Apsara/Yarn nimbus container's hearbeat dir
*/
public static String getContainerNimbusHearbeat() {
return System.getenv(CONTAINER_NIMBUS_HEARTBEAT);
}
protected static final String CONTAINER_SUPERVISOR_HEARTBEAT = "container.supervisor.heartbeat";
/**
* Get to know whether supervisor is run under Apsara/Yarn supervisor container
*/
public static boolean isEnableContainerSupervisor() {
String path = System.getenv(CONTAINER_SUPERVISOR_HEARTBEAT);
if (StringUtils.isBlank(path)) {
return false;
} else {
return true;
}
}
/**
* Get Apsara/Yarn supervisor container's hearbeat dir
*/
public static String getContainerSupervisorHearbeat() {
return System.getenv(CONTAINER_SUPERVISOR_HEARTBEAT);
}
protected static final String CONTAINER_HEARTBEAT_TIMEOUT_SECONDS = "container.heartbeat.timeout.seconds";
public static int getContainerHeartbeatTimeoutSeconds(Map conf) {
return JStormUtils.parseInt(conf.get(CONTAINER_HEARTBEAT_TIMEOUT_SECONDS), 240);
}
protected static final String CONTAINER_HEARTBEAT_FREQUENCE = "container.heartbeat.frequence";
public static int getContainerHeartbeatFrequence(Map conf) {
return JStormUtils.parseInt(conf.get(CONTAINER_HEARTBEAT_FREQUENCE), 10);
}
protected static final String JAVA_SANDBOX_ENABLE = "java.sandbox.enable";
public static boolean isJavaSandBoxEnable(Map conf) {
return JStormUtils.parseBoolean(conf.get(JAVA_SANDBOX_ENABLE), false);
}
protected static String SPOUT_SINGLE_THREAD = "spout.single.thread";
public static boolean isSpoutSingleThread(Map conf) {
return JStormUtils.parseBoolean(conf.get(SPOUT_SINGLE_THREAD), false);
}
public static void setSpoutSingleThread(Map conf, boolean enable) {
conf.put(SPOUT_SINGLE_THREAD, enable);
}
protected static String WORKER_STOP_WITHOUT_SUPERVISOR = "worker.stop.without.supervisor";
public static boolean isWorkerStopWithoutSupervisor(Map conf) {
return JStormUtils.parseBoolean(conf.get(WORKER_STOP_WITHOUT_SUPERVISOR), false);
}
public static String CGROUP_ROOT_DIR = "supervisor.cgroup.rootdir";
public static String getCgroupRootDir(Map conf) {
return (String) conf.get(CGROUP_ROOT_DIR);
}
public static String CGROUP_BASE_DIR = "supervisor.cgroup.basedir";
public static String getCgroupBaseDir(Map conf) {
return (String) conf.get(CGROUP_BASE_DIR);
}
protected static String NETTY_TRANSFER_ASYNC_AND_BATCH = "storm.messaging.netty.transfer.async.batch";
public static boolean isNettyTransferAsyncBatch(Map conf) {
return JStormUtils.parseBoolean(conf.get(NETTY_TRANSFER_ASYNC_AND_BATCH), true);
}
protected static final String USE_USERDEFINE_ASSIGNMENT = "use.userdefine.assignment";
public static void setUserDefineAssignment(Map conf, List<WorkerAssignment> userDefines) {
List<String> ret = new ArrayList<String>();
for (WorkerAssignment worker : userDefines) {
ret.add(Utils.to_json(worker));
}
conf.put(USE_USERDEFINE_ASSIGNMENT, ret);
}
public static List<WorkerAssignment> getUserDefineAssignment(Map conf) {
List<WorkerAssignment> ret = new ArrayList<WorkerAssignment>();
if (conf.get(USE_USERDEFINE_ASSIGNMENT) == null)
return ret;
for (String worker : (List<String>) conf.get(USE_USERDEFINE_ASSIGNMENT)) {
ret.add(WorkerAssignment.parseFromObj(Utils.from_json(worker)));
}
return ret;
}
protected static String NETTY_PENDING_BUFFER_TIMEOUT = "storm.messaging.netty.pending.buffer.timeout";
public static void setNettyPendingBufferTimeout(Map conf, Long timeout) {
conf.put(NETTY_PENDING_BUFFER_TIMEOUT, timeout);
}
public static long getNettyPendingBufferTimeout(Map conf) {
int messageTimeout = JStormUtils.parseInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS), 120);
if (JStormUtils.parseInt(conf.get(Config.TOPOLOGY_ACKER_EXECUTORS), 0) == 0) {
messageTimeout = messageTimeout * 10;
}
return JStormUtils.parseLong(conf.get(NETTY_PENDING_BUFFER_TIMEOUT), messageTimeout * 1000);
}
protected static final String MEMSIZE_PER_WORKER = "worker.memory.size";
public static void setMemSizePerWorker(Map conf, long memSize) {
conf.put(MEMSIZE_PER_WORKER, memSize);
}
protected static final String MEMSIZE_PER_TOPOLOGY_MASTER_WORKER = "topology.master.worker.memory.size";
public static void setMemSizePerTopologyMasterWorker(Map conf, long memSize) {
conf.put(MEMSIZE_PER_TOPOLOGY_MASTER_WORKER, memSize);
}
public static void setMemSizePerWorkerByKB(Map conf, long memSize) {
long size = memSize * 1024l;
setMemSizePerWorker(conf, size);
}
public static void setMemSizePerWorkerByMB(Map conf, long memSize) {
long size = memSize * 1024l;
setMemSizePerWorkerByKB(conf, size);
}
public static void setMemSizePerWorkerByGB(Map conf, long memSize) {
long size = memSize * 1024l;
setMemSizePerWorkerByMB(conf, size);
}
public static long getMemSizePerWorker(Map conf) {
long size = JStormUtils.parseLong(conf.get(MEMSIZE_PER_WORKER), JStormUtils.SIZE_1_G * 2);
return size > 0 ? size : JStormUtils.SIZE_1_G * 2;
}
public static Long getMemSizePerTopologyMasterWorker(Map conf) {
return JStormUtils.parseLong(conf.get(MEMSIZE_PER_TOPOLOGY_MASTER_WORKER));
}
protected static final String MIN_MEMSIZE_PER_WORKER = "worker.memory.min.size";
public static void setMemMinSizePerWorker(Map conf, long memSize) {
conf.put(MIN_MEMSIZE_PER_WORKER, memSize);
}
private static boolean isMemMinSizePerWorkerValid(Long size, long maxMemSize) {
if (size == null) {
return false;
} else if (size <= 128 * 1024 * 1024) {
return false;
} else if (size > maxMemSize) {
return false;
}
return true;
}
public static long getMemMinSizePerWorker(Map conf) {
long maxMemSize = getMemSizePerWorker(conf);
Long size = JStormUtils.parseLong(conf.get(MIN_MEMSIZE_PER_WORKER));
if (isMemMinSizePerWorkerValid(size, maxMemSize)) {
return size;
} else {
return maxMemSize;
}
}
protected static final String CPU_SLOT_PER_WORKER = "worker.cpu.slot.num";
public static void setCpuSlotNumPerWorker(Map conf, int slotNum) {
conf.put(CPU_SLOT_PER_WORKER, slotNum);
}
public static int getCpuSlotPerWorker(Map conf) {
int slot = JStormUtils.parseInt(conf.get(CPU_SLOT_PER_WORKER), 1);
return slot > 0 ? slot : 1;
}
protected static String TOPOLOGY_PERFORMANCE_METRICS = "topology.performance.metrics";
public static boolean isEnablePerformanceMetrics(Map conf) {
return JStormUtils.parseBoolean(conf.get(TOPOLOGY_PERFORMANCE_METRICS), true);
}
public static void setPerformanceMetrics(Map conf, boolean isEnable) {
conf.put(TOPOLOGY_PERFORMANCE_METRICS, isEnable);
}
protected static String NETTY_BUFFER_THRESHOLD_SIZE = "storm.messaging.netty.buffer.threshold";
public static long getNettyBufferThresholdSize(Map conf) {
return JStormUtils.parseLong(conf.get(NETTY_BUFFER_THRESHOLD_SIZE), 8 * JStormUtils.SIZE_1_M);
}
public static void setNettyBufferThresholdSize(Map conf, long size) {
conf.put(NETTY_BUFFER_THRESHOLD_SIZE, size);
}
protected static String NETTY_MAX_SEND_PENDING = "storm.messaging.netty.max.pending";
public static void setNettyMaxSendPending(Map conf, long pending) {
conf.put(NETTY_MAX_SEND_PENDING, pending);
}
public static long getNettyMaxSendPending(Map conf) {
return JStormUtils.parseLong(conf.get(NETTY_MAX_SEND_PENDING), 16);
}
protected static String DISRUPTOR_USE_SLEEP = "disruptor.use.sleep";
public static boolean isDisruptorUseSleep(Map conf) {
return JStormUtils.parseBoolean(conf.get(DISRUPTOR_USE_SLEEP), true);
}
public static void setDisruptorUseSleep(Map conf, boolean useSleep) {
conf.put(DISRUPTOR_USE_SLEEP, useSleep);
}
public static boolean isTopologyContainAcker(Map conf) {
int num = JStormUtils.parseInt(conf.get(Config.TOPOLOGY_ACKER_EXECUTORS), 1);
if (num > 0) {
return true;
} else {
return false;
}
}
protected static String NETTY_ASYNC_BLOCK = "storm.messaging.netty.async.block";
public static boolean isNettyASyncBlock(Map conf) {
return JStormUtils.parseBoolean(conf.get(NETTY_ASYNC_BLOCK), true);
}
public static void setNettyASyncBlock(Map conf, boolean block) {
conf.put(NETTY_ASYNC_BLOCK, block);
}
protected static String ALIMONITOR_METRICS_POST = "topology.alimonitor.metrics.post";
public static boolean isAlimonitorMetricsPost(Map conf) {
return JStormUtils.parseBoolean(conf.get(ALIMONITOR_METRICS_POST), true);
}
public static void setAlimonitorMetricsPost(Map conf, boolean post) {
conf.put(ALIMONITOR_METRICS_POST, post);
}
protected static String UI_CLUSTERS = "ui.clusters";
protected static String UI_CLUSTER_NAME = "name";
protected static String UI_CLUSTER_ZK_ROOT = "zkRoot";
protected static String UI_CLUSTER_ZK_SERVERS = "zkServers";
protected static String UI_CLUSTER_ZK_PORT = "zkPort";
public static List<Map> getUiClusters(Map conf) {
return (List<Map>) conf.get(UI_CLUSTERS);
}
public static void setUiClusters(Map conf, List<Map> uiClusters) {
conf.put(UI_CLUSTERS, uiClusters);
}
public static Map getUiClusterInfo(List<Map> uiClusters, String name) {
Map ret = null;
for (Map cluster : uiClusters) {
String clusterName = getUiClusterName(cluster);
if (clusterName.equals(name)) {
ret = cluster;
break;
}
}
return ret;
}
public static String getUiClusterName(Map uiCluster) {
return (String) uiCluster.get(UI_CLUSTER_NAME);
}
public static String getUiClusterZkRoot(Map uiCluster) {
return (String) uiCluster.get(UI_CLUSTER_ZK_ROOT);
}
public static List<String> getUiClusterZkServers(Map uiCluster) {
return (List<String>) uiCluster.get(UI_CLUSTER_ZK_SERVERS);
}
public static Integer getUiClusterZkPort(Map uiCluster) {
return JStormUtils.parseInt(uiCluster.get(UI_CLUSTER_ZK_PORT));
}
protected static String SPOUT_PEND_FULL_SLEEP = "spout.pending.full.sleep";
public static boolean isSpoutPendFullSleep(Map conf) {
return JStormUtils.parseBoolean(conf.get(SPOUT_PEND_FULL_SLEEP), false);
}
public static void setSpoutPendFullSleep(Map conf, boolean sleep) {
conf.put(SPOUT_PEND_FULL_SLEEP, sleep);
}
protected static String LOGVIEW_ENCODING = "supervisor.deamon.logview.encoding";
protected static String UTF8 = "utf-8";
public static String getLogViewEncoding(Map conf) {
String ret = (String) conf.get(LOGVIEW_ENCODING);
if (ret == null)
ret = UTF8;
return ret;
}
public static void setLogViewEncoding(Map conf, String enc) {
conf.put(LOGVIEW_ENCODING, enc);
}
protected static String LOG_PAGE_SIZE = "log.page.size";
public static int getLogPageSize(Map conf) {
return JStormUtils.parseInt(conf.get(LOG_PAGE_SIZE), 64 * 1024);
}
public static void setLogPageSize(Map conf, int pageSize) {
conf.put(LOG_PAGE_SIZE, pageSize);
}
public static String MAX_MATCH_PER_LOG_SEARCH = "max.match.per.log.search";
public static int getMaxMatchPerLogSearch(Map conf) {
return JStormUtils.parseInt(conf.get(MAX_MATCH_PER_LOG_SEARCH), 10);
}
public static void setMaxMatchPerLogSearch(Map conf, int maxMatch) {
conf.put(MAX_MATCH_PER_LOG_SEARCH, maxMatch);
}
public static String MAX_BLOCKS_PER_LOG_SEARCH = "max.blocks.per.log.search";
public static int getMaxBlocksPerLogSearch(Map conf) {
return JStormUtils.parseInt(conf.get(MAX_BLOCKS_PER_LOG_SEARCH), 1024);
}
// logger name -> log level map <String, String>
public static String CHANGE_LOG_LEVEL_CONFIG = "change.log.level.config";
public static Map<String, String> getChangeLogLevelConfig(Map conf) {
return (Map<String, String>) conf.get(CHANGE_LOG_LEVEL_CONFIG);
}
// this timestamp is used to check whether we need to change log level
public static String CHANGE_LOG_LEVEL_TIMESTAMP = "change.log.level.timestamp";
public static Long getChangeLogLevelTimeStamp(Map conf) {
return (Long) conf.get(CHANGE_LOG_LEVEL_TIMESTAMP);
}
public static String TASK_STATUS_ACTIVE = "Active";
public static String TASK_STATUS_INACTIVE = "Inactive";
public static String TASK_STATUS_STARTING = "Starting";
protected static String ALIMONITOR_TOPO_METIRC_NAME = "topology.alimonitor.topo.metrics.name";
protected static String ALIMONITOR_TASK_METIRC_NAME = "topology.alimonitor.task.metrics.name";
protected static String ALIMONITOR_WORKER_METIRC_NAME = "topology.alimonitor.worker.metrics.name";
protected static String ALIMONITOR_USER_METIRC_NAME = "topology.alimonitor.user.metrics.name";
public static String getAlmonTopoMetricName(Map conf) {
return (String) conf.get(ALIMONITOR_TOPO_METIRC_NAME);
}
public static String getAlmonTaskMetricName(Map conf) {
return (String) conf.get(ALIMONITOR_TASK_METIRC_NAME);
}
public static String getAlmonWorkerMetricName(Map conf) {
return (String) conf.get(ALIMONITOR_WORKER_METIRC_NAME);
}
public static String getAlmonUserMetricName(Map conf) {
return (String) conf.get(ALIMONITOR_USER_METIRC_NAME);
}
protected static String SPOUT_PARALLELISM = "topology.spout.parallelism";
protected static String BOLT_PARALLELISM = "topology.bolt.parallelism";
public static Integer getSpoutParallelism(Map conf, String componentName) {
Integer ret = null;
Map<String, String> map = (Map<String, String>) (conf.get(SPOUT_PARALLELISM));
if (map != null)
ret = JStormUtils.parseInt(map.get(componentName));
return ret;
}
public static Integer getBoltParallelism(Map conf, String componentName) {
Integer ret = null;
Map<String, String> map = (Map<String, String>) (conf.get(BOLT_PARALLELISM));
if (map != null)
ret = JStormUtils.parseInt(map.get(componentName));
return ret;
}
protected static String SUPERVISOR_SLOTS_PORTS_BASE = "supervisor.slots.ports.base";
public static int getSupervisorSlotsPortsBase(Map conf) {
return JStormUtils.parseInt(conf.get(SUPERVISOR_SLOTS_PORTS_BASE), 6800);
}
// SUPERVISOR_SLOTS_PORTS_BASE don't provide setting function, it must be
// set by configuration
protected static String SUPERVISOR_SLOTS_PORT_CPU_WEIGHT = "supervisor.slots.port.cpu.weight";
public static double getSupervisorSlotsPortCpuWeight(Map conf) {
Object value = conf.get(SUPERVISOR_SLOTS_PORT_CPU_WEIGHT);
Double ret = JStormUtils.convertToDouble(value);
if (ret == null || ret <= 0) {
return 1.2;
} else {
return ret;
}
}
protected static String SUPERVISOR_SLOTS_PORT_MEM_WEIGHT = "supervisor.slots.port.mem.weight";
public static double getSupervisorSlotsPortMemWeight(Map conf) {
Object value = conf.get(SUPERVISOR_SLOTS_PORT_MEM_WEIGHT);
Double ret = JStormUtils.convertToDouble(value);
if (ret == null || ret <= 0) {
return 0.7;
} else {
return ret;
}
}
protected static String SUPERVISOR_ENABLE_AUTO_ADJUST_SLOTS = "supervisor.enable.auto.adjust.slots";
public static boolean isSupervisorEnableAutoAdjustSlots(Map conf) {
return JStormUtils.parseBoolean(conf.get(SUPERVISOR_ENABLE_AUTO_ADJUST_SLOTS), false);
}
// SUPERVISOR_SLOTS_PORT_CPU_WEIGHT don't provide setting function, it must
// be set by configuration
protected static String USER_DEFINED_LOG4J_CONF = "user.defined.log4j.conf";
public static String getUserDefinedLog4jConf(Map conf) {
return (String) conf.get(USER_DEFINED_LOG4J_CONF);
}
public static void setUserDefinedLog4jConf(Map conf, String fileName) {
conf.put(USER_DEFINED_LOG4J_CONF, fileName);
}
protected static String USER_DEFINED_LOGBACK_CONF = "user.defined.logback.conf";
public static String getUserDefinedLogbackConf(Map conf) {
return (String) conf.get(USER_DEFINED_LOGBACK_CONF);
}
public static void setUserDefinedLogbackConf(Map conf, String fileName) {
conf.put(USER_DEFINED_LOGBACK_CONF, fileName);
}
protected static String TASK_ERROR_INFO_REPORT_INTERVAL = "topology.task.error.report.interval";
public static Integer getTaskErrorReportInterval(Map conf) {
return JStormUtils.parseInt(conf.get(TASK_ERROR_INFO_REPORT_INTERVAL), 60);
}
public static void setTaskErrorReportInterval(Map conf, Integer interval) {
conf.put(TASK_ERROR_INFO_REPORT_INTERVAL, interval);
}
protected static String DEFAULT_CACHE_TIMEOUT = "default.cache.timeout";
public static int getDefaultCacheTimeout(Map conf) {
return JStormUtils.parseInt(conf.get(DEFAULT_CACHE_TIMEOUT), 60);
}
public static void setDefaultCacheTimeout(Map conf, int timeout) {
conf.put(DEFAULT_CACHE_TIMEOUT, timeout);
}
protected static String WORKER_MERTRIC_REPORT_CHECK_FREQUENCY = "worker.metric.report.frequency.secs";
public static int getWorkerMetricReportCheckFrequency(Map conf) {
return JStormUtils.parseInt(conf.get(WORKER_MERTRIC_REPORT_CHECK_FREQUENCY), 60);
}
public static void setWorkerMetricReportFrequency(Map conf, int frequence) {
conf.put(WORKER_MERTRIC_REPORT_CHECK_FREQUENCY, frequence);
}
/**
* Store local worker port/workerId/supervisorId to configuration
*/
protected static String LOCAL_WORKER_PORT = "local.worker.port";
protected static String LOCLA_WORKER_ID = "local.worker.id";
protected static String LOCAL_SUPERVISOR_ID = "local.supervisor.id";
public static int getLocalWorkerPort(Map conf) {
return JStormUtils.parseInt(conf.get(LOCAL_WORKER_PORT));
}
public static void setLocalWorkerPort(Map conf, int port) {
conf.put(LOCAL_WORKER_PORT, port);
}
public static String getLocalWorkerId(Map conf) {
return (String) conf.get(LOCLA_WORKER_ID);
}
public static void setLocalWorkerId(Map conf, String workerId) {
conf.put(LOCLA_WORKER_ID, workerId);
}
public static String getLocalSupervisorId(Map conf) {
return (String) conf.get(LOCAL_SUPERVISOR_ID);
}
public static void setLocalSupervisorId(Map conf, String supervisorId) {
conf.put(LOCAL_SUPERVISOR_ID, supervisorId);
}
protected static String WORKER_CPU_CORE_UPPER_LIMIT = "worker.cpu.core.upper.limit";
public static Integer getWorkerCpuCoreUpperLimit(Map conf) {
return JStormUtils.parseInt(conf.get(WORKER_CPU_CORE_UPPER_LIMIT), 1);
}
public static void setWorkerCpuCoreUpperLimit(Map conf, Integer cpuUpperLimit) {
conf.put(WORKER_CPU_CORE_UPPER_LIMIT, cpuUpperLimit);
}
protected static String CLUSTER_NAME = "cluster.name";
public static String getClusterName(Map conf) {
return (String) conf.get(CLUSTER_NAME);
}
public static void setClusterName(Map conf, String clusterName) {
conf.put(CLUSTER_NAME, clusterName);
}
protected static final String NIMBUS_CACHE_CLASS = "nimbus.cache.class";
public static String getNimbusCacheClass(Map conf) {
return (String) conf.get(NIMBUS_CACHE_CLASS);
}
/**
* if this is set, nimbus cache db will be clean when start nimbus
*/
protected static final String NIMBUS_CACHE_RESET = "nimbus.cache.reset";
public static boolean getNimbusCacheReset(Map conf) {
return JStormUtils.parseBoolean(conf.get(NIMBUS_CACHE_RESET), true);
}
/**
* if this is set, nimbus metrics cache db will be clean when start nimbus
*/
protected static final String NIMBUS_METRIC_CACHE_RESET = "nimbus.metric.cache.reset";
public static boolean getMetricCacheReset(Map conf) {
return JStormUtils.parseBoolean(conf.get(NIMBUS_METRIC_CACHE_RESET), false);
}
public static final double DEFAULT_METRIC_SAMPLE_RATE = 0.05d;
public static final String TOPOLOGY_METRIC_SAMPLE_RATE = "topology.metric.sample.rate";
public static double getMetricSampleRate(Map conf) {
double sampleRate = JStormUtils.parseDouble(conf.get(TOPOLOGY_METRIC_SAMPLE_RATE), DEFAULT_METRIC_SAMPLE_RATE);
if (!conf.containsKey(TOPOLOGY_METRIC_SAMPLE_RATE)) {
conf.put(TOPOLOGY_METRIC_SAMPLE_RATE, sampleRate);
}
return sampleRate;
}
public static final String TOPOLOGY_TIMER_UPDATE_INTERVAL = "topology.timer.update.interval";
public static long getTimerUpdateInterval(Map conf) {
return JStormUtils.parseLong(conf.get(TOPOLOGY_TIMER_UPDATE_INTERVAL), 10);
}
public static void setTopologyTimerUpdateInterval(Map conf, long interval) {
conf.put(TOPOLOGY_TIMER_UPDATE_INTERVAL, interval);
}
public static final String CACHE_TIMEOUT_LIST = "cache.timeout.list";
public static List<Integer> getCacheTimeoutList(Map conf) {
return (List<Integer>) conf.get(CACHE_TIMEOUT_LIST);
}
public static final String METRIC_UPLOADER_CLASS = "nimbus.metric.uploader.class";
public static String getMetricUploaderClass(Map<Object, Object> conf) {
return (String) conf.get(METRIC_UPLOADER_CLASS);
}
public static final String METRIC_QUERY_CLIENT_CLASS = "nimbus.metric.query.client.class";
public static String getMetricQueryClientClass(Map<Object, Object> conf) {
return (String) conf.get(METRIC_QUERY_CLIENT_CLASS);
}
protected static String TASK_MSG_BATCH_SIZE = "task.msg.batch.size";
public static Integer getTaskMsgBatchSize(Map conf) {
return JStormUtils.parseInt(conf.get(TASK_MSG_BATCH_SIZE), 1);
}
public static void setTaskMsgBatchSize(Map conf, Integer batchSize) {
conf.put(TASK_MSG_BATCH_SIZE, batchSize);
}
public static String TASK_BATCH_TUPLE = "task.batch.tuple";
public static Boolean isTaskBatchTuple(Map conf) {
return JStormUtils.parseBoolean(conf.get(TASK_BATCH_TUPLE), false);
}
public static void setTaskBatchTuple(Map conf, boolean isBatchTuple) {
conf.put(TASK_BATCH_TUPLE, isBatchTuple);
}
protected static String TASK_BATCH_FLUSH_INTERVAL_MS = "task.msg.batch.flush.interval.millis";
public static Integer getTaskMsgFlushInervalMs(Map conf) {
return JStormUtils.parseInt(conf.get(TASK_BATCH_FLUSH_INTERVAL_MS), 2);
}
public static void setTaskMsgFlushInervalMs(Map conf, Integer flushMs) {
conf.put(TASK_BATCH_FLUSH_INTERVAL_MS, flushMs);
}
protected static String TOPOLOGY_MAX_WORKER_NUM_FOR_NETTY_METRICS = "topology.max.worker.num.for.netty.metrics";
public static void setTopologyMaxWorkerNumForNettyMetrics(Map conf, int num) {
conf.put(TOPOLOGY_MAX_WORKER_NUM_FOR_NETTY_METRICS, num);
}
public static int getTopologyMaxWorkerNumForNettyMetrics(Map conf) {
return JStormUtils.parseInt(conf.get(TOPOLOGY_MAX_WORKER_NUM_FOR_NETTY_METRICS), 100);
}
protected static String UI_ONE_TABLE_PAGE_SIZE = "ui.one.table.page.size";
public static long getUiOneTablePageSize(Map conf) {
return JStormUtils.parseLong(conf.get(UI_ONE_TABLE_PAGE_SIZE), 200);
}
protected static String MAX_PENDING_METRIC_NUM = "topology.max.pending.metric.num";
public static int getMaxPendingMetricNum(Map conf) {
return JStormUtils.parseInt(conf.get(MAX_PENDING_METRIC_NUM), 200);
}
protected static String TOPOLOGY_MASTER_SINGLE_WORKER = "topology.master.single.worker";
public static Boolean getTopologyMasterSingleWorker(Map conf) {
Boolean ret = JStormUtils.parseBoolean(conf.get(TOPOLOGY_MASTER_SINGLE_WORKER));
return ret;
}
public static String TOPOLOGY_BACKPRESSURE_WATER_MARK_HIGH = "topology.backpressure.water.mark.high";
public static double getBackpressureWaterMarkHigh(Map conf) {
return JStormUtils.parseDouble(conf.get(TOPOLOGY_BACKPRESSURE_WATER_MARK_HIGH), 0.8);
}
public static String TOPOLOGY_BACKPRESSURE_WATER_MARK_LOW = "topology.backpressure.water.mark.low";
public static double getBackpressureWaterMarkLow(Map conf) {
return JStormUtils.parseDouble(conf.get(TOPOLOGY_BACKPRESSURE_WATER_MARK_LOW), 0.05);
}
public static String TOPOLOGY_BACKPRESSURE_ENABLE = "topology.backpressure.enable";
public static boolean isBackpressureEnable(Map conf) {
return JStormUtils.parseBoolean(conf.get(TOPOLOGY_BACKPRESSURE_ENABLE), false);
}
protected static String SUPERVISOR_CHECK_WORKER_BY_SYSTEM_INFO = "supervisor.check.worker.by.system.info";
public static boolean isCheckWorkerAliveBySystemInfo(Map conf) {
return JStormUtils.parseBoolean(conf.get(SUPERVISOR_CHECK_WORKER_BY_SYSTEM_INFO), true);
}
protected static String TOPOLOGY_TASK_HEARTBEAT_SEND_NUMBER = "topology.task.heartbeat.send.number";
public static int getTopologyTaskHbSendNumber(Map conf) {
return JStormUtils.parseInt(conf.get(TOPOLOGY_TASK_HEARTBEAT_SEND_NUMBER), 2000);
}
protected static String PROCESS_LAUNCHER_ENABLE = "process.launcher.enable";
public static boolean isProcessLauncherEnable(Map conf) {
return JStormUtils.parseBoolean(conf.get(PROCESS_LAUNCHER_ENABLE), true);
}
protected static String PROCESS_LAUNCHER_SLEEP_SECONDS = "process.launcher.sleep.seconds";
public static int getProcessLauncherSleepSeconds(Map conf) {
return JStormUtils.parseInt(conf.get(PROCESS_LAUNCHER_SLEEP_SECONDS), 60);
}
protected static String PROCESS_LAUNCHER_CHILDOPTS = "process.launcher.childopts";
public static String getProcessLauncherChildOpts(Map conf) {
return (String) conf.get(PROCESS_LAUNCHER_CHILDOPTS);
}
protected static String MAX_PENDING_BATCH_SIZE = "max.pending.batch.size";
public static int getMaxPendingBatchSize(Map conf) {
return JStormUtils.parseInt(conf.get(MAX_PENDING_BATCH_SIZE), 10 * getTaskMsgBatchSize(conf));
}
protected static String TASK_DESERIALIZE_THREAD_NUM = "task.deserialize.thread.num";
public static Integer getTaskDeserializeThreadNum(Map conf) {
return JStormUtils.parseInt(conf.get(TASK_DESERIALIZE_THREAD_NUM), 1);
}
protected static String TASK_SERIALIZE_THREAD_NUM = "task.serialize.thread.num";
public static Integer getTaskSerializeThreadNum(Map conf) {
return JStormUtils.parseInt(conf.get(TASK_SERIALIZE_THREAD_NUM), 1);
}
protected static String WORKER_DESERIALIZE_THREAD_RATIO = "worker.deserialize.thread.ratio";
public static double getWorkerDeserializeThreadRatio(Map conf) {
return JStormUtils.parseDouble(conf.get(WORKER_DESERIALIZE_THREAD_RATIO), 0);
}
protected static String WORKER_SERIALIZE_THREAD_RATIO = "worker.serialize.thread.ratio";
public static double getWorkerSerializeThreadRatio(Map conf) {
return JStormUtils.parseDouble(conf.get(WORKER_SERIALIZE_THREAD_RATIO), 0);
}
protected static String DISRUPTOR_BUFFER_SIZE = "disruptor.buffer.size";
public static int getDisruptorBufferSize(Map conf) {
return JStormUtils.parseInt(conf.get(DISRUPTOR_BUFFER_SIZE), 10);
}
protected static String DISRUPTOR_BUFFER_FLUSH_MS = "disruptor.buffer.interval.millis";
public static long getDisruptorBufferFlushMs(Map conf) {
return JStormUtils.parseLong(conf.get(DISRUPTOR_BUFFER_FLUSH_MS), 5);
}
protected static String WORKER_FLUSH_POOL_MAX_SIZE = "worker.flush.pool.max.size";
public static Integer getWorkerFlushPoolMaxSize(Map conf) {
return JStormUtils.parseInt(conf.get(WORKER_FLUSH_POOL_MAX_SIZE));
}
protected static String WORKER_FLUSH_POOL_MIN_SIZE = "worker.flush.pool.min.size";
public static Integer getWorkerFlushPoolMinSize(Map conf) {
return JStormUtils.parseInt(conf.get(WORKER_FLUSH_POOL_MIN_SIZE));
}
protected static String TRANSACTION_BATCH_SNAPSHOT_TIMEOUT = "transaction.batch.snapshot.timeout";
public static int getTransactionBatchSnapshotTimeout(Map conf) {
return JStormUtils.parseInt(conf.get(TRANSACTION_BATCH_SNAPSHOT_TIMEOUT), 120);
}
protected static String TOPOLOGY_TRANSACTION_STATE_OPERATOR_CLASS = "topology.transaction.state.operator.class";
public static String getTopologyStateOperatorClass(Map conf) {
return (String) conf.get(TOPOLOGY_TRANSACTION_STATE_OPERATOR_CLASS);
}
// default is 64k
protected static String TRANSACTION_CACHE_BATCH_FLUSH_SIZE = "transaction.cache.batch.flush.size";
public static int getTransactionCacheBatchFlushSize(Map conf) {
return JStormUtils.parseInt(conf.get(TRANSACTION_CACHE_BATCH_FLUSH_SIZE), 64 * 1024);
}
protected static String TRANSACTION_CACHE_BLOCK_SIZE = "transaction.cache.block.size";
public static Long getTransactionCacheBlockSize(Map conf) {
return JStormUtils.parseLong(conf.get(TRANSACTION_CACHE_BLOCK_SIZE));
}
protected static String TRANSACTION_MAX_CACHE_BLOCK_NUM = "transaction.max.cache.block.num";
public static Integer getTransactionMaxCacheBlockNum(Map conf) {
return JStormUtils.parseInt(conf.get(TRANSACTION_MAX_CACHE_BLOCK_NUM));
}
protected static final String NIMBUS_CONFIG_UPDATE_HANDLER_CLASS = "nimbus.config.update.handler.class";
public static String getNimbusConfigUpdateHandlerClass(Map conf) {
String klass = (String) conf.get(NIMBUS_CONFIG_UPDATE_HANDLER_CLASS);
if (StringUtils.isBlank(klass)) {
klass = DefaultConfigUpdateHandler.class.getName();
}
return klass;
}
public static final String TOPOLOGY_HOT_DEPLOGY_ENABLE = "topology.hot.deploy.enable";
public static boolean getTopologyHotDeplogyEnable(Map conf) {
return JStormUtils.parseBoolean(conf.get(TOPOLOGY_HOT_DEPLOGY_ENABLE), false);
}
public static String TASK_CLEANUP_TIMEOUT_SEC = "task.cleanup.timeout.sec";
public static int getTaskCleanupTimeoutSec(Map conf) {
return JStormUtils.parseInt(conf.get(TASK_CLEANUP_TIMEOUT_SEC), 10);
}
public static void setTaskCleanupTimeoutSec(Map conf, int timeout) {
conf.put(TASK_CLEANUP_TIMEOUT_SEC, timeout);
}
protected static final String SHUFFLE_ENABLE_INTER_PATH = "shuffle.enable.inter.path";
public static boolean getShuffleEnableInterPath(Map conf) {
return JStormUtils.parseBoolean(conf.get(SHUFFLE_ENABLE_INTER_PATH), true);
}
public static void setShuffleEnableInterPath(Map conf, boolean enable) {
conf.put(SHUFFLE_ENABLE_INTER_PATH, enable);
}
protected static final String SHUFFLE_INTER_LOAD_MARK = "shuffle.inter.load.mark";
public static double getShuffleInterLoadMark(Map conf) {
return JStormUtils.parseDouble(conf.get(SHUFFLE_INTER_LOAD_MARK), 0.2);
}
public static void setShuffleInterLoadMark(Map conf, double value) {
conf.put(SHUFFLE_INTER_LOAD_MARK, value);
}
protected static final String TOPOLOGY_MASTER_THREAD_POOL_SIZE = "topology.master.thread.pool.size";
public static int getTopologyMasterThreadPoolSize(Map conf) {
return JStormUtils.parseInt(conf.get(TOPOLOGY_MASTER_THREAD_POOL_SIZE), 16);
}
public static void setTopologyMasterThreadPoolSize(Map conf, int value) {
conf.put(TOPOLOGY_MASTER_THREAD_POOL_SIZE, value);
}
private static final Object CLUSTER_MAX_CONCURRENT_UPLOAD_METRIC_NUM = "cluster.max.concurrent.upload.metric.num";
public static int getMaxConcurrentUploadingNum(Map conf) {
return JStormUtils.parseInt(conf.get(CLUSTER_MAX_CONCURRENT_UPLOAD_METRIC_NUM), 20);
}
private static final String JSTORM_ON_YARN = "jstorm.on.yarn";
public static boolean isJStormOnYarn(Map conf) {
return JStormUtils.parseBoolean(conf.get(JSTORM_ON_YARN), false);
}
public static final String NETTY_CLIENT_FLOW_CTRL_WAIT_TIME_MS = "netty.client.flow.ctrl.wait.time.ms";
public static int getNettyFlowCtrlWaitTime(Map conf) {
return JStormUtils.parseInt(conf.get(NETTY_CLIENT_FLOW_CTRL_WAIT_TIME_MS), 5);
}
public static final String NETTY_CLIENT_FLOW_CTRL_CACHE_SIZE = "netty.client.flow.ctrl.cache.size";
public static Integer getNettyFlowCtrlCacheSize(Map conf) {
return JStormUtils.parseInt(conf.get(NETTY_CLIENT_FLOW_CTRL_CACHE_SIZE));
}
public static final String DISRUPTOR_QUEUE_BATCH_MODE = "disruptor.queue.batch.mode";
public static Boolean isDisruptorQueueBatchMode(Map conf) {
return JStormUtils.parseBoolean(conf.get(DISRUPTOR_QUEUE_BATCH_MODE), isTaskBatchTuple(conf));
}
public static String TOPOLOGY_ACCURATE_METRIC = "topology.accurate.metric";
public static Boolean getTopologyAccurateMetric(Map conf) {
return JStormUtils.parseBoolean(conf.get(TOPOLOGY_ACCURATE_METRIC), false);
}
public static String TOPOLOGY_HISTOGRAM_SIZE = "topology.histogram.size";
public static Integer getTopologyHistogramSize(Map conf) {
return JStormUtils.parseInt(conf.get(TOPOLOGY_HISTOGRAM_SIZE), 256);
}
} | apache-2.0 |
bradwoo8621/nest-old | arcteryx-meta-beans/src/main/java/com/github/nest/arcteryx/meta/beans/IBeanDescriptorContext.java | 478 | /**
*
*/
package com.github.nest.arcteryx.meta.beans;
import com.github.nest.arcteryx.meta.IResourceDescriptorContext;
import com.github.nest.arcteryx.meta.beans.internal.IValidationConfiguration;
/**
* bean descriptor context.
*
* @author brad.wu
*/
public interface IBeanDescriptorContext extends IResourceDescriptorContext {
/**
* get validation configuration
*
* @return
*/
IValidationConfiguration getValidationConfiguration();
}
| apache-2.0 |
exalt-tech/trex-stateless-gui | src/main/java/com/exalttech/trex/remote/models/params/TrafficParams.java | 3417 | /**
* *****************************************************************************
* Copyright (c) 2016
*
* 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.exalttech.trex.remote.models.params;
import com.exalttech.trex.remote.models.multiplier.Multiplier;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import javax.annotation.Generated;
/**
*
* @author GeorgeKh
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
"duration",
"force",
"handler",
"mul",
"port_id"
})
public class TrafficParams extends Params {
@JsonProperty("duration")
private Double duration;
@JsonProperty("force")
private Boolean force;
@JsonProperty("handler")
private String handler;
@JsonProperty("mul")
private Multiplier mul;
@JsonProperty("port_id")
private Integer portId;
/**
*
* @param force
* @param handler
* @param mul
* @param portId
*/
public TrafficParams(Boolean force, String handler, Multiplier mul, Integer portId) {
this.force = force;
this.handler = handler;
this.mul = mul;
this.portId = portId;
}
/**
*
* @return The duration
*/
@JsonProperty("duration")
public Double getDuration() {
return duration;
}
/**
*
* @param duration The duration
*/
@JsonProperty("duration")
public void setDuration(Double duration) {
this.duration = duration;
}
/**
*
* @return The force
*/
@JsonProperty("force")
public Boolean getForce() {
return force;
}
/**
*
* @param force The force
*/
@JsonProperty("force")
public void setForce(Boolean force) {
this.force = force;
}
/**
*
* @return The handler
*/
@JsonProperty("handler")
public String getHandler() {
return handler;
}
/**
*
* @param handler The handler
*/
@JsonProperty("handler")
public void setHandler(String handler) {
this.handler = handler;
}
/**
*
* @return The mul
*/
@JsonProperty("mul")
public Multiplier getMul() {
return mul;
}
/**
*
* @param mul The mul
*/
@JsonProperty("mul")
public void setMul(Multiplier mul) {
this.mul = mul;
}
/**
*
* @return The portId
*/
@JsonProperty("port_id")
public Integer getPortId() {
return portId;
}
/**
*
* @param portId The port_id
*/
@JsonProperty("port_id")
public void setPortId(Integer portId) {
this.portId = portId;
}
}
| apache-2.0 |
apache/sanselan | src/test/java/org/apache/commons/imaging/formats/jpeg/xmp/JpegXmpDumpTest.java | 1909 | /*
* 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.imaging.formats.jpeg.xmp;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.imaging.common.bytesource.ByteSource;
import org.apache.commons.imaging.common.bytesource.ByteSourceFile;
import org.apache.commons.imaging.formats.jpeg.JpegImageParser;
import org.apache.commons.imaging.util.Debug;
public class JpegXmpDumpTest extends JpegXmpBaseTest
{
public void test() throws Exception
{
List images = getImagesWithXmpData();
for (int i = 0; i < images.size(); i++)
{
if (i % 10 == 0)
Debug.purgeMemory();
File imageFile = (File) images.get(i);
Debug.debug("imageFile", imageFile);
Debug.debug();
ByteSource byteSource = new ByteSourceFile(imageFile);
Map params = new HashMap();
String xmpXml = new JpegImageParser().getXmpXml(byteSource, params );
assertNotNull(xmpXml);
Debug.debug("xmpXml", xmpXml);
Debug.debug();
}
}
}
| apache-2.0 |
Fabryprog/camel | components/camel-soap/src/test/java/org/apache/camel/dataformat/soap/SoapCxfServerTest.java | 3407 | /*
* 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.dataformat.soap;
import java.util.List;
import com.example.customerservice.Customer;
import com.example.customerservice.CustomerService;
import com.example.customerservice.GetCustomersByName;
import com.example.customerservice.GetCustomersByNameResponse;
import com.example.customerservice.NoSuchCustomer;
import com.example.customerservice.NoSuchCustomerException;
import org.apache.camel.Produce;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.dataformat.soap.name.ElementNameStrategy;
import org.apache.camel.dataformat.soap.name.ServiceInterfaceStrategy;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Checks for interoperability between a CXF server that is attached using
* the Camel transport for CXF and a dynamic proxy using the SOAP data format
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class SoapCxfServerTest extends RouteBuilder {
@Produce("direct:camelClient")
CustomerService customerServiceProxy;
@Test
public void testSuccess() throws NoSuchCustomerException {
GetCustomersByName request = new GetCustomersByName();
request.setName("test");
GetCustomersByNameResponse response = customerServiceProxy.getCustomersByName(request);
Assert.assertNotNull(response);
List<Customer> customers = response.getReturn();
Assert.assertEquals(1, customers.size());
Assert.assertEquals("test", customers.get(0).getName());
}
@Test
public void testFault() {
GetCustomersByName request = new GetCustomersByName();
request.setName("none");
try {
customerServiceProxy.getCustomersByName(request);
Assert.fail("NoSuchCustomerException expected");
} catch (NoSuchCustomerException e) {
NoSuchCustomer info = e.getFaultInfo();
Assert.assertEquals("none", info.getCustomerId());
}
}
public void configure() throws Exception {
String jaxbPackage = GetCustomersByName.class.getPackage().getName();
ElementNameStrategy elNameStrat = new ServiceInterfaceStrategy(CustomerService.class, true);
SoapJaxbDataFormat soapDataFormat = new SoapJaxbDataFormat(jaxbPackage, elNameStrat);
from("direct:camelClient") //
.marshal(soapDataFormat) //
.to("direct:cxfEndpoint") //
.unmarshal(soapDataFormat);
}
}
| apache-2.0 |
shixuan-fan/presto | presto-tests/src/main/java/com/facebook/presto/tests/DistributedQueryRunner.java | 29359 | /*
* 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.tests;
import com.facebook.airlift.discovery.server.testing.TestingDiscoveryServer;
import com.facebook.airlift.log.Logger;
import com.facebook.airlift.testing.Assertions;
import com.facebook.presto.Session;
import com.facebook.presto.Session.SessionBuilder;
import com.facebook.presto.common.QualifiedObjectName;
import com.facebook.presto.cost.StatsCalculator;
import com.facebook.presto.execution.QueryInfo;
import com.facebook.presto.execution.QueryManager;
import com.facebook.presto.metadata.AllNodes;
import com.facebook.presto.metadata.Catalog;
import com.facebook.presto.metadata.InternalNode;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.metadata.SessionPropertyManager;
import com.facebook.presto.server.BasicQueryInfo;
import com.facebook.presto.server.testing.TestingPrestoServer;
import com.facebook.presto.spi.ConnectorId;
import com.facebook.presto.spi.Plugin;
import com.facebook.presto.spi.QueryId;
import com.facebook.presto.spi.WarningCollector;
import com.facebook.presto.spi.eventlistener.EventListener;
import com.facebook.presto.split.PageSourceManager;
import com.facebook.presto.split.SplitManager;
import com.facebook.presto.sql.parser.SqlParserOptions;
import com.facebook.presto.sql.planner.ConnectorPlanOptimizerManager;
import com.facebook.presto.sql.planner.NodePartitioningManager;
import com.facebook.presto.sql.planner.Plan;
import com.facebook.presto.testing.MaterializedResult;
import com.facebook.presto.testing.QueryRunner;
import com.facebook.presto.testing.TestingAccessControlManager;
import com.facebook.presto.transaction.TransactionManager;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Closer;
import com.google.inject.Module;
import io.airlift.units.Duration;
import org.intellij.lang.annotations.Language;
import org.jdbi.v3.core.Handle;
import org.jdbi.v3.core.Jdbi;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.BiFunction;
import java.util.function.Function;
import static com.facebook.presto.testing.TestingSession.TESTING_CATALOG;
import static com.facebook.presto.testing.TestingSession.createBogusTestingCatalog;
import static com.facebook.presto.tests.AbstractTestQueries.TEST_CATALOG_PROPERTIES;
import static com.facebook.presto.tests.AbstractTestQueries.TEST_SYSTEM_PROPERTIES;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Throwables.throwIfUnchecked;
import static com.google.common.collect.Iterables.getOnlyElement;
import static io.airlift.units.Duration.nanosSince;
import static java.lang.System.nanoTime;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
public class DistributedQueryRunner
implements QueryRunner
{
private static final Logger log = Logger.get(DistributedQueryRunner.class);
private static final String ENVIRONMENT = "testing";
private static final SqlParserOptions DEFAULT_SQL_PARSER_OPTIONS = new SqlParserOptions();
private final TestingDiscoveryServer discoveryServer;
private final List<TestingPrestoServer> coordinators;
private final List<TestingPrestoServer> servers;
private final List<Process> externalWorkers;
private final List<Module> extraModules;
private final Closer closer = Closer.create();
private final List<TestingPrestoClient> prestoClients;
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private Optional<TestingPrestoServer> resourceManager = Optional.empty();
private final AtomicReference<Handle> testFunctionNamespacesHandle = new AtomicReference<>();
@Deprecated
public DistributedQueryRunner(Session defaultSession, int nodeCount)
throws Exception
{
this(defaultSession, nodeCount, ImmutableMap.of());
}
@Deprecated
public DistributedQueryRunner(Session defaultSession, int nodeCount, Map<String, String> extraProperties)
throws Exception
{
this(false, defaultSession, nodeCount, 1, extraProperties, ImmutableMap.of(), DEFAULT_SQL_PARSER_OPTIONS, ENVIRONMENT, Optional.empty(), Optional.empty(), ImmutableList.of());
}
public static Builder builder(Session defaultSession)
{
return new Builder(defaultSession);
}
private DistributedQueryRunner(
boolean resourceManagerEnabled,
Session defaultSession,
int nodeCount,
int coordinatorCount,
Map<String, String> extraProperties,
Map<String, String> coordinatorProperties,
SqlParserOptions parserOptions,
String environment,
Optional<Path> baseDataDir,
Optional<BiFunction<Integer, URI, Process>> externalWorkerLauncher,
List<Module> extraModules)
throws Exception
{
requireNonNull(defaultSession, "defaultSession is null");
this.extraModules = requireNonNull(extraModules, "extraModules is null");
try {
long start = nanoTime();
discoveryServer = new TestingDiscoveryServer(environment);
closer.register(() -> closeUnchecked(discoveryServer));
log.info("Created TestingDiscoveryServer in %s", nanosSince(start).convertToMostSuccinctTimeUnit());
URI discoveryUrl = discoveryServer.getBaseUrl();
log.info("Discovery URL %s", discoveryUrl);
ImmutableList.Builder<TestingPrestoServer> servers = ImmutableList.builder();
ImmutableList.Builder<TestingPrestoServer> coordinators = ImmutableList.builder();
Map<String, String> extraCoordinatorProperties = new HashMap<>();
if (externalWorkerLauncher.isPresent()) {
ImmutableList.Builder<Process> externalWorkersBuilder = ImmutableList.builder();
for (int i = 0; i < nodeCount; i++) {
externalWorkersBuilder.add(externalWorkerLauncher.get().apply(i, discoveryUrl));
}
externalWorkers = externalWorkersBuilder.build();
closer.register(() -> {
for (Process worker : externalWorkers) {
worker.destroyForcibly();
}
});
// Don't use coordinator as worker
extraCoordinatorProperties.put("node-scheduler.include-coordinator", "false");
}
else {
externalWorkers = ImmutableList.of();
for (int i = (coordinatorCount + (resourceManagerEnabled ? 1 : 0)); i < nodeCount; i++) {
TestingPrestoServer worker = closer.register(createTestingPrestoServer(discoveryUrl, false, resourceManagerEnabled, false, extraProperties, parserOptions, environment, baseDataDir, extraModules));
servers.add(worker);
}
}
extraCoordinatorProperties.put("experimental.iterative-optimizer-enabled", "true");
extraCoordinatorProperties.putAll(extraProperties);
extraCoordinatorProperties.putAll(coordinatorProperties);
for (int i = 0; i < coordinatorCount; i++) {
TestingPrestoServer coordinator = closer.register(createTestingPrestoServer(discoveryUrl, false, resourceManagerEnabled, true, extraCoordinatorProperties, parserOptions, environment, baseDataDir, extraModules));
servers.add(coordinator);
coordinators.add(coordinator);
extraCoordinatorProperties.remove("http-server.http.port");
}
if (resourceManagerEnabled) {
resourceManager = Optional.of(closer.register(createTestingPrestoServer(discoveryUrl, true, true, false, extraCoordinatorProperties, parserOptions, environment, baseDataDir, extraModules)));
servers.add(resourceManager.get());
}
this.servers = servers.build();
this.coordinators = coordinators.build();
}
catch (Exception e) {
try {
throw closer.rethrow(e, Exception.class);
}
finally {
closer.close();
}
}
// copy session using property manager in coordinator
defaultSession = defaultSession.toSessionRepresentation().toSession(coordinators.get(0).getMetadata().getSessionPropertyManager());
ImmutableList.Builder<TestingPrestoClient> prestoClientsBuilder = ImmutableList.builder();
for (int i = 0; i < coordinatorCount; i++) {
prestoClientsBuilder.add(closer.register(new TestingPrestoClient(coordinators.get(i), defaultSession)));
}
prestoClients = prestoClientsBuilder.build();
long start = nanoTime();
while (!allNodesGloballyVisible()) {
Assertions.assertLessThan(nanosSince(start), new Duration(30, SECONDS));
MILLISECONDS.sleep(10);
}
log.info("Announced servers in %s", nanosSince(start).convertToMostSuccinctTimeUnit());
start = nanoTime();
for (TestingPrestoServer server : servers) {
server.getMetadata().registerBuiltInFunctions(AbstractTestQueries.CUSTOM_FUNCTIONS);
}
log.info("Added functions in %s", nanosSince(start).convertToMostSuccinctTimeUnit());
for (TestingPrestoServer server : servers) {
// add bogus catalog for testing procedures and session properties
Catalog bogusTestingCatalog = createBogusTestingCatalog(TESTING_CATALOG);
server.getCatalogManager().registerCatalog(bogusTestingCatalog);
SessionPropertyManager sessionPropertyManager = server.getMetadata().getSessionPropertyManager();
sessionPropertyManager.addSystemSessionProperties(TEST_SYSTEM_PROPERTIES);
sessionPropertyManager.addConnectorSessionProperties(bogusTestingCatalog.getConnectorId(), TEST_CATALOG_PROPERTIES);
}
}
private static TestingPrestoServer createTestingPrestoServer(URI discoveryUri, boolean resourceManager, boolean resourceManagerEnabled, boolean coordinator, Map<String, String> extraProperties, SqlParserOptions parserOptions, String environment, Optional<Path> baseDataDir, List<Module> extraModules)
throws Exception
{
long start = nanoTime();
ImmutableMap.Builder<String, String> propertiesBuilder = ImmutableMap.<String, String>builder()
.put("query.client.timeout", "10m")
.put("exchange.http-client.idle-timeout", "1h")
.put("task.max-index-memory", "16kB") // causes index joins to fault load
.put("datasources", "system")
.put("distributed-index-joins-enabled", "true")
.put("exchange.checksum-enabled", "true");
if (coordinator) {
propertiesBuilder.put("node-scheduler.include-coordinator", "true");
propertiesBuilder.put("join-distribution-type", "PARTITIONED");
}
HashMap<String, String> properties = new HashMap<>(propertiesBuilder.build());
properties.putAll(extraProperties);
TestingPrestoServer server = new TestingPrestoServer(resourceManager, resourceManagerEnabled, coordinator, properties, environment, discoveryUri, parserOptions, extraModules, baseDataDir);
String nodeRole = coordinator ? "coordinator" : resourceManager ? "resourceManager" : "worker";
log.info("Created %s TestingPrestoServer in %s: %s", nodeRole, nanosSince(start).convertToMostSuccinctTimeUnit(), server.getBaseUrl());
return server;
}
private boolean allNodesGloballyVisible()
{
int expectedActiveNodes = externalWorkers.size() + servers.size();
for (TestingPrestoServer server : servers) {
AllNodes allNodes = server.refreshNodes();
if (!allNodes.getInactiveNodes().isEmpty() ||
(allNodes.getActiveNodes().size() != expectedActiveNodes)) {
return false;
}
}
return true;
}
public TestingPrestoClient getRandomClient()
{
return prestoClients.get(getRandomCoordinatorIndex());
}
private int getRandomCoordinatorIndex()
{
return ThreadLocalRandom.current().nextInt(prestoClients.size());
}
@Override
public int getNodeCount()
{
return servers.size();
}
@Override
public Session getDefaultSession()
{
return getRandomClient().getDefaultSession();
}
@Override
public TransactionManager getTransactionManager()
{
checkState(coordinators.size() == 1, "Expected a single coordinator");
return coordinators.get(0).getTransactionManager();
}
@Override
public Metadata getMetadata()
{
checkState(coordinators.size() == 1, "Expected a single coordinator");
return coordinators.get(0).getMetadata();
}
@Override
public SplitManager getSplitManager()
{
checkState(coordinators.size() == 1, "Expected a single coordinator");
return coordinators.get(0).getSplitManager();
}
@Override
public PageSourceManager getPageSourceManager()
{
checkState(coordinators.size() == 1, "Expected a single coordinator");
return coordinators.get(0).getPageSourceManager();
}
@Override
public NodePartitioningManager getNodePartitioningManager()
{
checkState(coordinators.size() == 1, "Expected a single coordinator");
return coordinators.get(0).getNodePartitioningManager();
}
@Override
public ConnectorPlanOptimizerManager getPlanOptimizerManager()
{
checkState(coordinators.size() == 1, "Expected a single coordinator");
return coordinators.get(0).getPlanOptimizerManager();
}
@Override
public StatsCalculator getStatsCalculator()
{
checkState(coordinators.size() == 1, "Expected a single coordinator");
return coordinators.get(0).getStatsCalculator();
}
@Override
public Optional<EventListener> getEventListener()
{
checkState(coordinators.size() == 1, "Expected a single coordinator");
return coordinators.get(0).getEventListener();
}
@Override
public TestingAccessControlManager getAccessControl()
{
checkState(coordinators.size() == 1, "Expected a single coordinator");
return coordinators.get(0).getAccessControl();
}
public TestingPrestoServer getCoordinator()
{
checkState(coordinators.size() == 1, "Expected a single coordinator");
return coordinators.get(0);
}
public List<TestingPrestoServer> getCoordinators()
{
return coordinators;
}
public Optional<TestingPrestoServer> getResourceManager()
{
return resourceManager;
}
public List<TestingPrestoServer> getServers()
{
return ImmutableList.copyOf(servers);
}
@Override
public void installPlugin(Plugin plugin)
{
long start = nanoTime();
for (TestingPrestoServer server : servers) {
server.installPlugin(plugin);
}
log.info("Installed plugin %s in %s", plugin.getClass().getSimpleName(), nanosSince(start).convertToMostSuccinctTimeUnit());
}
public void createCatalog(String catalogName, String connectorName)
{
createCatalog(catalogName, connectorName, ImmutableMap.of());
}
@Override
public void createCatalog(String catalogName, String connectorName, Map<String, String> properties)
{
long start = nanoTime();
Set<ConnectorId> connectorIds = new HashSet<>();
for (TestingPrestoServer server : servers) {
connectorIds.add(server.createCatalog(catalogName, connectorName, properties));
}
ConnectorId connectorId = getOnlyElement(connectorIds);
log.info("Created catalog %s (%s) in %s", catalogName, connectorId, nanosSince(start));
// wait for all nodes to announce the new catalog
start = nanoTime();
while (!isConnectorVisibleToAllNodes(connectorId)) {
Assertions.assertLessThan(nanosSince(start), new Duration(100, SECONDS), "waiting for connector " + connectorId + " to be initialized in every node");
try {
MILLISECONDS.sleep(10);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
log.info("Announced catalog %s (%s) in %s", catalogName, connectorId, nanosSince(start));
}
@Override
public void loadFunctionNamespaceManager(String functionNamespaceManagerName, String catalogName, Map<String, String> properties)
{
for (TestingPrestoServer server : servers) {
server.getMetadata().getFunctionAndTypeManager().loadFunctionNamespaceManager(functionNamespaceManagerName, catalogName, properties);
}
}
/**
* This method exists only because it is currently impossible to create a function namespace from the query engine,
* and therefore the query runner needs to be aware of the H2 handle in order to create function namespaces when
* required by the tests.
* <p>
* TODO: Remove when there is a generic way of creating function namespaces as if creating schemas.
*/
public void enableTestFunctionNamespaces(List<String> catalogNames, Map<String, String> additionalProperties)
{
checkState(testFunctionNamespacesHandle.get() == null, "Test function namespaces already enabled");
String databaseName = String.valueOf(nanoTime()) + "_" + ThreadLocalRandom.current().nextInt();
Map<String, String> properties = ImmutableMap.<String, String>builder()
.put("database-name", databaseName)
.putAll(additionalProperties)
.build();
installPlugin(new H2FunctionNamespaceManagerPlugin());
for (String catalogName : catalogNames) {
loadFunctionNamespaceManager("h2", catalogName, properties);
}
Handle handle = Jdbi.open(H2ConnectionModule.getJdbcUrl(databaseName));
testFunctionNamespacesHandle.set(handle);
closer.register(handle);
}
public void createTestFunctionNamespace(String catalogName, String schemaName)
{
checkState(testFunctionNamespacesHandle.get() != null, "Test function namespaces not enabled");
testFunctionNamespacesHandle.get().execute("INSERT INTO function_namespaces SELECT ?, ?", catalogName, schemaName);
}
private boolean isConnectorVisibleToAllNodes(ConnectorId connectorId)
{
if (!externalWorkers.isEmpty()) {
return true;
}
for (TestingPrestoServer server : servers) {
server.refreshNodes();
Set<InternalNode> activeNodesWithConnector = server.getActiveNodesWithConnector(connectorId);
if (activeNodesWithConnector.size() != servers.size()) {
return false;
}
}
return true;
}
@Override
public List<QualifiedObjectName> listTables(Session session, String catalog, String schema)
{
lock.readLock().lock();
try {
return getRandomClient().listTables(session, catalog, schema);
}
finally {
lock.readLock().unlock();
}
}
@Override
public boolean tableExists(Session session, String table)
{
lock.readLock().lock();
try {
return getRandomClient().tableExists(session, table);
}
finally {
lock.readLock().unlock();
}
}
@Override
public MaterializedResult execute(@Language("SQL") String sql)
{
return execute(getRandomCoordinatorIndex(), sql);
}
@Override
public MaterializedResult execute(Session session, @Language("SQL") String sql)
{
return execute(getRandomCoordinatorIndex(), session, sql);
}
public ResultWithQueryId<MaterializedResult> executeWithQueryId(Session session, @Language("SQL") String sql)
{
return executeWithQueryId(getRandomCoordinatorIndex(), session, sql);
}
@Override
public MaterializedResultWithPlan executeWithPlan(Session session, String sql, WarningCollector warningCollector)
{
ResultWithQueryId<MaterializedResult> resultWithQueryId = executeWithQueryId(session, sql);
return new MaterializedResultWithPlan(resultWithQueryId.getResult().toTestTypes(), getQueryPlan(resultWithQueryId.getQueryId()));
}
public MaterializedResult execute(int coordinator, @Language("SQL") String sql)
{
checkArgument(coordinator >= 0 && coordinator < coordinators.size());
lock.readLock().lock();
try {
return prestoClients.get(coordinator).execute(sql).getResult();
}
finally {
lock.readLock().unlock();
}
}
public MaterializedResult execute(int coordinator, Session session, @Language("SQL") String sql)
{
checkArgument(coordinator >= 0 && coordinator < coordinators.size());
lock.readLock().lock();
try {
return prestoClients.get(coordinator).execute(session, sql).getResult();
}
finally {
lock.readLock().unlock();
}
}
public ResultWithQueryId<MaterializedResult> executeWithQueryId(int coordinator, Session session, @Language("SQL") String sql)
{
checkArgument(coordinator >= 0 && coordinator < coordinators.size());
lock.readLock().lock();
try {
return prestoClients.get(coordinator).execute(session, sql);
}
finally {
lock.readLock().unlock();
}
}
@Override
public Plan createPlan(Session session, String sql, WarningCollector warningCollector)
{
QueryId queryId = executeWithQueryId(session, sql).getQueryId();
Plan queryPlan = getQueryPlan(queryId);
checkState(coordinators.size() == 1, "Expected a single coordinator");
coordinators.get(0).getQueryManager().cancelQuery(queryId);
return queryPlan;
}
public List<BasicQueryInfo> getQueries()
{
checkState(coordinators.size() == 1, "Expected a single coordinator");
return coordinators.get(0).getQueryManager().getQueries();
}
public QueryInfo getQueryInfo(QueryId queryId)
{
checkState(coordinators.size() == 1, "Expected a single coordinator");
return coordinators.get(0).getQueryManager().getFullQueryInfo(queryId);
}
public Plan getQueryPlan(QueryId queryId)
{
checkState(coordinators.size() == 1, "Expected a single coordinator");
return coordinators.get(0).getQueryPlan(queryId);
}
@Override
public Lock getExclusiveLock()
{
return lock.writeLock();
}
@Override
public final void close()
{
cancelAllQueries();
try {
closer.close();
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private void cancelAllQueries()
{
for (TestingPrestoServer coordinator : coordinators) {
QueryManager queryManager = coordinator.getQueryManager();
for (BasicQueryInfo queryInfo : queryManager.getQueries()) {
if (!queryInfo.getState().isDone()) {
queryManager.cancelQuery(queryInfo.getQueryId());
}
}
}
}
private static void closeUnchecked(AutoCloseable closeable)
{
try {
closeable.close();
}
catch (Exception e) {
throwIfUnchecked(e);
throw new RuntimeException(e);
}
}
public static class Builder
{
private Session defaultSession;
private int nodeCount = 4;
private int coordinatorCount = 1;
private Map<String, String> extraProperties = ImmutableMap.of();
private Map<String, String> coordinatorProperties = ImmutableMap.of();
private SqlParserOptions parserOptions = DEFAULT_SQL_PARSER_OPTIONS;
private String environment = ENVIRONMENT;
private Optional<Path> baseDataDir = Optional.empty();
private Optional<BiFunction<Integer, URI, Process>> externalWorkerLauncher = Optional.empty();
private boolean resourceManagerEnabled;
private List<Module> extraModules = ImmutableList.of();
protected Builder(Session defaultSession)
{
this.defaultSession = requireNonNull(defaultSession, "defaultSession is null");
}
public Builder amendSession(Function<SessionBuilder, SessionBuilder> amendSession)
{
SessionBuilder builder = Session.builder(defaultSession);
this.defaultSession = amendSession.apply(builder).build();
return this;
}
public Builder setNodeCount(int nodeCount)
{
this.nodeCount = nodeCount;
return this;
}
public Builder setCoordinatorCount(int coordinatorCount)
{
this.coordinatorCount = coordinatorCount;
return this;
}
public Builder setExtraProperties(Map<String, String> extraProperties)
{
this.extraProperties = extraProperties;
return this;
}
/**
* Sets extra properties being equal to a map containing given key and value.
* Note, that calling this method OVERWRITES previously set property values.
* As a result, it should only be used when only one extra property needs to be set.
*/
public Builder setSingleExtraProperty(String key, String value)
{
return setExtraProperties(ImmutableMap.of(key, value));
}
public Builder setCoordinatorProperties(Map<String, String> coordinatorProperties)
{
this.coordinatorProperties = coordinatorProperties;
return this;
}
/**
* Sets coordinator properties being equal to a map containing given key and value.
* Note, that calling this method OVERWRITES previously set property values.
* As a result, it should only be used when only one coordinator property needs to be set.
*/
public Builder setSingleCoordinatorProperty(String key, String value)
{
return setCoordinatorProperties(ImmutableMap.of(key, value));
}
public Builder setParserOptions(SqlParserOptions parserOptions)
{
this.parserOptions = parserOptions;
return this;
}
public Builder setEnvironment(String environment)
{
this.environment = environment;
return this;
}
public Builder setBaseDataDir(Optional<Path> baseDataDir)
{
this.baseDataDir = requireNonNull(baseDataDir, "baseDataDir is null");
return this;
}
public Builder setExternalWorkerLauncher(Optional<BiFunction<Integer, URI, Process>> externalWorkerLauncher)
{
this.externalWorkerLauncher = requireNonNull(externalWorkerLauncher, "externalWorkerLauncher is null");
return this;
}
public Builder setResourceManagerEnabled(boolean resourceManagerEnabled)
{
this.resourceManagerEnabled = resourceManagerEnabled;
return this;
}
public Builder setExtraModules(List<Module> extraModules)
{
this.extraModules = extraModules;
return this;
}
public DistributedQueryRunner build()
throws Exception
{
return new DistributedQueryRunner(resourceManagerEnabled, defaultSession, nodeCount, coordinatorCount, extraProperties, coordinatorProperties, parserOptions, environment, baseDataDir, externalWorkerLauncher, extraModules);
}
}
}
| apache-2.0 |
jimmyMaci/wicket-googlevis | src/main/java/com/markatta/wicket/googlevis/PieChartConfiguration.java | 989 | package com.markatta.wicket.googlevis;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
*
* @author johan
*/
public final class PieChartConfiguration extends AbstractConfiguration implements Configuration, Serializable {
private static final long serialVersionUID = 1L;
private final boolean is3D;
public PieChartConfiguration(String title, int height, int width, boolean is3D) {
super(title, height, width);
this.is3D = is3D;
}
@Override
public Set<String> getPackages() {
return Collections.singleton("corechart");
}
@Override
public String getChartClass() {
return "google.visualization.PieChart";
}
@Override
public Map<String, Object> getVisualizationOptions() {
Map<String, Object> options = super.getVisualizationOptions();
options.put("is3D", is3D);
return options;
}
}
| apache-2.0 |
sdole/aws-sdk-java | aws-java-sdk-kinesis/src/main/java/com/amazonaws/services/kinesisfirehose/model/PutRecordResult.java | 3330 | /*
* Copyright 2010-2015 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.kinesisfirehose.model;
import java.io.Serializable;
/**
* <p>
* Contains the output of <a>PutRecord</a>.
* </p>
*/
public class PutRecordResult implements Serializable, Cloneable {
/**
* <p>
* The ID of the record.
* </p>
*/
private String recordId;
/**
* <p>
* The ID of the record.
* </p>
*
* @param recordId
* The ID of the record.
*/
public void setRecordId(String recordId) {
this.recordId = recordId;
}
/**
* <p>
* The ID of the record.
* </p>
*
* @return The ID of the record.
*/
public String getRecordId() {
return this.recordId;
}
/**
* <p>
* The ID of the record.
* </p>
*
* @param recordId
* The ID of the record.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public PutRecordResult withRecordId(String recordId) {
setRecordId(recordId);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getRecordId() != null)
sb.append("RecordId: " + getRecordId());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof PutRecordResult == false)
return false;
PutRecordResult other = (PutRecordResult) obj;
if (other.getRecordId() == null ^ this.getRecordId() == null)
return false;
if (other.getRecordId() != null
&& other.getRecordId().equals(this.getRecordId()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode
+ ((getRecordId() == null) ? 0 : getRecordId().hashCode());
return hashCode;
}
@Override
public PutRecordResult clone() {
try {
return (PutRecordResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
} | apache-2.0 |
wu-sheng/sky-walking | test/plugin/runner-helper/src/main/java/org/apache/skywalking/plugin/test/helper/RunningType.java | 910 | /*
* 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.skywalking.plugin.test.helper;
public enum RunningType {
Container, DockerCompose
}
| apache-2.0 |
chirino/activemq | activemq-itests-spring31/src/test/java/org/apache/activemq/itest/spring31/ActiveMQSpringProfile31Test.java | 1666 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.itest.spring31;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.Profile;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertNotNull;
/**
*
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("cool")
@Ignore("AMQ-3723")
public class ActiveMQSpringProfile31Test extends AbstractJUnit4SpringContextTests {
@Test
public void testSpringProfile31() throws Exception {
assertNotNull("Should find broker", applicationContext.getBean("myBroker"));
}
}
| apache-2.0 |
ind9/jets3t | src/org/jets3t/service/multithread/DownloadPackage.java | 4588 | /*
* jets3t : Java Extra-Tasty S3 Toolkit (for Amazon S3 online storage service)
* This is a java.net project, see https://jets3t.dev.java.net/
*
* Copyright 2006 James Murty
*
* 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.jets3t.service.multithread;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jets3t.service.io.GZipInflatingOutputStream;
import org.jets3t.service.model.S3Object;
import org.jets3t.service.security.EncryptionUtil;
/**
* A simple container object to associate one of an {@link S3Object} or a signed URL string
* with an output file, to which the S3 object's data will be written.
* <p>
* This class is used by
* {@link S3ServiceMulti#downloadObjects(org.jets3t.service.model.S3Bucket, DownloadPackage[])}
* to download objects.
*
* @author James Murty
*/
public class DownloadPackage {
private static final Log log = LogFactory.getLog(DownloadPackage.class);
private S3Object object = null;
private String signedUrl = null;
private File outputFile = null;
private boolean isUnzipping = false;
private EncryptionUtil encryptionUtil = null;
private boolean appendToFile = false;
public DownloadPackage(S3Object object, File outputFile) {
this(object, outputFile, false, null);
}
public DownloadPackage(S3Object object, File outputFile, boolean isUnzipping,
EncryptionUtil encryptionUtil)
{
this.object = object;
this.outputFile = outputFile;
this.isUnzipping = isUnzipping;
this.encryptionUtil = encryptionUtil;
}
public DownloadPackage(String signedUrl, File outputFile, boolean isUnzipping,
EncryptionUtil encryptionUtil)
{
this.signedUrl = signedUrl;
this.outputFile = outputFile;
this.isUnzipping = isUnzipping;
this.encryptionUtil = encryptionUtil;
}
public S3Object getObject() {
return object;
}
public File getDataFile() {
return outputFile;
}
public String getSignedUrl() {
return signedUrl;
}
public void setSignedUrl(String url) {
signedUrl = url;
}
public boolean isSignedDownload() {
return signedUrl != null;
}
public boolean isAppendToFile() {
return appendToFile;
}
public void setAppendToFile(boolean appendToFile) {
this.appendToFile = appendToFile;
}
/**
* Creates an output stream to receive the object's data. The output stream is based on a
* FileOutputStream, but will also be wrapped in a GZipInflatingOutputStream if
* isUnzipping is true and/or a decrypting output stream if this package has an associated
* non-null EncryptionUtil.
*
* @return
* an output stream that writes data to the output file managed by this class.
*
* @throws Exception
*/
public OutputStream getOutputStream() throws Exception {
// Create parent directories for file, if necessary.
if (outputFile.getParentFile() != null) {
outputFile.getParentFile().mkdirs();
}
OutputStream outputStream = new FileOutputStream(outputFile, appendToFile);
if (isUnzipping) {
log.debug("Inflating gzipped data for object: " + object.getKey());
outputStream = new GZipInflatingOutputStream(outputStream);
}
if (encryptionUtil != null) {
log.debug("Decrypting encrypted data for object: " + object.getKey());
outputStream = encryptionUtil.decrypt(outputStream);
}
return outputStream;
}
}
| apache-2.0 |
apache/cocoon | blocks/cocoon-validation/cocoon-validation-impl/src/main/java/org/apache/cocoon/components/validation/impl/AbstractSchemaParser.java | 3285 | /*
* 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.cocoon.components.validation.impl;
import org.apache.avalon.framework.activity.Disposable;
import org.apache.avalon.framework.activity.Initializable;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.avalon.framework.service.Serviceable;
import org.apache.excalibur.source.SourceResolver;
import org.apache.excalibur.xml.EntityResolver;
import org.apache.cocoon.components.validation.SchemaParser;
import org.apache.cocoon.util.AbstractLogEnabled;
/**
* <p>A {@link SchemaParser} caching {@link org.apache.cocoon.components.validation.Schema}
* instances for multiple use.</p>
*
* <p>A {@link org.apache.cocoon.components.validation.Schema} will be cached until its
* {@link org.apache.excalibur.source.SourceValidity} expires.</p>
*
* @version $Id$
*/
public abstract class AbstractSchemaParser extends AbstractLogEnabled
implements Serviceable, Initializable, Disposable, SchemaParser {
/** <p>The {@link ServiceManager} configured for this instance.</p> */
protected ServiceManager serviceManager;
/** <p>The {@link SourceResolver} to resolve URIs into {@link org.apache.excalibur.source.Source}s.</p> */
protected SourceResolver sourceResolver;
/** <p>The {@link EntityResolver} resolving against catalogs of public IDs.</p> */
protected EntityResolver entityResolver;
/**
* <p>Create a new {@link AbstractSchemaParser} instance.</p>
*/
public AbstractSchemaParser() {
super();
}
/**
* <p>Contextualize this component specifying a {@link ServiceManager} instance.</p>
*/
public void service(ServiceManager manager)
throws ServiceException {
this.serviceManager = manager;
}
/**
* <p>Initialize this component instance.</p>
*
* <p>A this point component resolution will happen.</p>
*/
public void initialize()
throws Exception {
this.entityResolver = (EntityResolver) this.serviceManager.lookup(EntityResolver.ROLE);
this.sourceResolver = (SourceResolver) this.serviceManager.lookup(SourceResolver.ROLE);
}
/**
* <p>Dispose this component instance.</p>
*/
public void dispose() {
if (this.entityResolver != null) this.serviceManager.release(this.entityResolver);
if (this.sourceResolver != null) this.serviceManager.release(this.sourceResolver);
}
}
| apache-2.0 |
sujitbehera27/MyRoboticsProjects-Arduino | src/org/myrobotlab/roomba/RTTTLParser.java | 3137 | package org.myrobotlab.roomba;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
*/
public class RTTTLParser {
public static HashMap noteToNum;
static {
noteToNum = new HashMap();
noteToNum.put("c", new Integer(0));
noteToNum.put("c#", new Integer(1));
noteToNum.put("d", new Integer(2));
noteToNum.put("d#", new Integer(3));
noteToNum.put("e", new Integer(4));
noteToNum.put("f", new Integer(5));
noteToNum.put("f#", new Integer(6));
noteToNum.put("g", new Integer(7));
noteToNum.put("g#", new Integer(8));
noteToNum.put("a", new Integer(9));
noteToNum.put("a#", new Integer(10));
noteToNum.put("b", new Integer(11));
noteToNum.put("h", new Integer(7));
}
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("usage: roombacomm.RTTTLParser <rttlstring>");
System.exit(0);
}
String rtttl = args[0];
ArrayList notelist = parse(rtttl);
for (int i = 0; i < notelist.size(); i++) {
System.out.println("notelist[" + i + "]=" + notelist.get(i));
}
}
public static ArrayList parse(String rtttl) {
System.out.println("parsing: " + rtttl);
String rtttl_working = rtttl.toLowerCase();
String parts[] = rtttl_working.split(":");
String name = parts[0];
String defaults[] = parts[1].split("[,=]");
String notes[] = parts[2].split(",");
// global defaults
int bpm = 63;
int octave = 6;
int duration = 4;
ArrayList notelist = new ArrayList();
for (int i = 0; i < defaults.length; i++) {
// System.out.println("defaults["+i+"]="+defaults[i]);
if (defaults[i].equals("b"))
try {
bpm = Integer.parseInt(defaults[i + 1]);
} catch (Exception e) {
}
else if (defaults[i].equals("o"))
try {
octave = Integer.parseInt(defaults[i + 1]);
} catch (Exception e) {
}
else if (defaults[i].equals("d"))
try {
duration = Integer.parseInt(defaults[i + 1]);
} catch (Exception e) {
}
}
System.out.println("bpm:" + bpm + ",octave:" + octave + ",duration:" + duration);
for (int i = 0; i < notes.length; i++) {
Matcher m = Pattern.compile("(\\d+)*(.+?)(\\d)*(\\.)*").matcher(notes[i]);
m.find();
// group(1) == duration (optional)
// group(2) == note (required)
// group(3) == scale (optional)
// group(4) == triplet (optional)
int dur = duration;
int oct = octave;
if (m.group(1) != null)
try {
dur = Integer.parseInt(m.group(1));
} catch (Exception e) {
}
if (m.group(4) != null && m.group(4).equals("."))
dur += dur / 2;
if (m.group(3) != null)
try {
oct = Integer.parseInt(m.group(3));
} catch (Exception e) {
}
if (m.group(2) != null) {
int notenum;
if (m.group(2).equals("p")) {
notenum = 0;
} else {
Integer nn = (Integer) noteToNum.get(m.group(2));
notenum = nn.intValue();
notenum = notenum + 12 * oct;
}
dur = bpmToMillis(bpm) / dur;
notelist.add(new Note(notenum, dur));
}
}
return notelist;
}
public static int bpmToMillis(int bpm) {
return (60 * 1000) / bpm;
}
}
| apache-2.0 |
Governance/overlord-commons | overlord-commons-services/src/test/java/org/overlord/commons/services/AbstractServiceRegistryTest.java | 4658 | /*
* JBoss, Home of Professional Open Source
* Copyright 2008-13, Red Hat Middleware LLC, and others contributors as indicated
* by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.overlord.commons.services;
import static org.junit.Assert.*;
import java.util.Set;
import org.junit.Test;
public class AbstractServiceRegistryTest {
@Test
public void testServiceInit() {
AbstractServiceRegistry sr=new AbstractServiceRegistry() {
@Override
public <T> T getSingleService(Class<T> serviceInterface)
throws IllegalStateException {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> Set<T> getServices(Class<T> serviceInterface) {
// TODO Auto-generated method stub
return null;
}
};
TestServiceImpl impl=new TestServiceImpl();
sr.init(impl);
if (!impl.isInit()) {
fail("TestServiceImpl has not been initialized"); //$NON-NLS-1$
}
if (impl.isClose()) {
fail("TestServiceImpl should not have been closed"); //$NON-NLS-1$
}
}
@Test
public void testServiceClose() {
AbstractServiceRegistry sr=new AbstractServiceRegistry() {
@Override
public <T> T getSingleService(Class<T> serviceInterface)
throws IllegalStateException {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> Set<T> getServices(Class<T> serviceInterface) {
// TODO Auto-generated method stub
return null;
}
};
TestServiceImpl impl=new TestServiceImpl();
sr.close(impl);
if (impl.isInit()) {
fail("TestServiceImpl should not have been initialized"); //$NON-NLS-1$
}
if (!impl.isClose()) {
fail("TestServiceImpl has not been closed"); //$NON-NLS-1$
}
}
@Test
public void testServiceInitException() {
AbstractServiceRegistry sr=new AbstractServiceRegistry() {
@Override
public <T> T getSingleService(Class<T> serviceInterface)
throws IllegalStateException {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> Set<T> getServices(Class<T> serviceInterface) {
// TODO Auto-generated method stub
return null;
}
};
TestServiceImpl impl=new TestServiceImpl();
impl.fail();
try {
sr.init(impl);
fail("Should have thrown exception"); //$NON-NLS-1$
} catch (Exception e) {
// Ignore
}
}
@Test
public void testServiceCloseFail() {
AbstractServiceRegistry sr=new AbstractServiceRegistry() {
@Override
public <T> T getSingleService(Class<T> serviceInterface)
throws IllegalStateException {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> Set<T> getServices(Class<T> serviceInterface) {
// TODO Auto-generated method stub
return null;
}
};
TestServiceImpl impl=new TestServiceImpl();
impl.fail();
try {
sr.close(impl);
fail("Should have thrown exception"); //$NON-NLS-1$
} catch (Exception e) {
// Ignore
}
}
}
| apache-2.0 |
ServiceComb/java-chassis | demo/demo-schema/src/main/java/org/apache/servicecomb/demo/DemoConst.java | 996 | /*
* 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.servicecomb.demo;
import org.apache.servicecomb.core.Const;
public interface DemoConst {
String[] transports = new String[] {"highway", "rest", Const.ANY_TRANSPORT};
}
| apache-2.0 |
kkllwww007/anthelion | anthelion/src/main/java/com/yahoo/research/robme/anthelion/framework/AnthProcessor.java | 13235 | package com.yahoo.research.robme.anthelion.framework;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Properties;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import com.yahoo.research.robme.anthelion.models.AnthHost;
import com.yahoo.research.robme.anthelion.models.AnthURL;
import com.yahoo.research.robme.anthelion.models.ClassificationMode;
import com.yahoo.research.robme.anthelion.models.banditfunction.DomainValueFunction;
/**
* Main class of the Anthelion module. This class includes all the necessary
* components to manipulate an incoming {@link AnthURL} list, reorder the list
* and push it to a given {@link AnthURL} output list. Within the process, the
* URLs will be attached to the hosts and a bandit approach will always select
* the next host, URLs should be crawled from. Within the Domain-Entity a
* {@link PriorityQueue} is filled with URLs based on the score, calculated by
* the {@link AnthOnlineClassifier}.
*
* @author Robert Meusel (robert@dwslab.de)
*
*/
public class AnthProcessor {
private BufferedWriter logFileWriter;
private boolean writeLog;
protected Queue<AnthURL> inputList;
protected Queue<AnthURL> outputList;
private boolean useStaticClassifier = false;
protected ConcurrentHashMap<String, AnthHost> knownDomains = new ConcurrentHashMap<String, AnthHost>();
private Thread banditThread;
private Thread pusherThread;
private Thread pullerThread;
private Thread statusThread;
private UrlPusher pusher;
private UrlPuller puller;
private StatusPrinter statusViewer;
private AnthBandit bandit;
protected AnthOnlineClassifier onlineLearner;
protected ArrayBlockingQueue<AnthHost> queuedDomains;
public AnthProcessor(Queue<AnthURL> inputList, Queue<AnthURL> outputList,
Properties prop) {
new AnthProcessor(inputList, outputList, prop, null);
}
/**
* Use to initialize crawler or add additional feedback. Will immediately
* start the learning process.
*
* @param list
* of {@link AnthURL}s which should be used to learn.
*/
public void initiateClassifier(List<AnthURL> list) {
onlineLearner.initialize(list);
}
public AnthProcessor(Queue<AnthURL> inputList, Queue<AnthURL> outputList,
Properties prop, String logFile) {
if (prop.getProperty("classifier.static") != null) {
useStaticClassifier = Boolean.parseBoolean(prop
.getProperty("classifier.static"));
}
if (prop.get("bandit.lambdadecay") == null) {
bandit = new AnthBandit(Double.parseDouble(prop
.getProperty("bandit.lambda")), Integer.parseInt(prop
.getProperty("domain.known.min")), Integer.parseInt(prop
.getProperty("domain.queue.offertime")), this);
} else {
bandit = new AnthBandit(
Double.parseDouble(prop.getProperty("bandit.lambda")),
Integer.parseInt(prop.getProperty("domain.known.min")),
Integer.parseInt(prop.getProperty("domain.queue.offertime")),
this, Boolean.parseBoolean(prop
.getProperty("bandit.lambdadecay")), Integer
.parseInt(prop
.getProperty("bandit.lambdadecayvalue")));
}
pusher = new UrlPusher(this, ClassificationMode.valueOf(prop
.getProperty("classifier.mode")) == ClassificationMode.OnDemand);
try {
puller = new UrlPuller(
this,
Integer.parseInt(prop.getProperty("inputlist.size")),
ClassificationMode.valueOf(prop
.getProperty("classifier.mode")) == ClassificationMode.OnExplore,
(DomainValueFunction) Class.forName(
prop.getProperty("domain.value.function"))
.newInstance());
} catch (NumberFormatException | InstantiationException
| IllegalAccessException | ClassNotFoundException e1) {
System.out.println("Could not find HostValueFunction");
e1.printStackTrace();
System.exit(0);
}
if (logFile != null) {
try {
this.logFileWriter = new BufferedWriter(new FileWriter(
new File(logFile)));
writeLog = true;
} catch (IOException e) {
System.out.println("Could not create logWriter");
writeLog = false;
}
} else {
// just for readability
writeLog = false;
}
statusViewer = new StatusPrinter();
// setting references
this.inputList = inputList;
this.outputList = outputList;
// initializing
queuedDomains = new ArrayBlockingQueue<AnthHost>(Integer.parseInt(prop
.getProperty("domain.queue.size")));
banditThread = new Thread(bandit, "Anthelion Bandit");
pusherThread = new Thread(pusher, "Anthelion URL Pusher");
pullerThread = new Thread(puller, "Anthelion URL Puller");
statusThread = new Thread(statusViewer, "Anthelion Status Viewer");
onlineLearner = new AnthOnlineClassifier(
prop.getProperty("classifier.name"),
prop.getProperty("classifier.options"),
Integer.parseInt(prop.getProperty("classifier.hashtricksize")),
Integer.parseInt(prop.getProperty("classifier.learn.batchsize")));
}
/**
* Start the threads.
*/
public void start() {
statusThread.start();
System.out.println("Started Status Viewer");
pullerThread.start();
System.out.println("Started Url Puller");
banditThread.start();
System.out.println("Started Bandit");
pusherThread.start();
System.out.println("Started Url Pusher");
}
/**
* Stop the threads.
*/
public void stop() {
puller.switchOf();
System.out.println("Switched of Url Puller");
bandit.switchOf();
System.out.println("Switched of Bandit");
pusher.switchOf();
System.out.println("Switched of Url Pusher");
statusViewer.switchOf();
System.out.println("Switched of Status Viewer");
}
/**
* Check the status of the threads.
*/
public void getStatus() {
System.out.println("Status Url Puller: " + pullerThread.getState());
System.out.println("Status Bandit: " + banditThread.getState());
System.out.println("Status Url Pusher: " + pusherThread.getState());
}
/**
* Switch of the URL Puller to empty the internal queue.
*/
public void runEmpty() {
puller.switchOf();
System.out.println("Switched of Url Puller");
}
/**
* Push crawled feedback back into the system.
*
* @param url
* URL String - as we assume the data structure used by the
* crawler is different than the internal data structure.
* @param sem
* if the URL included structured data or not.
* @throws URISyntaxException
* if the URL String is not valid based on the {@link URI}
* specifications.
*/
public void addFeedback(String url, boolean sem) throws URISyntaxException {
// we need to give feedback to the classifier and the domains itself
URI uri = new URI(url);
addFeedback(uri, sem);
}
public void addFeedback(URI uri, boolean sem) {
AnthHost domain = knownDomains.get((uri.getHost() != null ? uri
.getHost() : AnthURL.UNKNOWNHOST));
if (domain == null) {
return;
}
AnthURL aurl = domain.returnFeedback(uri, sem);
if (aurl == null) {
// there is one way this could happen - if the URL was two times in
// the process. If the time between the two appearance is great
// enough Anthelion will also push the URL multiple times as
// feedback.
return;
}
// learn / update classifier if not static
if (!useStaticClassifier) {
onlineLearner.pushFeedback(aurl);
}
}
private class StatusPrinter implements Runnable {
public StatusPrinter() {
if (writeLog) {
writeLogFileHeader();
}
}
protected boolean run;
public void switchOf() {
run = false;
}
private void writeLogFileHeader() {
if (writeLog) {
String header = "LogTime\tInputListSize\tUrlsPulled\tGoodUrlsPulled\tOutputListSize\tPushedUrls\tPusherProcessingTime\tPushedGoodUrls\tPushedBadUrls\tKnownDomains\tDomainsInQueue\tReadyUrls\tReadyDomains\tUrlsWaitingForFeedback\tBanditProcessingTime\tBanditArmsPulled\tBanditGoodArmsPulled\tBanditBadArmsPulled\tClassifierRight\tClassifierTotal\tClassifiedRightsPushed\n";
try {
logFileWriter.write(header);
logFileWriter.flush();
} catch (IOException e) {
System.out.println("LogFile is not ready to be written.");
writeLog = false;
}
} else {
System.out.println("LogFile is not ready to be written.");
}
}
@Override
public void run() {
run = true;
while (run) {
Iterator<Map.Entry<String, AnthHost>> iter = knownDomains
.entrySet().iterator();
int rdyDomains = 0;
int readyUrls = 0;
int feedback = 0;
int processed = 0;
int right = 0;
int banditGood = 0;
int banditBad = 0;
while (iter.hasNext()) {
Map.Entry<String, AnthHost> pairs = (Map.Entry<String, AnthHost>) iter
.next();
if (pairs.getValue().rdyToEnqueue()) {
rdyDomains++;
}
readyUrls += pairs.getValue().getReadyUrlsSize();
feedback += pairs.getValue().getAwaitingFeedbackSize();
processed += pairs.getValue().visitedUrls;
right += pairs.getValue().predictedRight;
banditGood += pairs.getValue().goodUrls;
banditBad += pairs.getValue().badUrls;
}
StringBuilder sb = new StringBuilder();
if (writeLog) {
// date
sb.append(new Date());
sb.append("\t");
// size of input list
sb.append(inputList.size());
sb.append("\t");
// number of pulled urls
sb.append(puller.pulledUrl);
sb.append("\t");
// number of good pulled urls
sb.append(puller.goodPulledUrl);
sb.append("\t");
// size of output list
sb.append(outputList.size());
sb.append("\t");
// number of pushed URLs
sb.append(pusher.pushedUrl);
sb.append("\t");
// processing time of pusher
sb.append(pusher.processingTime);
sb.append("\t");
// good pushed
sb.append(pusher.good);
sb.append("\t");
// bad pushed
sb.append(pusher.bad);
sb.append("\t");
// number of known domains
sb.append(knownDomains.size());
sb.append("\t");
// queue size of domains to be choosen from
sb.append(queuedDomains.size());
sb.append("\t");
// number of urls ready to be taken by pusher
sb.append(readyUrls);
sb.append("\t");
// ready domains
sb.append(rdyDomains);
sb.append("\t");
// waiting for feedback
sb.append(feedback);
sb.append("\t");
// bandit processing time
sb.append(bandit.processingTime);
sb.append("\t");
// number of arms pulled by bandit
sb.append(bandit.armsPulled);
sb.append("\t");
sb.append(banditGood);
sb.append("\t");
sb.append(banditBad);
sb.append("\t");
// right classified
sb.append(right);
sb.append("\t");
// classified in total
sb.append(processed);
sb.append("\t");
// predicted right pushed
sb.append(pusher.predictedRight);
sb.append("\n");
try {
logFileWriter.write(sb.toString());
logFileWriter.flush();
} catch (IOException e) {
System.out
.println("Could not write log. Switch to console.");
writeLog = false;
}
} else {
// status about the queues
sb.append("\n----------------------------------------------------\n");
sb.append(new Date());
sb.append(" Status Viewer says: ");
sb.append("\nInput queue: ");
sb.append(inputList.size());
sb.append("\nPulled URLs (good): ");
sb.append(puller.pulledUrl);
sb.append(" (");
sb.append(puller.goodPulledUrl);
sb.append(")\nOutput queue: ");
sb.append(outputList.size());
sb.append("\nPushed URLs: ");
sb.append(pusher.pushedUrl);
sb.append("\nKnown Domains: ");
sb.append(knownDomains.size());
sb.append("\nQueued Domains: ");
sb.append(queuedDomains.size());
sb.append("\nQueued Urls: ");
sb.append(readyUrls);
sb.append(" with ");
sb.append(rdyDomains);
sb.append(" domains beeing ready.");
sb.append("\nWaiting for feedback from URLs: ");
sb.append(feedback);
sb.append("\nBandit Processing time (ms): ");
sb.append((double) bandit.processingTime
/ bandit.armsPulled);
sb.append(" after pulling ");
sb.append(bandit.armsPulled);
sb.append(" arms.");
// processing rate
sb.append("\nAvg Time to pull new URL from queue (ms): ");
sb.append((double) pusher.processingTime / pusher.pushedUrl);
sb.append("\nCrawling Ratio (good/bad): ");
long good = pusher.good;
long bad = pusher.bad;
sb.append((double) good / bad);
sb.append(" (");
sb.append(good);
sb.append("/");
sb.append(bad);
sb.append(")");
// accuracy
sb.append("\nClassifier Accuracy: ");
sb.append((double) right / processed);
sb.append(" (");
sb.append(right);
sb.append("/");
sb.append(processed);
sb.append(")");
sb.append("\n");
System.out.println(sb.toString());
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
| apache-2.0 |
sdole/aws-sdk-java | aws-java-sdk-directory/src/main/java/com/amazonaws/services/directory/model/transform/DirectoryDescriptionJsonMarshaller.java | 6295 | /*
* Copyright 2010-2015 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.directory.model.transform;
import static com.amazonaws.util.StringUtils.UTF8;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.List;
import com.amazonaws.AmazonClientException;
import com.amazonaws.services.directory.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;
/**
* DirectoryDescriptionMarshaller
*/
public class DirectoryDescriptionJsonMarshaller {
/**
* Marshall the given parameter object, and output to a JSONWriter
*/
public void marshall(DirectoryDescription directoryDescription,
JSONWriter jsonWriter) {
if (directoryDescription == null) {
throw new AmazonClientException(
"Invalid argument passed to marshall(...)");
}
try {
jsonWriter.object();
if (directoryDescription.getDirectoryId() != null) {
jsonWriter.key("DirectoryId").value(
directoryDescription.getDirectoryId());
}
if (directoryDescription.getName() != null) {
jsonWriter.key("Name").value(directoryDescription.getName());
}
if (directoryDescription.getShortName() != null) {
jsonWriter.key("ShortName").value(
directoryDescription.getShortName());
}
if (directoryDescription.getSize() != null) {
jsonWriter.key("Size").value(directoryDescription.getSize());
}
if (directoryDescription.getAlias() != null) {
jsonWriter.key("Alias").value(directoryDescription.getAlias());
}
if (directoryDescription.getAccessUrl() != null) {
jsonWriter.key("AccessUrl").value(
directoryDescription.getAccessUrl());
}
if (directoryDescription.getDescription() != null) {
jsonWriter.key("Description").value(
directoryDescription.getDescription());
}
com.amazonaws.internal.SdkInternalList<String> dnsIpAddrsList = (com.amazonaws.internal.SdkInternalList<String>) directoryDescription
.getDnsIpAddrs();
if (!dnsIpAddrsList.isEmpty() || !dnsIpAddrsList.isAutoConstruct()) {
jsonWriter.key("DnsIpAddrs");
jsonWriter.array();
for (String dnsIpAddrsListValue : dnsIpAddrsList) {
if (dnsIpAddrsListValue != null) {
jsonWriter.value(dnsIpAddrsListValue);
}
}
jsonWriter.endArray();
}
if (directoryDescription.getStage() != null) {
jsonWriter.key("Stage").value(directoryDescription.getStage());
}
if (directoryDescription.getLaunchTime() != null) {
jsonWriter.key("LaunchTime").value(
directoryDescription.getLaunchTime());
}
if (directoryDescription.getStageLastUpdatedDateTime() != null) {
jsonWriter.key("StageLastUpdatedDateTime").value(
directoryDescription.getStageLastUpdatedDateTime());
}
if (directoryDescription.getType() != null) {
jsonWriter.key("Type").value(directoryDescription.getType());
}
if (directoryDescription.getVpcSettings() != null) {
jsonWriter.key("VpcSettings");
DirectoryVpcSettingsDescriptionJsonMarshaller.getInstance()
.marshall(directoryDescription.getVpcSettings(),
jsonWriter);
}
if (directoryDescription.getConnectSettings() != null) {
jsonWriter.key("ConnectSettings");
DirectoryConnectSettingsDescriptionJsonMarshaller.getInstance()
.marshall(directoryDescription.getConnectSettings(),
jsonWriter);
}
if (directoryDescription.getRadiusSettings() != null) {
jsonWriter.key("RadiusSettings");
RadiusSettingsJsonMarshaller.getInstance().marshall(
directoryDescription.getRadiusSettings(), jsonWriter);
}
if (directoryDescription.getRadiusStatus() != null) {
jsonWriter.key("RadiusStatus").value(
directoryDescription.getRadiusStatus());
}
if (directoryDescription.getStageReason() != null) {
jsonWriter.key("StageReason").value(
directoryDescription.getStageReason());
}
if (directoryDescription.getSsoEnabled() != null) {
jsonWriter.key("SsoEnabled").value(
directoryDescription.getSsoEnabled());
}
jsonWriter.endObject();
} catch (Throwable t) {
throw new AmazonClientException(
"Unable to marshall request to JSON: " + t.getMessage(), t);
}
}
private static DirectoryDescriptionJsonMarshaller instance;
public static DirectoryDescriptionJsonMarshaller getInstance() {
if (instance == null)
instance = new DirectoryDescriptionJsonMarshaller();
return instance;
}
}
| apache-2.0 |
gehel/spring-social-bitbucket | src/test/java/org/springframework/social/bitbucket/api/v2/impl/TeamV2TemplateTest.java | 6293 | /**
* Copyright (C) 2012 Eric Bottard / Guillaume Lederrey (eric.bottard+ghpublic@gmail.com / guillaume.lederrey@gmail.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 org.springframework.social.bitbucket.api.v2.impl;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.social.bitbucket.api.BitBucketSCM;
import org.springframework.social.bitbucket.api.v2.payload.*;
import static org.junit.Assert.assertEquals;
import static org.springframework.http.HttpMethod.GET;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
public class TeamV2TemplateTest extends BaseV2TemplateTest {
@Test
public void testGetTeam() {
mockServer
.expect(requestTo("https://api.bitbucket.org/2.0/teams/1team"))
.andExpect(method(GET))
.andRespond(
withSuccess(jsonResource("get-team"),
MediaType.APPLICATION_JSON));
BitBucketV2Account team = bitBucket.getTeamOperations().getTeam("1team");
assertEquals("1team", team.getUsername());
assertEquals(BitBucketV2Kind.team, team.getKind());
assertEquals("", team.getWebsite());
assertEquals("the team", team.getDisplayName());
assertEquals("", team.getLocation());
}
@Test
public void testGetTeamMembers() {
mockServer
.expect(requestTo("https://api.bitbucket.org/2.0/teams/1team/members"))
.andExpect(method(GET))
.andRespond(
withSuccess(jsonResource("get-team-members"),
MediaType.APPLICATION_JSON));
AccountPage page = bitBucket.getTeamOperations().getMembers("1team");
assertEquals(50, page.getPageLength());
assertEquals(1, page.getPage());
assertEquals(1, page.getSize());
assertEquals(1, page.getValues().size());
BitBucketV2Account user = page.getValues().get(0);
assertEquals("tutorials", user.getUsername());
assertEquals("https://tutorials.bitbucket.org/", user.getWebsite());
assertEquals("first name last", user.getDisplayName());
assertEquals("Santa Monica, CA", user.getLocation());
}
@Test
public void testGetTeamFollowers() {
mockServer
.expect(requestTo("https://api.bitbucket.org/2.0/teams/1team/followers"))
.andExpect(method(GET))
.andRespond(
withSuccess(jsonResource("get-team-followers"),
MediaType.APPLICATION_JSON));
AccountPage page = bitBucket.getTeamOperations().getFollowers("1team");
assertEquals(10, page.getPageLength());
assertEquals(1, page.getPage());
assertEquals(1, page.getSize());
assertEquals(1, page.getValues().size());
BitBucketV2Account user = page.getValues().get(0);
assertEquals("tutorials", user.getUsername());
assertEquals(BitBucketV2Kind.team, user.getKind());
assertEquals("https://tutorials.bitbucket.org/", user.getWebsite());
assertEquals("first name last", user.getDisplayName());
assertEquals("Santa Monica, CA", user.getLocation());
}
@Test
public void testGetTeamFollowing() {
mockServer
.expect(requestTo("https://api.bitbucket.org/2.0/teams/1team/following"))
.andExpect(method(GET))
.andRespond(
withSuccess(jsonResource("get-team-following"),
MediaType.APPLICATION_JSON));
AccountPage page = bitBucket.getTeamOperations().getFollowing("1team");
assertEquals(10, page.getPageLength());
assertEquals(1, page.getPage());
assertEquals(1, page.getSize());
assertEquals(1, page.getValues().size());
BitBucketV2Account user = page.getValues().get(0);
assertEquals("bitbucket", user.getUsername());
assertEquals(BitBucketV2Kind.team, user.getKind());
assertEquals("http://bitbucket.org/", user.getWebsite());
assertEquals("Atlassian Bitbucket", user.getDisplayName());
assertEquals("", user.getLocation());
}
@Test
public void testGetTeamRepositories() {
mockServer
.expect(requestTo("https://api.bitbucket.org/2.0/teams/1team/repositories"))
.andExpect(method(GET))
.andRespond(
withSuccess(jsonResource("get-team-repositories"),
MediaType.APPLICATION_JSON));
RepositoryPage page = bitBucket.getTeamOperations().getRepositories("1team");
assertEquals(10, page.getPageLength());
assertEquals(1, page.getPage());
assertEquals(4, page.getSize());
assertEquals(4, page.getValues().size());
BitBucketV2Repository repository = page.getValues().get(0);
assertEquals(BitBucketSCM.git, repository.getScm());
assertEquals(false, repository.hasWiki());
assertEquals("", repository.getDescription());
assertEquals(BitBucketForkPolicy.allowForks, repository.getForkPolicy());
assertEquals("java", repository.getLanguage());
assertEquals("1team/myarfx", repository.getFullName());
assertEquals(false, repository.hasIssues());
assertEquals(203173, repository.getSize());
assertEquals(false, repository.isPrivate());
assertEquals("MyArfX", repository.getName());
}
}
| apache-2.0 |
mayl8822/binnavi | src/main/java/com/google/security/zynamics/zylib/yfileswrap/gui/zygraph/edges/ZyInfoEdge.java | 5052 | // Copyright 2011-2016 Google LLC
//
// 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.zylib.yfileswrap.gui.zygraph.edges;
import com.google.security.zynamics.zylib.general.ListenerProvider;
import com.google.security.zynamics.zylib.gui.zygraph.edges.CBend;
import com.google.security.zynamics.zylib.gui.zygraph.edges.EdgeType;
import com.google.security.zynamics.zylib.gui.zygraph.edges.IViewEdge;
import com.google.security.zynamics.zylib.gui.zygraph.edges.IViewEdgeListener;
import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.nodes.ZyGraphNode;
import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.realizers.ZyEdgeRealizer;
import y.base.Edge;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
public class ZyInfoEdge extends ZyGraphEdge<ZyGraphNode<?>, ZyInfoEdge, IViewEdge<?>> {
public ZyInfoEdge(final ZyGraphNode<?> source, final ZyGraphNode<?> target, final Edge edge,
final ZyEdgeRealizer<ZyInfoEdge> r) {
super(source, target, edge, r, new CInfoEdge());
}
private static class CInfoEdge implements IViewEdge<Object> {
private final List<CBend> m_bends = new ArrayList<CBend>();
private final ListenerProvider<IViewEdgeListener> m_listeners =
new ListenerProvider<IViewEdgeListener>();
@Override
public void addBend(final double x, final double y) {
final CBend path = new CBend(x, y);
// if (m_paths.contains(path))
// {
// return;
// }
m_bends.add(path);
for (final IViewEdgeListener listener : m_listeners) {
try {
listener.addedBend(this, path);
} catch (final Exception exception) {
exception.printStackTrace();
}
}
}
@Override
public void addListener(final IViewEdgeListener listener) {
m_listeners.addListener(listener);
}
@Override
public void clearBends() {
m_bends.clear();
for (final IViewEdgeListener listener : m_listeners) {
try {
listener.clearedBends(this);
} catch (final Exception exception) {
exception.printStackTrace();
}
}
}
@Override
public int getBendCount() {
return m_bends.size();
}
@Override
public List<CBend> getBends() {
return new ArrayList<CBend>(m_bends);
}
@Override
public Color getColor() {
return Color.BLACK;
}
@Override
public int getId() {
return 0;
}
@Override
public Object getSource() {
return null;
}
@Override
public Object getTarget() {
return null;
}
@Override
public EdgeType getType() {
return EdgeType.TEXTNODE_EDGE;
}
@Override
public double getX1() {
return 0;
}
@Override
public double getX2() {
return 0;
}
@Override
public double getY1() {
return 0;
}
@Override
public double getY2() {
return 0;
}
@Override
public void insertBend(final int index, final double x, final double y) {
final CBend path = new CBend(x, y);
m_bends.add(index, path);
for (final IViewEdgeListener listener : m_listeners) {
try {
listener.insertedBend(this, index, path);
} catch (final Exception exception) {
exception.printStackTrace();
}
}
}
@Override
public boolean isSelected() {
return false;
}
@Override
public boolean isVisible() {
return true;
}
@Override
public void removeBend(final int index) {
m_bends.remove(index);
}
@Override
public void removeListener(final IViewEdgeListener listener) {
m_listeners.removeListener(listener);
}
@Override
public void setColor(final Color color) {
// Ignore this
}
@Override
public void setEdgeType(final EdgeType type) {
// Ignore this
}
@Override
public void setId(final int id) {
}
@Override
public void setSelected(final boolean selected) {
// Ignore this
}
@Override
public void setVisible(final boolean visible) {
// Ignore this
}
@Override
public void setX1(final double x1) {
// Ignore this
}
@Override
public void setX2(final double x2) {
// Ignore this
}
@Override
public void setY1(final double y1) {
// Ignore this
}
@Override
public void setY2(final double y2) {
// Ignore this
}
}
}
| apache-2.0 |
JavaMicroService/rapidpm-microservice-examples | modules/example009/src/main/java/org/rapidpm/microservice/filestore/servlet/ServletService.java | 3141 | /*
* 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.rapidpm.microservice.filestore.servlet;
import org.rapidpm.microservice.filestore.api.FileStoreResponse;
import org.rapidpm.microservice.filestore.api.FileStoreServiceMessage;
import org.rapidpm.microservice.filestore.api.StorageStatus;
import org.rapidpm.microservice.filestore.impl.FileStoreService;
import org.rapidpm.microservice.filestore.impl.RequestEncodingHelper;
import org.rapidpm.microservice.filestore.impl.UnknownActionException;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXB;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(urlPatterns = "/servletservice")
public class ServletService extends HttpServlet {
@Inject FileStoreService fileStoreService;
@Override
public void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
public void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
FileStoreServiceMessage message = extractFileStoreServiceMessage(req);
FileStoreResponse fileStoreResponse = handleFileStoreMessage(message);
final PrintWriter writer = resp.getWriter();
JAXB.marshal(fileStoreResponse, writer);
writer.close();
}
private FileStoreResponse handleFileStoreMessage(FileStoreServiceMessage message) {
FileStoreResponse fileStoreResponse = new FileStoreResponse();
try {
fileStoreResponse = fileStoreService.handleMessage(message);
} catch (UnknownActionException e) {
e.printStackTrace();
fileStoreResponse.status = StorageStatus.ERROR;
fileStoreResponse.message = e.getMessage();
}
return fileStoreResponse;
}
private FileStoreServiceMessage extractFileStoreServiceMessage(HttpServletRequest req) {
String xmlBase64 = req.getParameter("xml");
final String fromBase64 = RequestEncodingHelper.decodeFromBase64(xmlBase64);
return RequestEncodingHelper.parseXmlToMessage(fromBase64);
}
}
| apache-2.0 |
betfair/cougar | cougar-framework/cougar-core-impl/src/main/java/com/betfair/cougar/core/impl/ev/AbstractServiceRegistration.java | 3138 | /*
* Copyright 2014, The Sporting Exchange 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.betfair.cougar.core.impl.ev;
import com.betfair.cougar.api.ExecutionContext;
import com.betfair.cougar.api.Service;
import com.betfair.cougar.core.api.BindingDescriptor;
import com.betfair.cougar.core.api.BindingDescriptorRegistrationListener;
import com.betfair.cougar.core.api.ServiceDefinition;
import com.betfair.cougar.core.api.ServiceRegistrar;
import com.betfair.cougar.core.api.ev.*;
import com.betfair.cougar.core.api.events.Event;
import com.betfair.cougar.core.api.transports.EventTransport;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
/**
* Abstract service registerer, includes an implementation of the method that
* introduces the Transport BindingDescriptors to the transport collection
*/
public abstract class AbstractServiceRegistration implements EVServiceRegistration {
//This is the applications executableResolver
private ExecutableResolver resolver;
private ServiceDefinition serviceDefinition;
private Service service;
private String namespace;
private Set<BindingDescriptor> bindingDescriptors = Collections.emptySet();
@Override
public void introduceServiceToEV(ExecutionVenue ev, ServiceRegistrar serviceRegistrar, CompoundExecutableResolver compoundExecutableResolver) {
compoundExecutableResolver.registerExecutableResolver(namespace, getResolver());
serviceRegistrar.registerService(namespace, getServiceDefinition(), getService(), compoundExecutableResolver);
}
public abstract void introduceServiceToTransports(Iterator<? extends BindingDescriptorRegistrationListener> transports);
public Set<BindingDescriptor> getBindingDescriptors() {
return bindingDescriptors;
}
public void setBindingDescriptors(Set<BindingDescriptor> bindingDescriptors) {
this.bindingDescriptors = bindingDescriptors;
}
public ExecutableResolver getResolver() {
return resolver;
}
public void setResolver(ExecutableResolver resolver) {
this.resolver = resolver;
}
public Service getService() {
return service;
}
public void setService(Service service) {
this.service = service;
}
public ServiceDefinition getServiceDefinition() {
return serviceDefinition;
}
public void setServiceDefinition(ServiceDefinition serviceDefinition) {
this.serviceDefinition = serviceDefinition;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
}
| apache-2.0 |
yokmama/honki_android | Chapter09/Lesson41/after_jissyu4/core/src/com/yokmama/learn10/chapter09/lesson41/Hero.java | 7980 | package com.yokmama.learn10.chapter09.lesson41;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
/**
* キャラクターの制御
*/
class Hero {
// テクスチャタイルの横幅
private static final int TEXTURE_TILE_WIDTH = 64;
private static final int TEXTURE_TILE_HEIGHT = 64;
// ジャンプ時間
private static final float TIME_DURATION_RUNNING = 0.05f;
private static final float TIME_DURATION_JUMPING = 0.05f;
private static final float TIME_DURATION_WIN = 0.2f;
// アニメーションの状態(または添字)
private final static int ANIM_STATE_STILL = -1;
private final static int ANIM_STATE_RUNNING = 0;
private final static int ANIM_STATE_JUMPING = 1;
private final static int ANIM_STATE_WIN = 2;
// 地面からの距離
public static final float HERO_FLOOR_Y = 40;
// 画面左からの距離
public static final float HERO_LEFT_X = 150;
// テクスチャ
private final TextureRegion deadFrame;
private final Animation[] animations = new Animation[3];
private TextureRegion animStillFrame;
// アニメーションの状態
private int animState;
// 現在のアニメーションの状態を続けた時間
private float currentStateDisplayTime;
// キャラクターの移動速度
float heroVelocityX = 400;
// キャラクタの位置
final Vector2 position = new Vector2();
// キャラクタの速度
final Vector2 velocity = new Vector2();
// キャラクタの衝突判定用範囲オブジェクト
final Rectangle collisionRect = new Rectangle();
// ゲームオーバー
private static final float DEAD_JUMP_HEIGHT = 100.0f;
private boolean isDead;
private float deadPosY;
private boolean hasDeathAnimEnded;
// ゲームクリア
private final static int WIN_ANIM_STATE_WAIT_FOR_LANDING = 0;
private final static int WIN_ANIM_STATE_RUN = 1;
private final static int WIN_ANIM_STATE_SPIRAL = 2;
private final static int WIN_ANIM_STATE_STATIC = 3;
private boolean hasWon;
private int winAnimState;
// ジャンプ
private static final float JUMP_TIME = 1.0f;
private static final float JUMP_HEIGHT = 300.0f;
private boolean isJumping;
private boolean isDoubleJumping;
private float jumpingTime;
public Hero(Texture heroTexture) {
// テクスチャから、状態毎に TextureRegion を取得する
Array<TextureRegion> regions;
TextureRegion[][] split = TextureRegion.split(heroTexture,
TEXTURE_TILE_WIDTH, TEXTURE_TILE_HEIGHT);
regions = new Array<TextureRegion>();
regions.addAll(split[1], 0, 4);
regions.addAll(split[2], 0, 4);
animations[ANIM_STATE_RUNNING] = new Animation(TIME_DURATION_RUNNING,
regions, Animation.PlayMode.LOOP);
regions = new Array<TextureRegion>();
regions.addAll(split[3], 0, 7);
animations[ANIM_STATE_JUMPING] = new Animation(TIME_DURATION_JUMPING,
regions, Animation.PlayMode.NORMAL);
regions = new Array<TextureRegion>();
regions.addAll(split[0], 3, 2);
animations[ANIM_STATE_WIN] = new Animation(TIME_DURATION_WIN,
regions, Animation.PlayMode.LOOP);
// ゲームオーバー時の表示
deadFrame = split[0][3];
init();
}
public void init() {
animState = ANIM_STATE_STILL;
animStillFrame = animations[ANIM_STATE_RUNNING].getKeyFrame(0);
position.set(Hero.HERO_LEFT_X, Hero.HERO_FLOOR_Y);
velocity.set(0, 0);
hasWon = false;
isDead = false;
hasDeathAnimEnded = false;
isJumping = false;
isDoubleJumping = false;
}
public void startRunning() {
animState = ANIM_STATE_RUNNING;
velocity.set(heroVelocityX, 0);
}
public void update(float deltaTime) {
currentStateDisplayTime += deltaTime;
// ゲームオーバー時のアニメーション
if (isDead) {
updateDeadAnimation(deltaTime);
return;
}
if (isJumping) {
// ジャンプ中
jumpingTime += deltaTime;
float jumpTime = jumpingTime / Hero.JUMP_TIME;
position.y = HERO_FLOOR_Y + jumpFunc(jumpTime) * JUMP_HEIGHT;
if (jumpingTime >= Hero.JUMP_TIME) {
// ジャンプ終了時
isJumping = false;
isDoubleJumping = false;
animState = ANIM_STATE_RUNNING;
currentStateDisplayTime = 0;
position.y = HERO_FLOOR_Y;
}
}
// ゲームクリア時のアニメーション
if (hasWon && !isJumping) {
updateWinAnimation(deltaTime);
}
position.mulAdd(velocity, deltaTime);
collisionRect.set(position.x + 30, position.y, 40, 68);
}
private void updateDeadAnimation(float deltaTime) {
float deadTimeFraction = currentStateDisplayTime / 0.75f;
position.y = deadPosY + deadFunc(deadTimeFraction) * DEAD_JUMP_HEIGHT;
if (deadTimeFraction >= 0.75f) {
hasDeathAnimEnded = true;
}
}
private void updateWinAnimation(float deltaTime) {
if (winAnimState == WIN_ANIM_STATE_WAIT_FOR_LANDING) {
winAnimState = WIN_ANIM_STATE_RUN;
animState = ANIM_STATE_RUNNING;
currentStateDisplayTime = 0;
}
else if (winAnimState == WIN_ANIM_STATE_RUN) {
if (currentStateDisplayTime > 0.4f) {
winAnimState = WIN_ANIM_STATE_SPIRAL;
animState = ANIM_STATE_WIN;
currentStateDisplayTime = 0;
velocity.set(0, 0);
}
}
else if (winAnimState == WIN_ANIM_STATE_SPIRAL) {
if (currentStateDisplayTime > 1.4f) {
winAnimState = WIN_ANIM_STATE_STATIC;
animState = ANIM_STATE_STILL;
animStillFrame = animations[ANIM_STATE_WIN].getKeyFrame(0);
currentStateDisplayTime = 0;
}
}
}
private float deadFunc(float t) {
t = Math.min(Math.max(t, 0.0f), 1.0f);
return -7.6f * t * t + 5.62f * t;
}
public void draw(MyGdxGame game) {
if (hasDeathAnimEnded)
return;
if (animState == ANIM_STATE_STILL) {
game.batch.draw(animStillFrame,
position.x, position.y, 100, 98);
}
else {
game.batch.draw(animations[animState]
.getKeyFrame(currentStateDisplayTime),
position.x, position.y, 100, 98);
}
}
// ゲームクリア通知
public void win() {
hasWon = true;
winAnimState = WIN_ANIM_STATE_WAIT_FOR_LANDING;
velocity.set(300, 0);
}
// ゲームオーバー通知
public void die() {
isDead = true;
animStillFrame = deadFrame;
animState = ANIM_STATE_STILL;
currentStateDisplayTime = 0.0f;
deadPosY = position.y;
}
public void jump() {
if (!isJumping) {
isJumping = true;
jumpingTime = 0;
animState = ANIM_STATE_JUMPING;
currentStateDisplayTime = 0;
}
else if (!isDoubleJumping) {
if (jumpingTime > JUMP_TIME / 2.0f) {
isDoubleJumping = true;
jumpingTime = JUMP_TIME - jumpingTime;
currentStateDisplayTime = 0;
}
}
}
private float jumpFunc(float t) {
t = Math.min(Math.max(t, 0.0f), 1.0f);
return t * (-4.0f * t + 4.0f);
}
}
| apache-2.0 |
OpenBEL/openbel-contributions | kamml/src/kamml/Constants.java | 2245 | /*
* Copyright (C) 2014 Selventa, 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 kamml;
/**
* Constants.
*
* @author Nick Bargnesi
*/
class Constants {
/** GraphML header. */
final static String HEADER;
/** Graph element. */
final static String GRAPH;
/** Data element. */
final static String DATA_FMT;
/** Node element format. */
final static String NODE_FMT;
/** Edge element format. */
final static String EDGE_FMT;
/** Key element format. */
final static String KEY_FMT;
/** GraphML footer. */
final static String FOOTER;
static {
HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\"" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
" xsi:schemaLocation=\"http://graphml.graphdrawing.org/" +
"xmlns http://graphml.graphdrawing.org/xmlns/1.0/graph" +
"ml.xsd\">\n";
GRAPH = "<graph id=\"G\" edgedefault=\"directed\" parse.nod" +
"eids=\"canonical\" parse.edgeids=\"canonical\" par" +
"se.order=\"nodesfirst\">\n";
DATA_FMT = "<data key=\"%s\">%s</data>\n";
NODE_FMT = "<node id=\"%s\"><data key=\"key1\">%s</data>" +
"<data key=\"key2\">%s</data></node>\n";
EDGE_FMT = "<edge id=\"%s\" source=\"%s\" target=\"%s\">" +
"<data key=\"key3\">%s</data>" +
"<data key=\"key4\">%s</data></edge>\n";
KEY_FMT = "<key id=\"%s\" for=\"%s\" attr.name=\"%s\" attr." +
"type=\"%s\"/>\n";
FOOTER = "</graph></graphml>\n";
}
} | apache-2.0 |
lucastheisen/mina-sshd | sshd-core/src/main/java/org/apache/sshd/client/ClientFactoryManager.java | 2302 | /*
* 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.sshd.client;
import org.apache.sshd.common.FactoryManager;
import org.apache.sshd.common.TcpipForwarderFactory;
/**
* The <code>ClientFactoryManager</code> enable the retrieval of additional
* configuration needed specifically for the client side.
*
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
*/
public interface ClientFactoryManager extends FactoryManager {
/**
* Key used to set the heartbeat interval in milliseconds (0 to disable which is the default value)
*/
public static final String HEARTBEAT_INTERVAL = "hearbeat-interval";
/**
* Key used to check the hearbeat request that should be sent to the server (default is keepalive@sshd.apache.org).
*/
public static final String HEARTBEAT_REQUEST = "heartbeat-request";
/**
* Retrieve the server key verifier to be used to check the key when connecting
* to an ssh server.
*
* @return the server key verifier to use
*/
ServerKeyVerifier getServerKeyVerifier();
/**
* Retrieve the TcpipForwarder factory to be used to accept incoming connections
* and forward data.
*
* @return A <code>TcpipForwarderFactory</code>
*/
TcpipForwarderFactory getTcpipForwarderFactory();
/**
* Retrieve the UserInteraction object to communicate with the user.
*
* @return A <code>UserInteraction</code> or <code>null</code>
*/
UserInteraction getUserInteraction();
}
| apache-2.0 |
ChinaQuants/Strata | modules/math/src/main/java/com/opengamma/strata/math/impl/rootfinding/SingleRootFinder.java | 873 | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.math.impl.rootfinding;
import java.util.function.Function;
/**
* Interface for classes that attempt to find a root for a one-dimensional function
* (see {@link Function}) $f(x)$ bounded by user-supplied values,
* $x_1$ and $x_2$. If there is not a single root between these bounds, an exception is thrown.
*
* @param <S> The input type of the function
* @param <T> The output type of the function
*/
public interface SingleRootFinder<S, T> {
/**
* Finds the root.
*
* @param function the function, not null
* @param roots the roots, not null
* @return a root lying between x1 and x2
*/
@SuppressWarnings("unchecked")
S getRoot(Function<S, T> function, S... roots);
}
| apache-2.0 |
WIgor/hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/AMRMProxyService.java | 23228 | /**
* 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.yarn.server.nodemanager.amrmproxy;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.ipc.Server;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.SaslRpcServer;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.apache.hadoop.service.AbstractService;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.yarn.api.ApplicationMasterProtocol;
import org.apache.hadoop.yarn.api.protocolrecords.AllocateRequest;
import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse;
import org.apache.hadoop.yarn.api.protocolrecords.FinishApplicationMasterRequest;
import org.apache.hadoop.yarn.api.protocolrecords.FinishApplicationMasterResponse;
import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterRequest;
import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterResponse;
import org.apache.hadoop.yarn.api.protocolrecords.StartContainerRequest;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.event.AsyncDispatcher;
import org.apache.hadoop.yarn.event.EventHandler;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
import org.apache.hadoop.yarn.ipc.YarnRPC;
import org.apache.hadoop.yarn.security.AMRMTokenIdentifier;
import org.apache.hadoop.yarn.security.ContainerTokenIdentifier;
import org.apache.hadoop.yarn.server.nodemanager.Context;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEventType;
import org.apache.hadoop.yarn.server.nodemanager.scheduler.DistributedScheduler;
import org.apache.hadoop.yarn.server.security.MasterKeyData;
import org.apache.hadoop.yarn.server.utils.BuilderUtils;
import org.apache.hadoop.yarn.server.utils.YarnServerSecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
/**
* AMRMProxyService is a service that runs on each node manager that can be used
* to intercept and inspect messages from application master to the cluster
* resource manager. It listens to messages from the application master and
* creates a request intercepting pipeline instance for each application. The
* pipeline is a chain of interceptor instances that can inspect and modify the
* request/response as needed.
*/
public class AMRMProxyService extends AbstractService implements
ApplicationMasterProtocol {
private static final Logger LOG = LoggerFactory
.getLogger(AMRMProxyService.class);
private Server server;
private final Context nmContext;
private final AsyncDispatcher dispatcher;
private InetSocketAddress listenerEndpoint;
private AMRMProxyTokenSecretManager secretManager;
private Map<ApplicationId, RequestInterceptorChainWrapper> applPipelineMap;
/**
* Creates an instance of the service.
*
* @param nmContext
* @param dispatcher
*/
public AMRMProxyService(Context nmContext, AsyncDispatcher dispatcher) {
super(AMRMProxyService.class.getName());
Preconditions.checkArgument(nmContext != null, "nmContext is null");
Preconditions.checkArgument(dispatcher != null, "dispatcher is null");
this.nmContext = nmContext;
this.dispatcher = dispatcher;
this.applPipelineMap =
new ConcurrentHashMap<ApplicationId, RequestInterceptorChainWrapper>();
this.dispatcher.register(ApplicationEventType.class,
new ApplicationEventHandler());
}
@Override
protected void serviceStart() throws Exception {
LOG.info("Starting AMRMProxyService");
Configuration conf = getConfig();
YarnRPC rpc = YarnRPC.create(conf);
UserGroupInformation.setConfiguration(conf);
this.listenerEndpoint =
conf.getSocketAddr(YarnConfiguration.AMRM_PROXY_ADDRESS,
YarnConfiguration.DEFAULT_AMRM_PROXY_ADDRESS,
YarnConfiguration.DEFAULT_AMRM_PROXY_PORT);
Configuration serverConf = new Configuration(conf);
serverConf.set(
CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION,
SaslRpcServer.AuthMethod.TOKEN.toString());
int numWorkerThreads =
serverConf.getInt(
YarnConfiguration.AMRM_PROXY_CLIENT_THREAD_COUNT,
YarnConfiguration.DEFAULT_AMRM_PROXY_CLIENT_THREAD_COUNT);
this.secretManager = new AMRMProxyTokenSecretManager(serverConf);
this.secretManager.start();
this.server =
rpc.getServer(ApplicationMasterProtocol.class, this,
listenerEndpoint, serverConf, this.secretManager,
numWorkerThreads);
this.server.start();
LOG.info("AMRMProxyService listening on address: "
+ this.server.getListenerAddress());
super.serviceStart();
}
@Override
protected void serviceStop() throws Exception {
LOG.info("Stopping AMRMProxyService");
if (this.server != null) {
this.server.stop();
}
this.secretManager.stop();
super.serviceStop();
}
/**
* This is called by the AMs started on this node to register with the RM.
* This method does the initial authorization and then forwards the request to
* the application instance specific intercepter chain.
*/
@Override
public RegisterApplicationMasterResponse registerApplicationMaster(
RegisterApplicationMasterRequest request) throws YarnException,
IOException {
LOG.info("Registering application master." + " Host:"
+ request.getHost() + " Port:" + request.getRpcPort()
+ " Tracking Url:" + request.getTrackingUrl());
RequestInterceptorChainWrapper pipeline =
authorizeAndGetInterceptorChain();
return pipeline.getRootInterceptor()
.registerApplicationMaster(request);
}
/**
* This is called by the AMs started on this node to unregister from the RM.
* This method does the initial authorization and then forwards the request to
* the application instance specific intercepter chain.
*/
@Override
public FinishApplicationMasterResponse finishApplicationMaster(
FinishApplicationMasterRequest request) throws YarnException,
IOException {
LOG.info("Finishing application master. Tracking Url:"
+ request.getTrackingUrl());
RequestInterceptorChainWrapper pipeline =
authorizeAndGetInterceptorChain();
return pipeline.getRootInterceptor().finishApplicationMaster(request);
}
/**
* This is called by the AMs started on this node to send heart beat to RM.
* This method does the initial authorization and then forwards the request to
* the application instance specific pipeline, which is a chain of request
* intercepter objects. One application request processing pipeline is created
* per AM instance.
*/
@Override
public AllocateResponse allocate(AllocateRequest request)
throws YarnException, IOException {
AMRMTokenIdentifier amrmTokenIdentifier =
YarnServerSecurityUtils.authorizeRequest();
RequestInterceptorChainWrapper pipeline =
getInterceptorChain(amrmTokenIdentifier);
AllocateResponse allocateResponse =
pipeline.getRootInterceptor().allocate(request);
updateAMRMTokens(amrmTokenIdentifier, pipeline, allocateResponse);
return allocateResponse;
}
/**
* Callback from the ContainerManager implementation for initializing the
* application request processing pipeline.
*
* @param request - encapsulates information for starting an AM
* @throws IOException
* @throws YarnException
*/
public void processApplicationStartRequest(StartContainerRequest request)
throws IOException, YarnException {
LOG.info("Callback received for initializing request "
+ "processing pipeline for an AM");
ContainerTokenIdentifier containerTokenIdentifierForKey =
BuilderUtils.newContainerTokenIdentifier(request
.getContainerToken());
ApplicationAttemptId appAttemptId =
containerTokenIdentifierForKey.getContainerID()
.getApplicationAttemptId();
Credentials credentials =
YarnServerSecurityUtils.parseCredentials(request
.getContainerLaunchContext());
Token<AMRMTokenIdentifier> amrmToken =
getFirstAMRMToken(credentials.getAllTokens());
if (amrmToken == null) {
throw new YarnRuntimeException(
"AMRMToken not found in the start container request for application:"
+ appAttemptId.toString());
}
// Substitute the existing AMRM Token with a local one. Keep the rest of the
// tokens in the credentials intact.
Token<AMRMTokenIdentifier> localToken =
this.secretManager.createAndGetAMRMToken(appAttemptId);
credentials.addToken(localToken.getService(), localToken);
DataOutputBuffer dob = new DataOutputBuffer();
credentials.writeTokenStorageToStream(dob);
request.getContainerLaunchContext().setTokens(
ByteBuffer.wrap(dob.getData(), 0, dob.getLength()));
initializePipeline(containerTokenIdentifierForKey.getContainerID()
.getApplicationAttemptId(),
containerTokenIdentifierForKey.getApplicationSubmitter(),
amrmToken, localToken);
}
/**
* Initializes the request intercepter pipeline for the specified application.
*
* @param applicationAttemptId
* @param user
* @param amrmToken
*/
protected void initializePipeline(
ApplicationAttemptId applicationAttemptId, String user,
Token<AMRMTokenIdentifier> amrmToken,
Token<AMRMTokenIdentifier> localToken) {
RequestInterceptorChainWrapper chainWrapper = null;
synchronized (applPipelineMap) {
if (applPipelineMap.containsKey(applicationAttemptId.getApplicationId())) {
LOG.warn("Request to start an already existing appId was received. "
+ " This can happen if an application failed and a new attempt "
+ "was created on this machine. ApplicationId: "
+ applicationAttemptId.toString());
return;
}
chainWrapper = new RequestInterceptorChainWrapper();
this.applPipelineMap.put(applicationAttemptId.getApplicationId(),
chainWrapper);
}
// We register the pipeline instance in the map first and then initialize it
// later because chain initialization can be expensive and we would like to
// release the lock as soon as possible to prevent other applications from
// blocking when one application's chain is initializing
LOG.info("Initializing request processing pipeline for application. "
+ " ApplicationId:" + applicationAttemptId + " for the user: "
+ user);
RequestInterceptor interceptorChain =
this.createRequestInterceptorChain();
interceptorChain.init(createApplicationMasterContext(
applicationAttemptId, user, amrmToken, localToken));
chainWrapper.init(interceptorChain, applicationAttemptId);
}
/**
* Shuts down the request processing pipeline for the specified application
* attempt id.
*
* @param applicationId
*/
protected void stopApplication(ApplicationId applicationId) {
Preconditions.checkArgument(applicationId != null,
"applicationId is null");
RequestInterceptorChainWrapper pipeline =
this.applPipelineMap.remove(applicationId);
if (pipeline == null) {
LOG.info("Request to stop an application that does not exist. Id:"
+ applicationId);
} else {
LOG.info("Stopping the request processing pipeline for application: "
+ applicationId);
try {
pipeline.getRootInterceptor().shutdown();
} catch (Throwable ex) {
LOG.warn(
"Failed to shutdown the request processing pipeline for app:"
+ applicationId, ex);
}
}
}
private void updateAMRMTokens(AMRMTokenIdentifier amrmTokenIdentifier,
RequestInterceptorChainWrapper pipeline,
AllocateResponse allocateResponse) {
AMRMProxyApplicationContextImpl context =
(AMRMProxyApplicationContextImpl) pipeline.getRootInterceptor()
.getApplicationContext();
// check to see if the RM has issued a new AMRMToken & accordingly update
// the real ARMRMToken in the current context
if (allocateResponse.getAMRMToken() != null) {
LOG.info("RM rolled master-key for amrm-tokens");
org.apache.hadoop.yarn.api.records.Token token =
allocateResponse.getAMRMToken();
// Do not propagate this info back to AM
allocateResponse.setAMRMToken(null);
org.apache.hadoop.security.token.Token<AMRMTokenIdentifier> newTokenId =
new org.apache.hadoop.security.token.Token<AMRMTokenIdentifier>(
token.getIdentifier().array(), token.getPassword().array(),
new Text(token.getKind()), new Text(token.getService()));
context.setAMRMToken(newTokenId);
}
// Check if the local AMRMToken is rolled up and update the context and
// response accordingly
MasterKeyData nextMasterKey =
this.secretManager.getNextMasterKeyData();
if (nextMasterKey != null
&& nextMasterKey.getMasterKey().getKeyId() != amrmTokenIdentifier
.getKeyId()) {
Token<AMRMTokenIdentifier> localToken = context.getLocalAMRMToken();
if (nextMasterKey.getMasterKey().getKeyId() != context
.getLocalAMRMTokenKeyId()) {
LOG.info("The local AMRMToken has been rolled-over."
+ " Send new local AMRMToken back to application: "
+ pipeline.getApplicationId());
localToken =
this.secretManager.createAndGetAMRMToken(pipeline
.getApplicationAttemptId());
context.setLocalAMRMToken(localToken);
}
allocateResponse
.setAMRMToken(org.apache.hadoop.yarn.api.records.Token
.newInstance(localToken.getIdentifier(), localToken
.getKind().toString(), localToken.getPassword(),
localToken.getService().toString()));
}
}
private AMRMProxyApplicationContext createApplicationMasterContext(
ApplicationAttemptId applicationAttemptId, String user,
Token<AMRMTokenIdentifier> amrmToken,
Token<AMRMTokenIdentifier> localToken) {
AMRMProxyApplicationContextImpl appContext =
new AMRMProxyApplicationContextImpl(this.nmContext, getConfig(),
applicationAttemptId, user, amrmToken, localToken);
return appContext;
}
/**
* Gets the Request intercepter chains for all the applications.
*
* @return the request intercepter chains.
*/
protected Map<ApplicationId, RequestInterceptorChainWrapper> getPipelines() {
return this.applPipelineMap;
}
/**
* This method creates and returns reference of the first intercepter in the
* chain of request intercepter instances.
*
* @return the reference of the first intercepter in the chain
*/
protected RequestInterceptor createRequestInterceptorChain() {
Configuration conf = getConfig();
List<String> interceptorClassNames = getInterceptorClassNames(conf);
RequestInterceptor pipeline = null;
RequestInterceptor current = null;
for (String interceptorClassName : interceptorClassNames) {
try {
Class<?> interceptorClass =
conf.getClassByName(interceptorClassName);
if (RequestInterceptor.class.isAssignableFrom(interceptorClass)) {
RequestInterceptor interceptorInstance =
(RequestInterceptor) ReflectionUtils.newInstance(
interceptorClass, conf);
if (pipeline == null) {
pipeline = interceptorInstance;
current = interceptorInstance;
continue;
} else {
current.setNextInterceptor(interceptorInstance);
current = interceptorInstance;
}
} else {
throw new YarnRuntimeException("Class: " + interceptorClassName
+ " not instance of "
+ RequestInterceptor.class.getCanonicalName());
}
} catch (ClassNotFoundException e) {
throw new YarnRuntimeException(
"Could not instantiate ApplicationMasterRequestInterceptor: "
+ interceptorClassName, e);
}
}
if (pipeline == null) {
throw new YarnRuntimeException(
"RequestInterceptor pipeline is not configured in the system");
}
return pipeline;
}
/**
* Returns the comma separated intercepter class names from the configuration.
*
* @param conf
* @return the intercepter class names as an instance of ArrayList
*/
private List<String> getInterceptorClassNames(Configuration conf) {
String configuredInterceptorClassNames =
conf.get(
YarnConfiguration.AMRM_PROXY_INTERCEPTOR_CLASS_PIPELINE,
YarnConfiguration.DEFAULT_AMRM_PROXY_INTERCEPTOR_CLASS_PIPELINE);
List<String> interceptorClassNames = new ArrayList<String>();
Collection<String> tempList =
StringUtils.getStringCollection(configuredInterceptorClassNames);
for (String item : tempList) {
interceptorClassNames.add(item.trim());
}
// Make sure DistributedScheduler is present at the beginning of the chain.
if (this.nmContext.isDistributedSchedulingEnabled()) {
interceptorClassNames.add(0, DistributedScheduler.class.getName());
}
return interceptorClassNames;
}
/**
* Authorizes the request and returns the application specific request
* processing pipeline.
*
* @return the the intercepter wrapper instance
* @throws YarnException
*/
private RequestInterceptorChainWrapper authorizeAndGetInterceptorChain()
throws YarnException {
AMRMTokenIdentifier tokenIdentifier =
YarnServerSecurityUtils.authorizeRequest();
return getInterceptorChain(tokenIdentifier);
}
private RequestInterceptorChainWrapper getInterceptorChain(
AMRMTokenIdentifier tokenIdentifier) throws YarnException {
ApplicationAttemptId appAttemptId =
tokenIdentifier.getApplicationAttemptId();
synchronized (this.applPipelineMap) {
if (!this.applPipelineMap.containsKey(appAttemptId
.getApplicationId())) {
throw new YarnException(
"The AM request processing pipeline is not initialized for app: "
+ appAttemptId.getApplicationId().toString());
}
return this.applPipelineMap.get(appAttemptId.getApplicationId());
}
}
@SuppressWarnings("unchecked")
private Token<AMRMTokenIdentifier> getFirstAMRMToken(
Collection<Token<? extends TokenIdentifier>> allTokens) {
Iterator<Token<? extends TokenIdentifier>> iter = allTokens.iterator();
while (iter.hasNext()) {
Token<? extends TokenIdentifier> token = iter.next();
if (token.getKind().equals(AMRMTokenIdentifier.KIND_NAME)) {
return (Token<AMRMTokenIdentifier>) token;
}
}
return null;
}
@Private
public InetSocketAddress getBindAddress() {
return this.listenerEndpoint;
}
@Private
public AMRMProxyTokenSecretManager getSecretManager() {
return this.secretManager;
}
/**
* Private class for handling application stop events.
*
*/
class ApplicationEventHandler implements EventHandler<ApplicationEvent> {
@Override
public void handle(ApplicationEvent event) {
Application app =
AMRMProxyService.this.nmContext.getApplications().get(
event.getApplicationID());
if (app != null) {
switch (event.getType()) {
case FINISH_APPLICATION:
LOG.info("Application stop event received for stopping AppId:"
+ event.getApplicationID().toString());
AMRMProxyService.this.stopApplication(event.getApplicationID());
break;
default:
if (LOG.isDebugEnabled()) {
LOG.debug("AMRMProxy is ignoring event: " + event.getType());
}
break;
}
} else {
LOG.warn("Event " + event + " sent to absent application "
+ event.getApplicationID());
}
}
}
/**
* Private structure for encapsulating RequestInterceptor and
* ApplicationAttemptId instances.
*
*/
@Private
public static class RequestInterceptorChainWrapper {
private RequestInterceptor rootInterceptor;
private ApplicationAttemptId applicationAttemptId;
/**
* Initializes the wrapper with the specified parameters.
*
* @param rootInterceptor
* @param applicationAttemptId
*/
public synchronized void init(RequestInterceptor rootInterceptor,
ApplicationAttemptId applicationAttemptId) {
this.rootInterceptor = rootInterceptor;
this.applicationAttemptId = applicationAttemptId;
}
/**
* Gets the root request intercepter.
*
* @return the root request intercepter
*/
public synchronized RequestInterceptor getRootInterceptor() {
return rootInterceptor;
}
/**
* Gets the application attempt identifier.
*
* @return the application attempt identifier
*/
public synchronized ApplicationAttemptId getApplicationAttemptId() {
return applicationAttemptId;
}
/**
* Gets the application identifier.
*
* @return the application identifier
*/
public synchronized ApplicationId getApplicationId() {
return applicationAttemptId.getApplicationId();
}
}
}
| apache-2.0 |
FUNCATE/TerraMobile | sldparser/src/main/geotools/data/sort/PropertyComparator.java | 2054 | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2004-2008, Open Source Geospatial Foundation (OSGeo)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.geotools.data.sort;
import java.util.Comparator;
import org.opengis.feature.simple.SimpleFeature;
/**
* Compares two feature based on an attribute value
*
* @author Andrea Aime - GeoSolutions
*/
class PropertyComparator implements Comparator<SimpleFeature> {
String propertyName;
boolean ascending;
/**
* Builds a new comparator
*
* @param propertyName The property name to be used
* @param inverse If true the comparator will force an ascending order (descending otherwise)
*/
public PropertyComparator(String propertyName, boolean ascending) {
this.propertyName = propertyName;
this.ascending = ascending;
}
public int compare(SimpleFeature f1, SimpleFeature f2) {
int result = compareAscending(f1, f2);
if (ascending) {
return result;
} else {
return result * -1;
}
}
private int compareAscending(SimpleFeature f1, SimpleFeature f2) {
Comparable o1 = (Comparable) f1.getAttribute(propertyName);
Comparable o2 = (Comparable) f2.getAttribute(propertyName);
if (o1 == null) {
if (o2 == null) {
return 0;
} else {
return -1;
}
} else if (o2 == null) {
return 1;
} else {
return o1.compareTo(o2);
}
}
}
| apache-2.0 |
ChinaQuants/Strata | modules/pricer/src/test/java/com/opengamma/strata/pricer/curve/CalibrationZeroRateUsdOisIrsEurFxXCcyIrsTest.java | 27008 | /**
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.pricer.curve;
import static com.opengamma.strata.basics.currency.Currency.EUR;
import static com.opengamma.strata.basics.currency.Currency.USD;
import static com.opengamma.strata.basics.date.DayCounts.ACT_365F;
import static com.opengamma.strata.basics.index.IborIndices.EUR_EURIBOR_3M;
import static com.opengamma.strata.basics.index.IborIndices.USD_LIBOR_3M;
import static com.opengamma.strata.basics.index.OvernightIndices.USD_FED_FUND;
import static com.opengamma.strata.product.deposit.type.TermDepositConventions.USD_SHORT_DEPOSIT_T0;
import static com.opengamma.strata.product.deposit.type.TermDepositConventions.USD_SHORT_DEPOSIT_T1;
import static com.opengamma.strata.product.fx.type.FxSwapConventions.EUR_USD;
import static com.opengamma.strata.product.swap.type.FixedIborSwapConventions.EUR_FIXED_1Y_EURIBOR_3M;
import static com.opengamma.strata.product.swap.type.FixedIborSwapConventions.USD_FIXED_6M_LIBOR_3M;
import static com.opengamma.strata.product.swap.type.FixedOvernightSwapConventions.USD_FIXED_1Y_FED_FUND_OIS;
import static com.opengamma.strata.product.swap.type.XCcyIborIborSwapConventions.EUR_EURIBOR_3M_USD_LIBOR_3M;
import static org.testng.Assert.assertEquals;
import java.time.LocalDate;
import java.time.Period;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.opengamma.strata.basics.ReferenceData;
import com.opengamma.strata.basics.StandardId;
import com.opengamma.strata.basics.currency.CurrencyAmount;
import com.opengamma.strata.basics.currency.FxRate;
import com.opengamma.strata.basics.currency.MultiCurrencyAmount;
import com.opengamma.strata.basics.date.DayCount;
import com.opengamma.strata.basics.date.Tenor;
import com.opengamma.strata.data.FxRateId;
import com.opengamma.strata.data.ImmutableMarketData;
import com.opengamma.strata.data.ImmutableMarketDataBuilder;
import com.opengamma.strata.data.MarketDataFxRateProvider;
import com.opengamma.strata.data.MarketDataId;
import com.opengamma.strata.market.ValueType;
import com.opengamma.strata.market.curve.CurveGroupDefinition;
import com.opengamma.strata.market.curve.CurveGroupName;
import com.opengamma.strata.market.curve.CurveName;
import com.opengamma.strata.market.curve.CurveNode;
import com.opengamma.strata.market.curve.InterpolatedNodalCurveDefinition;
import com.opengamma.strata.market.curve.interpolator.CurveExtrapolator;
import com.opengamma.strata.market.curve.interpolator.CurveExtrapolators;
import com.opengamma.strata.market.curve.interpolator.CurveInterpolator;
import com.opengamma.strata.market.curve.interpolator.CurveInterpolators;
import com.opengamma.strata.market.curve.node.FixedIborSwapCurveNode;
import com.opengamma.strata.market.curve.node.FixedOvernightSwapCurveNode;
import com.opengamma.strata.market.curve.node.FraCurveNode;
import com.opengamma.strata.market.curve.node.FxSwapCurveNode;
import com.opengamma.strata.market.curve.node.IborFixingDepositCurveNode;
import com.opengamma.strata.market.curve.node.TermDepositCurveNode;
import com.opengamma.strata.market.curve.node.XCcyIborIborSwapCurveNode;
import com.opengamma.strata.market.observable.QuoteId;
import com.opengamma.strata.market.param.CurrencyParameterSensitivities;
import com.opengamma.strata.market.sensitivity.PointSensitivities;
import com.opengamma.strata.pricer.deposit.DiscountingIborFixingDepositProductPricer;
import com.opengamma.strata.pricer.deposit.DiscountingTermDepositProductPricer;
import com.opengamma.strata.pricer.fra.DiscountingFraTradePricer;
import com.opengamma.strata.pricer.fx.DiscountingFxSwapProductPricer;
import com.opengamma.strata.pricer.rate.ImmutableRatesProvider;
import com.opengamma.strata.pricer.rate.RatesProvider;
import com.opengamma.strata.pricer.sensitivity.MarketQuoteSensitivityCalculator;
import com.opengamma.strata.pricer.swap.DiscountingSwapProductPricer;
import com.opengamma.strata.product.ResolvedTrade;
import com.opengamma.strata.product.common.BuySell;
import com.opengamma.strata.product.deposit.ResolvedIborFixingDepositTrade;
import com.opengamma.strata.product.deposit.ResolvedTermDepositTrade;
import com.opengamma.strata.product.deposit.type.IborFixingDepositTemplate;
import com.opengamma.strata.product.deposit.type.TermDepositTemplate;
import com.opengamma.strata.product.fra.ResolvedFraTrade;
import com.opengamma.strata.product.fra.type.FraTemplate;
import com.opengamma.strata.product.fx.ResolvedFxSwapTrade;
import com.opengamma.strata.product.fx.type.FxSwapTemplate;
import com.opengamma.strata.product.swap.ResolvedSwapTrade;
import com.opengamma.strata.product.swap.type.FixedIborSwapTemplate;
import com.opengamma.strata.product.swap.type.FixedOvernightSwapTemplate;
import com.opengamma.strata.product.swap.type.XCcyIborIborSwapTemplate;
/**
* Test for curve calibration in USD and EUR.
* The USD curve is obtained by OIS and the EUR one by FX Swaps from USD.
*/
@Test
public class CalibrationZeroRateUsdOisIrsEurFxXCcyIrsTest {
private static final LocalDate VAL_DATE = LocalDate.of(2015, 11, 2);
private static final CurveInterpolator INTERPOLATOR_LINEAR = CurveInterpolators.LINEAR;
private static final CurveExtrapolator EXTRAPOLATOR_FLAT = CurveExtrapolators.FLAT;
private static final DayCount CURVE_DC = ACT_365F;
// reference data
private static final ReferenceData REF_DATA = ReferenceData.standard();
private static final String SCHEME = "CALIBRATION";
/** Curve names */
private static final String USD_DSCON_STR = "USD-DSCON-OIS";
private static final CurveName USD_DSCON_CURVE_NAME = CurveName.of(USD_DSCON_STR);
private static final String USD_FWD3_NAME = "USD-LIBOR3M-FRAIRS";
private static final CurveName USD_FWD3_CURVE_NAME = CurveName.of(USD_FWD3_NAME);
private static final String EUR_DSC_STR = "EUR-DSC-FXXCCY";
private static final CurveName EUR_DSC_CURVE_NAME = CurveName.of(EUR_DSC_STR);
private static final String EUR_FWD3_NAME = "EUR-EURIBOR3M-FRAIRS";
public static final CurveName EUR_FWD3_CURVE_NAME = CurveName.of(EUR_FWD3_NAME);
/** Data FX **/
private static final double FX_RATE_EUR_USD = 1.10;
private static final String EUR_USD_ID_VALUE = "EUR-USD";
/** Data for USD-DSCON curve */
/* Market values */
private static final double[] USD_DSC_MARKET_QUOTES = new double[] {
0.0016, 0.0022,
0.0013, 0.0016, 0.0020, 0.0026, 0.0033,
0.0039, 0.0053, 0.0066, 0.0090, 0.0111,
0.0128, 0.0143, 0.0156, 0.0167, 0.0175,
0.0183};
private static final int USD_DSC_NB_NODES = USD_DSC_MARKET_QUOTES.length;
private static final String[] USD_DSC_ID_VALUE = new String[] {
"USD-ON", "USD-TN",
"USD-OIS-1M", "USD-OIS-2M", "USD-OIS-3M", "USD-OIS-6M", "USD-OIS-9M",
"USD-OIS-1Y", "USD-OIS-18M", "USD-OIS-2Y", "USD-OIS-3Y", "USD-OIS-4Y",
"USD-OIS-5Y", "USD-OIS-6Y", "USD-OIS-7Y", "USD-OIS-8Y", "USD-OIS-9Y",
"USD-OIS-10Y"};
/* Nodes */
private static final CurveNode[] USD_DSC_NODES = new CurveNode[USD_DSC_NB_NODES];
/* Tenors */
private static final Period[] USD_DSC_OIS_TENORS = new Period[] {
Period.ofMonths(1), Period.ofMonths(2), Period.ofMonths(3), Period.ofMonths(6), Period.ofMonths(9),
Period.ofYears(1), Period.ofMonths(18), Period.ofYears(2), Period.ofYears(3), Period.ofYears(4),
Period.ofYears(5), Period.ofYears(6), Period.ofYears(7), Period.ofYears(8), Period.ofYears(9),
Period.ofYears(10)};
private static final int USD_DSC_NB_OIS_NODES = USD_DSC_OIS_TENORS.length;
static {
USD_DSC_NODES[0] = TermDepositCurveNode.of(
TermDepositTemplate.of(Period.ofDays(1), USD_SHORT_DEPOSIT_T0),
QuoteId.of(StandardId.of(SCHEME, USD_DSC_ID_VALUE[0])));
USD_DSC_NODES[1] = TermDepositCurveNode.of(TermDepositTemplate.of(Period.ofDays(1), USD_SHORT_DEPOSIT_T1),
QuoteId.of(StandardId.of(SCHEME, USD_DSC_ID_VALUE[1])));
for (int i = 0; i < USD_DSC_NB_OIS_NODES; i++) {
USD_DSC_NODES[2 + i] = FixedOvernightSwapCurveNode.of(
FixedOvernightSwapTemplate.of(Period.ZERO, Tenor.of(USD_DSC_OIS_TENORS[i]), USD_FIXED_1Y_FED_FUND_OIS),
QuoteId.of(StandardId.of(SCHEME, USD_DSC_ID_VALUE[2 + i])));
}
}
/** Data for USD-LIBOR3M curve */
/* Market values */
private static final double[] USD_FWD3_MARKET_QUOTES = new double[] {
0.003341,
0.0049, 0.0063,
0.0057, 0.0087, 0.0112, 0.0134, 0.0152,
0.0181, 0.0209};
private static final int USD_FWD3_NB_NODES = USD_FWD3_MARKET_QUOTES.length;
private static final String[] USD_FWD3_ID_VALUE = new String[] {
"USD-Fixing-3M",
"USD-FRA3Mx6M", "USD-FRA6Mx9M",
"USD-IRS3M-1Y", "USD-IRS3M-2Y", "USD-IRS3M-3Y", "USD-IRS3M-4Y", "USD-IRS3M-5Y",
"USD-IRS3M-7Y", "USD-IRS3M-10Y"};
/* Nodes */
private static final CurveNode[] USD_FWD3_NODES = new CurveNode[USD_FWD3_NB_NODES];
/* Tenors */
private static final Period[] USD_FWD3_FRA_TENORS = new Period[] { // Period to start
Period.ofMonths(3), Period.ofMonths(6)};
private static final int USD_FWD3_NB_FRA_NODES = USD_FWD3_FRA_TENORS.length;
private static final Period[] USD_FWD3_IRS_TENORS = new Period[] {
Period.ofYears(1), Period.ofYears(2), Period.ofYears(3), Period.ofYears(4), Period.ofYears(5),
Period.ofYears(7), Period.ofYears(10)};
private static final int USD_FWD3_NB_IRS_NODES = USD_FWD3_IRS_TENORS.length;
static {
USD_FWD3_NODES[0] = IborFixingDepositCurveNode.of(
IborFixingDepositTemplate.of(USD_LIBOR_3M),
QuoteId.of(StandardId.of(SCHEME, USD_FWD3_ID_VALUE[0])));
for (int i = 0; i < USD_FWD3_NB_FRA_NODES; i++) {
USD_FWD3_NODES[i + 1] = FraCurveNode.of(
FraTemplate.of(USD_FWD3_FRA_TENORS[i], USD_LIBOR_3M),
QuoteId.of(StandardId.of(SCHEME, USD_FWD3_ID_VALUE[i + 1])));
}
for (int i = 0; i < USD_FWD3_NB_IRS_NODES; i++) {
USD_FWD3_NODES[i + 1 + USD_FWD3_NB_FRA_NODES] = FixedIborSwapCurveNode.of(
FixedIborSwapTemplate.of(Period.ZERO, Tenor.of(USD_FWD3_IRS_TENORS[i]), USD_FIXED_6M_LIBOR_3M),
QuoteId.of(StandardId.of(SCHEME, USD_FWD3_ID_VALUE[i + 1 + USD_FWD3_NB_FRA_NODES])));
}
}
/** Data for EUR-DSC curve */
/* Market values */
private static final double[] EUR_DSC_MARKET_QUOTES = new double[] {
0.0004, 0.0012, 0.0019, 0.0043, 0.0074,
0.0109, -0.0034, -0.0036, -0.0038, -0.0039,
-0.0040, -0.0039};
private static final int EUR_DSC_NB_NODES = EUR_DSC_MARKET_QUOTES.length;
private static final String[] EUR_DSC_ID_VALUE = new String[] {
"EUR-USD-FX-1M", "EUR-USD-FX-2M", "EUR-USD-FX-3M", "EUR-USD-FX-6M", "EUR-USD-FX-9M",
"EUR-USD-FX-1Y", "EUR-USD-XCCY-2Y", "EUR-USD-XCCY-3Y", "EUR-USD-XCCY-4Y", "EUR-USD-XCCY-5Y",
"EUR-USD-XCCY-7Y", "EUR-USD-XCCY-10Y"};
/* Nodes */
private static final CurveNode[] EUR_DSC_NODES = new CurveNode[EUR_DSC_NB_NODES];
/* Tenors */
private static final Period[] EUR_DSC_FX_TENORS = new Period[] {
Period.ofMonths(1), Period.ofMonths(2), Period.ofMonths(3), Period.ofMonths(6), Period.ofMonths(9),
Period.ofYears(1)};
private static final int EUR_DSC_NB_FX_NODES = EUR_DSC_FX_TENORS.length;
private static final Period[] EUR_DSC_XCCY_TENORS = new Period[] {
Period.ofYears(2), Period.ofYears(3), Period.ofYears(4), Period.ofYears(5), Period.ofYears(7),
Period.ofYears(10)};
private static final int EUR_DSC_NB_XCCY_NODES = EUR_DSC_XCCY_TENORS.length;
static {
for (int i = 0; i < EUR_DSC_NB_FX_NODES; i++) {
EUR_DSC_NODES[i] = FxSwapCurveNode.of(
FxSwapTemplate.of(EUR_DSC_FX_TENORS[i], EUR_USD),
QuoteId.of(StandardId.of(SCHEME, EUR_DSC_ID_VALUE[i])));
}
for (int i = 0; i < EUR_DSC_NB_XCCY_NODES; i++) {
EUR_DSC_NODES[EUR_DSC_NB_FX_NODES + i] = XCcyIborIborSwapCurveNode.of(
XCcyIborIborSwapTemplate.of(
Tenor.of(EUR_DSC_XCCY_TENORS[i]), EUR_EURIBOR_3M_USD_LIBOR_3M),
QuoteId.of(StandardId.of(SCHEME, EUR_DSC_ID_VALUE[EUR_DSC_NB_FX_NODES + i])));
}
}
/** Data for EUR-EURIBOR3M curve */
/* Market values */
private static final double[] EUR_FWD3_MARKET_QUOTES = new double[] {
-0.00066,
-0.0010, -0.0006,
-0.0012, -0.0010, -0.0004, 0.0006, 0.0019,
0.0047, 0.0085};
private static final int EUR_FWD3_NB_NODES = EUR_FWD3_MARKET_QUOTES.length;
private static final String[] EUR_FWD3_ID_VALUE = new String[] {
"EUR-Fixing-3M",
"EUR-FRA3Mx6M", "EUR-FRA6Mx9M",
"EUR-IRS3M-1Y", "EUR-IRS3M-2Y", "EUR-IRS3M-3Y", "EUR-IRS3M-4Y", "EUR-IRS3M-5Y",
"EUR-IRS3M-7Y", "EUR-IRS3M-10Y"};
/* Nodes */
private static final CurveNode[] EUR_FWD3_NODES = new CurveNode[EUR_FWD3_NB_NODES];
/* Tenors */
private static final Period[] EUR_FWD3_FRA_TENORS = new Period[] { // Period to start
Period.ofMonths(3), Period.ofMonths(6)};
private static final int EUR_FWD3_NB_FRA_NODES = EUR_FWD3_FRA_TENORS.length;
private static final Period[] EUR_FWD3_IRS_TENORS = new Period[] {
Period.ofYears(1), Period.ofYears(2), Period.ofYears(3), Period.ofYears(4), Period.ofYears(5),
Period.ofYears(7), Period.ofYears(10)};
private static final int EUR_FWD3_NB_IRS_NODES = EUR_FWD3_IRS_TENORS.length;
static {
EUR_FWD3_NODES[0] = IborFixingDepositCurveNode.of(IborFixingDepositTemplate.of(EUR_EURIBOR_3M),
QuoteId.of(StandardId.of(SCHEME, EUR_FWD3_ID_VALUE[0])));
for (int i = 0; i < EUR_FWD3_NB_FRA_NODES; i++) {
EUR_FWD3_NODES[i + 1] = FraCurveNode.of(FraTemplate.of(EUR_FWD3_FRA_TENORS[i], EUR_EURIBOR_3M),
QuoteId.of(StandardId.of(SCHEME, EUR_FWD3_ID_VALUE[i + 1])));
}
for (int i = 0; i < EUR_FWD3_NB_IRS_NODES; i++) {
EUR_FWD3_NODES[i + 1 + EUR_FWD3_NB_FRA_NODES] = FixedIborSwapCurveNode.of(
FixedIborSwapTemplate.of(Period.ZERO, Tenor.of(EUR_FWD3_IRS_TENORS[i]), EUR_FIXED_1Y_EURIBOR_3M),
QuoteId.of(StandardId.of(SCHEME, EUR_FWD3_ID_VALUE[i + 1 + EUR_FWD3_NB_FRA_NODES])));
}
}
/** All quotes for the curve calibration */
private static final ImmutableMarketData ALL_QUOTES;
static {
ImmutableMarketDataBuilder builder = ImmutableMarketData.builder(VAL_DATE);
for (int i = 0; i < USD_DSC_NB_NODES; i++) {
builder.addValue(QuoteId.of(StandardId.of(SCHEME, USD_DSC_ID_VALUE[i])), USD_DSC_MARKET_QUOTES[i]);
}
for (int i = 0; i < USD_FWD3_NB_NODES; i++) {
builder.addValue(QuoteId.of(StandardId.of(SCHEME, USD_FWD3_ID_VALUE[i])), USD_FWD3_MARKET_QUOTES[i]);
}
for (int i = 0; i < EUR_DSC_NB_NODES; i++) {
builder.addValue(QuoteId.of(StandardId.of(SCHEME, EUR_DSC_ID_VALUE[i])), EUR_DSC_MARKET_QUOTES[i]);
}
for (int i = 0; i < EUR_FWD3_NB_NODES; i++) {
builder.addValue(QuoteId.of(StandardId.of(SCHEME, EUR_FWD3_ID_VALUE[i])), EUR_FWD3_MARKET_QUOTES[i]);
}
builder.addValue(QuoteId.of(StandardId.of(SCHEME, EUR_USD_ID_VALUE)), FX_RATE_EUR_USD);
builder.addValue(FxRateId.of(EUR, USD), FxRate.of(EUR, USD, FX_RATE_EUR_USD));
ALL_QUOTES = builder.build();
}
private static final DiscountingIborFixingDepositProductPricer FIXING_PRICER =
DiscountingIborFixingDepositProductPricer.DEFAULT;
private static final DiscountingFraTradePricer FRA_PRICER =
DiscountingFraTradePricer.DEFAULT;
private static final DiscountingSwapProductPricer SWAP_PRICER =
DiscountingSwapProductPricer.DEFAULT;
private static final DiscountingTermDepositProductPricer DEPO_PRICER =
DiscountingTermDepositProductPricer.DEFAULT;
private static final DiscountingFxSwapProductPricer FX_PRICER =
DiscountingFxSwapProductPricer.DEFAULT;
private static final MarketQuoteSensitivityCalculator MQC = MarketQuoteSensitivityCalculator.DEFAULT;
private static final CurveCalibrator CALIBRATOR = CurveCalibrator.of(1e-9, 1e-9, 100);
// Constants
private static final double TOLERANCE_PV = 1.0E-6;
private static final double TOLERANCE_PV_DELTA = 1.0E+3;
private static final CurveGroupName CURVE_GROUP_NAME = CurveGroupName.of("USD-DSCON-EUR-DSC");
private static final InterpolatedNodalCurveDefinition USD_DSC_CURVE_DEFN =
InterpolatedNodalCurveDefinition.builder()
.name(USD_DSCON_CURVE_NAME)
.xValueType(ValueType.YEAR_FRACTION)
.yValueType(ValueType.ZERO_RATE)
.dayCount(CURVE_DC)
.interpolator(INTERPOLATOR_LINEAR)
.extrapolatorLeft(EXTRAPOLATOR_FLAT)
.extrapolatorRight(EXTRAPOLATOR_FLAT)
.nodes(USD_DSC_NODES).build();
private static final InterpolatedNodalCurveDefinition USD_FWD3_CURVE_DEFN =
InterpolatedNodalCurveDefinition.builder()
.name(USD_FWD3_CURVE_NAME)
.xValueType(ValueType.YEAR_FRACTION)
.yValueType(ValueType.ZERO_RATE)
.dayCount(CURVE_DC)
.interpolator(INTERPOLATOR_LINEAR)
.extrapolatorLeft(EXTRAPOLATOR_FLAT)
.extrapolatorRight(EXTRAPOLATOR_FLAT)
.nodes(USD_FWD3_NODES).build();
private static final InterpolatedNodalCurveDefinition EUR_DSC_CURVE_DEFN =
InterpolatedNodalCurveDefinition.builder()
.name(EUR_DSC_CURVE_NAME)
.xValueType(ValueType.YEAR_FRACTION)
.yValueType(ValueType.ZERO_RATE)
.dayCount(CURVE_DC)
.interpolator(INTERPOLATOR_LINEAR)
.extrapolatorLeft(EXTRAPOLATOR_FLAT)
.extrapolatorRight(EXTRAPOLATOR_FLAT)
.nodes(EUR_DSC_NODES).build();
private static final InterpolatedNodalCurveDefinition EUR_FWD3_CURVE_DEFN =
InterpolatedNodalCurveDefinition.builder()
.name(EUR_FWD3_CURVE_NAME)
.xValueType(ValueType.YEAR_FRACTION)
.yValueType(ValueType.ZERO_RATE)
.dayCount(CURVE_DC)
.interpolator(INTERPOLATOR_LINEAR)
.extrapolatorLeft(EXTRAPOLATOR_FLAT)
.extrapolatorRight(EXTRAPOLATOR_FLAT)
.nodes(EUR_FWD3_NODES).build();
private static final CurveGroupDefinition CURVE_GROUP_CONFIG =
CurveGroupDefinition.builder()
.name(CURVE_GROUP_NAME)
.addCurve(USD_DSC_CURVE_DEFN, USD, USD_FED_FUND)
.addForwardCurve(USD_FWD3_CURVE_DEFN, USD_LIBOR_3M)
.addDiscountCurve(EUR_DSC_CURVE_DEFN, EUR)
.addForwardCurve(EUR_FWD3_CURVE_DEFN, EUR_EURIBOR_3M).build();
private static final CurveGroupDefinition GROUP_1 =
CurveGroupDefinition.builder()
.name(CurveGroupName.of("USD-DSCON"))
.addCurve(USD_DSC_CURVE_DEFN, USD, USD_FED_FUND)
.build();
private static final CurveGroupDefinition GROUP_2 =
CurveGroupDefinition.builder()
.name(CurveGroupName.of("USD-LIBOR3M"))
.addForwardCurve(USD_FWD3_CURVE_DEFN, USD_LIBOR_3M)
.build();
private static final CurveGroupDefinition GROUP_3 =
CurveGroupDefinition.builder()
.name(CurveGroupName.of("EUR-DSC-EURIBOR3M"))
.addDiscountCurve(EUR_DSC_CURVE_DEFN, EUR)
.addForwardCurve(EUR_FWD3_CURVE_DEFN, EUR_EURIBOR_3M).build();
private static final ImmutableRatesProvider KNOWN_DATA = ImmutableRatesProvider.builder(VAL_DATE)
.fxRateProvider(MarketDataFxRateProvider.of(ALL_QUOTES))
.build();
//-------------------------------------------------------------------------
public void calibration_present_value_oneGroup() {
RatesProvider result = CALIBRATOR.calibrate(CURVE_GROUP_CONFIG, ALL_QUOTES, REF_DATA);
assertPresentValue(result);
}
public void calibration_present_value_threeGroups() {
RatesProvider result =
CALIBRATOR.calibrate(ImmutableList.of(GROUP_1, GROUP_2, GROUP_3), KNOWN_DATA, ALL_QUOTES, REF_DATA);
assertPresentValue(result);
}
private void assertPresentValue(RatesProvider result) {
// Test PV USD;
List<ResolvedTrade> usdTrades = new ArrayList<>();
for (CurveNode USD_DSC_NODE : USD_DSC_NODES) {
usdTrades.add(USD_DSC_NODE.resolvedTrade(1d, ALL_QUOTES, REF_DATA));
}
// Depo
for (int i = 0; i < 2; i++) {
CurrencyAmount pvDep = DEPO_PRICER.presentValue(
((ResolvedTermDepositTrade) usdTrades.get(i)).getProduct(), result);
assertEquals(pvDep.getAmount(), 0.0, TOLERANCE_PV);
}
// OIS
for (int i = 0; i < USD_DSC_NB_OIS_NODES; i++) {
MultiCurrencyAmount pvOis = SWAP_PRICER.presentValue(
((ResolvedSwapTrade) usdTrades.get(2 + i)).getProduct(), result);
assertEquals(pvOis.getAmount(USD).getAmount(), 0.0, TOLERANCE_PV);
}
// Test PV USD Fwd3
List<ResolvedTrade> fwd3Trades = new ArrayList<>();
for (int i = 0; i < USD_FWD3_NB_NODES; i++) {
fwd3Trades.add(USD_FWD3_NODES[i].resolvedTrade(1d, ALL_QUOTES, REF_DATA));
}
// Fixing
CurrencyAmount pvFixing = FIXING_PRICER.presentValue(
((ResolvedIborFixingDepositTrade) fwd3Trades.get(0)).getProduct(), result);
assertEquals(pvFixing.getAmount(), 0.0, TOLERANCE_PV);
// FRA
for (int i = 0; i < USD_FWD3_NB_FRA_NODES; i++) {
CurrencyAmount pvFra = FRA_PRICER.presentValue(
((ResolvedFraTrade) fwd3Trades.get(i + 1)), result);
assertEquals(pvFra.getAmount(), 0.0, TOLERANCE_PV);
}
// IRS
for (int i = 0; i < USD_FWD3_NB_IRS_NODES; i++) {
MultiCurrencyAmount pvIrs = SWAP_PRICER.presentValue(
((ResolvedSwapTrade) fwd3Trades.get(i + 1 + USD_FWD3_NB_FRA_NODES)).getProduct(), result);
assertEquals(pvIrs.getAmount(USD).getAmount(), 0.0, TOLERANCE_PV);
}
// Test DSC EUR;
List<ResolvedTrade> eurTrades = new ArrayList<>();
for (CurveNode EUR_DSC_NODE : EUR_DSC_NODES) {
eurTrades.add(EUR_DSC_NODE.resolvedTrade(1d, ALL_QUOTES, REF_DATA));
}
// FX
for (int i = 0; i < EUR_DSC_NB_FX_NODES; i++) {
MultiCurrencyAmount pvFx = FX_PRICER.presentValue(
((ResolvedFxSwapTrade) eurTrades.get(i)).getProduct(), result);
assertEquals(pvFx.convertedTo(USD, result).getAmount(), 0.0, TOLERANCE_PV);
}
// XCCY
for (int i = 0; i < EUR_DSC_NB_XCCY_NODES; i++) {
MultiCurrencyAmount pvFx = SWAP_PRICER.presentValue(
((ResolvedSwapTrade) eurTrades.get(EUR_DSC_NB_FX_NODES + i)).getProduct(), result);
assertEquals(pvFx.convertedTo(USD, result).getAmount(), 0.0, TOLERANCE_PV);
}
// Test PV EUR Fwd3
List<ResolvedTrade> eurFwd3Trades = new ArrayList<>();
for (int i = 0; i < EUR_FWD3_NB_NODES; i++) {
eurFwd3Trades.add(EUR_FWD3_NODES[i].resolvedTrade(1d, ALL_QUOTES, REF_DATA));
}
// Fixing
CurrencyAmount eurPvFixing = FIXING_PRICER.presentValue(
((ResolvedIborFixingDepositTrade) eurFwd3Trades.get(0)).getProduct(), result);
assertEquals(eurPvFixing.getAmount(), 0.0, TOLERANCE_PV);
// FRA
for (int i = 0; i < EUR_FWD3_NB_FRA_NODES; i++) {
CurrencyAmount pvFra = FRA_PRICER.presentValue(
((ResolvedFraTrade) eurFwd3Trades.get(i + 1)), result);
assertEquals(pvFra.getAmount(), 0.0, TOLERANCE_PV);
}
// IRS
for (int i = 0; i < EUR_FWD3_NB_IRS_NODES; i++) {
MultiCurrencyAmount pvIrs = SWAP_PRICER.presentValue(
((ResolvedSwapTrade) eurFwd3Trades.get(i + 1 + EUR_FWD3_NB_FRA_NODES)).getProduct(), result);
assertEquals(pvIrs.getAmount(EUR).getAmount(), 0.0, TOLERANCE_PV);
}
}
public void calibration_market_quote_sensitivity_one_group() {
double shift = 1.0E-6;
Function<ImmutableMarketData, RatesProvider> f =
marketData -> CALIBRATOR.calibrate(CURVE_GROUP_CONFIG, marketData, REF_DATA);
calibration_market_quote_sensitivity_check(f, shift);
}
private void calibration_market_quote_sensitivity_check(
Function<ImmutableMarketData, RatesProvider> calibrator,
double shift) {
double notional = 100_000_000.0;
double fx = 1.1111;
double fxPts = 0.0012;
ResolvedFxSwapTrade trade = EUR_USD
.createTrade(VAL_DATE, Period.ofWeeks(6), Period.ofMonths(5), BuySell.BUY, notional, fx, fxPts, REF_DATA)
.resolve(REF_DATA);
RatesProvider result = CALIBRATOR.calibrate(CURVE_GROUP_CONFIG, ALL_QUOTES, REF_DATA);
PointSensitivities pts = FX_PRICER.presentValueSensitivity(trade.getProduct(), result);
CurrencyParameterSensitivities ps = result.parameterSensitivity(pts);
CurrencyParameterSensitivities mqs = MQC.sensitivity(ps, result);
double pvUsd = FX_PRICER.presentValue(trade.getProduct(), result).getAmount(USD).getAmount();
double pvEur = FX_PRICER.presentValue(trade.getProduct(), result).getAmount(EUR).getAmount();
double[] mqsUsd1Computed = mqs.getSensitivity(USD_DSCON_CURVE_NAME, USD).getSensitivity().toArray();
for (int i = 0; i < USD_DSC_NB_NODES; i++) {
Map<MarketDataId<?>, Object> map = new HashMap<>(ALL_QUOTES.getValues());
map.put(QuoteId.of(StandardId.of(SCHEME, USD_DSC_ID_VALUE[i])), USD_DSC_MARKET_QUOTES[i] + shift);
ImmutableMarketData marketData = ImmutableMarketData.of(VAL_DATE, map);
RatesProvider rpShifted = calibrator.apply(marketData);
double pvS = FX_PRICER.presentValue(trade.getProduct(), rpShifted).getAmount(USD).getAmount();
assertEquals(mqsUsd1Computed[i], (pvS - pvUsd) / shift, TOLERANCE_PV_DELTA);
}
double[] mqsUsd2Computed = mqs.getSensitivity(USD_DSCON_CURVE_NAME, EUR).getSensitivity().toArray();
for (int i = 0; i < USD_DSC_NB_NODES; i++) {
Map<MarketDataId<?>, Object> map = new HashMap<>(ALL_QUOTES.getValues());
map.put(QuoteId.of(StandardId.of(SCHEME, USD_DSC_ID_VALUE[i])), USD_DSC_MARKET_QUOTES[i] + shift);
ImmutableMarketData marketData = ImmutableMarketData.of(VAL_DATE, map);
RatesProvider rpShifted = calibrator.apply(marketData);
double pvS = FX_PRICER.presentValue(trade.getProduct(), rpShifted).getAmount(EUR).getAmount();
assertEquals(mqsUsd2Computed[i], (pvS - pvEur) / shift, TOLERANCE_PV_DELTA);
}
double[] mqsEur1Computed = mqs.getSensitivity(EUR_DSC_CURVE_NAME, USD).getSensitivity().toArray();
for (int i = 0; i < EUR_DSC_NB_NODES; i++) {
assertEquals(mqsEur1Computed[i], 0.0, TOLERANCE_PV_DELTA);
}
double[] mqsEur2Computed = mqs.getSensitivity(EUR_DSC_CURVE_NAME, EUR).getSensitivity().toArray();
for (int i = 0; i < EUR_DSC_NB_NODES; i++) {
Map<MarketDataId<?>, Object> map = new HashMap<>(ALL_QUOTES.getValues());
map.put(QuoteId.of(StandardId.of(SCHEME, EUR_DSC_ID_VALUE[i])), EUR_DSC_MARKET_QUOTES[i] + shift);
ImmutableMarketData marketData = ImmutableMarketData.of(VAL_DATE, map);
RatesProvider rpShifted = calibrator.apply(marketData);
double pvS = FX_PRICER.presentValue(trade.getProduct(), rpShifted).getAmount(EUR).getAmount();
assertEquals(mqsEur2Computed[i], (pvS - pvEur) / shift, TOLERANCE_PV_DELTA, "Node " + i);
}
}
}
| apache-2.0 |
proteus-h2020/proteus-websocket-endpoint | src/main/java/eu/proteus/producer/model/SensorMeasurementMapper.java | 1832 | package eu.proteus.producer.model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SensorMeasurementMapper {
private static final Logger logger = LoggerFactory.getLogger(SensorMeasurementMapper.class);
public static SensorMeasurement map(String rowText) {
String[] columns = rowText.split(",");
columns[0] = fixCoilName(columns[0]); //BUG - Some coilId are " ". Replace it by -1
SensorMeasurement row = null;
switch (columns.length) {
case 5:
row = map2d(columns);
break;
case 4:
row = map1d(columns);
break;
default:
logger.warn("Unkown number of columns: " + columns.length);
return null;
}
logger.debug("Current row: " + row);
return row;
}
private static String fixCoilName(String coilName) {
if (coilName.trim().equals("")) {
coilName = "-1";
}
return coilName;
}
private static SensorMeasurement map1d(String[] columns) {
return new SensorMeasurement1D(
Integer.parseInt(columns[0]),
Double.parseDouble(columns[1]),
parseVarIdentifier(columns[2]),
Double.parseDouble(columns[3])
);
}
private static SensorMeasurement map2d(String[] columns) {
return new SensorMeasurement2D(
Integer.parseInt(columns[0]),
Double.parseDouble(columns[1]),
Double.parseDouble(columns[2]),
parseVarIdentifier(columns[3]),
Double.parseDouble(columns[4])
);
}
private static int parseVarIdentifier(String varName){
return Integer.parseInt(varName.split("C")[1]);
}
}
| apache-2.0 |
Skunnyk/dbpedia-spotlight-model | core/src/main/java/org/dbpedia/spotlight/model/ContextSearcher.java | 1201 | /**
* Copyright 2011 Pablo Mendes, Max Jakob
*
* 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.dbpedia.spotlight.model;
import org.dbpedia.spotlight.exceptions.SearchException;
import org.dbpedia.spotlight.model.vsm.FeatureVector;
import java.util.List;
/**
* TODO Merge with ContextStore
*/
public interface ContextSearcher { //TODO We should have a ResourceSearcher, OccurrenceSearcher and DefinitionSearcher
public List<FeatureVector> get(DBpediaResource resource) throws SearchException;
//TODO this only makes sense for ResourceSearcher
public DBpediaResource getDBpediaResource(int docNo) throws SearchException;
public int getNumberOfEntries();
}
| apache-2.0 |
beav/netty-ant | src/main/java/org/jboss/netty/example/http/snoop/HttpSnoopClientPipelineFactory.java | 2232 | /*
* Copyright 2011 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 org.jboss.netty.example.http.snoop;
import static org.jboss.netty.channel.Channels.*;
import javax.net.ssl.SSLEngine;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.example.securechat.SecureChatSslContextFactory;
import org.jboss.netty.handler.codec.http.HttpClientCodec;
import org.jboss.netty.handler.codec.http.HttpContentDecompressor;
import org.jboss.netty.handler.ssl.SslHandler;
public class HttpSnoopClientPipelineFactory implements ChannelPipelineFactory {
private final boolean ssl;
public HttpSnoopClientPipelineFactory(boolean ssl) {
this.ssl = ssl;
}
public ChannelPipeline getPipeline() throws Exception {
// Create a default pipeline implementation.
ChannelPipeline pipeline = pipeline();
// Enable HTTPS if necessary.
if (ssl) {
SSLEngine engine =
SecureChatSslContextFactory.getClientContext().createSSLEngine();
engine.setUseClientMode(true);
pipeline.addLast("ssl", new SslHandler(engine));
}
pipeline.addLast("codec", new HttpClientCodec());
// Remove the following line if you don't want automatic content decompression.
pipeline.addLast("inflater", new HttpContentDecompressor());
// Uncomment the following line if you don't want to handle HttpChunks.
//pipeline.addLast("aggregator", new HttpChunkAggregator(1048576));
pipeline.addLast("handler", new HttpSnoopClientHandler());
return pipeline;
}
}
| apache-2.0 |
NLPchina/ansj_seg | plugin/ansj_solr4_plugin/src/main/java/org/ansj/solr/AnsjTokenizerFactory.java | 2014 | package org.ansj.solr;
import org.ansj.lucene.util.AnsjTokenizer;
import org.ansj.splitWord.analysis.IndexAnalysis;
import org.ansj.splitWord.analysis.ToAnalysis;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.util.TokenizerFactory;
import org.apache.lucene.util.AttributeFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class AnsjTokenizerFactory extends TokenizerFactory {
public final Logger logger = LoggerFactory.getLogger(getClass());
private boolean pstemming;
private boolean isQuery;
private String stopwordsDir;
public Set<String> filter;
public AnsjTokenizerFactory(Map<String, String> args) {
super(args);
assureMatchVersion();
isQuery = getBoolean(args, "isQuery", true);
pstemming = getBoolean(args, "pstemming", false);
stopwordsDir = get(args, "words");
addStopwords(stopwordsDir);
}
/**
* 添加停用词
*
* @param dir
*/
private void addStopwords(String dir) {
if (dir == null) {
logger.info("no stopwords dir");
return;
}
logger.info("stopwords: {}", dir);
filter = new HashSet<String>();
File file = new File(dir);
try (FileInputStream fis = new FileInputStream(file)) {
InputStreamReader reader = new InputStreamReader(fis, "UTF-8");
BufferedReader br = new BufferedReader(reader);
String word = br.readLine();
while (word != null) {
filter.add(word);
word = br.readLine();
}
} catch (FileNotFoundException e) {
logger.info("No stopword file found");
} catch (IOException e) {
logger.info("stopword file io exception");
}
}
@Override
public Tokenizer create(AttributeFactory factory, Reader input) {
if (isQuery == true) {
return new AnsjTokenizer(new ToAnalysis(input), input, filter, pstemming);
} else {
return new AnsjTokenizer(new IndexAnalysis(input), input, filter, pstemming);
}
}
} | apache-2.0 |
comsysto/mongodb-onlineshop | dataloader/src/main/java/com/comsysto/dataloader/generator/DataGenerator.java | 10485 | package com.comsysto.dataloader.generator;
import com.comsysto.common.util.SeoUtils;
import com.comsysto.dataloader.reader.AddressCsvReader;
import com.comsysto.dataloader.reader.ProductCsvReader;
import com.comsysto.dataloader.reader.SupplierCsvReader;
import com.comsysto.dataloader.reader.UserCsvReader;
import com.comsysto.shop.repository.user.api.UserRepository;
import com.comsysto.shop.repository.user.model.Address;
import com.comsysto.shop.repository.user.model.Role;
import com.comsysto.shop.repository.user.model.User;
import com.comsysto.shop.repository.order.api.OrderIdProvider;
import com.comsysto.shop.repository.order.api.OrderRepository;
import com.comsysto.shop.repository.order.model.DeliveryAddress;
import com.comsysto.shop.repository.order.model.Order;
import com.comsysto.shop.repository.order.model.OrderItem;
import com.comsysto.shop.repository.order.model.Supplier;
import com.comsysto.shop.repository.product.api.ProductRepository;
import com.comsysto.shop.repository.product.model.Product;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.*;
/**
* This dataloader loads a basic data set in the database when the application starts and the
* database is empty
* <p/>
* for the test environment the drop.collections can be set to true and the dataloader will
* always clean the database and so run every time with a fixed set of test data
*
* @author zutherb
*/
@Component("dataGenerator")
@ManagedResource(objectName = "com.comsysto.generator:name=DataGenerator")
public class DataGenerator {
private static Logger logger = LoggerFactory.getLogger(DataGenerator.class);
private List<Supplier> suppliers;
private boolean randomPizzaIds = true;
private int salesPizzaId = 0;
@Value("${generator.drop.collections}")
private boolean dropCollections;
@Value("${generator.generate.orders}")
private int generateOrders;
@Value("${mongo.db}")
private String database;
@Value("${authentication.salt}")
private String authenticationSalt;
@Autowired
@Qualifier("productRepository")
private ProductRepository productRepository;
@Autowired
@Qualifier("productCsvReader")
private ProductCsvReader productCsvReader;
@Autowired
@Qualifier("userRepository")
private UserRepository userRepository;
@Autowired
@Qualifier("userCsvReader")
private UserCsvReader userCsvReader;
@Autowired
@Qualifier("addressCsvReader")
private AddressCsvReader addressCsvReader;
@Autowired
@Qualifier("orderRepository")
private OrderRepository orderRepository;
@Autowired
@Qualifier("supplierCsvReader")
private SupplierCsvReader supplierCsvReader;
@Autowired
@Qualifier("orderIdProvider")
private OrderIdProvider orderIdProvider;
@Autowired
@Qualifier("userPasswordEncoder")
private ShaPasswordEncoder passwordEncoder;
@Autowired
@Qualifier("mongoTemplate")
private MongoTemplate mongoOperations;
@ManagedOperation
@PostConstruct
public void initializeDatabase() throws IOException {
cleanCollections();
createSupplierList();
if(productRepository.findAll().isEmpty()){
createProducts();
createUsers();
createOrders();
}
}
private void createSupplierList() throws IOException {
suppliers = supplierCsvReader.parseCsv();
}
public void cleanCollections() {
if (dropCollections) {
mongoOperations.getDb().dropDatabase();
logger.info("Collections were dropped");
}
}
public void createProducts() throws IOException {
for (Product product : productCsvReader.parseCsv()) {
product.setUrlname(SeoUtils.urlFriendly(product.getName()));
productRepository.save(product);
}
}
public void createUsers() throws IOException {
Iterator<Address> addresses = addressCsvReader.parseCsv().iterator();
for (User user : userCsvReader.parseCsv()) {
user.setAddress(addresses.next());
user.setUsername(user.getFirstname().toLowerCase() + "." + user.getLastname().toLowerCase());
user.setPassword(passwordEncoder.encodePassword("customer123", authenticationSalt));
user.getRoles().add(new Role("customer"));
userRepository.save(user);
}
User user = new User("admin", "Bernd", "Zuther", passwordEncoder.encodePassword("admin123", authenticationSalt),
new Address("Lindwurmstraße", "80337", "München", "97"), Collections.singleton(new Role("admin")));
user.setEmail("bernd.zuther@gmail.com");
userRepository.save(user);
}
public void createOrders() throws IOException {
List<User> users = userRepository.findAll();
List<Product> products = productRepository.findAll();
List<Address> addresses = addressCsvReader.parseCsv();
for (int i = 0; i < generateOrders; i++) {
saveOrder(users, products, addresses);
}
}
@ManagedOperation
public void createOrdersMoreOrders(int orders) throws IOException {
List<User> users = userRepository.findAll();
List<Product> products = productRepository.findAll();
List<Address> addresses = addressCsvReader.parseCsv();
for (int i = 0; i < orders; i++) {
saveOrder(users, products, addresses);
}
}
@Async
private void saveOrder(List<User> users, List<Product> products, List<Address> addresses) {
Order order = createOrder(users, addresses, products);
orderRepository.save(order);
}
public Order createOrder(List<User> users, List<Address> addresses, List<Product> products) {
User randomUser = getRandomUser(users);
Order order = new Order();
order.setOrderId(orderIdProvider.nextVal());
order.setUserId(randomUser.getId());
order.setDeliveryAddress(getRandomDeliveryAddress(getRandomUser(users), addresses));
order.setSupplier(suppliers.get(getRandom(0, suppliers.size() - 1)));
order.setSessionId("dataGenerator");
addOrderItems(randomUser, order.getOrderItems(), products);
order.setOrderDate(getRandomDate());
return order;
}
private void addOrderItems(User randomUser,
List<OrderItem> orderItems, List<Product> products) {
int random = getRandom(1, 6);
for (int i = 0; i < random; i++) {
OrderItem orderItem = new OrderItem(getRandomPizza(randomUser, products));
orderItems.add(orderItem);
}
}
private Product getRandomPizza(User randomUser, List<Product> products) {
int counter = 0;
if (randomPizzaIds) {
int timestamp = (int) (new Date().getTime() / 1000);
int random2 = getRandom(1, 3);
timestamp /= random2;
counter = timestamp % products.size();
Product product = products.get(counter);
if (randomUser.getCategories().contains(product.getCategory())) {
return product;
} else {
for (Product productWithUserCategory : products) {
if (randomUser.getCategories().contains(productWithUserCategory.getCategory())) {
return productWithUserCategory;
}
}
}
} else {
counter = salesPizzaId % products.size();
return products.get(counter);
}
return products.get(counter);
}
private DeliveryAddress getRandomDeliveryAddress(User user, List<Address> addresses) {
Address address = addresses.get(getRandom(0, addresses.size() - 1));
return new DeliveryAddress(user, address);
}
public User getRandomUser(List<User> users) {
return users.get(getRandom(0, users.size() - 1));
}
public int getRandom(int minimum, int maximum) {
Random rn = new Random();
int n = maximum - minimum + 1;
int i = Math.abs(rn.nextInt()) % n;
return minimum + i;
}
public Date getRandomDate() {
try {
int year = new DateTime().getYear();
int randomYear = getRandom(year - 2, year);
int randomMonth = getRandom(1, 12);
int randomDayOfMonth = getRandom(1, 31);
DateTime dateTime = new DateTime(randomYear, randomMonth, randomDayOfMonth, getRandom(0, 23), getRandom(0, 59));
if (dateTime.isBefore(new DateTime().withTimeAtStartOfDay())) {
return dateTime.toDate();
} else {
return getRandomDate();
}
} catch (Exception e) {
return getRandomDate();
}
}
@ManagedAttribute
public boolean isDropCollections() {
return dropCollections;
}
@ManagedAttribute
public boolean isRandomPizzaIds() {
return randomPizzaIds;
}
@ManagedAttribute
public void setRandomPizzaIds(boolean randomPizzaIds) {
this.randomPizzaIds = randomPizzaIds;
}
@ManagedAttribute
public void setDropCollections(boolean dropCollections) {
this.dropCollections = dropCollections;
}
@ManagedAttribute
public int getSalesPizzaId() {
return salesPizzaId;
}
@ManagedAttribute
public void setSalesPizzaId(int salesPizzaId) {
this.salesPizzaId = salesPizzaId;
}
@ManagedAttribute
public int getGenerateOrders() {
return generateOrders;
}
@ManagedAttribute
public void setGenerateOrders(int generateOrders) {
this.generateOrders = generateOrders;
}
}
| apache-2.0 |
asereda-gs/immutables | value-fixture/src/org/immutables/fixture/UseImmutableCollections.java | 2294 | /*
Copyright 2015 Immutables Authors and 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.immutables.fixture;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import java.lang.annotation.RetentionPolicy;
import org.immutables.value.Value;
@Value.Immutable
public interface UseImmutableCollections {
ImmutableList<String> list();
ImmutableSet<Integer> set();
ImmutableSet<RetentionPolicy> enumSet();
@Value.NaturalOrder
ImmutableSortedSet<RetentionPolicy> sortedSet();
ImmutableMultiset<String> multiset();
ImmutableMap<String, Integer> map();
ImmutableMap<RetentionPolicy, Integer> enumMap();
@Value.ReverseOrder
ImmutableSortedMap<RetentionPolicy, Integer> sortedMap();
ImmutableMultimap<String, Integer> multimap();
ImmutableSetMultimap<String, Integer> setMultimap();
ImmutableListMultimap<String, Integer> listMultimap();
default void use() {
ImmutableUseImmutableCollections.builder()
.addList("a", "b")
.addSet(1, 2)
.addEnumSet(RetentionPolicy.CLASS)
.addSortedSet(RetentionPolicy.RUNTIME)
.addMultiset("c", "c")
.putMap("d", 1)
.putEnumMap(RetentionPolicy.RUNTIME, 2)
.putSortedMap(RetentionPolicy.SOURCE, 3)
.putMultimap("e", 2)
.putSetMultimap("f", 5)
.putListMultimap("g", 6)
.build();
}
}
| apache-2.0 |
audit4j/audit4j-core | src/test/java/org/audit4j/core/dto/FieldTest.java | 5072 | package org.audit4j.core.dto;
import org.junit.*;
import static org.junit.Assert.*;
/**
* The class <code>FieldTest</code> contains tests for the class <code>{@link Field}</code>.
*
* @generatedBy CodePro at 2/4/15 9:27 AM
* @author JanithB
* @version $Revision: 1.0 $
*/
public class FieldTest {
/**
* Run the Field() constructor test.
*
* @throws Exception
*
* @generatedBy CodePro at 2/4/15 9:27 AM
*/
@Test
public void testField_1()
throws Exception {
Field result = new Field();
// add additional test code here
assertNotNull(result);
assertEquals(null, result.getName());
assertEquals(null, result.getValue());
assertEquals(null, result.getType());
}
/**
* Run the Field(String,String) constructor test.
*
* @throws Exception
*
* @generatedBy CodePro at 2/4/15 9:27 AM
*/
@Test
public void testField_2()
throws Exception {
String name = "";
String value = "";
Field result = new Field(name, value);
// add additional test code here
assertNotNull(result);
assertEquals("", result.getName());
assertEquals("", result.getValue());
assertEquals("java.lang.String", result.getType());
}
/**
* Run the Field(String,String,String) constructor test.
*
* @throws Exception
*
* @generatedBy CodePro at 2/4/15 9:27 AM
*/
@Test
public void testField_3()
throws Exception {
String name = "";
String value = "";
String type = "";
Field result = new Field(name, value, type);
// add additional test code here
assertNotNull(result);
assertEquals("", result.getName());
assertEquals("", result.getValue());
assertEquals("", result.getType());
}
/**
* Run the String getName() method test.
*
* @throws Exception
*
* @generatedBy CodePro at 2/4/15 9:27 AM
*/
@Test
public void testGetName_1()
throws Exception {
Field fixture = new Field("", "", "");
String result = fixture.getName();
// add additional test code here
assertEquals("", result);
}
/**
* Run the String getType() method test.
*
* @throws Exception
*
* @generatedBy CodePro at 2/4/15 9:27 AM
*/
@Test
public void testGetType_1()
throws Exception {
Field fixture = new Field("", "", "");
String result = fixture.getType();
// add additional test code here
assertEquals("", result);
}
/**
* Run the String getValue() method test.
*
* @throws Exception
*
* @generatedBy CodePro at 2/4/15 9:27 AM
*/
@Test
public void testGetValue_1()
throws Exception {
Field fixture = new Field("", "", "");
String result = fixture.getValue();
// add additional test code here
assertEquals("", result);
}
/**
* Run the void setName(String) method test.
*
* @throws Exception
*
* @generatedBy CodePro at 2/4/15 9:27 AM
*/
@Test
public void testSetName_1()
throws Exception {
Field fixture = new Field("", "", "");
String name = "";
fixture.setName(name);
// add additional test code here
}
/**
* Run the void setType(String) method test.
*
* @throws Exception
*
* @generatedBy CodePro at 2/4/15 9:27 AM
*/
@Test
public void testSetType_1()
throws Exception {
Field fixture = new Field("", "", "");
String type = "";
fixture.setType(type);
// add additional test code here
}
/**
* Run the void setValue(String) method test.
*
* @throws Exception
*
* @generatedBy CodePro at 2/4/15 9:27 AM
*/
@Test
public void testSetValue_1()
throws Exception {
Field fixture = new Field("", "", "");
String value = "";
fixture.setValue(value);
// add additional test code here
}
/**
* Perform pre-test initialization.
*
* @throws Exception
* if the initialization fails for some reason
*
* @generatedBy CodePro at 2/4/15 9:27 AM
*/
@Before
public void setUp()
throws Exception {
// add additional set up code here
}
/**
* Perform post-test clean-up.
*
* @throws Exception
* if the clean-up fails for some reason
*
* @generatedBy CodePro at 2/4/15 9:27 AM
*/
@After
public void tearDown()
throws Exception {
// Add additional tear down code here
}
/**
* Launch the test.
*
* @param args the command line arguments
*
* @generatedBy CodePro at 2/4/15 9:27 AM
*/
public static void main(String[] args) {
new org.junit.runner.JUnitCore().run(FieldTest.class);
}
} | apache-2.0 |
inserpio/neo4j-apoc-procedures | src/test/java/apoc/lock/LockTest.java | 1649 | package apoc.lock;
import apoc.util.TestUtil;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
import org.neo4j.helpers.collection.Iterators;
import org.neo4j.test.TestGraphDatabaseFactory;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
public class LockTest {
private static GraphDatabaseService db;
@BeforeClass
public static void setUp() throws Exception {
db = new TestGraphDatabaseFactory().newImpermanentDatabase();
TestUtil.registerProcedure(db, Lock.class);
}
@AfterClass
public static void tearDown() {
db.shutdown();
}
@Test
public void shouldReadLockBlockAWrite() throws Exception {
Node node;
try (Transaction tx = db.beginTx()) {
node = db.createNode();
tx.success();
}
try (Transaction tx = db.beginTx()) {
final Object n = Iterators.single(db.execute("match (n) CALL apoc.lock.read.nodes([n]) return n").columnAs("n"));
assertEquals(n, node);
final Thread thread = new Thread(() -> {
db.execute("match (n) delete n");
});
thread.start();
thread.join(TimeUnit.SECONDS.toMillis(1));
// the blocked thread didn't do any work, so we still have nodes
long count = Iterators.count(db.execute("match (n) return n").columnAs("n"));
assertEquals(1, count);
tx.success();
}
}
}
| apache-2.0 |
gunnarmorling/beanvalidation-api | src/test/java/javax/validation/FooValidationProvider.java | 3865 | /*
* Bean Validation API
*
* License: Apache License, Version 2.0
* See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
*/
package javax.validation;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import javax.validation.FooValidationProvider.DummyConfiguration;
import javax.validation.spi.BootstrapState;
import javax.validation.spi.ConfigurationState;
import javax.validation.spi.ValidationProvider;
import javax.validation.valueextraction.ValueExtractor;
/**
* @author Hardy Ferentschik
*/
public class FooValidationProvider implements ValidationProvider<DummyConfiguration> {
public static List<SoftReference<FooValidationProvider>> createdValidationProviders = new ArrayList<>();
public FooValidationProvider() {
createdValidationProviders.add( new SoftReference<>( this ) );
}
@Override
public DummyConfiguration createSpecializedConfiguration(BootstrapState state) {
return null;
}
@Override
public DummyConfiguration createGenericConfiguration(BootstrapState state) {
return new DummyConfiguration();
}
@Override
public ValidatorFactory buildValidatorFactory(ConfigurationState configurationState) {
return new DummyValidatorFactory();
}
public static class DummyConfiguration implements Configuration<DummyConfiguration> {
@Override
public DummyConfiguration ignoreXmlConfiguration() {
return null;
}
@Override
public DummyConfiguration messageInterpolator(MessageInterpolator interpolator) {
return null;
}
@Override
public DummyConfiguration traversableResolver(TraversableResolver resolver) {
return null;
}
@Override
public DummyConfiguration constraintValidatorFactory(ConstraintValidatorFactory constraintValidatorFactory) {
return null;
}
@Override
public DummyConfiguration parameterNameProvider(ParameterNameProvider parameterNameProvider) {
return null;
}
@Override
public DummyConfiguration clockProvider(ClockProvider clockProvider) {
return null;
}
@Override
public DummyConfiguration addValueExtractor(ValueExtractor<?> extractor) {
return null;
}
@Override
public DummyConfiguration addMapping(InputStream stream) {
return null;
}
@Override
public DummyConfiguration addProperty(String name, String value) {
return null;
}
@Override
public MessageInterpolator getDefaultMessageInterpolator() {
return null;
}
@Override
public TraversableResolver getDefaultTraversableResolver() {
return null;
}
@Override
public ConstraintValidatorFactory getDefaultConstraintValidatorFactory() {
return null;
}
@Override
public ParameterNameProvider getDefaultParameterNameProvider() {
return null;
}
@Override
public ClockProvider getDefaultClockProvider() {
return null;
}
@Override
public BootstrapConfiguration getBootstrapConfiguration() {
return null;
}
@Override
public ValidatorFactory buildValidatorFactory() {
return new DummyValidatorFactory();
}
}
public static class DummyValidatorFactory implements ValidatorFactory {
@Override
public Validator getValidator() {
return null;
}
@Override
public ValidatorContext usingContext() {
return null;
}
@Override
public MessageInterpolator getMessageInterpolator() {
return null;
}
@Override
public TraversableResolver getTraversableResolver() {
return null;
}
@Override
public ConstraintValidatorFactory getConstraintValidatorFactory() {
return null;
}
@Override
public ParameterNameProvider getParameterNameProvider() {
return null;
}
@Override
public ClockProvider getClockProvider() {
return null;
}
@Override
public <T> T unwrap(Class<T> type) {
return null;
}
@Override
public void close() {
}
}
}
| apache-2.0 |
darionyaphet/flink | flink-formats/flink-avro/src/main/java/org/apache/flink/formats/avro/AvroRowSerializationSchema.java | 12684 | /*
* 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.formats.avro;
import org.apache.flink.api.common.serialization.SerializationSchema;
import org.apache.flink.formats.avro.typeutils.AvroSchemaConverter;
import org.apache.flink.types.Row;
import org.apache.flink.util.Preconditions;
import org.apache.avro.LogicalType;
import org.apache.avro.LogicalTypes;
import org.apache.avro.Schema;
import org.apache.avro.SchemaParseException;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.generic.IndexedRecord;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.io.Encoder;
import org.apache.avro.io.EncoderFactory;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.specific.SpecificDatumWriter;
import org.apache.avro.specific.SpecificRecord;
import org.apache.avro.util.Utf8;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TimeZone;
/**
* Serialization schema that serializes {@link Row} into Avro bytes.
*
* <p>Serializes objects that are represented in (nested) Flink rows. It support types that
* are compatible with Flink's Table & SQL API.
*
* <p>Note: Changes in this class need to be kept in sync with the corresponding runtime
* class {@link AvroRowDeserializationSchema} and schema converter {@link AvroSchemaConverter}.
*/
public class AvroRowSerializationSchema implements SerializationSchema<Row> {
/**
* Used for time conversions from SQL types.
*/
private static final TimeZone LOCAL_TZ = TimeZone.getDefault();
/**
* Avro record class for serialization. Might be null if record class is not available.
*/
private Class<? extends SpecificRecord> recordClazz;
/**
* Schema string for deserialization.
*/
private String schemaString;
/**
* Avro serialization schema.
*/
private transient Schema schema;
/**
* Writer to serialize Avro record into a byte array.
*/
private transient DatumWriter<IndexedRecord> datumWriter;
/**
* Output stream to serialize records into byte array.
*/
private transient ByteArrayOutputStream arrayOutputStream;
/**
* Low-level class for serialization of Avro values.
*/
private transient Encoder encoder;
/**
* Creates an Avro serialization schema for the given specific record class.
*
* @param recordClazz Avro record class used to serialize Flink's row to Avro's record
*/
public AvroRowSerializationSchema(Class<? extends SpecificRecord> recordClazz) {
Preconditions.checkNotNull(recordClazz, "Avro record class must not be null.");
this.recordClazz = recordClazz;
this.schema = SpecificData.get().getSchema(recordClazz);
this.schemaString = schema.toString();
this.datumWriter = new SpecificDatumWriter<>(schema);
this.arrayOutputStream = new ByteArrayOutputStream();
this.encoder = EncoderFactory.get().binaryEncoder(arrayOutputStream, null);
}
/**
* Creates an Avro serialization schema for the given Avro schema string.
*
* @param avroSchemaString Avro schema string used to serialize Flink's row to Avro's record
*/
public AvroRowSerializationSchema(String avroSchemaString) {
Preconditions.checkNotNull(avroSchemaString, "Avro schema must not be null.");
this.recordClazz = null;
this.schemaString = avroSchemaString;
try {
this.schema = new Schema.Parser().parse(avroSchemaString);
} catch (SchemaParseException e) {
throw new IllegalArgumentException("Could not parse Avro schema string.", e);
}
this.datumWriter = new GenericDatumWriter<>(schema);
this.arrayOutputStream = new ByteArrayOutputStream();
this.encoder = EncoderFactory.get().binaryEncoder(arrayOutputStream, null);
}
@Override
public byte[] serialize(Row row) {
try {
// convert to record
final GenericRecord record = convertRowToAvroRecord(schema, row);
arrayOutputStream.reset();
datumWriter.write(record, encoder);
encoder.flush();
return arrayOutputStream.toByteArray();
} catch (Exception e) {
throw new RuntimeException("Failed to serialize row.", e);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final AvroRowSerializationSchema that = (AvroRowSerializationSchema) o;
return Objects.equals(recordClazz, that.recordClazz) && Objects.equals(schemaString, that.schemaString);
}
@Override
public int hashCode() {
return Objects.hash(recordClazz, schemaString);
}
// --------------------------------------------------------------------------------------------
private GenericRecord convertRowToAvroRecord(Schema schema, Row row) {
final List<Schema.Field> fields = schema.getFields();
final int length = fields.size();
final GenericRecord record = new GenericData.Record(schema);
for (int i = 0; i < length; i++) {
final Schema.Field field = fields.get(i);
record.put(i, convertFlinkType(field.schema(), row.getField(i)));
}
return record;
}
private Object convertFlinkType(Schema schema, Object object) {
if (object == null) {
return null;
}
switch (schema.getType()) {
case RECORD:
if (object instanceof Row) {
return convertRowToAvroRecord(schema, (Row) object);
}
throw new IllegalStateException("Row expected but was: " + object.getClass());
case ENUM:
return new GenericData.EnumSymbol(schema, object.toString());
case ARRAY:
final Schema elementSchema = schema.getElementType();
final Object[] array = (Object[]) object;
final GenericData.Array<Object> convertedArray = new GenericData.Array<>(array.length, schema);
for (Object element : array) {
convertedArray.add(convertFlinkType(elementSchema, element));
}
return convertedArray;
case MAP:
final Map<?, ?> map = (Map<?, ?>) object;
final Map<Utf8, Object> convertedMap = new HashMap<>();
for (Map.Entry<?, ?> entry : map.entrySet()) {
convertedMap.put(
new Utf8(entry.getKey().toString()),
convertFlinkType(schema.getValueType(), entry.getValue()));
}
return convertedMap;
case UNION:
final List<Schema> types = schema.getTypes();
final int size = types.size();
final Schema actualSchema;
if (size == 2 && types.get(0).getType() == Schema.Type.NULL) {
actualSchema = types.get(1);
} else if (size == 2 && types.get(1).getType() == Schema.Type.NULL) {
actualSchema = types.get(0);
} else if (size == 1) {
actualSchema = types.get(0);
} else {
// generic type
return object;
}
return convertFlinkType(actualSchema, object);
case FIXED:
// check for logical type
if (object instanceof BigDecimal) {
return new GenericData.Fixed(
schema,
convertFromDecimal(schema, (BigDecimal) object));
}
return new GenericData.Fixed(schema, (byte[]) object);
case STRING:
return new Utf8(object.toString());
case BYTES:
// check for logical type
if (object instanceof BigDecimal) {
return ByteBuffer.wrap(convertFromDecimal(schema, (BigDecimal) object));
}
return ByteBuffer.wrap((byte[]) object);
case INT:
// check for logical types
if (object instanceof Date) {
return convertFromDate(schema, (Date) object);
} else if (object instanceof LocalDate) {
return convertFromDate(schema, Date.valueOf((LocalDate) object));
} else if (object instanceof Time) {
return convertFromTimeMillis(schema, (Time) object);
} else if (object instanceof LocalTime) {
return convertFromTimeMillis(schema, Time.valueOf((LocalTime) object));
}
return object;
case LONG:
// check for logical type
if (object instanceof Timestamp) {
return convertFromTimestamp(schema, (Timestamp) object);
} else if (object instanceof LocalDateTime) {
return convertFromTimestamp(schema, Timestamp.valueOf((LocalDateTime) object));
} else if (object instanceof Time) {
return convertFromTimeMicros(schema, (Time) object);
}
return object;
case FLOAT:
case DOUBLE:
case BOOLEAN:
return object;
}
throw new RuntimeException("Unsupported Avro type:" + schema);
}
private byte[] convertFromDecimal(Schema schema, BigDecimal decimal) {
final LogicalType logicalType = schema.getLogicalType();
if (logicalType instanceof LogicalTypes.Decimal) {
final LogicalTypes.Decimal decimalType = (LogicalTypes.Decimal) logicalType;
// rescale to target type
final BigDecimal rescaled = decimal.setScale(decimalType.getScale(), BigDecimal.ROUND_UNNECESSARY);
// byte array must contain the two's-complement representation of the
// unscaled integer value in big-endian byte order
return decimal.unscaledValue().toByteArray();
} else {
throw new RuntimeException("Unsupported decimal type.");
}
}
private int convertFromDate(Schema schema, Date date) {
final LogicalType logicalType = schema.getLogicalType();
if (logicalType == LogicalTypes.date()) {
// adopted from Apache Calcite
final long converted = toEpochMillis(date);
return (int) (converted / 86400000L);
} else {
throw new RuntimeException("Unsupported date type.");
}
}
private int convertFromTimeMillis(Schema schema, Time date) {
final LogicalType logicalType = schema.getLogicalType();
if (logicalType == LogicalTypes.timeMillis()) {
// adopted from Apache Calcite
final long converted = toEpochMillis(date);
return (int) (converted % 86400000L);
} else {
throw new RuntimeException("Unsupported time type.");
}
}
private long convertFromTimeMicros(Schema schema, Time date) {
final LogicalType logicalType = schema.getLogicalType();
if (logicalType == LogicalTypes.timeMicros()) {
// adopted from Apache Calcite
final long converted = toEpochMillis(date);
return (converted % 86400000L) * 1000L;
} else {
throw new RuntimeException("Unsupported time type.");
}
}
private long convertFromTimestamp(Schema schema, Timestamp date) {
final LogicalType logicalType = schema.getLogicalType();
if (logicalType == LogicalTypes.timestampMillis()) {
// adopted from Apache Calcite
final long time = date.getTime();
return time + (long) LOCAL_TZ.getOffset(time);
} else if (logicalType == LogicalTypes.timestampMicros()) {
long millis = date.getTime();
long micros = millis * 1000 + (date.getNanos() % 1_000_000 / 1000);
long offset = LOCAL_TZ.getOffset(millis) * 1000L;
return micros + offset;
} else {
throw new RuntimeException("Unsupported timestamp type.");
}
}
private long toEpochMillis(java.util.Date date) {
final long time = date.getTime();
return time + (long) LOCAL_TZ.getOffset(time);
}
private void writeObject(ObjectOutputStream outputStream) throws IOException {
outputStream.writeObject(recordClazz);
outputStream.writeObject(schemaString); // support for null
}
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream inputStream) throws ClassNotFoundException, IOException {
recordClazz = (Class<? extends SpecificRecord>) inputStream.readObject();
schemaString = (String) inputStream.readObject();
if (recordClazz != null) {
schema = SpecificData.get().getSchema(recordClazz);
} else {
schema = new Schema.Parser().parse(schemaString);
}
datumWriter = new SpecificDatumWriter<>(schema);
arrayOutputStream = new ByteArrayOutputStream();
encoder = EncoderFactory.get().binaryEncoder(arrayOutputStream, null);
}
}
| apache-2.0 |
BurntGameProductions/Path-to-Mani | main/src/com/tnf/ptm/common/GameOptions.java | 31731 | /*
* Copyright 2017 TheNightForum
*
* 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.tnf.ptm.common;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.Input;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;
public class GameOptions {
public static final String FILE_NAME = "settings.ini";
public static final int CONTROL_KB = 0;
public static final int CONTROL_MIXED = 1;
public static final int CONTROL_MOUSE = 2;
public static final int CONTROL_CONTROLLER = 3;
public static final String DEFAULT_MOUSE_UP = "W";
public static final String DEFAULT_MOUSE_DOWN = "S";
public static final String DEFAULT_UP = "Up";
public static final String DEFAULT_DOWN = "Down";
public static final String DEFAULT_LEFT = "Left";
public static final String DEFAULT_RIGHT = "Right";
public static final String DEFAULT_SHOOT = "Space";
public static final String DEFAULT_SHOOT2 = "L-Ctrl";
public static final String DEFAULT_ABILITY = "L-Shift";
public static final String DEFAULT_ESCAPE = "Escape";
public static final String DEFAULT_MAP = "Tab";
public static final String DEFAULT_INVENTORY = "I";
public static final String DEFAULT_TALK = "T";
public static final String DEFAULT_PAUSE = "P";
public static final String DEFAULT_DROP = "D";
public static final String DEFAULT_SELL = "S";
public static final String DEFAULT_BUY = "B";
public static final String DEFAULT_CHANGE_SHIP = "C";
public static final String DEFAULT_HIRE_SHIP = "H";
public static final int DEFAULT_AXIS_SHOOT = 1;
public static final int DEFAULT_AXIS_SHOOT2 = 0;
public static final int DEFAULT_AXIS_ABILITY = -1;
public static final int DEFAULT_AXIS_LEFT_RIGHT = 2;
public static final boolean DEFAULT_AXIS_LEFT_RIGHT_INVERTED_ = false;
public static final int DEFAULT_AXIS_UP_DOWN = 5;
public static final boolean DEFAULT_AXIS_UP_DOWN_INVERTED_ = false;
public static final int DEFAULT_BUTTON_SHOOT = -1;
public static final int DEFAULT_BUTTON_SHOOT2 = -1;
public static final int DEFAULT_BUTTON_ABILITY = 14;
public static final int DEFAULT_BUTTON_UP = -1;
public static final int DEFAULT_BUTTON_DOWN = -1;
public static final int DEFAULT_BUTTON_LEFT = -1;
public static final int DEFAULT_BUTTON_RIGHT = -1;
public int x;
public int y;
public boolean fullscreen;
public int controlType;
public float sfxVolumeMultiplier;
public float musicVolumeMultiplier;
public boolean canSellEquippedItems;
private String keyUpMouseName;
private String keyDownMouseName;
private String keyUpName;
private String keyDownName;
private String keyLeftName;
private String keyRightName;
private String keyShootName;
private String keyShoot2Name;
private String keyAbilityName;
private String keyEscapeName;
private String keyMapName;
private String keyInventoryName;
private String keyTalkName;
private String keyPauseName;
private String keyDropName;
private String keySellMenuName;
private String keyBuyMenuName;
private String keyChangeShipMenuName;
private String keyHireShipMenuName;
private int controllerAxisShoot;
private int controllerAxisShoot2;
private int controllerAxisAbility;
private int controllerAxisLeftRight;
private boolean isControllerAxisLeftRightInverted;
private int controllerAxisUpDown;
private boolean isControllerAxisUpDownInverted;
private int controllerButtonShoot;
private int controllerButtonShoot2;
private int controllerButtonAbility;
private int controllerButtonLeft;
private int controllerButtonRight;
private int controllerButtonUp;
private int controllerButtonDown;
private SortedSet<String> supportedResolutions = new TreeSet<String>();
private Iterator<String> resolutionIterator = null;
public GameOptions(boolean mobile, PtmFileReader reader) {
IniReader r = new IniReader(FILE_NAME, reader, false);
x = r.getInt("x", 800);
y = r.getInt("y", 600);
fullscreen = r.getBoolean("fullscreen", false);
controlType = mobile ? CONTROL_KB : r.getInt("controlType", CONTROL_MIXED);
sfxVolumeMultiplier = r.getFloat("sfxVol", 1);
musicVolumeMultiplier = r.getFloat("musicVol", 1);
keyUpMouseName = r.getString("keyUpMouse", DEFAULT_MOUSE_UP);
keyDownMouseName = r.getString("keyDownMouse", DEFAULT_MOUSE_DOWN);
keyUpName = r.getString("keyUp", DEFAULT_UP);
keyDownName = r.getString("keyDown", DEFAULT_DOWN);
keyLeftName = r.getString("keyLeft", DEFAULT_LEFT);
keyRightName = r.getString("keyRight", DEFAULT_RIGHT);
keyShootName = r.getString("keyShoot", DEFAULT_SHOOT);
keyShoot2Name = r.getString("keyShoot2", DEFAULT_SHOOT2);
keyAbilityName = r.getString("keyAbility", DEFAULT_ABILITY);
keyEscapeName = r.getString("keyEscape", DEFAULT_ESCAPE);
keyMapName = r.getString("keyMap", DEFAULT_MAP);
keyInventoryName = r.getString("keyInventory", DEFAULT_INVENTORY);
keyTalkName = r.getString("keyTalk", DEFAULT_TALK);
keyPauseName = r.getString("keyPause", DEFAULT_PAUSE);
keyDropName = r.getString("keyDrop", DEFAULT_DROP);
keySellMenuName = r.getString("keySellMenu", DEFAULT_SELL);
keyBuyMenuName = r.getString("keyBuyMenu", DEFAULT_BUY);
keyChangeShipMenuName = r.getString("keyChangeShipMenu", DEFAULT_CHANGE_SHIP);
keyHireShipMenuName = r.getString("keyHireShipMenu", DEFAULT_HIRE_SHIP);
controllerAxisShoot = r.getInt("controllerAxisShoot", DEFAULT_AXIS_SHOOT);
controllerAxisShoot2 = r.getInt("controllerAxisShoot2", DEFAULT_AXIS_SHOOT2);
controllerAxisAbility = r.getInt("controllerAxisAbility", DEFAULT_AXIS_ABILITY);
controllerAxisLeftRight = r.getInt("controllerAxisLeftRight", DEFAULT_AXIS_LEFT_RIGHT);
isControllerAxisLeftRightInverted = r.getBoolean("isControllerAxisLeftRightInverted", DEFAULT_AXIS_LEFT_RIGHT_INVERTED_);
controllerAxisUpDown = r.getInt("controllerAxisUpDown", DEFAULT_AXIS_UP_DOWN);
isControllerAxisUpDownInverted = r.getBoolean("isControllerAxisUpDownInverted", DEFAULT_AXIS_UP_DOWN_INVERTED_);
controllerButtonShoot = r.getInt("controllerButtonShoot", DEFAULT_BUTTON_SHOOT);
controllerButtonShoot2 = r.getInt("controllerButtonShoot2", DEFAULT_BUTTON_SHOOT2);
controllerButtonAbility = r.getInt("controllerButtonAbility", DEFAULT_BUTTON_ABILITY);
controllerButtonLeft = r.getInt("controllerButtonLeft", DEFAULT_BUTTON_LEFT);
controllerButtonRight = r.getInt("controllerButtonRight", DEFAULT_BUTTON_RIGHT);
controllerButtonUp = r.getInt("controllerButtonUp", DEFAULT_BUTTON_UP);
controllerButtonDown = r.getInt("controllerButtonDown", DEFAULT_BUTTON_DOWN);
canSellEquippedItems = r.getBoolean("canSellEquippedItems", false);
}
public void advanceReso() {
if (resolutionIterator == null) {
// Initialize resolution choices - get the resolutions that are supported
Graphics.DisplayMode displayModes[] = Gdx.graphics.getDisplayModes();
for (Graphics.DisplayMode d : displayModes) {
supportedResolutions.add(d.width + "x" + d.height);
}
resolutionIterator = supportedResolutions.iterator();
}
String nextResolution;
if (resolutionIterator.hasNext()) {
nextResolution = resolutionIterator.next();
} else {
// Probably somehow possible to get no entries at all which would crash, but then we're doomed anyway
resolutionIterator = supportedResolutions.iterator();
nextResolution = resolutionIterator.next();
}
// TODO: Probably should validate, but then there are still many things we should probably add! :-)
x = Integer.parseInt(nextResolution.substring(0, nextResolution.indexOf("x")));
y = Integer.parseInt(nextResolution.substring(nextResolution.indexOf("x") + 1, nextResolution.length()));
save();
}
public void advanceControlType(boolean mobile) {
if (controlType == CONTROL_KB) {
controlType = mobile ? CONTROL_MOUSE : CONTROL_MIXED;
} else if (controlType == CONTROL_MIXED) {
controlType = CONTROL_CONTROLLER;
// } else if (controlType == CONTROL_MIXED) {
// controlType = CONTROL_MOUSE;
} else {
controlType = CONTROL_KB;
}
save();
}
public void advanceFullscreen() {
fullscreen = !fullscreen;
save();
}
public void advanceSoundVolMul() {
if (sfxVolumeMultiplier == 0.f) {
sfxVolumeMultiplier = 0.25f;
} else if (sfxVolumeMultiplier == 0.25f) {
sfxVolumeMultiplier = 0.5f;
} else if (sfxVolumeMultiplier == 0.5f) {
sfxVolumeMultiplier = 0.75f;
} else if (sfxVolumeMultiplier == 0.75f) {
sfxVolumeMultiplier = 1.f;
} else {
sfxVolumeMultiplier = 0.f;
}
save();
}
public void advanceMusicVolMul() {
if (musicVolumeMultiplier == 0.f) {
musicVolumeMultiplier = 0.25f;
} else if (musicVolumeMultiplier == 0.25f) {
musicVolumeMultiplier = 0.5f;
} else if (musicVolumeMultiplier == 0.5f) {
musicVolumeMultiplier = 0.75f;
} else if (musicVolumeMultiplier == 0.75f) {
musicVolumeMultiplier = 1.f;
} else {
musicVolumeMultiplier = 0.f;
}
save();
}
/**
* Save the configuration settings to file.
*/
public void save() {
IniReader.write(FILE_NAME, "x", x, "y", y, "fullscreen", fullscreen, "controlType", controlType, "sfxVol", sfxVolumeMultiplier, "musicVol", musicVolumeMultiplier,
"canSellEquippedItems", canSellEquippedItems,
"keyUpMouse", getKeyUpMouseName(), "keyDownMouse", getKeyDownMouseName(), "keyUp", getKeyUpName(), "keyDown", keyDownName,
"keyLeft", keyLeftName, "keyRight", keyRightName, "keyShoot", keyShootName, "keyShoot2", getKeyShoot2Name(),
"keyAbility", getKeyAbilityName(), "keyEscape", getKeyEscapeName(), "keyMap", keyMapName, "keyInventory", keyInventoryName,
"keyTalk", getKeyTalkName(), "keyPause", getKeyPauseName(), "keyDrop", getKeyDropName(), "keySellMenu", getKeySellMenuName(),
"keyBuyMenu", getKeyBuyMenuName(), "keyChangeShipMenu", getKeyChangeShipMenuName(), "keyHireShipMenu", getKeyHireShipMenuName(),
"controllerAxisShoot", getControllerAxisShoot(), "controllerAxisShoot2", getControllerAxisShoot2(),
"controllerAxisAbility", getControllerAxisAbility(), "controllerAxisLeftRight", getControllerAxisLeftRight(),
"isControllerAxisLeftRightInverted", isControllerAxisLeftRightInverted(), "controllerAxisUpDown", getControllerAxisUpDown(),
"isControllerAxisUpDownInverted", isControllerAxisUpDownInverted(), "controllerButtonShoot", getControllerButtonShoot(),
"controllerButtonShoot2", getControllerButtonShoot2(), "controllerButtonAbility", getControllerButtonAbility(),
"controllerButtonLeft", getControllerButtonLeft(), "controllerButtonRight", getControllerButtonRight(),
"controllerButtonUp", getControllerButtonUp(), "controllerButtonDown", getControllerButtonDown());
}
/**
* Get the defined key for up when the input controlType is set to CONTROL_MIXED. This includes navigating down in menus.
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyUpMouse() {
return Input.Keys.valueOf(getKeyUpMouseName());
}
/**
* Get the defined key for down when the input controlType is set to CONTROL_MIXED.
* This includes activating the ship's thrusters and navigating up in menus.
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyDownMouse() {
return Input.Keys.valueOf(getKeyDownMouseName());
}
/**
* Get the readable name of the defined key for up when the input controlType is set to CONTROL_MIXED.
* This includes navigating down in menus.
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeyUpMouseName() {
return keyUpMouseName;
}
public void setKeyUpMouseName(String keyUpMouseName) {
this.keyUpMouseName = keyUpMouseName;
}
/**
* Get the readable name of the defined key for down when the input controlType is set to CONTROL_MIXED.
* This includes navigating down in menus.
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeyDownMouseName() {
return keyDownMouseName;
}
public void setKeyDownMouseName(String keyDownMouseName) {
this.keyDownMouseName = keyDownMouseName;
}
/**
* Get the defined key for up. This includes activating the ship's thrusters and navigating up in menus.
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyUp() {
return Input.Keys.valueOf(getKeyUpName());
}
/**
* Get the readable name of the defined key for up.
* This includes activating the ship's thrusters and navigating up in menus.
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeyUpName() {
return keyUpName;
}
public void setKeyUpName(String keyUpName) {
this.keyUpName = keyUpName;
}
/**
* Get the defined key for down. This includes navigating down in menus.
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyDown() {
return Input.Keys.valueOf(keyDownName);
}
/**
* Get the readable name of the defined key for down.
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeyDownName() {
return keyDownName;
}
public void setKeyDownName(String keyDownName) {
this.keyDownName = keyDownName;
}
/**
* Get the defined key for left. This includes rotating the ship left and navigating left in menus.
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyLeft() {
return Input.Keys.valueOf(keyLeftName);
}
/**
* Get the readable name of the defined key for left.
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeyLeftName() {
return keyLeftName;
}
public void setKeyLeftName(String keyLeftName) {
this.keyLeftName = keyLeftName;
}
/**
* Get the defined key for right. This includes rotating the ship right and navigating right in menus.
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyRight() {
return Input.Keys.valueOf(keyRightName);
}
/**
* Get the readable name of the defined key for right.
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeyRightName() {
return keyRightName;
}
public void setKeyRightName(String keyRightName) {
this.keyRightName = keyRightName;
}
/**
* Get the defined key for shooting the primary weapon.
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyShoot() {
return Input.Keys.valueOf(keyShootName);
}
/**
* Get the readable name of the defined key for shooting the primary weapon.
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeyShootName() {
return keyShootName;
}
public void setKeyShootName(String keyShootName) {
this.keyShootName = keyShootName;
}
/**
* Get the defined key for shooting the secondary weapon.
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyShoot2() {
return Input.Keys.valueOf(getKeyShoot2Name());
}
/**
* Get the readable name of the defined key for shooting the secondary weapon.
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeyShoot2Name() {
return keyShoot2Name;
}
public void setKeyShoot2Name(String keyShoot2Name) {
this.keyShoot2Name = keyShoot2Name;
}
/**
* Get the defined key for equipping and unequipping the primary weapon.
* This is currently set to the same key as keyShootName
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyEquip() {
return Input.Keys.valueOf(keyShootName);
}
/**
* Get the defined key for equipping and unequipping the primary weapon.
* This is currently set to the same key as keyShootName
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeyEquipName() {
return getKeyShootName();
}
/**
* Get the defined key for equipping and unequipping the secondary weapon.
* This is currently set to the same key as keyShoot2Name
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyEquip2() {
return Input.Keys.valueOf(getKeyShoot2Name());
}
/**
* Get the defined key for activating the ship's special ability.
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyAbility() {
return Input.Keys.valueOf(getKeyAbilityName());
}
/**
* Get the readable name of the defined key for activating the ship's special ability.
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeyAbilityName() {
return keyAbilityName;
}
public void setKeyAbilityName(String keyAbilityName) {
this.keyAbilityName = keyAbilityName;
}
/**
* Get the defined key for escape. This includes bringing up the in-game menu and exiting in-game menus.
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyEscape() {
return Input.Keys.valueOf(getKeyEscapeName());
}
/**
* Get the readable name of the defined key for escape.
* This includes bringing up the in-game menu and exiting in-game menus.
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeyEscapeName() {
return keyEscapeName;
}
public void setKeyEscapeName(String keyEscapeName) {
this.keyEscapeName = keyEscapeName;
}
/**
* Get the defined key for activating the menu.
* This is currently set to the same key as KeyEscape
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyMenu() {
return getKeyEscape();
}
/**
* Get the defined key for closing the menu.
* This is currently set to the same key as KeyEscape
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyClose() {
return getKeyEscape();
}
/**
* Get the readable name of the defined key for closing the menu
* This is currently set to the same key as KeyEscape
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeyCloseName() {
return getKeyEscapeName();
}
/**
* Get the defined key for buying items.
* This is currently set to the same key as KeyShoot
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyBuyItem() {
return getKeyShoot();
}
/**
* Get the defined key for buying items.
* This is currently set to the same key as KeyShoot
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeyBuyItemName() {
return getKeyShootName();
}
/**
* Get the defined key for selling items.
* This is currently set to the same key as KeyShoot
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeySellItem() {
return getKeyShoot();
}
/**
* Get the defined key for hiring ships.
* This is currently set to the same key as KeyShoot
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyHireShip() {
return getKeyShoot();
}
/**
* Get the defined key for changing ships.
* This is currently set to the same key as KeyShoot
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyChangeShip() {
return getKeyShoot();
}
/**
* Get the defined key for zooming out on the map.
* This is currently set to the same key as KeyUp
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyZoomIn() {
return getKeyUp();
}
/**
* Get the readable name of the defined key for zooming out on the map.
* This is currently set to the same key as KeyUp
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeyZoomInName() {
return getKeyUpName();
}
/**
* Get the defined key for zooming out on the map.
* This is currently set to the same key as KeyDown
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyZoomOut() {
return getKeyDown();
}
/**
* Get the defined key for opening and closing the map.
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyMap() {
return Input.Keys.valueOf(keyMapName);
}
/**
* Get the readable name of the defined key for opening and closing the map.
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeyMapName() {
return keyMapName;
}
public void setKeyMapName(String keyMapName) {
this.keyMapName = keyMapName;
}
/**
* Get the defined key for opening the inventory.
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyInventory() {
return Input.Keys.valueOf(keyInventoryName);
}
/**
* Get the readable name of the defined key for opening the inventory.
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeyInventoryName() {
return keyInventoryName;
}
public void setKeyInventoryName(String keyInventoryName) {
this.keyInventoryName = keyInventoryName;
}
/**
* Get the defined key for opening the talk menu.
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyTalk() {
return Input.Keys.valueOf(getKeyTalkName());
}
/**
* Get the readable name of the defined key for opening the talk menu.
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeyTalkName() {
return keyTalkName;
}
public void setKeyTalkName(String keyTalkName) {
this.keyTalkName = keyTalkName;
}
/**
* Get the defined key for pausing and continuing the game.
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyPause() {
return Input.Keys.valueOf(getKeyPauseName());
}
/**
* Get the readable name of the defined key for pausing and continuing the game.
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeyPauseName() {
return keyPauseName;
}
public void setKeyPauseName(String keyPauseName) {
this.keyPauseName = keyPauseName;
}
/**
* Get the defined key for dropping items.
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyDrop() {
return Input.Keys.valueOf(getKeyDropName());
}
/**
* Get the readable name of the defined key for dropping items.
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeyDropName() {
return keyDropName;
}
public void setKeyDropName(String keyDropName) {
this.keyDropName = keyDropName;
}
/**
* Get the defined key for the sell menu.
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeySellMenu() {
return Input.Keys.valueOf(getKeySellMenuName());
}
/**
* Get the readable name of the defined key for the sell menu.
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeySellMenuName() {
return keySellMenuName;
}
public void setKeySellMenuName(String keySellMenuName) {
this.keySellMenuName = keySellMenuName;
}
/**
* Get the defined key for the buy menu.
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyBuyMenu() {
return Input.Keys.valueOf(getKeyBuyMenuName());
}
/**
* Get the readable name of the defined key for the buy menu.
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeyBuyMenuName() {
return keyBuyMenuName;
}
public void setKeyBuyMenuName(String keyBuyMenuName) {
this.keyBuyMenuName = keyBuyMenuName;
}
/**
* Get the defined key for the change ship menu.
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyChangeShipMenu() {
return Input.Keys.valueOf(getKeyChangeShipMenuName());
}
/**
* Get the readable name of the defined key for the change ship menu.
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeyChangeShipMenuName() {
return keyChangeShipMenuName;
}
public void setKeyChangeShipMenuName(String keyChangeShipMenuName) {
this.keyChangeShipMenuName = keyChangeShipMenuName;
}
/**
* Get the defined key for the hire ship menu.
*
* @return int The keycode as defined in Input.Keys
*/
public int getKeyHireShipMenu() {
return Input.Keys.valueOf(getKeyHireShipMenuName());
}
/**
* Get the readable name of the defined key for the hire ship menu.
*
* @return String The readable name as defined in Input.Keys
*/
public String getKeyHireShipMenuName() {
return keyHireShipMenuName;
}
public void setKeyHireShipMenuName(String keyHireShipMenuName) {
this.keyHireShipMenuName = keyHireShipMenuName;
}
public int getControllerAxisShoot() {
return controllerAxisShoot;
}
public void setControllerAxisShoot(int controllerAxisShoot) {
this.controllerAxisShoot = controllerAxisShoot;
}
public int getControllerAxisShoot2() {
return controllerAxisShoot2;
}
public void setControllerAxisShoot2(int controllerAxisShoot2) {
this.controllerAxisShoot2 = controllerAxisShoot2;
}
public int getControllerAxisAbility() {
return controllerAxisAbility;
}
public void setControllerAxisAbility(int controllerAxisAbility) {
this.controllerAxisAbility = controllerAxisAbility;
}
public int getControllerAxisLeftRight() {
return controllerAxisLeftRight;
}
public void setControllerAxisLeftRight(int controllerAxisLeftRight) {
this.controllerAxisLeftRight = controllerAxisLeftRight;
}
public int getControllerAxisUpDown() {
return controllerAxisUpDown;
}
public void setControllerAxisUpDown(int controllerAxisUpDown) {
this.controllerAxisUpDown = controllerAxisUpDown;
}
public int getControllerButtonShoot() {
return controllerButtonShoot;
}
public void setControllerButtonShoot(int controllerButtonShoot) {
this.controllerButtonShoot = controllerButtonShoot;
}
public int getControllerButtonShoot2() {
return controllerButtonShoot2;
}
public void setControllerButtonShoot2(int controllerButtonShoot2) {
this.controllerButtonShoot2 = controllerButtonShoot2;
}
public int getControllerButtonAbility() {
return controllerButtonAbility;
}
public void setControllerButtonAbility(int controllerButtonAbility) {
this.controllerButtonAbility = controllerButtonAbility;
}
public int getControllerButtonLeft() {
return controllerButtonLeft;
}
public void setControllerButtonLeft(int controllerButtonLeft) {
this.controllerButtonLeft = controllerButtonLeft;
}
public int getControllerButtonRight() {
return controllerButtonRight;
}
public void setControllerButtonRight(int controllerButtonRight) {
this.controllerButtonRight = controllerButtonRight;
}
public int getControllerButtonUp() {
return controllerButtonUp;
}
public void setControllerButtonUp(int controllerButtonUp) {
this.controllerButtonUp = controllerButtonUp;
}
public boolean isControllerAxisLeftRightInverted() {
return isControllerAxisLeftRightInverted;
}
public boolean isControllerAxisUpDownInverted() {
return isControllerAxisUpDownInverted;
}
public void setIsControllerAxisLeftRightInverted(boolean isControllerAxisLeftRightInverted) {
this.isControllerAxisLeftRightInverted = isControllerAxisLeftRightInverted;
}
public void setIsControllerAxisUpDownInverted(boolean isControllerAxisUpDownInverted) {
this.isControllerAxisUpDownInverted = isControllerAxisUpDownInverted;
}
public int getControllerButtonDown() {
return controllerButtonDown;
}
public void setControllerButtonDown(int controllerButtonDown) {
this.controllerButtonDown = controllerButtonDown;
}
public String getSFXVolumeAsText() {
if (sfxVolumeMultiplier == 0.f) {
return "Off";
}
if (sfxVolumeMultiplier == 0.25f) {
return "Low";
}
if (sfxVolumeMultiplier == 0.5f) {
return "Medium";
}
if (sfxVolumeMultiplier == 0.75f) {
return "High";
}
return "Max";
}
public String getMusicVolumeAsText() {
if (musicVolumeMultiplier == 0.f) {
return "Off";
}
if (musicVolumeMultiplier == 0.25f) {
return "Low";
}
if (musicVolumeMultiplier == 0.5f) {
return "Medium";
}
if (musicVolumeMultiplier == 0.75f) {
return "High";
}
return "Max";
}
}
| apache-2.0 |
mdogan/hazelcast | hazelcast/src/main/java/com/hazelcast/internal/longregister/client/task/LongRegisterIncrementAndGetMessageTask.java | 2711 | /*
* Copyright (c) 2008-2020, Hazelcast, 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.hazelcast.internal.longregister.client.task;
import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.internal.longregister.client.codec.LongRegisterIncrementAndGetCodec;
import com.hazelcast.client.impl.protocol.task.AbstractPartitionMessageTask;
import com.hazelcast.internal.longregister.LongRegisterService;
import com.hazelcast.internal.longregister.operations.AddAndGetOperation;
import com.hazelcast.instance.impl.Node;
import com.hazelcast.internal.nio.Connection;
import com.hazelcast.security.permission.ActionConstants;
import com.hazelcast.security.permission.AtomicLongPermission;
import com.hazelcast.spi.impl.operationservice.Operation;
import java.security.Permission;
public class LongRegisterIncrementAndGetMessageTask
extends AbstractPartitionMessageTask<LongRegisterIncrementAndGetCodec.RequestParameters> {
public LongRegisterIncrementAndGetMessageTask(ClientMessage clientMessage, Node node, Connection connection) {
super(clientMessage, node, connection);
}
@Override
protected Operation prepareOperation() {
return new AddAndGetOperation(parameters.name, 1);
}
@Override
protected LongRegisterIncrementAndGetCodec.RequestParameters decodeClientMessage(ClientMessage clientMessage) {
return LongRegisterIncrementAndGetCodec.decodeRequest(clientMessage);
}
@Override
protected ClientMessage encodeResponse(Object response) {
return LongRegisterIncrementAndGetCodec.encodeResponse((Long) response);
}
@Override
public String getServiceName() {
return LongRegisterService.SERVICE_NAME;
}
@Override
public Permission getRequiredPermission() {
return new AtomicLongPermission(parameters.name, ActionConstants.ACTION_MODIFY);
}
@Override
public String getDistributedObjectName() {
return parameters.name;
}
@Override
public String getMethodName() {
return "incrementAndGet";
}
@Override
public Object[] getParameters() {
return null;
}
}
| apache-2.0 |
apache/geronimo-yoko | yoko-core/src/test/java/test/poa/TestLocationForwardServerHolder.java | 1587 | /*
* 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 test.poa;
//
// IDL:TestLocationForwardServer:1.0
//
final public class TestLocationForwardServerHolder implements org.omg.CORBA.portable.Streamable
{
public TestLocationForwardServer value;
public
TestLocationForwardServerHolder()
{
}
public
TestLocationForwardServerHolder(TestLocationForwardServer initial)
{
value = initial;
}
public void
_read(org.omg.CORBA.portable.InputStream in)
{
value = TestLocationForwardServerHelper.read(in);
}
public void
_write(org.omg.CORBA.portable.OutputStream out)
{
TestLocationForwardServerHelper.write(out, value);
}
public org.omg.CORBA.TypeCode
_type()
{
return TestLocationForwardServerHelper.type();
}
}
| apache-2.0 |
flofreud/aws-sdk-java | aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/Op.java | 1569 | /*
* Copyright 2010-2016 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.apigateway.model;
/**
*
*/
public enum Op {
Add("add"),
Remove("remove"),
Replace("replace"),
Move("move"),
Copy("copy"),
Test("test");
private String value;
private Op(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
/**
* Use this in place of valueOf.
*
* @param value
* real value
* @return Op corresponding to the value
*/
public static Op fromValue(String value) {
if (value == null || "".equals(value)) {
throw new IllegalArgumentException("Value cannot be null or empty!");
}
for (Op enumEntry : Op.values()) {
if (enumEntry.toString().equals(value)) {
return enumEntry;
}
}
throw new IllegalArgumentException("Cannot create enum from " + value
+ " value!");
}
}
| apache-2.0 |
hmcl/storm-apache | storm-server/src/test/java/org/apache/storm/LocalStateTest.java | 3130 | /**
* 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.storm;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.storm.generated.GlobalStreamId;
import org.apache.storm.testing.TmpPath;
import org.apache.storm.utils.LocalState;
import org.junit.Assert;
import org.junit.Test;
public class LocalStateTest {
@Test
public void testLocalState() throws Exception {
try (TmpPath dir1_tmp = new TmpPath(); TmpPath dir2_tmp = new TmpPath()) {
GlobalStreamId globalStreamId_a = new GlobalStreamId("a", "a");
GlobalStreamId globalStreamId_b = new GlobalStreamId("b", "b");
GlobalStreamId globalStreamId_c = new GlobalStreamId("c", "c");
GlobalStreamId globalStreamId_d = new GlobalStreamId("d", "d");
LocalState ls1 = new LocalState(dir1_tmp.getPath(), true);
LocalState ls2 = new LocalState(dir2_tmp.getPath(), true);
Assert.assertTrue(ls1.snapshot().isEmpty());
ls1.put("a", globalStreamId_a);
ls1.put("b", globalStreamId_b);
Map<String, GlobalStreamId> expected = new HashMap<>();
expected.put("a", globalStreamId_a);
expected.put("b", globalStreamId_b);
Assert.assertEquals(expected, ls1.snapshot());
Assert.assertEquals(expected, new LocalState(dir1_tmp.getPath(), true).snapshot());
Assert.assertTrue(ls2.snapshot().isEmpty());
ls2.put("b", globalStreamId_a);
ls2.put("b", globalStreamId_b);
ls2.put("b", globalStreamId_c);
ls2.put("b", globalStreamId_d);
Assert.assertEquals(globalStreamId_d, ls2.get("b"));
}
}
@Test
public void testEmptyState() throws IOException {
TmpPath tmp_dir = new TmpPath();
String dir = tmp_dir.getPath();
LocalState ls = new LocalState(dir, true);
GlobalStreamId gs_a = new GlobalStreamId("a", "a");
FileOutputStream data = FileUtils.openOutputStream(new File(dir, "12345"));
FileOutputStream version = FileUtils.openOutputStream(new File(dir, "12345.version"));
Assert.assertNull(ls.get("c"));
ls.put("a", gs_a);
Assert.assertEquals(gs_a, ls.get("a"));
}
}
| apache-2.0 |
godrin/TowerDefense | defend/src/com/cdm/view/enemy/AirMovingEnemy2.java | 853 | package com.cdm.view.enemy;
import com.badlogic.gdx.Gdx;
import com.cdm.view.Position;
import com.cdm.view.elements.units.PlayerUnit;
public abstract class AirMovingEnemy2 extends GroundMovingEnemy {
public AirMovingEnemy2(Position pos) {
super(pos);
}
protected Position createNextStep() {
Position nextStep = getLevel().getNextStepToUnit(
getPosition().tmp().alignedToGrid());
if (!nextStep.valid()) {
if (getLevel().getPlayerUnitAt(getPosition()) != null)
attack(getLevel()
.getPlayerUnitAt(getPosition().alignedToGrid()));
return getLevel().getSomeEnemyEndPosition();
}
return nextStep;
}
public void attack(PlayerUnit punit) {
// if (attackfreq > 2.0f) {
// attackfreq = 0.0f;
if (punit != null) {
Gdx.app.log("mode", "attack");
getLevel().unitDestroyed(punit.getPosition(), punit);
}
}
}
| apache-2.0 |
romy-khetan/hydrator-plugins | spark-plugins/src/test/java/co/cask/hydrator/plugin/spark/test/SpamMessage.java | 2655 | /*
* Copyright © 2016 Cask Data, 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 co.cask.hydrator.plugin.spark.test;
import co.cask.cdap.api.data.format.StructuredRecord;
import co.cask.cdap.api.data.schema.Schema;
import javax.annotation.Nullable;
/**
* Represents a string and whether that is spam or not.
*/
public class SpamMessage {
public static final String SPAM_FEATURES = "100";
public static final String SPAM_PREDICTION_FIELD = "isSpam";
public static final String TEXT_FIELD = "text";
static final Schema SCHEMA = Schema.recordOf(
"simpleMessage",
Schema.Field.of(SPAM_PREDICTION_FIELD, Schema.nullableOf(Schema.of(Schema.Type.DOUBLE))),
Schema.Field.of(TEXT_FIELD, Schema.of(Schema.Type.STRING))
);
private final String text;
@Nullable
private final Double spamPrediction;
public SpamMessage(String text) {
this(text, null);
}
public SpamMessage(String text, @Nullable Double spamPrediction) {
this.text = text;
this.spamPrediction = spamPrediction;
}
public StructuredRecord toStructuredRecord() {
StructuredRecord.Builder builder = StructuredRecord.builder(SCHEMA);
builder.set(TEXT_FIELD, text);
if (spamPrediction != null) {
builder.set(SPAM_PREDICTION_FIELD, spamPrediction);
}
return builder.build();
}
public static SpamMessage fromStructuredRecord(StructuredRecord structuredRecord) {
return new SpamMessage((String) structuredRecord.get(TEXT_FIELD),
(Double) structuredRecord.get(SPAM_PREDICTION_FIELD));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SpamMessage that = (SpamMessage) o;
if (!text.equals(that.text)) {
return false;
}
return !(spamPrediction != null ? !spamPrediction.equals(that.spamPrediction) : that.spamPrediction != null);
}
@Override
public int hashCode() {
int result = text.hashCode();
result = 31 * result + (spamPrediction != null ? spamPrediction.hashCode() : 0);
return result;
}
}
| apache-2.0 |
mdogan/hazelcast | hazelcast/src/main/java/com/hazelcast/internal/management/operation/GetCacheEntryViewEntryProcessor.java | 4734 | /*
* Copyright (c) 2008-2020, Hazelcast, 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.hazelcast.internal.management.operation;
import com.hazelcast.cache.CacheEntryView;
import com.hazelcast.cache.impl.CacheDataSerializerHook;
import com.hazelcast.cache.impl.CacheEntryProcessorEntry;
import com.hazelcast.cache.impl.record.CacheRecord;
import com.hazelcast.core.ReadOnly;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.IdentifiedDataSerializable;
import javax.cache.expiry.ExpiryPolicy;
import javax.cache.processor.EntryProcessor;
import javax.cache.processor.EntryProcessorException;
import javax.cache.processor.MutableEntry;
import java.io.IOException;
public class GetCacheEntryViewEntryProcessor implements EntryProcessor<Object, Object, CacheEntryView>,
IdentifiedDataSerializable, ReadOnly {
@Override
public CacheEntryView process(MutableEntry mutableEntry, Object... objects) throws EntryProcessorException {
CacheEntryProcessorEntry entry = (CacheEntryProcessorEntry) mutableEntry;
if (entry.getRecord() == null) {
return null;
}
return new CacheBrowserEntryView(entry);
}
@Override
public int getFactoryId() {
return CacheDataSerializerHook.F_ID;
}
@Override
public int getClassId() {
return CacheDataSerializerHook.GET_CACHE_ENTRY_VIEW_PROCESSOR;
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
}
@Override
public void readData(ObjectDataInput in) throws IOException {
}
public static class CacheBrowserEntryView implements CacheEntryView<Object, Object>, IdentifiedDataSerializable {
private Object value;
private long expirationTime;
private long creationTime;
private long lastAccessTime;
private long accessHit;
private ExpiryPolicy expiryPolicy;
public CacheBrowserEntryView() {
}
CacheBrowserEntryView(CacheEntryProcessorEntry entry) {
this.value = entry.getValue();
CacheRecord<Object, ExpiryPolicy> record = entry.getRecord();
this.expirationTime = record.getExpirationTime();
this.creationTime = record.getCreationTime();
this.lastAccessTime = record.getLastAccessTime();
this.accessHit = record.getHits();
this.expiryPolicy = record.getExpiryPolicy();
}
@Override
public Object getKey() {
return null;
}
@Override
public Object getValue() {
return value;
}
@Override
public long getExpirationTime() {
return expirationTime;
}
@Override
public long getCreationTime() {
return creationTime;
}
@Override
public long getLastAccessTime() {
return lastAccessTime;
}
@Override
public long getHits() {
return accessHit;
}
@Override
public ExpiryPolicy getExpiryPolicy() {
return expiryPolicy;
}
@Override
public int getFactoryId() {
return CacheDataSerializerHook.F_ID;
}
@Override
public int getClassId() {
return CacheDataSerializerHook.CACHE_BROWSER_ENTRY_VIEW;
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeObject(value);
out.writeLong(expirationTime);
out.writeLong(creationTime);
out.writeLong(lastAccessTime);
out.writeLong(accessHit);
out.writeObject(expiryPolicy);
}
@Override
public void readData(ObjectDataInput in) throws IOException {
value = in.readObject();
expirationTime = in.readLong();
creationTime = in.readLong();
lastAccessTime = in.readLong();
accessHit = in.readLong();
expiryPolicy = in.readObject();
}
}
}
| apache-2.0 |