repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
osmanpub/oracle-samples
jms/durablesubscriptionexample/durableconsumer/src/main/java/javaeetutorial/durableconsumer/DurableConsumer.java
2114
package javaeetutorial.durableconsumer; import java.io.IOException; import java.io.InputStreamReader; import javax.annotation.Resource; import javax.jms.ConnectionFactory; import javax.jms.JMSConsumer; import javax.jms.JMSContext; import javax.jms.JMSRuntimeException; import javax.jms.Topic; public class DurableConsumer { @Resource(lookup = "jms/DurableConnectionFactory") private static ConnectionFactory durableConnectionFactory; @Resource(lookup = "jms/MyTopic") private static Topic topic; public static void main(String[] args) { TextListener listener; JMSConsumer consumer; InputStreamReader inputStreamReader; char answer = '\0'; /* * In a try-with-resources block, create context. * Create durable consumer, if it does not exist already. * Register message listener (TextListener). * Receive text messages from destination. * When all messages have been received, type Q to quit. */ try (JMSContext context = durableConnectionFactory.createContext();) { System.out.println("Creating consumer for topic"); context.stop(); consumer = context.createDurableConsumer(topic, "MakeItLast"); listener = new TextListener(); consumer.setMessageListener(listener); System.out.println("Starting consumer"); context.start(); System.out.println("To end program, enter Q or q, then <return>"); inputStreamReader = new InputStreamReader(System.in); while (!((answer == 'q') || (answer == 'Q'))) { try { answer = (char) inputStreamReader.read(); } catch (IOException e) { System.err.println("I/O exception: " + e.toString()); } } } catch (JMSRuntimeException e) { System.err.println("Exception occurred: " + e.toString()); System.exit(1); } System.exit(0); } }
apache-2.0
xhochy/arrow
java/vector/src/test/java/org/apache/arrow/vector/ipc/BaseFileTest.java
36067
/* * 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.arrow.vector.ipc; import static org.apache.arrow.vector.TestUtils.newVarCharVector; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.util.Arrays; import java.util.List; import org.apache.arrow.memory.ArrowBuf; import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.memory.RootAllocator; import org.apache.arrow.util.Collections2; import org.apache.arrow.vector.BigIntVector; import org.apache.arrow.vector.DateMilliVector; import org.apache.arrow.vector.DecimalVector; import org.apache.arrow.vector.FieldVector; import org.apache.arrow.vector.IntVector; import org.apache.arrow.vector.NullVector; import org.apache.arrow.vector.TimeMilliVector; import org.apache.arrow.vector.UInt1Vector; import org.apache.arrow.vector.UInt2Vector; import org.apache.arrow.vector.UInt4Vector; import org.apache.arrow.vector.UInt8Vector; import org.apache.arrow.vector.VarBinaryVector; import org.apache.arrow.vector.VarCharVector; import org.apache.arrow.vector.VectorSchemaRoot; import org.apache.arrow.vector.complex.ListVector; import org.apache.arrow.vector.complex.MapVector; import org.apache.arrow.vector.complex.StructVector; import org.apache.arrow.vector.complex.impl.ComplexWriterImpl; import org.apache.arrow.vector.complex.impl.UnionListWriter; import org.apache.arrow.vector.complex.impl.UnionMapReader; import org.apache.arrow.vector.complex.impl.UnionMapWriter; import org.apache.arrow.vector.complex.reader.FieldReader; import org.apache.arrow.vector.complex.writer.BaseWriter.ComplexWriter; import org.apache.arrow.vector.complex.writer.BaseWriter.ListWriter; import org.apache.arrow.vector.complex.writer.BaseWriter.StructWriter; import org.apache.arrow.vector.complex.writer.BigIntWriter; import org.apache.arrow.vector.complex.writer.DateMilliWriter; import org.apache.arrow.vector.complex.writer.Float4Writer; import org.apache.arrow.vector.complex.writer.IntWriter; import org.apache.arrow.vector.complex.writer.TimeMilliWriter; import org.apache.arrow.vector.complex.writer.TimeStampMilliTZWriter; import org.apache.arrow.vector.complex.writer.TimeStampMilliWriter; import org.apache.arrow.vector.complex.writer.TimeStampNanoWriter; import org.apache.arrow.vector.complex.writer.UInt1Writer; import org.apache.arrow.vector.complex.writer.UInt2Writer; import org.apache.arrow.vector.complex.writer.UInt4Writer; import org.apache.arrow.vector.complex.writer.UInt8Writer; import org.apache.arrow.vector.dictionary.Dictionary; import org.apache.arrow.vector.dictionary.DictionaryEncoder; import org.apache.arrow.vector.dictionary.DictionaryProvider; import org.apache.arrow.vector.holders.NullableTimeStampMilliHolder; import org.apache.arrow.vector.types.pojo.ArrowType; import org.apache.arrow.vector.types.pojo.DictionaryEncoding; import org.apache.arrow.vector.types.pojo.Field; import org.apache.arrow.vector.types.pojo.FieldType; import org.apache.arrow.vector.util.JsonStringArrayList; import org.apache.arrow.vector.util.Text; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Helps testing the file formats. */ public class BaseFileTest { private static final Logger LOGGER = LoggerFactory.getLogger(BaseFileTest.class); protected static final int COUNT = 10; protected BufferAllocator allocator; @Before public void init() { allocator = new RootAllocator(Integer.MAX_VALUE); } @After public void tearDown() { allocator.close(); } private static short [] uint1Values = new short[]{0, 255, 1, 128, 2}; private static char [] uint2Values = new char[]{0, Character.MAX_VALUE, 1, Short.MAX_VALUE * 2, 2}; private static long [] uint4Values = new long[]{0, Integer.MAX_VALUE + 1L, 1, Integer.MAX_VALUE * 2L, 2}; private static BigInteger[] uint8Values = new BigInteger[]{BigInteger.valueOf(0), BigInteger.valueOf(Long.MAX_VALUE).multiply(BigInteger.valueOf(2)), BigInteger.valueOf(2), BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.valueOf(1)), BigInteger.valueOf(2)}; protected void writeData(int count, StructVector parent) { ComplexWriter writer = new ComplexWriterImpl("root", parent); StructWriter rootWriter = writer.rootAsStruct(); IntWriter intWriter = rootWriter.integer("int"); UInt1Writer uint1Writer = rootWriter.uInt1("uint1"); UInt2Writer uint2Writer = rootWriter.uInt2("uint2"); UInt4Writer uint4Writer = rootWriter.uInt4("uint4"); UInt8Writer uint8Writer = rootWriter.uInt8("uint8"); BigIntWriter bigIntWriter = rootWriter.bigInt("bigInt"); Float4Writer float4Writer = rootWriter.float4("float"); for (int i = 0; i < count; i++) { intWriter.setPosition(i); intWriter.writeInt(i); uint1Writer.setPosition(i); // TODO: Fix add safe write methods on uint methods. uint1Writer.setPosition(i); uint1Writer.writeUInt1((byte) uint1Values[i % uint1Values.length] ); uint2Writer.setPosition(i); uint2Writer.writeUInt2((char) uint2Values[i % uint2Values.length] ); uint4Writer.setPosition(i); uint4Writer.writeUInt4((int) uint4Values[i % uint4Values.length] ); uint8Writer.setPosition(i); uint8Writer.writeUInt8(uint8Values[i % uint8Values.length].longValue()); bigIntWriter.setPosition(i); bigIntWriter.writeBigInt(i); float4Writer.setPosition(i); float4Writer.writeFloat4(i == 0 ? Float.NaN : i); } writer.setValueCount(count); } protected void validateContent(int count, VectorSchemaRoot root) { for (int i = 0; i < count; i++) { Assert.assertEquals(i, root.getVector("int").getObject(i)); Assert.assertEquals((Short) uint1Values[i % uint1Values.length], ((UInt1Vector) root.getVector("uint1")).getObjectNoOverflow(i)); Assert.assertEquals("Failed for index: " + i, (Character) uint2Values[i % uint2Values.length], (Character) ((UInt2Vector) root.getVector("uint2")).get(i)); Assert.assertEquals("Failed for index: " + i, (Long) uint4Values[i % uint4Values.length], ((UInt4Vector) root.getVector("uint4")).getObjectNoOverflow(i)); Assert.assertEquals("Failed for index: " + i, uint8Values[i % uint8Values.length], ((UInt8Vector) root.getVector("uint8")).getObjectNoOverflow(i)); Assert.assertEquals(Long.valueOf(i), root.getVector("bigInt").getObject(i)); Assert.assertEquals(i == 0 ? Float.NaN : i, root.getVector("float").getObject(i)); } } protected void writeComplexData(int count, StructVector parent) { ArrowBuf varchar = allocator.buffer(3); varchar.readerIndex(0); varchar.setByte(0, 'a'); varchar.setByte(1, 'b'); varchar.setByte(2, 'c'); varchar.writerIndex(3); ComplexWriter writer = new ComplexWriterImpl("root", parent); StructWriter rootWriter = writer.rootAsStruct(); IntWriter intWriter = rootWriter.integer("int"); BigIntWriter bigIntWriter = rootWriter.bigInt("bigInt"); ListWriter listWriter = rootWriter.list("list"); StructWriter structWriter = rootWriter.struct("struct"); for (int i = 0; i < count; i++) { if (i % 5 != 3) { intWriter.setPosition(i); intWriter.writeInt(i); } bigIntWriter.setPosition(i); bigIntWriter.writeBigInt(i); listWriter.setPosition(i); listWriter.startList(); for (int j = 0; j < i % 3; j++) { listWriter.varChar().writeVarChar(0, 3, varchar); } listWriter.endList(); structWriter.setPosition(i); structWriter.start(); structWriter.timeStampMilli("timestamp").writeTimeStampMilli(i); structWriter.end(); } writer.setValueCount(count); varchar.getReferenceManager().release(); } public void printVectors(List<FieldVector> vectors) { for (FieldVector vector : vectors) { LOGGER.debug(vector.getField().getName()); int valueCount = vector.getValueCount(); for (int i = 0; i < valueCount; i++) { LOGGER.debug(String.valueOf(vector.getObject(i))); } } } protected void validateComplexContent(int count, VectorSchemaRoot root) { Assert.assertEquals(count, root.getRowCount()); printVectors(root.getFieldVectors()); for (int i = 0; i < count; i++) { Object intVal = root.getVector("int").getObject(i); if (i % 5 != 3) { Assert.assertEquals(i, intVal); } else { Assert.assertNull(intVal); } Assert.assertEquals(Long.valueOf(i), root.getVector("bigInt").getObject(i)); Assert.assertEquals(i % 3, ((List<?>) root.getVector("list").getObject(i)).size()); NullableTimeStampMilliHolder h = new NullableTimeStampMilliHolder(); FieldReader structReader = root.getVector("struct").getReader(); structReader.setPosition(i); structReader.reader("timestamp").read(h); Assert.assertEquals(i, h.value); } } private LocalDateTime makeDateTimeFromCount(int i) { return LocalDateTime.of(2000 + i, 1 + i, 1 + i, i, i, i, i * 100_000_000 + i); } protected void writeDateTimeData(int count, StructVector parent) { Assert.assertTrue(count < 100); ComplexWriter writer = new ComplexWriterImpl("root", parent); StructWriter rootWriter = writer.rootAsStruct(); DateMilliWriter dateWriter = rootWriter.dateMilli("date"); TimeMilliWriter timeWriter = rootWriter.timeMilli("time"); TimeStampMilliWriter timeStampMilliWriter = rootWriter.timeStampMilli("timestamp-milli"); TimeStampMilliTZWriter timeStampMilliTZWriter = rootWriter.timeStampMilliTZ("timestamp-milliTZ", "Europe/Paris"); TimeStampNanoWriter timeStampNanoWriter = rootWriter.timeStampNano("timestamp-nano"); for (int i = 0; i < count; i++) { LocalDateTime dt = makeDateTimeFromCount(i); // Number of days in milliseconds since epoch, stored as 64-bit integer, only date part is used dateWriter.setPosition(i); long dateLong = dt.toLocalDate().atStartOfDay().toInstant(ZoneOffset.UTC).toEpochMilli(); dateWriter.writeDateMilli(dateLong); // Time is a value in milliseconds since midnight, stored as 32-bit integer timeWriter.setPosition(i); int milliOfDay = (int) java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(dt.toLocalTime().toNanoOfDay()); timeWriter.writeTimeMilli(milliOfDay); // Timestamp as milliseconds since the epoch, stored as 64-bit integer timeStampMilliWriter.setPosition(i); timeStampMilliWriter.writeTimeStampMilli(dt.toInstant(ZoneOffset.UTC).toEpochMilli()); // Timestamp as milliseconds since epoch with timezone timeStampMilliTZWriter.setPosition(i); timeStampMilliTZWriter.writeTimeStampMilliTZ(dt.atZone(ZoneId.of("Europe/Paris")).toInstant().toEpochMilli()); // Timestamp as nanoseconds since epoch timeStampNanoWriter.setPosition(i); long tsNanos = dt.toInstant(ZoneOffset.UTC).toEpochMilli() * 1_000_000 + i; // need to add back in nano val timeStampNanoWriter.writeTimeStampNano(tsNanos); } writer.setValueCount(count); } protected void validateDateTimeContent(int count, VectorSchemaRoot root) { Assert.assertEquals(count, root.getRowCount()); printVectors(root.getFieldVectors()); for (int i = 0; i < count; i++) { LocalDateTime dt = makeDateTimeFromCount(i); LocalDateTime dtMilli = dt.minusNanos(i); LocalDateTime dateVal = ((DateMilliVector) root.getVector("date")).getObject(i); LocalDateTime dateExpected = dt.toLocalDate().atStartOfDay(); Assert.assertEquals(dateExpected, dateVal); LocalTime timeVal = ((TimeMilliVector) root.getVector("time")).getObject(i).toLocalTime(); Assert.assertEquals(dtMilli.toLocalTime(), timeVal); Object timestampMilliVal = root.getVector("timestamp-milli").getObject(i); Assert.assertEquals(dtMilli, timestampMilliVal); Object timestampMilliTZVal = root.getVector("timestamp-milliTZ").getObject(i); Assert.assertEquals(dt.atZone(ZoneId.of("Europe/Paris")).toInstant().toEpochMilli(), timestampMilliTZVal); Object timestampNanoVal = root.getVector("timestamp-nano").getObject(i); Assert.assertEquals(dt, timestampNanoVal); } } protected VectorSchemaRoot writeFlatDictionaryData( BufferAllocator bufferAllocator, DictionaryProvider.MapDictionaryProvider provider) { // Define dictionaries and add to provider VarCharVector dictionary1Vector = newVarCharVector("D1", bufferAllocator); dictionary1Vector.allocateNewSafe(); dictionary1Vector.set(0, "foo".getBytes(StandardCharsets.UTF_8)); dictionary1Vector.set(1, "bar".getBytes(StandardCharsets.UTF_8)); dictionary1Vector.set(2, "baz".getBytes(StandardCharsets.UTF_8)); dictionary1Vector.setValueCount(3); Dictionary dictionary1 = new Dictionary(dictionary1Vector, new DictionaryEncoding(1L, false, null)); provider.put(dictionary1); VarCharVector dictionary2Vector = newVarCharVector("D2", bufferAllocator); dictionary2Vector.allocateNewSafe(); dictionary2Vector.set(0, "micro".getBytes(StandardCharsets.UTF_8)); dictionary2Vector.set(1, "small".getBytes(StandardCharsets.UTF_8)); dictionary2Vector.set(2, "large".getBytes(StandardCharsets.UTF_8)); dictionary2Vector.setValueCount(3); Dictionary dictionary2 = new Dictionary(dictionary2Vector, new DictionaryEncoding(2L, false, null)); provider.put(dictionary2); // Populate the vectors VarCharVector vector1A = newVarCharVector("varcharA", bufferAllocator); vector1A.allocateNewSafe(); vector1A.set(0, "foo".getBytes(StandardCharsets.UTF_8)); vector1A.set(1, "bar".getBytes(StandardCharsets.UTF_8)); vector1A.set(3, "baz".getBytes(StandardCharsets.UTF_8)); vector1A.set(4, "bar".getBytes(StandardCharsets.UTF_8)); vector1A.set(5, "baz".getBytes(StandardCharsets.UTF_8)); vector1A.setValueCount(6); FieldVector encodedVector1A = (FieldVector) DictionaryEncoder.encode(vector1A, dictionary1); vector1A.close(); // Done with this vector after encoding // Write this vector using indices instead of encoding IntVector encodedVector1B = new IntVector("varcharB", bufferAllocator); encodedVector1B.allocateNewSafe(); encodedVector1B.set(0, 2); // "baz" encodedVector1B.set(1, 1); // "bar" encodedVector1B.set(2, 2); // "baz" encodedVector1B.set(4, 1); // "bar" encodedVector1B.set(5, 0); // "foo" encodedVector1B.setValueCount(6); VarCharVector vector2 = newVarCharVector("sizes", bufferAllocator); vector2.allocateNewSafe(); vector2.set(1, "large".getBytes(StandardCharsets.UTF_8)); vector2.set(2, "small".getBytes(StandardCharsets.UTF_8)); vector2.set(3, "small".getBytes(StandardCharsets.UTF_8)); vector2.set(4, "large".getBytes(StandardCharsets.UTF_8)); vector2.setValueCount(6); FieldVector encodedVector2 = (FieldVector) DictionaryEncoder.encode(vector2, dictionary2); vector2.close(); // Done with this vector after encoding List<Field> fields = Arrays.asList(encodedVector1A.getField(), encodedVector1B.getField(), encodedVector2.getField()); List<FieldVector> vectors = Collections2.asImmutableList(encodedVector1A, encodedVector1B, encodedVector2); return new VectorSchemaRoot(fields, vectors, encodedVector1A.getValueCount()); } protected void validateFlatDictionary(VectorSchemaRoot root, DictionaryProvider provider) { FieldVector vector1A = root.getVector("varcharA"); Assert.assertNotNull(vector1A); DictionaryEncoding encoding1A = vector1A.getField().getDictionary(); Assert.assertNotNull(encoding1A); Assert.assertEquals(1L, encoding1A.getId()); Assert.assertEquals(6, vector1A.getValueCount()); Assert.assertEquals(0, vector1A.getObject(0)); Assert.assertEquals(1, vector1A.getObject(1)); Assert.assertEquals(null, vector1A.getObject(2)); Assert.assertEquals(2, vector1A.getObject(3)); Assert.assertEquals(1, vector1A.getObject(4)); Assert.assertEquals(2, vector1A.getObject(5)); FieldVector vector1B = root.getVector("varcharB"); Assert.assertNotNull(vector1B); DictionaryEncoding encoding1B = vector1A.getField().getDictionary(); Assert.assertNotNull(encoding1B); Assert.assertTrue(encoding1A.equals(encoding1B)); Assert.assertEquals(1L, encoding1B.getId()); Assert.assertEquals(6, vector1B.getValueCount()); Assert.assertEquals(2, vector1B.getObject(0)); Assert.assertEquals(1, vector1B.getObject(1)); Assert.assertEquals(2, vector1B.getObject(2)); Assert.assertEquals(null, vector1B.getObject(3)); Assert.assertEquals(1, vector1B.getObject(4)); Assert.assertEquals(0, vector1B.getObject(5)); FieldVector vector2 = root.getVector("sizes"); Assert.assertNotNull(vector2); DictionaryEncoding encoding2 = vector2.getField().getDictionary(); Assert.assertNotNull(encoding2); Assert.assertEquals(2L, encoding2.getId()); Assert.assertEquals(6, vector2.getValueCount()); Assert.assertEquals(null, vector2.getObject(0)); Assert.assertEquals(2, vector2.getObject(1)); Assert.assertEquals(1, vector2.getObject(2)); Assert.assertEquals(1, vector2.getObject(3)); Assert.assertEquals(2, vector2.getObject(4)); Assert.assertEquals(null, vector2.getObject(5)); Dictionary dictionary1 = provider.lookup(1L); Assert.assertNotNull(dictionary1); VarCharVector dictionaryVector = ((VarCharVector) dictionary1.getVector()); Assert.assertEquals(3, dictionaryVector.getValueCount()); Assert.assertEquals(new Text("foo"), dictionaryVector.getObject(0)); Assert.assertEquals(new Text("bar"), dictionaryVector.getObject(1)); Assert.assertEquals(new Text("baz"), dictionaryVector.getObject(2)); Dictionary dictionary2 = provider.lookup(2L); Assert.assertNotNull(dictionary2); dictionaryVector = ((VarCharVector) dictionary2.getVector()); Assert.assertEquals(3, dictionaryVector.getValueCount()); Assert.assertEquals(new Text("micro"), dictionaryVector.getObject(0)); Assert.assertEquals(new Text("small"), dictionaryVector.getObject(1)); Assert.assertEquals(new Text("large"), dictionaryVector.getObject(2)); } protected VectorSchemaRoot writeNestedDictionaryData( BufferAllocator bufferAllocator, DictionaryProvider.MapDictionaryProvider provider) { // Define the dictionary and add to the provider VarCharVector dictionaryVector = newVarCharVector("D2", bufferAllocator); dictionaryVector.allocateNewSafe(); dictionaryVector.set(0, "foo".getBytes(StandardCharsets.UTF_8)); dictionaryVector.set(1, "bar".getBytes(StandardCharsets.UTF_8)); dictionaryVector.setValueCount(2); Dictionary dictionary = new Dictionary(dictionaryVector, new DictionaryEncoding(2L, false, null)); provider.put(dictionary); // Write the vector data using dictionary indices ListVector listVector = ListVector.empty("list", bufferAllocator); DictionaryEncoding encoding = dictionary.getEncoding(); listVector.addOrGetVector(new FieldType(true, encoding.getIndexType(), encoding)); listVector.allocateNew(); UnionListWriter listWriter = new UnionListWriter(listVector); listWriter.startList(); listWriter.writeInt(0); listWriter.writeInt(1); listWriter.endList(); listWriter.startList(); listWriter.writeInt(0); listWriter.endList(); listWriter.startList(); listWriter.writeInt(1); listWriter.endList(); listWriter.setValueCount(3); List<Field> fields = Collections2.asImmutableList(listVector.getField()); List<FieldVector> vectors = Collections2.asImmutableList(listVector); return new VectorSchemaRoot(fields, vectors, 3); } protected void validateNestedDictionary(VectorSchemaRoot root, DictionaryProvider provider) { FieldVector vector = root.getFieldVectors().get(0); Assert.assertNotNull(vector); Assert.assertNull(vector.getField().getDictionary()); Field nestedField = vector.getField().getChildren().get(0); DictionaryEncoding encoding = nestedField.getDictionary(); Assert.assertNotNull(encoding); Assert.assertEquals(2L, encoding.getId()); Assert.assertEquals(new ArrowType.Int(32, true), encoding.getIndexType()); Assert.assertEquals(3, vector.getValueCount()); Assert.assertEquals(Arrays.asList(0, 1), vector.getObject(0)); Assert.assertEquals(Arrays.asList(0), vector.getObject(1)); Assert.assertEquals(Arrays.asList(1), vector.getObject(2)); Dictionary dictionary = provider.lookup(2L); Assert.assertNotNull(dictionary); VarCharVector dictionaryVector = ((VarCharVector) dictionary.getVector()); Assert.assertEquals(2, dictionaryVector.getValueCount()); Assert.assertEquals(new Text("foo"), dictionaryVector.getObject(0)); Assert.assertEquals(new Text("bar"), dictionaryVector.getObject(1)); } protected VectorSchemaRoot writeDecimalData(BufferAllocator bufferAllocator) { DecimalVector decimalVector1 = new DecimalVector("decimal1", bufferAllocator, 10, 3); DecimalVector decimalVector2 = new DecimalVector("decimal2", bufferAllocator, 4, 2); DecimalVector decimalVector3 = new DecimalVector("decimal3", bufferAllocator, 16, 8); int count = 10; decimalVector1.allocateNew(count); decimalVector2.allocateNew(count); decimalVector3.allocateNew(count); for (int i = 0; i < count; i++) { decimalVector1.setSafe(i, new BigDecimal(BigInteger.valueOf(i), 3)); decimalVector2.setSafe(i, new BigDecimal(BigInteger.valueOf(i * (1 << 10)), 2)); decimalVector3.setSafe(i, new BigDecimal(BigInteger.valueOf(i * 1111111111111111L), 8)); } decimalVector1.setValueCount(count); decimalVector2.setValueCount(count); decimalVector3.setValueCount(count); List<Field> fields = Collections2.asImmutableList(decimalVector1.getField(), decimalVector2.getField(), decimalVector3.getField()); List<FieldVector> vectors = Collections2.asImmutableList(decimalVector1, decimalVector2, decimalVector3); return new VectorSchemaRoot(fields, vectors, count); } protected void validateDecimalData(VectorSchemaRoot root) { DecimalVector decimalVector1 = (DecimalVector) root.getVector("decimal1"); DecimalVector decimalVector2 = (DecimalVector) root.getVector("decimal2"); DecimalVector decimalVector3 = (DecimalVector) root.getVector("decimal3"); int count = 10; Assert.assertEquals(count, root.getRowCount()); for (int i = 0; i < count; i++) { // Verify decimal 1 vector BigDecimal readValue = decimalVector1.getObject(i); ArrowType.Decimal type = (ArrowType.Decimal) decimalVector1.getField().getType(); BigDecimal genValue = new BigDecimal(BigInteger.valueOf(i), type.getScale()); Assert.assertEquals(genValue, readValue); // Verify decimal 2 vector readValue = decimalVector2.getObject(i); type = (ArrowType.Decimal) decimalVector2.getField().getType(); genValue = new BigDecimal(BigInteger.valueOf(i * (1 << 10)), type.getScale()); Assert.assertEquals(genValue, readValue); // Verify decimal 3 vector readValue = decimalVector3.getObject(i); type = (ArrowType.Decimal) decimalVector3.getField().getType(); genValue = new BigDecimal(BigInteger.valueOf(i * 1111111111111111L), type.getScale()); Assert.assertEquals(genValue, readValue); } } protected VectorSchemaRoot writeNullData(int valueCount) { NullVector nullVector1 = new NullVector(); NullVector nullVector2 = new NullVector(); nullVector1.setValueCount(valueCount); nullVector2.setValueCount(valueCount); List<Field> fields = Collections2.asImmutableList(nullVector1.getField(), nullVector2.getField()); List<FieldVector> vectors = Collections2.asImmutableList(nullVector1, nullVector2); return new VectorSchemaRoot(fields, vectors, valueCount); } protected void validateNullData(VectorSchemaRoot root, int valueCount) { NullVector vector1 = (NullVector) root.getFieldVectors().get(0); NullVector vector2 = (NullVector) root.getFieldVectors().get(1); assertEquals(valueCount, vector1.getValueCount()); assertEquals(valueCount, vector2.getValueCount()); } public void validateUnionData(int count, VectorSchemaRoot root) { FieldReader unionReader = root.getVector("union").getReader(); for (int i = 0; i < count; i++) { unionReader.setPosition(i); switch (i % 4) { case 0: Assert.assertEquals(i, unionReader.readInteger().intValue()); break; case 1: Assert.assertEquals(i, unionReader.readLong().longValue()); break; case 2: Assert.assertEquals(i % 3, unionReader.size()); break; case 3: NullableTimeStampMilliHolder h = new NullableTimeStampMilliHolder(); unionReader.reader("timestamp").read(h); Assert.assertEquals(i, h.value); break; default: assert false : "Unexpected value in switch statement: " + i; } } } public void writeUnionData(int count, StructVector parent) { ArrowBuf varchar = allocator.buffer(3); varchar.readerIndex(0); varchar.setByte(0, 'a'); varchar.setByte(1, 'b'); varchar.setByte(2, 'c'); varchar.writerIndex(3); ComplexWriter writer = new ComplexWriterImpl("root", parent); StructWriter rootWriter = writer.rootAsStruct(); IntWriter intWriter = rootWriter.integer("union"); BigIntWriter bigIntWriter = rootWriter.bigInt("union"); ListWriter listWriter = rootWriter.list("union"); StructWriter structWriter = rootWriter.struct("union"); for (int i = 0; i < count; i++) { switch (i % 4) { case 0: intWriter.setPosition(i); intWriter.writeInt(i); break; case 1: bigIntWriter.setPosition(i); bigIntWriter.writeBigInt(i); break; case 2: listWriter.setPosition(i); listWriter.startList(); for (int j = 0; j < i % 3; j++) { listWriter.varChar().writeVarChar(0, 3, varchar); } listWriter.endList(); break; case 3: structWriter.setPosition(i); structWriter.start(); structWriter.timeStampMilli("timestamp").writeTimeStampMilli(i); structWriter.end(); break; default: assert false : "Unexpected value in switch statement: " + i; } } writer.setValueCount(count); varchar.getReferenceManager().release(); } protected void writeVarBinaryData(int count, StructVector parent) { Assert.assertTrue(count < 100); ComplexWriter writer = new ComplexWriterImpl("root", parent); StructWriter rootWriter = writer.rootAsStruct(); ListWriter listWriter = rootWriter.list("list"); ArrowBuf varbin = allocator.buffer(count); for (int i = 0; i < count; i++) { varbin.setByte(i, i); listWriter.setPosition(i); listWriter.startList(); for (int j = 0; j < i % 3; j++) { listWriter.varBinary().writeVarBinary(0, i + 1, varbin); } listWriter.endList(); } writer.setValueCount(count); varbin.getReferenceManager().release(); } protected void validateVarBinary(int count, VectorSchemaRoot root) { Assert.assertEquals(count, root.getRowCount()); ListVector listVector = (ListVector) root.getVector("list"); byte[] expectedArray = new byte[count]; int numVarBinaryValues = 0; for (int i = 0; i < count; i++) { expectedArray[i] = (byte) i; Object obj = listVector.getObject(i); List<?> objList = (List) obj; if (i % 3 == 0) { Assert.assertTrue(objList.isEmpty()); } else { byte[] expected = Arrays.copyOfRange(expectedArray, 0, i + 1); for (int j = 0; j < i % 3; j++) { byte[] result = (byte[]) objList.get(j); Assert.assertArrayEquals(result, expected); numVarBinaryValues++; } } } // ListVector lastSet should be the index of last value + 1 Assert.assertEquals(listVector.getLastSet(), count - 1); // VarBinaryVector lastSet should be the index of last value VarBinaryVector binaryVector = (VarBinaryVector) listVector.getChildrenFromFields().get(0); Assert.assertEquals(binaryVector.getLastSet(), numVarBinaryValues - 1); } protected void writeBatchData(ArrowWriter writer, IntVector vector, VectorSchemaRoot root) throws IOException { writer.start(); vector.setNull(0); vector.setSafe(1, 1); vector.setSafe(2, 2); vector.setNull(3); vector.setSafe(4, 1); vector.setValueCount(5); root.setRowCount(5); writer.writeBatch(); vector.setNull(0); vector.setSafe(1, 1); vector.setSafe(2, 2); vector.setValueCount(3); root.setRowCount(3); writer.writeBatch(); writer.end(); } protected void validateBatchData(ArrowReader reader, IntVector vector) throws IOException { reader.loadNextBatch(); assertEquals(vector.getValueCount(), 5); assertTrue(vector.isNull(0)); assertEquals(vector.get(1), 1); assertEquals(vector.get(2), 2); assertTrue(vector.isNull(3)); assertEquals(vector.get(4), 1); reader.loadNextBatch(); assertEquals(vector.getValueCount(), 3); assertTrue(vector.isNull(0)); assertEquals(vector.get(1), 1); assertEquals(vector.get(2), 2); } protected VectorSchemaRoot writeMapData(BufferAllocator bufferAllocator) { MapVector mapVector = MapVector.empty("map", bufferAllocator, false); MapVector sortedMapVector = MapVector.empty("mapSorted", bufferAllocator, true); mapVector.allocateNew(); sortedMapVector.allocateNew(); UnionMapWriter mapWriter = mapVector.getWriter(); UnionMapWriter sortedMapWriter = sortedMapVector.getWriter(); final int count = 10; for (int i = 0; i < count; i++) { // Write mapVector with NULL values // i == 1 is a NULL if (i != 1) { mapWriter.setPosition(i); mapWriter.startMap(); // i == 3 is an empty map if (i != 3) { for (int j = 0; j < i + 1; j++) { mapWriter.startEntry(); mapWriter.key().bigInt().writeBigInt(j); // i == 5 maps to a NULL value if (i != 5) { mapWriter.value().integer().writeInt(j); } mapWriter.endEntry(); } } mapWriter.endMap(); } // Write sortedMapVector sortedMapWriter.setPosition(i); sortedMapWriter.startMap(); for (int j = 0; j < i + 1; j++) { sortedMapWriter.startEntry(); sortedMapWriter.key().bigInt().writeBigInt(j); sortedMapWriter.value().integer().writeInt(j); sortedMapWriter.endEntry(); } sortedMapWriter.endMap(); } mapWriter.setValueCount(COUNT); sortedMapWriter.setValueCount(COUNT); List<Field> fields = Collections2.asImmutableList(mapVector.getField(), sortedMapVector.getField()); List<FieldVector> vectors = Collections2.asImmutableList(mapVector, sortedMapVector); return new VectorSchemaRoot(fields, vectors, count); } protected void validateMapData(VectorSchemaRoot root) { MapVector mapVector = (MapVector) root.getVector("map"); MapVector sortedMapVector = (MapVector) root.getVector("mapSorted"); final int count = 10; Assert.assertEquals(count, root.getRowCount()); UnionMapReader mapReader = new UnionMapReader(mapVector); UnionMapReader sortedMapReader = new UnionMapReader(sortedMapVector); for (int i = 0; i < count; i++) { // Read mapVector with NULL values mapReader.setPosition(i); if (i == 1) { assertFalse(mapReader.isSet()); } else { if (i == 3) { JsonStringArrayList<?> result = (JsonStringArrayList<?>) mapReader.readObject(); assertTrue(result.isEmpty()); } else { for (int j = 0; j < i + 1; j++) { mapReader.next(); assertEquals(j, mapReader.key().readLong().longValue()); if (i == 5) { assertFalse(mapReader.value().isSet()); } else { assertEquals(j, mapReader.value().readInteger().intValue()); } } } } // Read sortedMapVector sortedMapReader.setPosition(i); for (int j = 0; j < i + 1; j++) { sortedMapReader.next(); assertEquals(j, sortedMapReader.key().readLong().longValue()); assertEquals(j, sortedMapReader.value().readInteger().intValue()); } } } protected VectorSchemaRoot writeListAsMapData(BufferAllocator bufferAllocator) { ListVector mapEntryList = ListVector.empty("entryList", bufferAllocator); FieldType mapEntryType = new FieldType(false, ArrowType.Struct.INSTANCE, null, null); StructVector mapEntryData = new StructVector("entryData", bufferAllocator, mapEntryType, null); mapEntryData.addOrGet("myKey", new FieldType(false, new ArrowType.Int(64, true), null), BigIntVector.class); mapEntryData.addOrGet("myValue", FieldType.nullable(new ArrowType.Int(32, true)), IntVector.class); mapEntryList.initializeChildrenFromFields(Collections2.asImmutableList(mapEntryData.getField())); UnionListWriter entryWriter = mapEntryList.getWriter(); entryWriter.allocate(); final int count = 10; for (int i = 0; i < count; i++) { entryWriter.setPosition(i); entryWriter.startList(); for (int j = 0; j < i + 1; j++) { entryWriter.struct().start(); entryWriter.struct().bigInt("myKey").writeBigInt(j); entryWriter.struct().integer("myValue").writeInt(j); entryWriter.struct().end(); } entryWriter.endList(); } entryWriter.setValueCount(COUNT); MapVector mapVector = MapVector.empty("map", bufferAllocator, false); mapEntryList.makeTransferPair(mapVector).transfer(); List<Field> fields = Collections2.asImmutableList(mapVector.getField()); List<FieldVector> vectors = Collections2.asImmutableList(mapVector); return new VectorSchemaRoot(fields, vectors, count); } protected void validateListAsMapData(VectorSchemaRoot root) { MapVector sortedMapVector = (MapVector) root.getVector("map"); final int count = 10; Assert.assertEquals(count, root.getRowCount()); UnionMapReader sortedMapReader = new UnionMapReader(sortedMapVector); sortedMapReader.setKeyValueNames("myKey", "myValue"); for (int i = 0; i < count; i++) { sortedMapReader.setPosition(i); for (int j = 0; j < i + 1; j++) { sortedMapReader.next(); assertEquals(j, sortedMapReader.key().readLong().longValue()); assertEquals(j, sortedMapReader.value().readInteger().intValue()); } } } }
apache-2.0
ctripcorp/dal
dal-client/src/test/java/com/ctrip/platform/dal/dao/sqlbuilder/DeleteSqlBuilderTest.java
3071
package com.ctrip.platform.dal.dao.sqlbuilder; import com.ctrip.platform.dal.common.enums.DatabaseCategory; import junit.framework.Assert; import org.junit.Test; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.List; public class DeleteSqlBuilderTest { @Test public void test1() throws SQLException { List<String> in = new ArrayList<String>(); in.add("12"); in.add("12"); DeleteSqlBuilder builder = new DeleteSqlBuilder("Person", DatabaseCategory.MySql); builder.equal("a", "paramValue", Types.INTEGER); builder.and().in("b", in, Types.INTEGER); builder.and().like("b", "in", Types.INTEGER); builder.and().isNotNull("c"); builder.and().betweenNullable("d", null, "paramValue2", Types.INTEGER); builder.and().isNull("e"); String build_sql = builder.build(); String expected_sql = "DELETE FROM `Person` WHERE `a` = ? AND `b` in ( ?, ? ) " + "AND `b` LIKE ? AND `c` IS NOT NULL AND `e` IS NULL"; Assert.assertEquals(expected_sql, build_sql); expected_sql = "DELETE FROM `Person_0` WHERE `a` = ? AND `b` in ( ?, ? ) " + "AND `b` LIKE ? AND `c` IS NOT NULL AND `e` IS NULL"; Assert.assertEquals(expected_sql, builder.build("_0")); builder.buildParameters(); Assert.assertEquals(5, builder.getStatementParameterIndex()); Assert.assertEquals(4, builder.buildParameters().size()); Assert.assertEquals(1, builder.buildParameters().get(0).getIndex()); Assert.assertEquals("a", builder.buildParameters().get(0).getName()); Assert.assertEquals(Types.INTEGER, builder.buildParameters().get(0).getSqlType()); } @Test public void testNew() throws SQLException { List<String> in = new ArrayList<String>(); in.add("12"); in.add("12"); DeleteSqlBuilder builder = new DeleteSqlBuilder(); builder.equal("a", "paramValue", Types.INTEGER); builder.and().in("b", in, Types.INTEGER); builder.and().like("b", "in", Types.INTEGER); builder.and().isNotNull("c"); builder.and().betweenNullable("d", null, "paramValue2", Types.INTEGER); builder.and().isNull("e"); builder.from("Person").setDatabaseCategory(DatabaseCategory.MySql); String build_sql = builder.build(); String expected_sql = "DELETE FROM `Person` WHERE `a` = ? AND `b` in ( ? ) " + "AND `b` LIKE ? AND `c` IS NOT NULL AND `e` IS NULL"; Assert.assertEquals(expected_sql, build_sql); expected_sql = "DELETE FROM `Person_0` WHERE `a` = ? AND `b` in ( ? ) " + "AND `b` LIKE ? AND `c` IS NOT NULL AND `e` IS NULL"; Assert.assertEquals(expected_sql, builder.build("_0")); builder.buildParameters(); Assert.assertEquals(4, builder.getStatementParameterIndex()); Assert.assertEquals(3, builder.buildParameters().size()); Assert.assertEquals(1, builder.buildParameters().get(0).getIndex()); Assert.assertEquals("a", builder.buildParameters().get(0).getName()); Assert.assertEquals(Types.INTEGER, builder.buildParameters().get(0).getSqlType()); } }
apache-2.0
zaishi24/safetyckeck
src/com/safety/service/impl/SnmpDetailServiceImpl.java
1093
package com.safety.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.safety.dao.IBaseDAO; import com.safety.entity.DnsDetail; import com.safety.entity.SnmpDetail; import com.safety.service.IDetailService; @Service("snmpDetail") public class SnmpDetailServiceImpl implements IDetailService<SnmpDetail>{ @Resource private IBaseDAO<SnmpDetail> baseDAO; @Override public SnmpDetail getDetailById(int id) { // TODO Auto-generated method stub return baseDAO.get(SnmpDetail.class, id); } @Override public List<SnmpDetail> getAllDetail() { // TODO Auto-generated method stub return baseDAO.find("from SnmpDetail h order by create_time"); } @Override public void save(SnmpDetail detail) { // TODO Auto-generated method stub baseDAO.save(detail); } @Override public void update(SnmpDetail detail) { // TODO Auto-generated method stub baseDAO.update(detail); } @Override public void delete(SnmpDetail detail) { // TODO Auto-generated method stub baseDAO.delete(detail); } }
apache-2.0
swanandmehta/Chat-Inc
src/main/Java/com/chatinc/managerImpl/UserManager.java
1626
package com.chatinc.managerImpl; import java.util.List; import org.hibernate.Session; import com.chatinc.common.HibernetUtil; import com.chatinc.entity.User; import com.chatinc.manager.IUserManager; public class UserManager extends GlobalManager<User> implements IUserManager { @Override public User login(User user) { Session session = HibernetUtil.getNewSession(); String hql = "SELECT u FROM User u WHERE u.UserName = '"+user.getUserName()+"' AND u.Password = '"+user.getPassword()+"' "; List<User> userList = session.createQuery(hql, User.class).getResultList(); session.close(); return !userList.isEmpty() ? userList.get(0) : null; } @Override public List<User> findUser(User user) { Session session = HibernetUtil.getNewSession(); StringBuilder sb = new StringBuilder(); sb.append("SELECT * FROM chatinc.USER u WHERE "); if(user.getFirst() != null && !user.getFirst().isEmpty()){ sb.append(" u.first like '"+user.getFirst()+"%' "); } if(user.getLast() != null && !user.getLast().isEmpty()){ sb.append(" or u.last like '"+user.getLast()+"%' "); } List<User> userList = session.createNativeQuery(sb.toString(), User.class).getResultList(); session.close(); return !userList.isEmpty() ? userList : null; } @Override public User getUser(Integer userId) { Session session = HibernetUtil.getNewSession(); String hql = "SELECT u FROM User u WHERE u.id = "+userId; List<User> userList = session.createQuery(hql, User.class).getResultList(); return !userList.isEmpty() ? userList.get(0) : null; } }
apache-2.0
mmmsplay10/QuizUpWinner
quizup/o/וּ.java
670
package o; import android.os.Handler.Callback; import android.os.Message; import java.util.BitSet; @օ public final class וּ implements Handler.Callback, ᒡ { private static final String ˊ = וּ.class.getSimpleName(); private final BitSet ˋ; static { new וּ.1(); } public final boolean handleMessage(Message paramMessage) { if (!וּ.if.ˊ(paramMessage, this.ˋ)) { new StringBuilder("Unknown message type: ").append(paramMessage); return false; } return true; } } /* Location: /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar * Qualified Name: o.Ô¨µ * JD-Core Version: 0.6.2 */
apache-2.0
Mikk-x/Mikk_Code_P2P
app/src/main/java/cynthia/com/mikk_code_p2p/fragment/HomeFragment.java
5959
package cynthia.com.mikk_code_p2p.fragment; import android.content.Context; import android.os.SystemClock; import android.text.TextUtils; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.loopj.android.http.RequestParams; import com.squareup.picasso.Picasso; import com.youth.banner.Banner; import com.youth.banner.BannerConfig; import com.youth.banner.Transformer; import com.youth.banner.loader.ImageLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import butterknife.Bind; import cynthia.com.mikk_code_p2p.R; import cynthia.com.mikk_code_p2p.bean.Image; import cynthia.com.mikk_code_p2p.bean.Index; import cynthia.com.mikk_code_p2p.bean.Product; import cynthia.com.mikk_code_p2p.common.AppNetConfig; import cynthia.com.mikk_code_p2p.common.BaseFragment; import cynthia.com.mikk_code_p2p.ui.RoundProgress; /** * Created by shkstart on 2016/11/30 0030. */ public class HomeFragment extends BaseFragment { @Bind(R.id.iv_title_back) ImageView mIvTitleBack; @Bind(R.id.tv_title) TextView mTvTitle; @Bind(R.id.iv_title_setting) ImageView mIvTitleSetting; @Bind(R.id.banner) Banner mBanner; @Bind(R.id.tv_home_product) TextView mTvHomeProduct; @Bind(R.id.roundPro_home) RoundProgress mRoundProHome; @Bind(R.id.tv_home_yearrate) TextView mTvHomeYearrate; private Runnable runnable = new Runnable() { @Override public void run() { mRoundProHome.setMax(100); for (int i = 0; i < currentProress; i++) { mRoundProHome.setProgress(i + 1); SystemClock.sleep(20); //强制重绘 // roundProHome.invalidate();//只有主线程才可以如此调用 mRoundProHome.postInvalidate();//主线程、分线程都可以如此调用 } } }; private int currentProress; @Override protected RequestParams getParams() { return null; } @Override protected String getUrl() { return AppNetConfig.INDEX; } private Index index; @Override protected void initData(String content) { if (!TextUtils.isEmpty(content)){ index = new Index(); //解析json数据:GSON / FASTJSON JSONObject jsonObject = JSON.parseObject(content); //解析json对象数据 String proInfo = jsonObject.getString("proInfo"); Product product = JSON.parseObject(proInfo, Product.class); //解析json数组数据 String imageArr = jsonObject.getString("imageArr"); List<Image> images = jsonObject.parseArray(imageArr, Image.class); index.product = product; index.images = images; //更新页面数据 mTvHomeProduct.setText(product.name); mTvHomeYearrate.setText(product.yearRate + "%"); currentProress = Integer.parseInt(index.product.progress); //在分线程中,实现进度的动态变化 new Thread(runnable).start(); //设置banner样式 mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE); //设置图片加载器 mBanner.setImageLoader(new GlideImageLoader()); //设置图片地址构成的集合 ArrayList<String> imagesUrl = new ArrayList<String>(index.images.size()); // ArrayList<String> imagesUrl = new ArrayList<String>(index.images.size()); // for(int i = 0; i < imagesUrl.size(); i++) {//imagesUrl.size():0 for (int i = 0; i < index.images.size(); i++) {//index.images.size():4 imagesUrl.add(index.images.get(i).IMAURL); } // Log.e("TAG","imagesUrl"+imagesUrl); mBanner.setImages(imagesUrl); //设置banner动画效果 mBanner.setBannerAnimation(Transformer.DepthPage); //设置标题集合(当banner样式有显示title时) String[] titles = new String[]{"分享砍学费", "人脉总动员", "想不到你是这样的app", "购物节,爱不单行"}; mBanner.setBannerTitles(Arrays.asList(titles)); //设置自动轮播,默认为true mBanner.isAutoPlay(true); //设置轮播时间 mBanner.setDelayTime(1500); //设置指示器位置(当banner模式中有指示器时) mBanner.setIndicatorGravity(BannerConfig.CENTER); //banner设置方法全部调用完毕时最后调用 mBanner.start(); } } @Override protected void initTitle() { mIvTitleBack.setVisibility(View.GONE); mTvTitle.setText("首页"); mIvTitleSetting.setVisibility(View.GONE); } @Override public int getLayoutId() { return R.layout.fragment_home; } public class GlideImageLoader extends ImageLoader { @Override public void displayImage(Context context, Object path, ImageView imageView) { /** 常用的图片加载库: Universal Image Loader:一个强大的图片加载库,包含各种各样的配置,最老牌,使用也最广泛。 Picasso: Square出品,必属精品。和OkHttp搭配起来更配呦! Volley ImageLoader:Google官方出品,可惜不能加载本地图片~ Fresco:Facebook出的,天生骄傲!不是一般的强大。 Glide:Google推荐的图片加载库,专注于流畅的滚动。 */ //Picasso 加载图片简单用法 // Picasso.with(context).load((String) path).into(imageView); Picasso.with(context).load((String) path).into(imageView); } } }
apache-2.0
veraPDF/veraPDF-pdfbox
pdfbox/src/main/java/org/apache/pdfbox/pdmodel/font/PDType1Font.java
17367
/* * 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.pdfbox.pdmodel.font; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.fontbox.EncodedFont; import org.apache.fontbox.FontBoxFont; import org.apache.fontbox.type1.DamagedFontException; import org.apache.fontbox.type1.Type1Font; import org.apache.fontbox.util.BoundingBox; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.cos.COSStream; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.common.PDStream; import org.apache.pdfbox.pdmodel.font.encoding.Encoding; import org.apache.pdfbox.pdmodel.font.encoding.StandardEncoding; import org.apache.pdfbox.pdmodel.font.encoding.Type1Encoding; import org.apache.pdfbox.pdmodel.font.encoding.WinAnsiEncoding; import org.apache.pdfbox.util.Matrix; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A PostScript Type 1 Font. * * @author Ben Litchfield */ public class PDType1Font extends PDSimpleFont { private static final Log LOG = LogFactory.getLog(PDType1Font.class); // alternative names for glyphs which are commonly encountered private static final Map<String, String> ALT_NAMES = new HashMap<String, String>(); static { ALT_NAMES.put("ff", "f_f"); ALT_NAMES.put("ffi", "f_f_i"); ALT_NAMES.put("ffl", "f_f_l"); ALT_NAMES.put("fi", "f_i"); ALT_NAMES.put("fl", "f_l"); ALT_NAMES.put("st", "s_t"); ALT_NAMES.put("IJ", "I_J"); ALT_NAMES.put("ij", "i_j"); ALT_NAMES.put("ellipsis", "elipsis"); // misspelled in ArialMT } private static final int PFB_START_MARKER = 0x80; // todo: replace with enum? or getters? public static final PDType1Font TIMES_ROMAN = new PDType1Font("Times-Roman"); public static final PDType1Font TIMES_BOLD = new PDType1Font("Times-Bold"); public static final PDType1Font TIMES_ITALIC = new PDType1Font("Times-Italic"); public static final PDType1Font TIMES_BOLD_ITALIC = new PDType1Font("Times-BoldItalic"); public static final PDType1Font HELVETICA = new PDType1Font("Helvetica"); public static final PDType1Font HELVETICA_BOLD = new PDType1Font("Helvetica-Bold"); public static final PDType1Font HELVETICA_OBLIQUE = new PDType1Font("Helvetica-Oblique"); public static final PDType1Font HELVETICA_BOLD_OBLIQUE = new PDType1Font("Helvetica-BoldOblique"); public static final PDType1Font COURIER = new PDType1Font("Courier"); public static final PDType1Font COURIER_BOLD = new PDType1Font("Courier-Bold"); public static final PDType1Font COURIER_OBLIQUE = new PDType1Font("Courier-Oblique"); public static final PDType1Font COURIER_BOLD_OBLIQUE = new PDType1Font("Courier-BoldOblique"); public static final PDType1Font SYMBOL = new PDType1Font("Symbol"); public static final PDType1Font ZAPF_DINGBATS = new PDType1Font("ZapfDingbats"); private final Type1Font type1font; // embedded font private final FontBoxFont genericFont; // embedded or system font for rendering private final boolean isEmbedded; private final boolean isDamaged; private Matrix fontMatrix; private final AffineTransform fontMatrixTransform; private boolean isFontMatrixDefault; /** * Creates a Type 1 standard 14 font for embedding. * * @param baseFont One of the standard 14 PostScript names */ private PDType1Font(String baseFont) { super(baseFont); dict.setItem(COSName.SUBTYPE, COSName.TYPE1); dict.setName(COSName.BASE_FONT, baseFont); encoding = new WinAnsiEncoding(); dict.setItem(COSName.ENCODING, COSName.WIN_ANSI_ENCODING); // todo: could load the PFB font here if we wanted to support Standard 14 embedding type1font = null; FontMapping<FontBoxFont> mapping = FontMapper.getFontBoxFont(getBaseFont(), getFontDescriptor()); genericFont = mapping.getFont(); if (mapping.isFallback()) { String fontName; try { fontName = genericFont.getName(); } catch (IOException e) { fontName = "?"; } LOG.debug("Using fallback font " + fontName + " for base font " + getBaseFont()); } isEmbedded = false; isDamaged = false; fontMatrixTransform = new AffineTransform(); this.isFontMatrixDefault = Matrix.isFontMatrixDefault(this.getFontMatrix()); } /** * Creates a new Type 1 font for embedding. * * @param doc PDF document to write to * @param afmIn AFM file stream * @param pfbIn PFB file stream * @throws IOException */ public PDType1Font(PDDocument doc, InputStream afmIn, InputStream pfbIn) throws IOException { PDType1FontEmbedder embedder = new PDType1FontEmbedder(doc, dict, afmIn, pfbIn); encoding = embedder.getFontEncoding(); type1font = embedder.getType1Font(); genericFont = embedder.getType1Font(); isEmbedded = true; isDamaged = false; fontMatrixTransform = new AffineTransform(); } /** * Creates a Type 1 font from a Font dictionary in a PDF. * * @param fontDictionary font dictionary */ public PDType1Font(COSDictionary fontDictionary) throws IOException { super(fontDictionary); PDFontDescriptor fd = getFontDescriptor(); Type1Font t1 = null; boolean fontIsDamaged = false; if (fd != null) { // a Type1 font may contain a Type1C font PDStream fontFile3 = fd.getFontFile3(); if (fontFile3 != null) { throw new IllegalArgumentException("Use PDType1CFont for FontFile3"); } // or it may contain a PFB PDStream fontFile = fd.getFontFile(); if (fontFile != null) { try { COSStream stream = fontFile.getStream(); int length1 = stream.getInt(COSName.LENGTH1); int length2 = stream.getInt(COSName.LENGTH2); // repair Length1 if necessary byte[] bytes = fontFile.getByteArray(); length1 = repairLength1(bytes, length1); if (bytes.length > 0 && (bytes[0] & 0xff) == PFB_START_MARKER) { // some bad files embed the entire PFB, see PDFBOX-2607 t1 = Type1Font.createWithPFB(bytes); } else { // the PFB embedded as two segments back-to-back byte[] segment1 = Arrays.copyOfRange(bytes, 0, length1); byte[] segment2 = Arrays.copyOfRange(bytes, length1, length1 + length2); // empty streams are simply ignored if (length1 > 0 && length2 > 0) { t1 = Type1Font.createWithSegments(segment1, segment2); } } } catch (DamagedFontException e) { LOG.debug("Can't read damaged embedded Type1 font " + fd.getFontName()); fontIsDamaged = true; } catch (IOException e) { LOG.error("Can't read the embedded Type1 font " + fd.getFontName(), e); fontIsDamaged = true; } } } isEmbedded = t1 != null; isDamaged = fontIsDamaged; type1font = t1; // find a generic font to use for rendering, could be a .pfb, but might be a .ttf if (type1font != null) { genericFont = type1font; } else { FontMapping<FontBoxFont> mapping = FontMapper.getFontBoxFont(getBaseFont(), fd); genericFont = mapping.getFont(); if (mapping.isFallback()) { LOG.debug("Using fallback font " + genericFont.getName() + " for " + getBaseFont()); } } readEncoding(); fontMatrixTransform = getFontMatrix().createAffineTransform(); fontMatrixTransform.scale(1000, 1000); } /** * Some Type 1 fonts have an invalid Length1, which causes the binary segment of the font * to be truncated, see PDFBOX-2350. * * @param bytes Type 1 stream bytes * @param length1 Length1 from the Type 1 stream * @return repaired Length1 value */ private int repairLength1(byte[] bytes, int length1) { // scan backwards from the end of the first segment to find 'exec' int offset = Math.max(0, length1 - 4); while (offset > 0) { if (bytes[offset + 0] == 'e' && bytes[offset + 1] == 'x' && bytes[offset + 2] == 'e' && bytes[offset + 3] == 'c') { offset += 4; // skip additional CR LF space characters while (offset < length1 && (bytes[offset] == '\r' || bytes[offset] == '\n' || bytes[offset] == ' ')) { offset++; } break; } offset--; } if (length1 - offset != 0 && offset > 0) { LOG.debug("Ignored invalid Length1 for Type 1 font " + getName()); return offset; } return length1; } /** * Returns the PostScript name of the font. */ public String getBaseFont() { return dict.getNameAsString(COSName.BASE_FONT); } @Override public float getHeight(int code) throws IOException { String name = codeToName(code); if (getStandard14AFM() != null) { String afmName = getEncoding().getName(code); return getStandard14AFM().getCharacterHeight(afmName); // todo: isn't this the y-advance, not the height? } else { // todo: should be scaled by font matrix return (float) genericFont.getPath(name).getBounds().getHeight(); } } @Override protected byte[] encode(int unicode) throws IOException { if (unicode > 0xff) { throw new IllegalArgumentException("This font type only supports 8-bit code points"); } String name = getGlyphList().codePointToName(unicode); String nameInFont = getNameInFont(name); Map<String, Integer> inverted = getInvertedEncoding(); if (nameInFont.equals(".notdef") || !genericFont.hasGlyph(nameInFont)) { throw new IllegalArgumentException( String.format("No glyph for U+%04X in font %s", unicode, getName())); } int code = inverted.get(name); return new byte[] { (byte)code }; } @Override public float getWidthFromFont(int code) throws IOException { String name = codeToName(code); // width of .notdef is ignored for substitutes, see PDFBOX-1900 if (!isEmbedded && name.equals(".notdef")) { return 250; } float width = genericFont.getWidth(name); if (!isFontMatrixDefault) { Point2D p = new Point2D.Float(width, 0); fontMatrixTransform.transform(p, p); return (float) p.getX(); } else { return width; } } @Override public boolean isEmbedded() { return isEmbedded; } @Override public float getAverageFontWidth() { if (getStandard14AFM() != null) { return getStandard14AFM().getAverageCharacterWidth(); } else { return super.getAverageFontWidth(); } } @Override public int readCode(InputStream in) throws IOException { return in.read(); } @Override protected Encoding readEncodingFromFont() throws IOException { // extract from Type1 font/substitute if (genericFont instanceof EncodedFont) { return Type1Encoding.fromFontBox(((EncodedFont) genericFont).getEncoding()); } else { if (getStandard14AFM() != null) { // read from AFM return new Type1Encoding(getStandard14AFM()); } // default (only happens with TTFs) return StandardEncoding.INSTANCE; } } /** * Returns the embedded or substituted Type 1 font, or null if there is none. */ public Type1Font getType1Font() { return type1font; } @Override public FontBoxFont getFontBoxFont() { return genericFont; } @Override public String getName() { return getBaseFont(); } @Override public BoundingBox getBoundingBox() throws IOException { return genericFont.getFontBBox(); } //@Override public String codeToName(int code) throws IOException { String name = getEncoding().getName(code); return getNameInFont(name); } /** * Maps a PostScript glyph name to the name in the underlying font, for example when * using a TTF font we might map "W" to "uni0057". */ private String getNameInFont(String name) throws IOException { if (isEmbedded() || genericFont.hasGlyph(name)) { return name; } else { // try alternative name String altName = ALT_NAMES.get(name); if (altName != null && !name.equals(".notdef") && genericFont.hasGlyph(altName)) { return altName; } else { // try unicode name String unicodes = getGlyphList().toUnicode(name); if (unicodes != null && unicodes.length() == 1) { String uniName = String.format("uni%04X", unicodes.codePointAt(0)); if (genericFont.hasGlyph(uniName)) { return uniName; } } } } return ".notdef"; } @Override public GeneralPath getPath(String name) throws IOException { // Acrobat does not draw .notdef for Type 1 fonts, see PDFBOX-2421 // I suspect that it does do this for embedded fonts though, but this is untested if (name.equals(".notdef") && !isEmbedded) { return new GeneralPath(); } else { return genericFont.getPath(getNameInFont(name)); } } @Override public boolean hasGlyph(String name) throws IOException { return genericFont.hasGlyph(getNameInFont(name)); } @Override public Matrix getFontMatrix() { if (fontMatrix == null) { // PDF specified that Type 1 fonts use a 1000upem matrix, but some fonts specify // their own custom matrix anyway, for example PDFBOX-2298 List<Number> numbers = null; try { numbers = genericFont.getFontMatrix(); } catch (IOException e) { fontMatrix = DEFAULT_FONT_MATRIX; } if (numbers != null && numbers.size() == 6) { fontMatrix = new Matrix( numbers.get(0).floatValue(), numbers.get(1).floatValue(), numbers.get(2).floatValue(), numbers.get(3).floatValue(), numbers.get(4).floatValue(), numbers.get(5).floatValue()); } else { return super.getFontMatrix(); } } return fontMatrix; } @Override public boolean isDamaged() { return isDamaged; } }
apache-2.0
boneman1231/org.apache.felix
trunk/org.osgi.foundation/src/main/java/java/lang/IllegalAccessError.java
1016
/* * $Header: /cvshome/build/ee.foundation/src/java/lang/IllegalAccessError.java,v 1.6 2006/03/14 01:20:25 hargrave Exp $ * * (C) Copyright 2001 Sun Microsystems, Inc. * Copyright (c) OSGi Alliance (2001, 2005). 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 java.lang; public class IllegalAccessError extends java.lang.IncompatibleClassChangeError { public IllegalAccessError() { } public IllegalAccessError(java.lang.String var0) { } }
apache-2.0
jbosschina/cluster
jgroups/tankwar/src/main/java/org/jgroups/demo/tankwar/TankWar.java
1781
package org.jgroups.demo.tankwar; import org.jgroups.demo.tankwar.core.MainFrame; import org.jgroups.demo.tankwar.jgroups.AsychCommunication; /** * * mvn clean install dependency:copy-dependencies * * java -cp ./target/jgroups-demo-tankwar.jar:./target/dependency/* -Djava.net.preferIPv4Stack=true org.jgroups.demo.tankwar.TankWar -p tankwar-udp.xml -n node1 isGood * java -cp ./target/jgroups-demo-tankwar.jar:./target/dependency/* -Djava.net.preferIPv4Stack=true org.jgroups.demo.tankwar.TankWar -p tankwar-udp.xml -n node2 * * @author kylin * */ public class TankWar { private String jgroupsProps ; private String name ; private boolean isGood ; public TankWar(String jgroupsProps, String name, boolean isGood) { this.jgroupsProps = jgroupsProps; this.name = name; this.isGood = isGood; } public void doStart() { System.out.println("JGroups TankWar Demo doStart, [jgroupsProps=" + jgroupsProps + ", name=" + name + ", isGood=" + isGood + "]"); // Current use asynchronous Communication AsychCommunication comm = new AsychCommunication(jgroupsProps, name); new MainFrame(comm, isGood); } public static void main(String[] args) { String props = "udp.xml"; String name = null; boolean isGood = false ; for(int i=0; i < args.length; i++) { if (args[i].equals("-p")) { props = args[++i]; continue; } if (args[i].equals("-n") || args[i].equals("-name")) { name = args[++i]; continue; } if (args[i].equals("good")) { isGood = true ; continue; } System.out.println("Run Application with [-n <name>] [good]"); System.exit(1); } AsychCommunication comm = new AsychCommunication(props, name); MainFrame mainFrame = new MainFrame(comm, isGood); } }
apache-2.0
sbower/kuali-rice-1
shareddata/api/src/main/java/org/kuali/rice/shareddata/api/campus/CampusService.java
2957
/* * Copyright 2006-2011 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.shareddata.api.campus; import org.kuali.rice.core.api.exception.RiceIllegalArgumentException; import org.kuali.rice.shareddata.api.SharedDataConstants; import org.springframework.cache.annotation.Cacheable; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import java.util.List; /** * <p>CampusService interface.</p> * * @author Kuali Rice Team (rice.collab@kuali.org) */ @WebService(name = "campusService", targetNamespace = SharedDataConstants.Namespaces.SHAREDDATA_NAMESPACE_2_0 ) @SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL, parameterStyle = SOAPBinding.ParameterStyle.WRAPPED) public interface CampusService { /** * This will return a {@link Campus}. * * @param code the code of the campus to return * @throws IllegalArgumentException if the code is null * @throws IllegalStateException if the campus does not exist in the system under the * specific code */ @WebMethod(operationName="getCampus") @Cacheable(value=Campus.Cache.NAME, key="'code=' + #code") Campus getCampus(@WebParam(name = "code") String code) throws RiceIllegalArgumentException; /** * This will return all {@link Campus}. */ @WebMethod(operationName="findAllCampuses") @Cacheable(value=Campus.Cache.NAME, key="'all'") List<Campus> findAllCampuses(); /** * This will return a {@link CampusType}. * * @param code the code of the campus type to return * @return CampusType object represented by the passed in code * @throws IllegalArgumentException if the code is null * @throws IllegalStateException if the campus does not exist in the system under the * specific code */ @WebMethod(operationName="getCampusType") @Cacheable(value=CampusType.Cache.NAME, key="'code=' + #code") CampusType getCampusType(@WebParam(name = "code") String code) throws RiceIllegalArgumentException; /** * This will return all {@link CampusType}. */ @WebMethod(operationName="findAllCampusTypes") @Cacheable(value=CampusType.Cache.NAME, key="'all'") List<CampusType> findAllCampusTypes(); }
apache-2.0
brosander/nifi-android-s2s
s2s/src/main/java/com/hortonworks/hdf/android/sitetosite/client/persistence/SiteToSiteDB.java
8554
/* * Copyright 2017 Hortonworks, Inc. * All rights reserved. * * Hortonworks, Inc. licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * See the associated NOTICE file for additional information regarding copyright ownership. */ package com.hortonworks.hdf.android.sitetosite.client.persistence; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.os.Parcel; import com.hortonworks.hdf.android.sitetosite.client.SiteToSiteClientConfig; import com.hortonworks.hdf.android.sitetosite.client.SiteToSiteRemoteCluster; import com.hortonworks.hdf.android.sitetosite.client.peer.PeerStatus; import static com.hortonworks.hdf.android.sitetosite.client.persistence.SiteToSiteDBConstants.*; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; /** * Easily save and load state useful for site-to-site communication */ public class SiteToSiteDB { private static final int VERSION = 1; private static SQLiteOpenHelper sqLiteOpenHelper; //private final Context context; public SiteToSiteDB(Context context) { //this.context = context; synchronized (SiteToSiteDB.class) { if (sqLiteOpenHelper == null) { sqLiteOpenHelper = new SiteToSiteSQLiteOpenHelper(context, SiteToSiteDB.class.getSimpleName() + ".db", null, VERSION); } } } /** * Saves the peer status for a given url set and proxy * * @param siteToSiteClientConfig the configuration to save the peer status for */ public void savePeerStatus(SiteToSiteClientConfig siteToSiteClientConfig) throws SQLiteIOException { SQLiteDatabase writableDatabase = sqLiteOpenHelper.getWritableDatabase(); writableDatabase.beginTransaction(); try { writableDatabase.execSQL("DELETE FROM " + PEER_STATUSES_TABLE_NAME + " WHERE " + EXPIRATION_MILLIS_COLUMN + " <= ?", new Object[]{new Date().getTime()}); for (SiteToSiteRemoteCluster siteToSiteRemoteCluster : siteToSiteClientConfig.getRemoteClusters()) { PeerStatus peerStatus = siteToSiteRemoteCluster.getPeerStatus(); if (peerStatus == null) { continue; } Parcel parcel = Parcel.obtain(); peerStatus.writeToParcel(parcel, 0); parcel.setDataPosition(0); byte[] bytes = parcel.marshall(); String urlsString = getPeerUrlsString(siteToSiteRemoteCluster.getUrls()); String proxyHost = siteToSiteRemoteCluster.getProxyHost(); int proxyPort = siteToSiteRemoteCluster.getProxyPort(); writableDatabase.delete(PEER_STATUSES_TABLE_NAME, PEER_STATUS_WHERE_CLAUSE, new String[]{urlsString, proxyHost, Integer.toString(proxyPort)}); ContentValues values = new ContentValues(); values.put(PEER_STATUS_URLS_COLUMN, urlsString); if (proxyHost == null || proxyHost.isEmpty()) { values.putNull(PEER_STATUS_PROXY_HOST_COLUMN); values.putNull(PEER_STATUS_PROXY_PORT_COLUMN); } else { values.put(PEER_STATUS_PROXY_HOST_COLUMN, proxyHost); values.put(PEER_STATUS_PROXY_PORT_COLUMN, proxyPort); } values.put(CONTENT_COLUMN, bytes); values.put(EXPIRATION_MILLIS_COLUMN, new Date().getTime() + siteToSiteClientConfig.getPeerUpdateInterval(TimeUnit.MILLISECONDS)); writableDatabase.insertOrThrow(PEER_STATUSES_TABLE_NAME, null, values); } writableDatabase.setTransactionSuccessful(); } catch (SQLiteException e) { throw new SQLiteIOException("Unable to store peer status in database.", e); } finally { writableDatabase.endTransaction(); writableDatabase.close(); } } /** * Gets the peer status for a given url set and proxy * * @param siteToSiteClientConfig the config to get peer status for */ public void updatePeerStatusOnConfig(SiteToSiteClientConfig siteToSiteClientConfig) throws SQLiteIOException { SQLiteDatabase readableDatabase = sqLiteOpenHelper.getReadableDatabase(); try { for (SiteToSiteRemoteCluster siteToSiteRemoteCluster : siteToSiteClientConfig.getRemoteClusters()) { PeerStatus origPeerStatus = siteToSiteRemoteCluster.getPeerStatus(); List<String> parameters = new ArrayList<>(); String peerUrlsString = getPeerUrlsString(siteToSiteRemoteCluster.getUrls()); StringBuilder queryString = new StringBuilder(PEER_STATUS_URLS_COLUMN).append(" = ? AND ").append(PEER_STATUS_PROXY_HOST_COLUMN); parameters.add(peerUrlsString); String proxyHost = siteToSiteRemoteCluster.getProxyHost(); if (proxyHost == null || proxyHost.isEmpty()) { queryString.append(" IS NULL AND ").append(PEER_STATUS_PROXY_PORT_COLUMN).append(" IS NULL"); } else { queryString.append(" = ? AND ").append(PEER_STATUS_PROXY_PORT_COLUMN).append(" = ?"); parameters.add(proxyHost); parameters.add(Integer.toString(siteToSiteRemoteCluster.getProxyPort())); } Cursor cursor; cursor = readableDatabase.query(false, PEER_STATUSES_TABLE_NAME, new String[]{CONTENT_COLUMN}, queryString.toString(), parameters.toArray(new String[parameters.size()]), null, null, null, null); try { int contentIndex = cursor.getColumnIndexOrThrow(CONTENT_COLUMN); while (cursor.moveToNext()) { byte[] bytes = cursor.getBlob(contentIndex); Parcel parcel = Parcel.obtain(); parcel.unmarshall(bytes, 0, bytes.length); parcel.setDataPosition(0); PeerStatus dbPeerStatus = PeerStatus.CREATOR.createFromParcel(parcel); if (dbPeerStatus != null && (origPeerStatus == null || origPeerStatus.getLastPeerUpdate() < dbPeerStatus.getLastPeerUpdate())) { siteToSiteRemoteCluster.setPeerStatus(dbPeerStatus); origPeerStatus = dbPeerStatus; } } } finally { cursor.close(); } } } catch (SQLiteException e) { throw new SQLiteIOException("Unable to read peer status from database.", e); } finally { readableDatabase.close(); } } private String getPeerUrlsString(Set<String> peerUrlsPreference) { List<String> orderedUrls = new ArrayList<>(peerUrlsPreference); Collections.sort(orderedUrls); StringBuilder stringBuilder = new StringBuilder(); for (String orderedUrl : orderedUrls) { stringBuilder.append(orderedUrl); stringBuilder.append(","); } if (orderedUrls.size() > 0) { stringBuilder.setLength(stringBuilder.length() - 1); } return stringBuilder.toString(); } /** * Returns a readable sqlite db * * @return a readable sqlite db */ public SQLiteDatabase getReadableDatabase() { return sqLiteOpenHelper.getReadableDatabase(); } /** * Returns a writable sqlite db * * @return a writable sqlite db */ public SQLiteDatabase getWritableDatabase() { return sqLiteOpenHelper.getWritableDatabase(); } }
apache-2.0
yelllowme/wanglin
app/src/main/java/com/wanglinkeji/wanglin/activity/IssueBlogActivity.java
29749
package com.wanglinkeji.wanglin.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.text.Editable; import android.text.InputFilter; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextWatcher; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.lidroid.xutils.HttpUtils; import com.lidroid.xutils.exception.HttpException; import com.lidroid.xutils.http.RequestParams; import com.lidroid.xutils.http.ResponseInfo; import com.lidroid.xutils.http.callback.RequestCallBack; import com.lidroid.xutils.http.client.HttpRequest; import com.wanglinkeji.wanglin.R; import com.wanglinkeji.wanglin.adapter.GridViewAdapter_IssueBlog_ImageList; import com.wanglinkeji.wanglin.model.AtItemModel; import com.wanglinkeji.wanglin.model.PhotoModel; import com.wanglinkeji.wanglin.model.UserIdentityInfoModel; import com.wanglinkeji.wanglin.util.DBUtil; import com.wanglinkeji.wanglin.util.HttpUtil; import com.wanglinkeji.wanglin.util.NoLineClickSpan; import com.wanglinkeji.wanglin.util.OtherUtil; import com.wanglinkeji.wanglin.util.WangLinApplication; import com.wanglinkeji.wanglin.util.WanglinHttpResponseListener; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import io.github.rockerhieu.emojicon.EmojiconEditText; import io.github.rockerhieu.emojicon.EmojiconGridFragment; import io.github.rockerhieu.emojicon.EmojiconsFragment; import io.github.rockerhieu.emojicon.emoji.Emojicon; /** * Created by Administrator on 2016/9/21. * 发表吐槽页 */ public class IssueBlogActivity extends FragmentActivity implements View.OnClickListener,EmojiconGridFragment.OnEmojiconClickedListener, EmojiconsFragment.OnEmojiconBackspaceClickedListener { public static final int WHAT_FROM_HOUSE_ESTATE = 1, WHAT_FROM_CITY = 2; private ImageView imageView_cancle, imageView_isChoosedToIssueCity, imageView_addImage, imageView_aitUser, imageView_addFaceImage, imageView_isAnony; private TextView textView_issueBtn, textView_remianingTextNum; private EmojiconEditText editText_blogText; private LinearLayout layout_isChoosedToIssueCity, layout_isAnony; private FrameLayout layout_emojiIcon; private GridView gridView_imageList; private PopupWindow loading_page; private View rootView; //上传的图片数组 private List<String> images = new ArrayList<>(); //上传图片数组的顺序记录 private int image_order = 0; //发表吐槽时的小区Id和城市Id private int houseEstateId, cityId; //选择是否发布到同城吐槽 private boolean isChoosedToIssurCity = false; //是否匿名发布 private boolean isAnony = false; //来源:发表小区吐槽或者同城吐槽 private int whatFrom; private boolean isSetTextChangeListener = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.layout_activity_issue_blog); //刚进入这个界面时,选中图片List为空 PhotoModel.list_choosedPhotos = new ArrayList<>(); //@Item List也为空 AtItemModel.list_AtItem = new ArrayList<>(); viewInit(); setView_EmojiNotShow(); } @Override protected void onStart() { super.onStart(); //此处为了获取软键盘高度,手动弹出一次软键盘,并马上消失 editText_blogText.setFocusable(true); editText_blogText.setFocusableInTouchMode(true); editText_blogText.requestFocus(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode){ //从选择图片返回 case OtherUtil.REQUEST_CODE_ISSUE_BLOG_TO_CHOOSED_PHOTO:{ if (resultCode == RESULT_OK){ gridView_imageList.setAdapter(new GridViewAdapter_IssueBlog_ImageList(PhotoModel.list_choosedPhotos, IssueBlogActivity.this, R.layout.layout_gridview_item_housing_estate_nine_image)); } break; } //从@好友返回 case OtherUtil.REQUEST_CODE_ISSUE_BLOG_TO_AT_USER:{ if (resultCode == RESULT_OK){ //@之后的Edittext内容 String blog_text = editText_blogText.getText().toString(); int selectionStart = editText_blogText.getSelectionStart(); String[] temp = new String[]{blog_text.substring(0, selectionStart), blog_text.substring(selectionStart, blog_text.length())}; String current_text = temp[0] + "@" + AtItemModel.current_AtItem.getContent() + temp[1]; //添加Item之前改变其他Item for (int i = 0; i < AtItemModel.list_AtItem.size(); i++){ if (AtItemModel.list_AtItem.get(i).getStartIndex() >= selectionStart){ AtItemModel.list_AtItem.get(i).setStartIndex(AtItemModel.list_AtItem.get(i).getStartIndex() + AtItemModel.current_AtItem.getContent().length() + 1); AtItemModel.list_AtItem.get(i).setEndIndex(AtItemModel.list_AtItem.get(i).getEndIndex() + AtItemModel.current_AtItem.getContent().length() + 1); } } //向list_AtItem中添加元素 AtItemModel atItem = new AtItemModel(selectionStart, selectionStart + AtItemModel.current_AtItem.getContent().length(), "@" + AtItemModel.current_AtItem.getContent()); atItem.setAtId(AtItemModel.current_AtItem.getAtId()); atItem.setFromWhat(AtItemModel.current_AtItem.getFromWhat()); AtItemModel.list_AtItem.add(atItem); setEditText_afterAt(current_text, AtItemModel.list_AtItem, editText_blogText, editText_blogText.getSelectionStart() + atItem.getContent().length()); } break; } default: break; } } @Override public void onClick(View view) { switch (view.getId()){ //返回按钮 case R.id.imageview_issueBlog_cancle:{ IssueBlogActivity.this.finish(); break; } //发表按钮 case R.id.textview_issueBlog_issueBtn:{ if (PhotoModel.list_choosedPhotos.size() == 0 && editText_blogText.getText().length() == 0){ Toast.makeText(IssueBlogActivity.this, "吐槽不能为空哦!", Toast.LENGTH_SHORT).show(); }else { if (whatFrom == WHAT_FROM_HOUSE_ESTATE){ if (isChoosedToIssurCity == true){ cityId = UserIdentityInfoModel.getDefaultHouseEstate().getCityId(); houseEstateId = UserIdentityInfoModel.getDefaultHouseEstate().getId(); }else { houseEstateId = UserIdentityInfoModel.getDefaultHouseEstate().getId(); cityId = 0; } }else if (whatFrom == WHAT_FROM_CITY){ houseEstateId = 0; cityId = WangLinApplication.locationInfoModel.getLocationCityId(); }else { houseEstateId = 0; cityId = WangLinApplication.locationInfoModel.getLocationCityId(); } loading_page.showAtLocation(rootView, Gravity.CENTER, 0, 0); ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(view,InputMethodManager.SHOW_FORCED); ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘 //判断是否有上传的图片 if (PhotoModel.list_choosedPhotos.size() > 0){ RequestParams requestParams = new RequestParams(); requestParams.addBodyParameter("File", new File(PhotoModel.list_choosedPhotos.get(image_order).getPath())); uploadFirstImage(requestParams, HttpUtil.issBlog_uploadImage_url); }else { issueBlog(IssueBlogActivity.this, editText_blogText.getText().toString(), houseEstateId, WangLinApplication.locationInfoModel.getLocatonCity(), cityId, WangLinApplication.locationInfoModel.getLongitude(), WangLinApplication.locationInfoModel.getLatitude(), WangLinApplication.locationInfoModel.getAddress(), isAnony, images); } } break; } //同时发表到同城吐槽 case R.id.layout_issueBlog_issueToCityBlog:{ if (isChoosedToIssurCity == true){ isChoosedToIssurCity = false; imageView_isChoosedToIssueCity.setBackgroundResource(R.mipmap.rectangle_not_choosed_gray); }else { isChoosedToIssurCity = true; imageView_isChoosedToIssueCity.setBackgroundResource(R.mipmap.photo_choosed_icon); } break; } //是否匿名 case R.id.layout_issueBlog_isAnony:{ if (isAnony == true){ isAnony = false; imageView_isAnony.setBackgroundResource(R.mipmap.rectangle_not_choosed_gray); }else { isAnony = true; imageView_isAnony.setBackgroundResource(R.mipmap.photo_choosed_icon); } break; } //选择图片 case R.id.imageview_issueBlog_addImage:{ PhotoModel.finishText = "完成"; PhotoModel.photoCount = 9; Intent intent = new Intent(IssueBlogActivity.this, ChoosedPhoto_SmallActivity.class); startActivityForResult(intent, OtherUtil.REQUEST_CODE_ISSUE_BLOG_TO_CHOOSED_PHOTO); break; } //@好友 case R.id.imageview_issueBlog_aitUser:{ if (isChangeAtList_Add(editText_blogText.getSelectionStart(), AtItemModel.list_AtItem) >= 0){ Toast.makeText(IssueBlogActivity.this, "此处不能@,请将光标移到其他地方!", Toast.LENGTH_SHORT).show(); }else { Intent intent = new Intent(IssueBlogActivity.this, AT_UserActivity.class); startActivityForResult(intent, OtherUtil.REQUEST_CODE_ISSUE_BLOG_TO_AT_USER); } break; } //选择表情 case R.id.imageview_issueBlog_addFaceImage:{ Toast.makeText(IssueBlogActivity.this, "目前只支持输入法自带Emoji表情!", Toast.LENGTH_SHORT).show(); break; } default: break; } } @Override public void onEmojiconClicked(Emojicon emojicon) { EmojiconsFragment.input(editText_blogText, emojicon); } @Override public void onEmojiconBackspaceClicked(View v) { EmojiconsFragment.backspace(editText_blogText); } private void viewInit(){ whatFrom = getIntent().getIntExtra("whatFrom", WHAT_FROM_CITY); //设置EmojiIcon layout_emojiIcon = (FrameLayout) findViewById(R.id.layout_isssueBlog_emojiIcon); OtherUtil.setViewLayoutParams(layout_emojiIcon, false, 2.5f, 1); getSupportFragmentManager().beginTransaction().replace(R.id.layout_isssueBlog_emojiIcon, EmojiconsFragment.newInstance(false)).commit(); loading_page = OtherUtil.getLoadingPage(IssueBlogActivity.this); rootView = LayoutInflater.from(IssueBlogActivity.this).inflate(R.layout.layout_activity_issue_blog, null); imageView_isAnony = (ImageView)findViewById(R.id.imageview_issueBlog_isAnony); layout_isAnony = (LinearLayout)findViewById(R.id.layout_issueBlog_isAnony); layout_isAnony.setOnClickListener(this); imageView_cancle = (ImageView)findViewById(R.id.imageview_issueBlog_cancle); imageView_cancle.setOnClickListener(this); imageView_isChoosedToIssueCity = (ImageView)findViewById(R.id.imageview_issueBlog_isChoosedToIssueCityBlog); imageView_addImage = (ImageView)findViewById(R.id.imageview_issueBlog_addImage); imageView_addImage.setOnClickListener(this); imageView_aitUser = (ImageView)findViewById(R.id.imageview_issueBlog_aitUser); imageView_aitUser.setOnClickListener(this); imageView_addFaceImage = (ImageView)findViewById(R.id.imageview_issueBlog_addFaceImage); imageView_addFaceImage.setOnClickListener(this); textView_issueBtn = (TextView)findViewById(R.id.textview_issueBlog_issueBtn); textView_issueBtn.setOnClickListener(this); textView_remianingTextNum = (TextView)findViewById(R.id.textview_issueBlog_remainingTextNum); textView_remianingTextNum.setText("剩余" + WangLinApplication.BLOG_MAX_LENGTH +"字"); layout_isChoosedToIssueCity = (LinearLayout)findViewById(R.id.layout_issueBlog_issueToCityBlog); layout_isChoosedToIssueCity.setOnClickListener(this); gridView_imageList = (GridView)findViewById(R.id.gridview_issueBlog_imageList); editText_blogText = (EmojiconEditText) findViewById(R.id.edittext_issueBlog_blogText); OtherUtil.setViewLayoutParams(editText_blogText, false, 3, 1); editText_blogText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(WangLinApplication.BLOG_MAX_LENGTH)}); editText_blogText.addTextChangedListener(new TextWatcher() { int selection; @Override public void beforeTextChanged(CharSequence charSequence, int changeStartIndex, int deleteCount, int addCount) { //charSequence--未改变之前的内容 //changeStartIndex--内容被改变的开始位置 //deleteCount--原始文字被删除的个数 //addCount--新添加的内容的个数 if (isSetTextChangeListener == true){ //Log.d("yellow_temp_before", "charSequence:" + charSequence + "---changeStartIndex:" + changeStartIndex + "---deleteCount:" + deleteCount + "---addCount:" + addCount) ; //根据用户是增加还是删除内容 //如果是删除内容 if (deleteCount > 0){ selection = changeStartIndex; isChangeAtList_Delete(changeStartIndex, AtItemModel.list_AtItem, deleteCount); //修改被编辑@Item后面的Item for (int i = 0; i < AtItemModel.list_AtItem.size(); i++){ if (AtItemModel.list_AtItem.get(i).getStartIndex() > changeStartIndex){ AtItemModel.list_AtItem.get(i).setStartIndex(AtItemModel.list_AtItem.get(i).getStartIndex() - deleteCount); AtItemModel.list_AtItem.get(i).setEndIndex(AtItemModel.list_AtItem.get(i).getEndIndex() - deleteCount); } } //如果是增加内容 } if (addCount > 0){ selection = changeStartIndex + addCount; int position = isChangeAtList_Add(changeStartIndex, AtItemModel.list_AtItem); //position >=0 表示编辑了@列表 if (position >= 0){ AtItemModel.list_AtItem.remove(position); } //修改被编辑@Item后面的Item for (int i = 0; i < AtItemModel.list_AtItem.size(); i++){ if (AtItemModel.list_AtItem.get(i).getStartIndex() >= changeStartIndex){ AtItemModel.list_AtItem.get(i).setStartIndex(AtItemModel.list_AtItem.get(i).getStartIndex() + addCount); AtItemModel.list_AtItem.get(i).setEndIndex(AtItemModel.list_AtItem.get(i).getEndIndex() + addCount); } } } } } @Override public void onTextChanged(CharSequence charSequence, int changeStartIndex, int deleteCount, int addCount) { //charSequence--改变之后的新内容 //changeStartIndex--内容被改变的开始位置 //deleteCount--原始文字被删除的个数 //addCount--新添加的内容的个数 if (isSetTextChangeListener == true){ //Log.d("yellow_temp_on", "charSequence:" + charSequence + "---changeStartIndex:" + changeStartIndex + "---deleteCount:" + deleteCount + "---addCount:" + addCount) ; } } @Override public void afterTextChanged(Editable editable) { //editable最终内容 if (isSetTextChangeListener == true){ //Log.d("yellow_temp_after", editable.toString()); setEditText_afterAt(editable.toString(), AtItemModel.list_AtItem, editText_blogText, selection); } //统计字数 textView_remianingTextNum.setText("剩余" + (WangLinApplication.BLOG_MAX_LENGTH - editText_blogText.getText().length()) +"字"); } }); } //被修改的位置是否在@列表中的某个Item中,如果是,返回这个Item的postion,如果不是返回-1 private void isChangeAtList_Delete(int changeStartIndex,List<AtItemModel> list_AtItem, int deleteCount){ List<AtItemModel> list_AtItem_temp = new ArrayList<>(); for (int i = 0; i < list_AtItem.size(); i++){ for (int j = 0; j < deleteCount; j++){ if (changeStartIndex + j >= list_AtItem.get(i).getStartIndex() && changeStartIndex + j <= list_AtItem.get(i).getEndIndex()){ list_AtItem_temp.add(list_AtItem.get(i)); break; } } } for (int i = 0; i < list_AtItem_temp.size(); i++){ list_AtItem.remove(list_AtItem_temp.get(i)); } } //被修改的位置是否在@列表中的某个Item中,如果是,返回这个Item的postion,如果不是返回-1 private int isChangeAtList_Add(int changeStartIndex,List<AtItemModel> list_AtItem){ int position = -1; for (int i = 0; i < list_AtItem.size(); i++){ if (changeStartIndex > list_AtItem.get(i).getStartIndex() && changeStartIndex <= list_AtItem.get(i).getEndIndex()){ return i; } } return position; } //根据@列表(list_AtItem),设置EditText的样式 private void setEditText_afterAt(String current_text, List<AtItemModel> list_AtItem, EditText editText, int selection){ //设置@的内容样式 SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(current_text); for (int i = 0; i < list_AtItem.size(); i++){ spannableStringBuilder.setSpan(new NoLineClickSpan(), list_AtItem.get(i).getStartIndex(), list_AtItem.get(i).getEndIndex() + 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); } isSetTextChangeListener = false; editText.setText(spannableStringBuilder); isSetTextChangeListener = true; editText.setSelection(selection); } private void setView_EmojiNotShow(){ //设置“匿名发布”和“同时发布到同城吐槽” if (whatFrom == WHAT_FROM_HOUSE_ESTATE){ layout_isChoosedToIssueCity.setVisibility(View.VISIBLE); }else if (whatFrom == WHAT_FROM_CITY){ RelativeLayout.LayoutParams params_isAnony = (RelativeLayout.LayoutParams)layout_isAnony.getLayoutParams(); params_isAnony.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); params_isAnony.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); layout_isAnony.setLayoutParams(params_isAnony); layout_isChoosedToIssueCity.setVisibility(View.GONE); } } private void issueBlog(final Context context, String content, int houseEstateId, String cityName, int regionId, double Lng, double Lat, String Address, boolean isAnony, List<String> imageList){ Log.d("yellow_temp", content + "---" + houseEstateId + "---" + cityName + "---" + regionId + "---" + Lng + "---" + Lat + "---" + Address + "---" + isAnony); Map<String, String> params = new HashMap<>(); params.put("Content", content); params.put("VillageId", String.valueOf(houseEstateId)); params.put("CityName", cityName); params.put("RegionId", String.valueOf(regionId)); //如果选择发布到同城吐槽则填真实区域ID,反之填0 params.put("Lng", String.valueOf(Lng)); params.put("Lat", String.valueOf(Lat)); params.put("Address", Address); params.put("IsAnonymous", String.valueOf(isAnony)); for (int i = 0; i < imageList.size(); i++){ params.put("Imgs" + "[" + i + "]", imageList.get(i)); } List<AtItemModel> list_temp_atUser = new ArrayList<>(); List<AtItemModel> list_temp_atNeighbor = new ArrayList<>(); for (int i = 0; i < AtItemModel.list_AtItem.size(); i++){ if (AtItemModel.list_AtItem.get(i).getFromWhat() == AT_UserActivity.FROM_WHAT_AT_USER){ list_temp_atUser.add(AtItemModel.list_AtItem.get(i)); }else if (AtItemModel.list_AtItem.get(i).getFromWhat() == AT_UserActivity.FROM_WHAT_AT_NEIGHBOR){ list_temp_atNeighbor.add(AtItemModel.list_AtItem.get(i)); } } for (int i = 0; i < list_temp_atUser.size(); i++){ params.put("AtUserId" + "[" + i + "]", String.valueOf(list_temp_atUser.get(i).getAtId())); params.put("AtUser" + "[" + i + "]", list_temp_atUser.get(i).getContent()); //Log.d("yellow_temp", "AtUserId" + "[" + i + "]:" + String.valueOf(list_temp_atUser.get(i).getAtId()) + " AtUser" + "[" + i + "]:" + list_temp_atUser.get(i).getContent()); } for (int i = 0; i < list_temp_atNeighbor.size(); i++){ params.put("HouseId" + "[" + i + "]", String.valueOf(list_temp_atUser.get(i).getAtId())); params.put("House" + "[" + i + "]", list_temp_atUser.get(i).getContent()); } if (AtItemModel.list_AtItem.size() > 0){ params.put("ParmStr1", ((new Gson()).toJson(AtItemModel.list_AtItem)).toString()); Log.d("yellow_temp", "ParmStr1:" + ((new Gson()).toJson(AtItemModel.list_AtItem)).toString()); } HttpUtil.sendVolleyStringRequest_Post(context, HttpUtil.issueBlog_url, params, DBUtil.getLoginUser().getToken(), "yellow_issueBlog", new WanglinHttpResponseListener() { @Override public void onSuccessResponse(JSONObject jsonObject_response) { loading_page.dismiss(); Toast.makeText(context, "发布成功,请手动刷新", Toast.LENGTH_SHORT).show(); IssueBlogActivity.this.finish(); } @Override public void onConnectingError() { loading_page.dismiss(); } @Override public void onDisconnectError() { loading_page.dismiss(); } }); } private void uploadFirstImage(RequestParams requestParams, final String url){ HttpUtils httpUtils = new HttpUtils(); httpUtils.send(HttpRequest.HttpMethod.POST, url, requestParams, new RequestCallBack<String>() { @Override public void onSuccess(ResponseInfo<String> responseInfo) { Log.d("yellow_uploadImage_first", responseInfo.result); try { JSONObject jsonObject_response = new JSONObject(responseInfo.result); int requestCode = jsonObject_response.getInt("Code"); if (requestCode == 200){ image_order++; images.add(jsonObject_response.getString("Data")); if (PhotoModel.list_choosedPhotos.size() > 1){ RequestParams requestParams_other = new RequestParams(); requestParams_other.addBodyParameter("File", new File(PhotoModel.list_choosedPhotos.get(image_order).getPath())); uploadOtherImage(requestParams_other, url); }else { issueBlog(IssueBlogActivity.this, editText_blogText.getText().toString(), houseEstateId, UserIdentityInfoModel.getDefaultHouseEstate().getCity(), cityId, UserIdentityInfoModel.getDefaultHouseEstate().getLng(), UserIdentityInfoModel.getDefaultHouseEstate().getLat(), WangLinApplication.locationInfoModel.getAddress(), isAnony, images); } }else { String msg = jsonObject_response.getString("Msg"); HttpUtil.parseResponseCode(IssueBlogActivity.this, requestCode, msg); loading_page.dismiss(); } } catch (JSONException e) { Toast.makeText(IssueBlogActivity.this, "上传图片失败,失败原因:解析返回数据失败,请反馈!", Toast.LENGTH_SHORT).show(); loading_page.dismiss(); e.printStackTrace(); } } @Override public void onFailure(HttpException e, String s) { e.printStackTrace(); Toast.makeText(IssueBlogActivity.this, "上传图片失败,请稍后重试!", Toast.LENGTH_SHORT).show(); loading_page.dismiss(); } }); } private void uploadOtherImage(RequestParams requestParams, final String url){ HttpUtils httpUtils = new HttpUtils(); httpUtils.send(HttpRequest.HttpMethod.POST, url, requestParams, new RequestCallBack<String>() { @Override public void onSuccess(ResponseInfo<String> responseInfo) { Log.d("yellow_uploadImage_other", responseInfo.result); try { JSONObject jsonObject_response = new JSONObject(responseInfo.result); int requestCode = jsonObject_response.getInt("Code"); if (requestCode == 200){ image_order++; images.add(jsonObject_response.getString("Data")); if (image_order < PhotoModel.list_choosedPhotos.size()){ RequestParams requestParams_other = new RequestParams(); requestParams_other.addBodyParameter("File", new File(PhotoModel.list_choosedPhotos.get(image_order).getPath())); uploadOtherImage(requestParams_other, url); }else { issueBlog(IssueBlogActivity.this, editText_blogText.getText().toString(), houseEstateId, UserIdentityInfoModel.getDefaultHouseEstate().getCity(), cityId, UserIdentityInfoModel.getDefaultHouseEstate().getLng(), UserIdentityInfoModel.getDefaultHouseEstate().getLat(), WangLinApplication.locationInfoModel.getAddress(), isAnony, images); } }else { loading_page.dismiss(); String msg = jsonObject_response.getString("Msg"); HttpUtil.parseResponseCode(IssueBlogActivity.this, requestCode, msg); } } catch (JSONException e) { Toast.makeText(IssueBlogActivity.this, "上传图片失败,失败原因:解析返回数据失败,请反馈!", Toast.LENGTH_SHORT).show(); loading_page.dismiss(); e.printStackTrace(); } } @Override public void onFailure(HttpException e, String s) { e.printStackTrace(); loading_page.dismiss(); Toast.makeText(IssueBlogActivity.this, "上传图片失败,请稍后重试!", Toast.LENGTH_SHORT).show(); } }); } }
apache-2.0
fipar/presto
presto-raptor/src/main/java/com/facebook/presto/raptor/RaptorSplit.java
2947
/* * 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.raptor; import com.facebook.presto.spi.ConnectorSplit; import com.facebook.presto.spi.HostAddress; import com.facebook.presto.spi.predicate.TupleDomain; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import java.util.List; import java.util.UUID; import static com.google.common.base.MoreObjects.toStringHelper; import static java.util.Objects.requireNonNull; public class RaptorSplit implements ConnectorSplit { private final String connectorId; private final UUID shardUuid; private final List<HostAddress> addresses; private final TupleDomain<RaptorColumnHandle> effectivePredicate; @JsonCreator public RaptorSplit( @JsonProperty("connectorId") String connectorId, @JsonProperty("shardUuid") UUID shardUuid, @JsonProperty("effectivePredicate") TupleDomain<RaptorColumnHandle> effectivePredicate) { this(connectorId, shardUuid, ImmutableList.of(), effectivePredicate); } public RaptorSplit(String connectorId, UUID shardUuid, List<HostAddress> addresses, TupleDomain<RaptorColumnHandle> effectivePredicate) { this.connectorId = requireNonNull(connectorId, "connectorId is null"); this.shardUuid = requireNonNull(shardUuid, "shardUuid is null"); this.addresses = ImmutableList.copyOf(requireNonNull(addresses, "addresses is null")); this.effectivePredicate = requireNonNull(effectivePredicate, "effectivePredicate is null"); } @Override public boolean isRemotelyAccessible() { return false; } @Override public List<HostAddress> getAddresses() { return addresses; } @JsonProperty public String getConnectorId() { return connectorId; } @JsonProperty public UUID getShardUuid() { return shardUuid; } @JsonProperty public TupleDomain<RaptorColumnHandle> getEffectivePredicate() { return effectivePredicate; } @Override public Object getInfo() { return this; } @Override public String toString() { return toStringHelper(this) .add("shardUuid", shardUuid) .add("hosts", addresses) .toString(); } }
apache-2.0
ivankelly/bookkeeper
bookkeeper-server/src/main/java/org/apache/bookkeeper/bookie/Journal.java
49678
/** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.bookkeeper.bookie; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Stopwatch; import com.google.common.util.concurrent.MoreExecutors; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.util.Recycler; import io.netty.util.Recycler.Handle; import io.netty.util.concurrent.DefaultThreadFactory; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.apache.bookkeeper.bookie.LedgerDirsManager.NoWritableLedgerDirException; import org.apache.bookkeeper.common.collections.RecyclableArrayList; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.WriteCallback; import org.apache.bookkeeper.stats.Counter; import org.apache.bookkeeper.stats.NullStatsLogger; import org.apache.bookkeeper.stats.OpStatsLogger; import org.apache.bookkeeper.stats.StatsLogger; import org.apache.bookkeeper.util.IOUtils; import org.apache.bookkeeper.util.MathUtils; import org.apache.bookkeeper.util.collections.GrowableArrayBlockingQueue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provide journal related management. */ public class Journal extends BookieCriticalThread implements CheckpointSource { private static final Logger LOG = LoggerFactory.getLogger(Journal.class); private static final RecyclableArrayList.Recycler<QueueEntry> entryListRecycler = new RecyclableArrayList.Recycler<QueueEntry>(); private static final RecyclableArrayList<QueueEntry> EMPTY_ARRAY_LIST = new RecyclableArrayList<>(); /** * Filter to pickup journals. */ private interface JournalIdFilter { boolean accept(long journalId); } /** * For testability. */ @FunctionalInterface public interface BufferedChannelBuilder { BufferedChannelBuilder DEFAULT_BCBUILDER = (FileChannel fc, int capacity) -> new BufferedChannel(fc, capacity); BufferedChannel create(FileChannel fc, int capacity) throws IOException; } /** * List all journal ids by a specified journal id filer. * * @param journalDir journal dir * @param filter journal id filter * @return list of filtered ids */ static List<Long> listJournalIds(File journalDir, JournalIdFilter filter) { File logFiles[] = journalDir.listFiles(); if (logFiles == null || logFiles.length == 0) { return Collections.emptyList(); } List<Long> logs = new ArrayList<Long>(); for (File f: logFiles) { String name = f.getName(); if (!name.endsWith(".txn")) { continue; } String idString = name.split("\\.")[0]; long id = Long.parseLong(idString, 16); if (filter != null) { if (filter.accept(id)) { logs.add(id); } } else { logs.add(id); } } Collections.sort(logs); return logs; } /** * A wrapper over log mark to provide a checkpoint for users of journal * to do checkpointing. */ private static class LogMarkCheckpoint implements Checkpoint { final LastLogMark mark; public LogMarkCheckpoint(LastLogMark checkpoint) { this.mark = checkpoint; } @Override public int compareTo(Checkpoint o) { if (o == Checkpoint.MAX) { return -1; } else if (o == Checkpoint.MIN) { return 1; } return mark.getCurMark().compare(((LogMarkCheckpoint) o).mark.getCurMark()); } @Override public boolean equals(Object o) { if (!(o instanceof LogMarkCheckpoint)) { return false; } return 0 == compareTo((LogMarkCheckpoint) o); } @Override public int hashCode() { return mark.hashCode(); } @Override public String toString() { return mark.toString(); } } /** * Last Log Mark. */ public class LastLogMark { private final LogMark curMark; LastLogMark(long logId, long logPosition) { this.curMark = new LogMark(logId, logPosition); } void setCurLogMark(long logId, long logPosition) { curMark.setLogMark(logId, logPosition); } LastLogMark markLog() { return new LastLogMark(curMark.getLogFileId(), curMark.getLogFileOffset()); } public LogMark getCurMark() { return curMark; } void rollLog(LastLogMark lastMark) throws NoWritableLedgerDirException { byte buff[] = new byte[16]; ByteBuffer bb = ByteBuffer.wrap(buff); // we should record <logId, logPosition> marked in markLog // which is safe since records before lastMark have been // persisted to disk (both index & entry logger) lastMark.getCurMark().writeLogMark(bb); if (LOG.isDebugEnabled()) { LOG.debug("RollLog to persist last marked log : {}", lastMark.getCurMark()); } List<File> writableLedgerDirs = ledgerDirsManager .getWritableLedgerDirs(); for (File dir : writableLedgerDirs) { File file = new File(dir, lastMarkFileName); FileOutputStream fos = null; try { fos = new FileOutputStream(file); fos.write(buff); fos.getChannel().force(true); fos.close(); fos = null; } catch (IOException e) { LOG.error("Problems writing to " + file, e); } finally { // if stream already closed in try block successfully, // stream might have nullified, in such case below // call will simply returns IOUtils.close(LOG, fos); } } } /** * Read last mark from lastMark file. * The last mark should first be max journal log id, * and then max log position in max journal log. */ void readLog() { byte buff[] = new byte[16]; ByteBuffer bb = ByteBuffer.wrap(buff); LogMark mark = new LogMark(); for (File dir: ledgerDirsManager.getAllLedgerDirs()) { File file = new File(dir, lastMarkFileName); try { try (FileInputStream fis = new FileInputStream(file)) { int bytesRead = fis.read(buff); if (bytesRead != 16) { throw new IOException("Couldn't read enough bytes from lastMark." + " Wanted " + 16 + ", got " + bytesRead); } } bb.clear(); mark.readLogMark(bb); if (curMark.compare(mark) < 0) { curMark.setLogMark(mark.getLogFileId(), mark.getLogFileOffset()); } } catch (IOException e) { LOG.error("Problems reading from " + file + " (this is okay if it is the first time starting this " + "bookie"); } } } @Override public String toString() { return curMark.toString(); } } /** * Filter to return list of journals for rolling. */ private static class JournalRollingFilter implements JournalIdFilter { final LastLogMark lastMark; JournalRollingFilter(LastLogMark lastMark) { this.lastMark = lastMark; } @Override public boolean accept(long journalId) { if (journalId < lastMark.getCurMark().getLogFileId()) { return true; } else { return false; } } } /** * Scanner used to scan a journal. */ public interface JournalScanner { /** * Process a journal entry. * * @param journalVersion Journal Version * @param offset File offset of the journal entry * @param entry Journal Entry * @throws IOException */ void process(int journalVersion, long offset, ByteBuffer entry) throws IOException; } /** * Journal Entry to Record. */ private static class QueueEntry implements Runnable { ByteBuf entry; long ledgerId; long entryId; WriteCallback cb; Object ctx; long enqueueTime; boolean ackBeforeSync; OpStatsLogger journalAddEntryStats; Counter journalCbQueueSize; static QueueEntry create(ByteBuf entry, boolean ackBeforeSync, long ledgerId, long entryId, WriteCallback cb, Object ctx, long enqueueTime, OpStatsLogger journalAddEntryStats, Counter journalCbQueueSize) { QueueEntry qe = RECYCLER.get(); qe.entry = entry; qe.ackBeforeSync = ackBeforeSync; qe.cb = cb; qe.ctx = ctx; qe.ledgerId = ledgerId; qe.entryId = entryId; qe.enqueueTime = enqueueTime; qe.journalAddEntryStats = journalAddEntryStats; qe.journalCbQueueSize = journalCbQueueSize; return qe; } @Override public void run() { if (LOG.isDebugEnabled()) { LOG.debug("Acknowledge Ledger: {}, Entry: {}", ledgerId, entryId); } journalCbQueueSize.dec(); journalAddEntryStats.registerSuccessfulEvent(MathUtils.elapsedNanos(enqueueTime), TimeUnit.NANOSECONDS); cb.writeComplete(0, ledgerId, entryId, null, ctx); recycle(); } private final Handle<QueueEntry> recyclerHandle; private QueueEntry(Handle<QueueEntry> recyclerHandle) { this.recyclerHandle = recyclerHandle; } private static final Recycler<QueueEntry> RECYCLER = new Recycler<QueueEntry>() { protected QueueEntry newObject(Recycler.Handle<QueueEntry> handle) { return new QueueEntry(handle); } }; private void recycle() { recyclerHandle.recycle(this); } } /** * Token which represents the need to force a write to the Journal. */ @VisibleForTesting public class ForceWriteRequest { private JournalChannel logFile; private RecyclableArrayList<QueueEntry> forceWriteWaiters; private boolean shouldClose; private boolean isMarker; private long lastFlushedPosition; private long logId; public int process(boolean shouldForceWrite) throws IOException { forceWriteQueueSize.dec(); if (isMarker) { return 0; } try { if (shouldForceWrite) { long startTime = MathUtils.nowInNano(); this.logFile.forceWrite(false); journalSyncStats.registerSuccessfulEvent(MathUtils.elapsedNanos(startTime), TimeUnit.NANOSECONDS); } lastLogMark.setCurLogMark(this.logId, this.lastFlushedPosition); // Notify the waiters that the force write succeeded for (int i = 0; i < forceWriteWaiters.size(); i++) { QueueEntry qe = forceWriteWaiters.get(i); if (qe != null) { cbThreadPool.execute(qe); } journalCbQueueSize.inc(); } return forceWriteWaiters.size(); } finally { closeFileIfNecessary(); } } public void closeFileIfNecessary() { // Close if shouldClose is set if (shouldClose) { // We should guard against exceptions so its // safe to call in catch blocks try { logFile.close(); // Call close only once shouldClose = false; } catch (IOException ioe) { LOG.error("I/O exception while closing file", ioe); } } } private final Handle<ForceWriteRequest> recyclerHandle; private ForceWriteRequest(Handle<ForceWriteRequest> recyclerHandle) { this.recyclerHandle = recyclerHandle; } private void recycle() { logFile = null; if (forceWriteWaiters != null) { forceWriteWaiters.recycle(); forceWriteWaiters = null; } recyclerHandle.recycle(this); } } private ForceWriteRequest createForceWriteRequest(JournalChannel logFile, long logId, long lastFlushedPosition, RecyclableArrayList<QueueEntry> forceWriteWaiters, boolean shouldClose, boolean isMarker) { ForceWriteRequest req = forceWriteRequestsRecycler.get(); req.forceWriteWaiters = forceWriteWaiters; req.logFile = logFile; req.logId = logId; req.lastFlushedPosition = lastFlushedPosition; req.shouldClose = shouldClose; req.isMarker = isMarker; forceWriteQueueSize.inc(); return req; } private final Recycler<ForceWriteRequest> forceWriteRequestsRecycler = new Recycler<ForceWriteRequest>() { protected ForceWriteRequest newObject( Recycler.Handle<ForceWriteRequest> handle) { return new ForceWriteRequest(handle); } }; /** * ForceWriteThread is a background thread which makes the journal durable periodically. * */ private class ForceWriteThread extends BookieCriticalThread { volatile boolean running = true; // This holds the queue entries that should be notified after a // successful force write Thread threadToNotifyOnEx; // should we group force writes private final boolean enableGroupForceWrites; // make flush interval as a parameter public ForceWriteThread(Thread threadToNotifyOnEx, boolean enableGroupForceWrites) { super("ForceWriteThread"); this.threadToNotifyOnEx = threadToNotifyOnEx; this.enableGroupForceWrites = enableGroupForceWrites; } @Override public void run() { LOG.info("ForceWrite Thread started"); boolean shouldForceWrite = true; int numReqInLastForceWrite = 0; while (running) { ForceWriteRequest req = null; try { req = forceWriteRequests.take(); // Force write the file and then notify the write completions // if (!req.isMarker) { if (shouldForceWrite) { // if we are going to force write, any request that is already in the // queue will benefit from this force write - post a marker prior to issuing // the flush so until this marker is encountered we can skip the force write if (enableGroupForceWrites) { forceWriteRequests.put(createForceWriteRequest(req.logFile, 0, 0, null, false, true)); } // If we are about to issue a write, record the number of requests in // the last force write and then reset the counter so we can accumulate // requests in the write we are about to issue if (numReqInLastForceWrite > 0) { forceWriteGroupingCountStats.registerSuccessfulValue(numReqInLastForceWrite); numReqInLastForceWrite = 0; } } } numReqInLastForceWrite += req.process(shouldForceWrite); if (enableGroupForceWrites // if its a marker we should switch back to flushing && !req.isMarker // This indicates that this is the last request in a given file // so subsequent requests will go to a different file so we should // flush on the next request && !req.shouldClose) { shouldForceWrite = false; } else { shouldForceWrite = true; } } catch (IOException ioe) { LOG.error("I/O exception in ForceWrite thread", ioe); running = false; } catch (InterruptedException e) { Thread.currentThread().interrupt(); LOG.error("ForceWrite thread interrupted", e); // close is idempotent if (null != req) { req.shouldClose = true; req.closeFileIfNecessary(); } running = false; } finally { if (req != null) { req.recycle(); } } } // Regardless of what caused us to exit, we should notify the // the parent thread as it should either exit or be in the process // of exiting else we will have write requests hang threadToNotifyOnEx.interrupt(); } // shutdown sync thread void shutdown() throws InterruptedException { running = false; this.interrupt(); this.join(); } } static final int PADDING_MASK = -0x100; static void writePaddingBytes(JournalChannel jc, ByteBuf paddingBuffer, int journalAlignSize) throws IOException { int bytesToAlign = (int) (jc.bc.position() % journalAlignSize); if (0 != bytesToAlign) { int paddingBytes = journalAlignSize - bytesToAlign; if (paddingBytes < 8) { paddingBytes = journalAlignSize - (8 - paddingBytes); } else { paddingBytes -= 8; } paddingBuffer.clear(); // padding mask paddingBuffer.writeInt(PADDING_MASK); // padding len paddingBuffer.writeInt(paddingBytes); // padding bytes paddingBuffer.writerIndex(paddingBuffer.writerIndex() + paddingBytes); jc.preAllocIfNeeded(paddingBuffer.readableBytes()); // write padding bytes jc.bc.write(paddingBuffer); } } static final long MB = 1024 * 1024L; static final int KB = 1024; // max journal file size final long maxJournalSize; // pre-allocation size for the journal files final long journalPreAllocSize; // write buffer size for the journal files final int journalWriteBufferSize; // number journal files kept before marked journal final int maxBackupJournals; final File journalDirectory; final ServerConfiguration conf; final ForceWriteThread forceWriteThread; // Time after which we will stop grouping and issue the flush private final long maxGroupWaitInNanos; // Threshold after which we flush any buffered journal entries private final long bufferedEntriesThreshold; // Threshold after which we flush any buffered journal writes private final long bufferedWritesThreshold; // should we flush if the queue is empty private final boolean flushWhenQueueEmpty; // should we hint the filesystem to remove pages from cache after force write private final boolean removePagesFromCache; // Should data be fsynced on disk before triggering the callback private final boolean syncData; private final LastLogMark lastLogMark = new LastLogMark(0, 0); private static final String LAST_MARK_DEFAULT_NAME = "lastMark"; private final String lastMarkFileName; /** * The thread pool used to handle callback. */ private final ExecutorService cbThreadPool; // journal entry queue to commit final BlockingQueue<QueueEntry> queue = new GrowableArrayBlockingQueue<QueueEntry>(); final BlockingQueue<ForceWriteRequest> forceWriteRequests = new GrowableArrayBlockingQueue<ForceWriteRequest>(); volatile boolean running = true; private final LedgerDirsManager ledgerDirsManager; // Expose Stats private final OpStatsLogger journalAddEntryStats; private final OpStatsLogger journalForceLedgerStats; private final OpStatsLogger journalSyncStats; private final OpStatsLogger journalCreationStats; private final OpStatsLogger journalFlushStats; private final OpStatsLogger journalProcessTimeStats; private final OpStatsLogger journalQueueStats; private final OpStatsLogger forceWriteGroupingCountStats; private final OpStatsLogger forceWriteBatchEntriesStats; private final OpStatsLogger forceWriteBatchBytesStats; private final Counter journalQueueSize; private final Counter forceWriteQueueSize; private final Counter journalCbQueueSize; private final Counter flushMaxWaitCounter; private final Counter flushMaxOutstandingBytesCounter; private final Counter flushEmptyQueueCounter; private final Counter journalWriteBytes; public Journal(int journalIndex, File journalDirectory, ServerConfiguration conf, LedgerDirsManager ledgerDirsManager) { this(journalIndex, journalDirectory, conf, ledgerDirsManager, NullStatsLogger.INSTANCE); } public Journal(int journalIndex, File journalDirectory, ServerConfiguration conf, LedgerDirsManager ledgerDirsManager, StatsLogger statsLogger) { super("BookieJournal-" + conf.getBookiePort()); this.ledgerDirsManager = ledgerDirsManager; this.conf = conf; this.journalDirectory = journalDirectory; this.maxJournalSize = conf.getMaxJournalSizeMB() * MB; this.journalPreAllocSize = conf.getJournalPreAllocSizeMB() * MB; this.journalWriteBufferSize = conf.getJournalWriteBufferSizeKB() * KB; this.syncData = conf.getJournalSyncData(); this.maxBackupJournals = conf.getMaxBackupJournals(); this.forceWriteThread = new ForceWriteThread(this, conf.getJournalAdaptiveGroupWrites()); this.maxGroupWaitInNanos = TimeUnit.MILLISECONDS.toNanos(conf.getJournalMaxGroupWaitMSec()); this.bufferedWritesThreshold = conf.getJournalBufferedWritesThreshold(); this.bufferedEntriesThreshold = conf.getJournalBufferedEntriesThreshold(); if (conf.getNumJournalCallbackThreads() > 0) { this.cbThreadPool = Executors.newFixedThreadPool(conf.getNumJournalCallbackThreads(), new DefaultThreadFactory("bookie-journal-callback")); } else { this.cbThreadPool = MoreExecutors.newDirectExecutorService(); } // Unless there is a cap on the max wait (which requires group force writes) // we cannot skip flushing for queue empty this.flushWhenQueueEmpty = maxGroupWaitInNanos <= 0 || conf.getJournalFlushWhenQueueEmpty(); this.removePagesFromCache = conf.getJournalRemovePagesFromCache(); // read last log mark if (conf.getJournalDirs().length == 1) { lastMarkFileName = LAST_MARK_DEFAULT_NAME; } else { lastMarkFileName = LAST_MARK_DEFAULT_NAME + "." + journalIndex; } lastLogMark.readLog(); if (LOG.isDebugEnabled()) { LOG.debug("Last Log Mark : {}", lastLogMark.getCurMark()); } // Expose Stats journalAddEntryStats = statsLogger.getOpStatsLogger(BookKeeperServerStats.JOURNAL_ADD_ENTRY); journalForceLedgerStats = statsLogger.getOpStatsLogger(BookKeeperServerStats.JOURNAL_FORCE_LEDGER); journalSyncStats = statsLogger.getOpStatsLogger(BookKeeperServerStats.JOURNAL_SYNC); journalCreationStats = statsLogger.getOpStatsLogger(BookKeeperServerStats.JOURNAL_CREATION_LATENCY); journalFlushStats = statsLogger.getOpStatsLogger(BookKeeperServerStats.JOURNAL_FLUSH_LATENCY); journalQueueStats = statsLogger.getOpStatsLogger(BookKeeperServerStats.JOURNAL_QUEUE_LATENCY); journalProcessTimeStats = statsLogger.getOpStatsLogger(BookKeeperServerStats.JOURNAL_PROCESS_TIME_LATENCY); forceWriteGroupingCountStats = statsLogger.getOpStatsLogger(BookKeeperServerStats.JOURNAL_FORCE_WRITE_GROUPING_COUNT); forceWriteBatchEntriesStats = statsLogger.getOpStatsLogger(BookKeeperServerStats.JOURNAL_FORCE_WRITE_BATCH_ENTRIES); forceWriteBatchBytesStats = statsLogger.getOpStatsLogger(BookKeeperServerStats.JOURNAL_FORCE_WRITE_BATCH_BYTES); journalQueueSize = statsLogger.getCounter(BookKeeperServerStats.JOURNAL_QUEUE_SIZE); forceWriteQueueSize = statsLogger.getCounter(BookKeeperServerStats.JOURNAL_FORCE_WRITE_QUEUE_SIZE); journalCbQueueSize = statsLogger.getCounter(BookKeeperServerStats.JOURNAL_CB_QUEUE_SIZE); flushMaxWaitCounter = statsLogger.getCounter(BookKeeperServerStats.JOURNAL_NUM_FLUSH_MAX_WAIT); flushMaxOutstandingBytesCounter = statsLogger.getCounter(BookKeeperServerStats.JOURNAL_NUM_FLUSH_MAX_OUTSTANDING_BYTES); flushEmptyQueueCounter = statsLogger.getCounter(BookKeeperServerStats.JOURNAL_NUM_FLUSH_EMPTY_QUEUE); journalWriteBytes = statsLogger.getCounter(BookKeeperServerStats.JOURNAL_WRITE_BYTES); } public File getJournalDirectory() { return journalDirectory; } public LastLogMark getLastLogMark() { return lastLogMark; } /** * Application tried to schedule a checkpoint. After all the txns added * before checkpoint are persisted, a <i>checkpoint</i> will be returned * to application. Application could use <i>checkpoint</i> to do its logic. */ @Override public Checkpoint newCheckpoint() { return new LogMarkCheckpoint(lastLogMark.markLog()); } /** * Telling journal a checkpoint is finished. * * @throws IOException */ @Override public void checkpointComplete(Checkpoint checkpoint, boolean compact) throws IOException { if (!(checkpoint instanceof LogMarkCheckpoint)) { return; // we didn't create this checkpoint, so dont do anything with it } LogMarkCheckpoint lmcheckpoint = (LogMarkCheckpoint) checkpoint; LastLogMark mark = lmcheckpoint.mark; mark.rollLog(mark); if (compact) { // list the journals that have been marked List<Long> logs = listJournalIds(journalDirectory, new JournalRollingFilter(mark)); // keep MAX_BACKUP_JOURNALS journal files before marked journal if (logs.size() >= maxBackupJournals) { int maxIdx = logs.size() - maxBackupJournals; for (int i = 0; i < maxIdx; i++) { long id = logs.get(i); // make sure the journal id is smaller than marked journal id if (id < mark.getCurMark().getLogFileId()) { File journalFile = new File(journalDirectory, Long.toHexString(id) + ".txn"); if (!journalFile.delete()) { LOG.warn("Could not delete old journal file {}", journalFile); } LOG.info("garbage collected journal " + journalFile.getName()); } } } } } /** * Scan the journal. * * @param journalId Journal Log Id * @param journalPos Offset to start scanning * @param scanner Scanner to handle entries * @throws IOException */ public void scanJournal(long journalId, long journalPos, JournalScanner scanner) throws IOException { JournalChannel recLog; if (journalPos <= 0) { recLog = new JournalChannel(journalDirectory, journalId, journalPreAllocSize, journalWriteBufferSize); } else { recLog = new JournalChannel(journalDirectory, journalId, journalPreAllocSize, journalWriteBufferSize, journalPos); } int journalVersion = recLog.getFormatVersion(); try { ByteBuffer lenBuff = ByteBuffer.allocate(4); ByteBuffer recBuff = ByteBuffer.allocate(64 * 1024); while (true) { // entry start offset long offset = recLog.fc.position(); // start reading entry lenBuff.clear(); fullRead(recLog, lenBuff); if (lenBuff.remaining() != 0) { break; } lenBuff.flip(); int len = lenBuff.getInt(); if (len == 0) { break; } boolean isPaddingRecord = false; if (len == PADDING_MASK) { if (journalVersion >= JournalChannel.V5) { // skip padding bytes lenBuff.clear(); fullRead(recLog, lenBuff); if (lenBuff.remaining() != 0) { break; } lenBuff.flip(); len = lenBuff.getInt(); if (len == 0) { continue; } isPaddingRecord = true; } else { throw new IOException("Invalid record found with negative length : " + len); } } recBuff.clear(); if (recBuff.remaining() < len) { recBuff = ByteBuffer.allocate(len); } recBuff.limit(len); if (fullRead(recLog, recBuff) != len) { // This seems scary, but it just means that this is where we // left off writing break; } recBuff.flip(); if (!isPaddingRecord) { scanner.process(journalVersion, offset, recBuff); } } } finally { recLog.close(); } } /** * Replay journal files. * * @param scanner Scanner to process replayed entries. * @throws IOException */ public void replay(JournalScanner scanner) throws IOException { final LogMark markedLog = lastLogMark.getCurMark(); List<Long> logs = listJournalIds(journalDirectory, new JournalIdFilter() { @Override public boolean accept(long journalId) { if (journalId < markedLog.getLogFileId()) { return false; } return true; } }); // last log mark may be missed due to no sync up before // validate filtered log ids only when we have markedLogId if (markedLog.getLogFileId() > 0) { if (logs.size() == 0 || logs.get(0) != markedLog.getLogFileId()) { throw new IOException("Recovery log " + markedLog.getLogFileId() + " is missing"); } } if (LOG.isDebugEnabled()) { LOG.debug("Try to relay journal logs : {}", logs); } // TODO: When reading in the journal logs that need to be synced, we // should use BufferedChannels instead to minimize the amount of // system calls done. for (Long id: logs) { long logPosition = 0L; if (id == markedLog.getLogFileId()) { logPosition = markedLog.getLogFileOffset(); } LOG.info("Replaying journal {} from position {}", id, logPosition); scanJournal(id, logPosition, scanner); } } public void logAddEntry(ByteBuffer entry, boolean ackBeforeSync, WriteCallback cb, Object ctx) { logAddEntry(Unpooled.wrappedBuffer(entry), ackBeforeSync, cb, ctx); } /** * record an add entry operation in journal. */ public void logAddEntry(ByteBuf entry, boolean ackBeforeSync, WriteCallback cb, Object ctx) { long ledgerId = entry.getLong(entry.readerIndex() + 0); long entryId = entry.getLong(entry.readerIndex() + 8); logAddEntry(ledgerId, entryId, entry, ackBeforeSync, cb, ctx); } @VisibleForTesting void logAddEntry(long ledgerId, long entryId, ByteBuf entry, boolean ackBeforeSync, WriteCallback cb, Object ctx) { //Retain entry until it gets written to journal entry.retain(); journalQueueSize.inc(); queue.add(QueueEntry.create( entry, ackBeforeSync, ledgerId, entryId, cb, ctx, MathUtils.nowInNano(), journalAddEntryStats, journalQueueSize)); } void forceLedger(long ledgerId, WriteCallback cb, Object ctx) { journalQueueSize.inc(); queue.add(QueueEntry.create( null, false /* ackBeforeSync */, ledgerId, Bookie.METAENTRY_ID_FORCE_LEDGER, cb, ctx, MathUtils.nowInNano(), journalForceLedgerStats, journalQueueSize)); } /** * Get the length of journal entries queue. * * @return length of journal entry queue. */ public int getJournalQueueLength() { return queue.size(); } /** * A thread used for persisting journal entries to journal files. * * <p> * Besides persisting journal entries, it also takes responsibility of * rolling journal files when a journal file reaches journal file size * limitation. * </p> * <p> * During journal rolling, it first closes the writing journal, generates * new journal file using current timestamp, and continue persistence logic. * Those journals will be garbage collected in SyncThread. * </p> * @see org.apache.bookkeeper.bookie.SyncThread */ @Override public void run() { LOG.info("Starting journal on {}", journalDirectory); RecyclableArrayList<QueueEntry> toFlush = entryListRecycler.newInstance(); int numEntriesToFlush = 0; ByteBuf lenBuff = Unpooled.buffer(4); ByteBuf paddingBuff = Unpooled.buffer(2 * conf.getJournalAlignmentSize()); paddingBuff.writeZero(paddingBuff.capacity()); final int journalFormatVersionToWrite = conf.getJournalFormatVersionToWrite(); final int journalAlignmentSize = conf.getJournalAlignmentSize(); BufferedChannel bc = null; JournalChannel logFile = null; forceWriteThread.start(); Stopwatch journalCreationWatcher = Stopwatch.createUnstarted(); Stopwatch journalFlushWatcher = Stopwatch.createUnstarted(); long batchSize = 0; try { List<Long> journalIds = listJournalIds(journalDirectory, null); // Should not use MathUtils.now(), which use System.nanoTime() and // could only be used to measure elapsed time. // http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#nanoTime%28%29 long logId = journalIds.isEmpty() ? System.currentTimeMillis() : journalIds.get(journalIds.size() - 1); long lastFlushPosition = 0; boolean groupWhenTimeout = false; long dequeueStartTime = 0L; QueueEntry qe = null; while (true) { // new journal file to write if (null == logFile) { logId = logId + 1; journalCreationWatcher.reset().start(); logFile = new JournalChannel(journalDirectory, logId, journalPreAllocSize, journalWriteBufferSize, journalAlignmentSize, removePagesFromCache, journalFormatVersionToWrite, getBufferedChannelBuilder()); journalCreationStats.registerSuccessfulEvent( journalCreationWatcher.stop().elapsed(TimeUnit.NANOSECONDS), TimeUnit.NANOSECONDS); bc = logFile.getBufferedChannel(); lastFlushPosition = bc.position(); } if (qe == null) { if (dequeueStartTime != 0) { journalProcessTimeStats.registerSuccessfulEvent(MathUtils.elapsedNanos(dequeueStartTime), TimeUnit.NANOSECONDS); } if (numEntriesToFlush == 0) { qe = queue.take(); dequeueStartTime = MathUtils.nowInNano(); journalQueueStats.registerSuccessfulEvent(MathUtils.elapsedNanos(qe.enqueueTime), TimeUnit.NANOSECONDS); } else { long pollWaitTimeNanos = maxGroupWaitInNanos - MathUtils.elapsedNanos(toFlush.get(0).enqueueTime); if (flushWhenQueueEmpty || pollWaitTimeNanos < 0) { pollWaitTimeNanos = 0; } qe = queue.poll(pollWaitTimeNanos, TimeUnit.NANOSECONDS); dequeueStartTime = MathUtils.nowInNano(); if (qe != null) { journalQueueStats.registerSuccessfulEvent(MathUtils.elapsedNanos(qe.enqueueTime), TimeUnit.NANOSECONDS); } boolean shouldFlush = false; // We should issue a forceWrite if any of the three conditions below holds good // 1. If the oldest pending entry has been pending for longer than the max wait time if (maxGroupWaitInNanos > 0 && !groupWhenTimeout && (MathUtils .elapsedNanos(toFlush.get(0).enqueueTime) > maxGroupWaitInNanos)) { groupWhenTimeout = true; } else if (maxGroupWaitInNanos > 0 && groupWhenTimeout && qe != null && MathUtils.elapsedNanos(qe.enqueueTime) < maxGroupWaitInNanos) { // when group timeout, it would be better to look forward, as there might be lots of // entries already timeout // due to a previous slow write (writing to filesystem which impacted by force write). // Group those entries in the queue // a) already timeout // b) limit the number of entries to group groupWhenTimeout = false; shouldFlush = true; flushMaxWaitCounter.inc(); } else if (qe != null && ((bufferedEntriesThreshold > 0 && toFlush.size() > bufferedEntriesThreshold) || (bc.position() > lastFlushPosition + bufferedWritesThreshold))) { // 2. If we have buffered more than the buffWriteThreshold or bufferedEntriesThreshold shouldFlush = true; flushMaxOutstandingBytesCounter.inc(); } else if (qe == null) { // We should get here only if we flushWhenQueueEmpty is true else we would wait // for timeout that would put is past the maxWait threshold // 3. If the queue is empty i.e. no benefit of grouping. This happens when we have one // publish at a time - common case in tests. shouldFlush = true; flushEmptyQueueCounter.inc(); } // toFlush is non null and not empty so should be safe to access getFirst if (shouldFlush) { if (journalFormatVersionToWrite >= JournalChannel.V5) { writePaddingBytes(logFile, paddingBuff, journalAlignmentSize); } journalFlushWatcher.reset().start(); bc.flush(); for (int i = 0; i < toFlush.size(); i++) { QueueEntry entry = toFlush.get(i); if (entry != null && (!syncData || entry.ackBeforeSync)) { toFlush.set(i, null); numEntriesToFlush--; cbThreadPool.execute(entry); } } lastFlushPosition = bc.position(); journalFlushStats.registerSuccessfulEvent( journalFlushWatcher.stop().elapsed(TimeUnit.NANOSECONDS), TimeUnit.NANOSECONDS); // Trace the lifetime of entries through persistence if (LOG.isDebugEnabled()) { for (QueueEntry e : toFlush) { if (e != null) { LOG.debug("Written and queuing for flush Ledger: {} Entry: {}", e.ledgerId, e.entryId); } } } forceWriteBatchEntriesStats.registerSuccessfulValue(numEntriesToFlush); forceWriteBatchBytesStats.registerSuccessfulValue(batchSize); boolean shouldRolloverJournal = (lastFlushPosition > maxJournalSize); if (syncData) { // Trigger data sync to disk in the "Force-Write" thread. // Callback will be triggered after data is committed to disk forceWriteRequests.put(createForceWriteRequest(logFile, logId, lastFlushPosition, toFlush, shouldRolloverJournal, false)); toFlush = entryListRecycler.newInstance(); numEntriesToFlush = 0; } else { // Data is already written on the file (though it might still be in the OS page-cache) lastLogMark.setCurLogMark(logId, lastFlushPosition); toFlush.clear(); numEntriesToFlush = 0; if (shouldRolloverJournal) { forceWriteRequests.put( createForceWriteRequest( logFile, logId, lastFlushPosition, EMPTY_ARRAY_LIST, shouldRolloverJournal, false)); } } batchSize = 0L; // check whether journal file is over file limit if (shouldRolloverJournal) { // if the journal file is rolled over, the journal file will be closed after last // entry is force written to disk. the `bc` is not used anymore, so close it to release // the buffers in `bc`. IOUtils.close(LOG, bc); logFile = null; continue; } } } } if (!running) { LOG.info("Journal Manager is asked to shut down, quit."); break; } if (qe == null) { // no more queue entry continue; } if (qe.entryId != Bookie.METAENTRY_ID_FORCE_LEDGER) { int entrySize = qe.entry.readableBytes(); journalWriteBytes.add(entrySize); journalQueueSize.dec(); batchSize += (4 + entrySize); lenBuff.clear(); lenBuff.writeInt(entrySize); // preAlloc based on size logFile.preAllocIfNeeded(4 + entrySize); bc.write(lenBuff); bc.write(qe.entry); qe.entry.release(); } toFlush.add(qe); numEntriesToFlush++; qe = null; } } catch (IOException ioe) { LOG.error("I/O exception in Journal thread!", ioe); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); LOG.warn("Journal exits when shutting down", ie); } finally { // There could be packets queued for forceWrite on this logFile // That is fine as this exception is going to anyway take down the // the bookie. If we execute this as a part of graceful shutdown, // close will flush the file system cache making any previous // cached writes durable so this is fine as well. IOUtils.close(LOG, bc); IOUtils.close(LOG, logFile); } LOG.info("Journal exited loop!"); } public BufferedChannelBuilder getBufferedChannelBuilder() { return BufferedChannelBuilder.DEFAULT_BCBUILDER; } /** * Shuts down the journal. */ public synchronized void shutdown() { try { if (!running) { return; } LOG.info("Shutting down Journal"); forceWriteThread.shutdown(); cbThreadPool.shutdown(); if (!cbThreadPool.awaitTermination(5, TimeUnit.SECONDS)) { LOG.warn("Couldn't shutdown journal callback thread gracefully. Forcing"); } cbThreadPool.shutdownNow(); running = false; this.interrupt(); this.join(); LOG.info("Finished Shutting down Journal thread"); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); LOG.warn("Interrupted during shutting down journal : ", ie); } } private static int fullRead(JournalChannel fc, ByteBuffer bb) throws IOException { int total = 0; while (bb.remaining() > 0) { int rc = fc.read(bb); if (rc <= 0) { return total; } total += rc; } return total; } // /** * Wait for the Journal thread to exit. * This is method is needed in order to mock the journal, we can't mock final method of java.lang.Thread class * * @throws InterruptedException */ @VisibleForTesting public void joinThread() throws InterruptedException { join(); } }
apache-2.0
liquid-mind/warp
src/main/internal/java/ch/shaktipat/saraswati/internal/pobject/PersistentProcess.java
4272
package ch.shaktipat.saraswati.internal.pobject; import java.security.Principal; import java.util.Set; import java.util.Stack; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; import ch.shaktipat.saraswati.common.Event; import ch.shaktipat.saraswati.internal.pobject.PersistentProcessImpl.VolatilityChangeType; import ch.shaktipat.saraswati.internal.pobject.aux.pprocess.PFrame; import ch.shaktipat.saraswati.internal.pobject.aux.pprocess.PProcessExecutionSegment; import ch.shaktipat.saraswati.internal.pobject.aux.pprocess.PProcessExecutionSegmentResult; import ch.shaktipat.saraswati.internal.pobject.aux.pprocess.PProcessPMethodCommunicationArea; import ch.shaktipat.saraswati.pobject.oid.PEventQueueOID; import ch.shaktipat.saraswati.pobject.oid.PEventTopicOID; import ch.shaktipat.saraswati.pobject.oid.POwnableObjectOID; import ch.shaktipat.saraswati.pobject.oid.PProcessOID; import ch.shaktipat.saraswati.volatility.VolatileResource; import ch.shaktipat.saraswati.volatility.Volatility; public interface PersistentProcess extends PersistentObject { // Shared with external @Override public PProcessOID getOID(); public String[] getStates(); public String[] getLeafStates(); public Principal getOwningPrincipal(); public StackTraceElement[] getStackTrace(); public void setCheckpoint(); public boolean getDestroyOnCompletion(); public boolean getAutoCheckpointing(); public UUID subscribe( PEventQueueOID targetQueueOID, String filterExpr, boolean singleEventSubscription ); public boolean unsubscribe( UUID subscriptionID ); public void send( Event event ); // Volatility methods public Volatility getInitialVolatility(); public void setInitialVolatility( Volatility initialVolatility ); public VolatileResource createVolatileResource(); public VolatileResource destroyVolatileResource(); public Volatility getVolatility(); public Volatility getVolatileResourcesVolatility(); // Internal public Set< POwnableObjectOID > getOwnableObjectOIDs(); public void addOwnableObjectOID( POwnableObjectOID ownableObjectOID ); public void removeOwnableObjectOID( POwnableObjectOID ownableObjectOID ); public ReadLock getExecutionStateReadLock(); public WriteLock getExecutionStateWriteLock(); public Runnable getRunnable(); public Callable< ? > getCallable(); public PProcessOID getParentOID(); public Stack< PProcessExecutionSegment > getpProcessExecutionSegmentStack(); public PProcessExecutionSegmentResult getpProcessExecutionSegmentResult(); public Set< PProcessOID > getChildOIDs(); public void addChildOID( PProcessOID childOID ); public void fireEvent( String event ); public boolean isInState( String state ); public boolean getRequestedSuspension(); public void setRequestSuspension( boolean requestSuspension ); public boolean getRequestCancellation(); public void setRequestCancellation( boolean requestCancellation ); public void notifyVolatilityChange( VolatilityChangeType changeType ); @Override public PersistentProcess getSelfProxy(); @Override public PersistentProcess getOtherProxy(); public String getSystemLog(); public void setSystemLog( String systemLog ); public String getApplicationLog(); public void setApplicationLog( String applicationLog ); public void setupInitialVolatilityActual( Volatility currentVolatility ); // Internal (execution) public void startProcess( Volatility currentVolatility ); public void terminateProcess( Throwable t ); public void handleEvent( Event event ); public void handleEventPrepareProcessToContinue( Event event ); public void resumeProcess(); public void invokeTestMethod( Volatility currentVolatility, String testClassName, String methodName, Class< ? >[] paramTypes, Object[] params ); public PProcessExecutionSegmentResult invokeStaticIntializer( Class< ? > theClass ) throws ClassNotFoundException; public void setLineNumber( int lineNumber ); public PFrame getCurrentPFrame(); public PProcessPMethodCommunicationArea getPProcessPMethodCommunicationArea(); public PEventQueueOID getEventQueueOID(); public PEventTopicOID getEventTopicOID(); public void checkForSuspensionOrCancellation(); }
apache-2.0
satoshi-kimura/samurai-dao
src/main/java/jp/dodododo/dao/util/PreparedStatementUtil.java
2083
package jp.dodododo.dao.util; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import jp.dodododo.dao.config.DaoConfig; import jp.dodododo.dao.exception.SQLRuntimeException; import jp.dodododo.dao.log.SlowQuery; import jp.dodododo.dao.log.SqlLogRegistry; /** * * @author Satoshi Kimura */ public abstract class PreparedStatementUtil extends StatementUtil { public static int executeUpdate(PreparedStatement ps) { return executeUpdate(ps, null); } public static int executeUpdate(PreparedStatement ps, SqlLogRegistry sqlLogRegistry) { try { int ret = ps.executeUpdate(); return ret; } catch (SQLException e) { throw new SQLRuntimeException(sqlLogRegistry.getLast().getCompleteSql(), e); } } public static void addBatch(PreparedStatement ps) { addBatch(ps, null); } public static void addBatch(PreparedStatement ps, SqlLogRegistry sqlLogRegistry) { try { ps.addBatch(); } catch (SQLException e) { throw new SQLRuntimeException(sqlLogRegistry.getLast().getCompleteSql(), e); } } public static int[] executeBatch(PreparedStatement ps) { return executeBatch(ps, null); } public static int[] executeBatch(PreparedStatement ps, SqlLogRegistry sqlLogRegistry) { try { int[] ret = ps.executeBatch(); return ret; } catch (SQLException e) { throw new SQLRuntimeException(sqlLogRegistry.getLast().getCompleteSql(), e); } } public static ResultSet executeQuery(PreparedStatement ps) { return executeQuery(ps, null); } public static ResultSet executeQuery(PreparedStatement ps, SqlLogRegistry sqlLogRegistry) { try { double start = System.currentTimeMillis(); ResultSet resultSet = ps.executeQuery(); double end = System.currentTimeMillis(); double time = (end - start) / 1000D; if (DaoConfig.getDefaultConfig().getLongQuerySeconds() < time) { SlowQuery.warn(time, sqlLogRegistry.getLast().getCompleteSql()); } return resultSet; } catch (SQLException e) { throw new SQLRuntimeException(sqlLogRegistry.getLast().getCompleteSql(), e); } } }
apache-2.0
NovaOrdis/playground
algorithms/insertion-sort/src/main/java/io/novaordis/playground/algorithms/insertionsort/Configuration.java
653
package io.novaordis.playground.algorithms.insertionsort; import java.util.ArrayList; import java.util.List; /** * @author Ovidiu Feodorov <ovidiu@swim.ai> * @since 6/3/18 */ public class Configuration { List<Integer> list = new ArrayList<>(); public Configuration(String[] args) { for(String s: args) { int i = Integer.parseInt(s); list.add(i); } } public int[] getArray() { int[] result = new int[list.size()]; int index = 0; for(Integer i: list) { result[index] = list.get(index); index ++; } return result; } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-iot1clickprojects/src/main/java/com/amazonaws/services/iot1clickprojects/model/transform/DescribeProjectRequestProtocolMarshaller.java
2677
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.iot1clickprojects.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.iot1clickprojects.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * DescribeProjectRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DescribeProjectRequestProtocolMarshaller implements Marshaller<Request<DescribeProjectRequest>, DescribeProjectRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON).requestUri("/projects/{projectName}") .httpMethodName(HttpMethodName.GET).hasExplicitPayloadMember(false).hasPayloadMembers(false).serviceName("AWSIoT1ClickProjects").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public DescribeProjectRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<DescribeProjectRequest> marshall(DescribeProjectRequest describeProjectRequest) { if (describeProjectRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<DescribeProjectRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, describeProjectRequest); protocolMarshaller.startMarshalling(); DescribeProjectRequestMarshaller.getInstance().marshall(describeProjectRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
moreus/hadoop
hadoop-0.23.10/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/CompletedTaskAttempt.java
5235
/** * 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.mapreduce.v2.hs; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.mapreduce.Counters; import org.apache.hadoop.mapreduce.TypeConverter; import org.apache.hadoop.mapreduce.jobhistory.JobHistoryParser.TaskAttemptInfo; import org.apache.hadoop.mapreduce.v2.api.records.Phase; import org.apache.hadoop.mapreduce.v2.api.records.TaskAttemptId; import org.apache.hadoop.mapreduce.v2.api.records.TaskAttemptReport; import org.apache.hadoop.mapreduce.v2.api.records.TaskAttemptState; import org.apache.hadoop.mapreduce.v2.api.records.TaskId; import org.apache.hadoop.mapreduce.v2.app.job.TaskAttempt; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.util.Records; public class CompletedTaskAttempt implements TaskAttempt { private final TaskAttemptInfo attemptInfo; private final TaskAttemptId attemptId; private final TaskAttemptState state; private final List<String> diagnostics = new ArrayList<String>(); private TaskAttemptReport report; private String localDiagMessage; CompletedTaskAttempt(TaskId taskId, TaskAttemptInfo attemptInfo) { this.attemptInfo = attemptInfo; this.attemptId = TypeConverter.toYarn(attemptInfo.getAttemptId()); if (attemptInfo.getTaskStatus() != null) { this.state = TaskAttemptState.valueOf(attemptInfo.getTaskStatus()); } else { this.state = TaskAttemptState.KILLED; localDiagMessage = "Attmpt state missing from History : marked as KILLED"; diagnostics.add(localDiagMessage); } if (attemptInfo.getError() != null) { diagnostics.add(attemptInfo.getError()); } } @Override public ContainerId getAssignedContainerID() { return attemptInfo.getContainerId(); } @Override public String getAssignedContainerMgrAddress() { return attemptInfo.getHostname() + ":" + attemptInfo.getPort(); } @Override public String getNodeHttpAddress() { return attemptInfo.getTrackerName() + ":" + attemptInfo.getHttpPort(); } @Override public String getNodeRackName() { return attemptInfo.getRackname(); } @Override public Counters getCounters() { return attemptInfo.getCounters(); } @Override public TaskAttemptId getID() { return attemptId; } @Override public float getProgress() { return 1.0f; } @Override public synchronized TaskAttemptReport getReport() { if (report == null) { constructTaskAttemptReport(); } return report; } @Override public Phase getPhase() { return Phase.CLEANUP; } @Override public TaskAttemptState getState() { return state; } @Override public boolean isFinished() { return true; } @Override public List<String> getDiagnostics() { return diagnostics; } @Override public long getLaunchTime() { return attemptInfo.getStartTime(); } @Override public long getFinishTime() { return attemptInfo.getFinishTime(); } @Override public long getShuffleFinishTime() { return attemptInfo.getShuffleFinishTime(); } @Override public long getSortFinishTime() { return attemptInfo.getSortFinishTime(); } @Override public int getShufflePort() { return attemptInfo.getShufflePort(); } private void constructTaskAttemptReport() { report = Records.newRecord(TaskAttemptReport.class); report.setTaskAttemptId(attemptId); report.setTaskAttemptState(state); report.setProgress(getProgress()); report.setStartTime(attemptInfo.getStartTime()); report.setFinishTime(attemptInfo.getFinishTime()); report.setShuffleFinishTime(attemptInfo.getShuffleFinishTime()); report.setSortFinishTime(attemptInfo.getSortFinishTime()); if (localDiagMessage != null) { report .setDiagnosticInfo(attemptInfo.getError() + ", " + localDiagMessage); } else { report.setDiagnosticInfo(attemptInfo.getError()); } // report.setPhase(attemptInfo.get); //TODO report.setStateString(attemptInfo.getState()); report.setCounters(TypeConverter.toYarn(getCounters())); report.setContainerId(attemptInfo.getContainerId()); if (attemptInfo.getHostname() == null) { report.setNodeManagerHost("UNKNOWN"); } else { report.setNodeManagerHost(attemptInfo.getHostname()); report.setNodeManagerPort(attemptInfo.getPort()); } report.setNodeManagerHttpPort(attemptInfo.getHttpPort()); } }
apache-2.0
jimsimon/gson-provider
src/main/java/com/fenix/rs/GsonJSONProvider.java
2298
package com.fenix.rs; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @Provider @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public final class GsonJSONProvider implements MessageBodyWriter<Object>, MessageBodyReader<Object> { private static final String UTF_8 = "UTF-8"; private Gson gson; private Gson getGson() { if (gson == null) { final GsonBuilder gsonBuilder = new GsonBuilder(); gson = gsonBuilder.create(); } return gson; } @Override public boolean isReadable(Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType) { return true; } @Override public Object readFrom(Class<Object> clazz, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException { try (InputStreamReader streamReader = new InputStreamReader(entityStream, UTF_8)) { return getGson().fromJson(streamReader, type); } } @Override public boolean isWriteable(Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType) { return true; } @Override public long getSize(Object object, Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType) { return -1; } @Override public void writeTo(Object object, Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws UnsupportedEncodingException, IOException { try (OutputStreamWriter writer = new OutputStreamWriter(entityStream, UTF_8)) { getGson().toJson(object, type, writer); } } }
apache-2.0
Chaklader/RESTful-Spring-Apache-Cxf
src/main/java/mobi/puut/entities/User.java
1946
package mobi.puut.entities; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.HashSet; import java.util.Set; /** * Created by Chaklader on 6/13/17. */ @Entity @Table(name = "users") public class User { @Id @Column(name = "id", unique = true, nullable = false) @NotNull @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @NotNull @Column(name = "name") @Size(min = 5, max = 45, message = "Name must be between 5 and 45 characters.") private String name; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "user_id") Set<Status> statuses = new HashSet<Status>(0); public User() { } public User(int id, String name) { super(); this.id = id; this.name = name; } public User(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Status> getStatuses() { return statuses; } public void setStatuses(Set<Status> statuses) { this.statuses = statuses; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof User)) return false; User user = (User) o; if (getId() != user.getId()) return false; return getName().equals(user.getName()); } @Override public int hashCode() { int result = getId(); result = 31 * result + getName().hashCode(); return result; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
apache-2.0
googleapis/api-compiler
src/main/java/com/google/api/tools/framework/model/Location.java
1087
/* * Copyright (C) 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.tools.framework.model; /** * An abstraction of a source location. */ public interface Location { /** * Get the location as a string readable to users and interpretable by IDEs. The actual * semantics depends on the underlying source type. This may or not be the same as * toString(). */ String getDisplayString(); /** * Get the name of the containing entity of this location, in most cases its a file name. */ String getContainerName(); }
apache-2.0
Swapnil133609/Zeus-Controls
app/src/main/java/com/swapnil133609/zeuscontrols/utils/root/LinuxUtils.java
3222
/* * Copyright (C) 2015 Willi Ye * * 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.swapnil133609.zeuscontrols.utils.root; import java.io.IOException; import java.io.RandomAccessFile; /** * This code is from http://stackoverflow.com/a/13342738 */ public class LinuxUtils { /** * Return the first line of /proc/stat or null if failed. */ public String readSystemStat() { try { RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r"); String value = reader.readLine(); reader.close(); return value; } catch (IOException e) { e.printStackTrace(); } return null; } /** * Compute and return the total CPU usage, in percent. * * @param start first content of /proc/stat. Not null. * @param end second content of /proc/stat. Not null. * @return the CPU use in percent, or -1f if the stats are inverted or on * error * @see {@link #readSystemStat()} */ public float getSystemCpuUsage(String start, String end) { String[] stat = start.split(" "); long idle1 = getSystemIdleTime(stat); long up1 = getSystemUptime(stat); stat = end.split(" "); long idle2 = getSystemIdleTime(stat); long up2 = getSystemUptime(stat); // don't know how it is possible but we should care about zero and // negative values. float cpu = -1f; if (idle1 >= 0 && up1 >= 0 && idle2 >= 0 && up2 >= 0) { if ((up2 + idle2) > (up1 + idle1) && up2 >= up1) { cpu = (up2 - up1) / (float) ((up2 + idle2) - (up1 + idle1)); cpu *= 100.0f; } } return cpu; } /** * Return the sum of uptimes read from /proc/stat. * * @param stat see {@link #readSystemStat()} */ public long getSystemUptime(String[] stat) { long l = 0L; for (int i = 2; i < stat.length; i++) { if (i != 5) { // bypass any idle mode. There is currently only one. try { l += Long.parseLong(stat[i]); } catch (NumberFormatException e) { e.printStackTrace(); return -1L; } } } return l; } /** * Return the sum of idle times read from /proc/stat. * * @param stat see {@link #readSystemStat()} */ public long getSystemIdleTime(String[] stat) { try { return Long.parseLong(stat[5]); } catch (NumberFormatException e) { e.printStackTrace(); } return -1L; } }
apache-2.0
Salamahin/teamnotifier
src/main/java/com/home/teamnotifier/core/responses/status/EnvironmentInfo.java
1531
package com.home.teamnotifier.core.responses.status; import com.fasterxml.jackson.annotation.*; import com.google.common.collect.ImmutableList; import java.util.List; import java.util.Objects; @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonAutoDetect( fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.NONE) @JsonTypeName("EnvironmentInfo") public class EnvironmentInfo { private final String name; private final List<ServerInfo> servers; @JsonCreator public EnvironmentInfo( @JsonProperty("name") final String name, @JsonProperty("servers") final List<ServerInfo> servers ) { this.name = name; this.servers = ImmutableList.copyOf(servers); } @Override public int hashCode() { return Objects.hash(name, servers); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final EnvironmentInfo that = (EnvironmentInfo) o; return Objects.equals(name, that.name) && Objects.equals(servers, that.servers); } }
apache-2.0
JAVA201708/Homework
201708/20170828/Team1/Malanlan/examples/ex01/Data.java
635
import java.util.Scanner; public class Data { public static void main (String[]args) { Scanner sc=new Scanner(System.in); int [] data = {8,4,2,1,23,344,12}; int sum=0; int i; for(i=0;i<data.length;i++) { System.out.println(data[i]); sum+=data[i]; } System.out.println("数据之和"+sum); System.out.println("请输入一个数据:"); int a=sc.nextInt(); for(i=0;i<data.length;i++) { if(a==data[i]) { System.out.println("包含此数"); break; } else if(i==data.length-1) { System.out.println("不包含"); } } sc.close(); } }
apache-2.0
leafclick/intellij-community
plugins/devkit/devkit-core/src/navigation/LineMarkerInfoHelper.java
4926
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.devkit.navigation; import com.intellij.codeInsight.daemon.RelatedItemLineMarkerInfo; import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder; import com.intellij.navigation.GotoRelatedItem; import com.intellij.openapi.editor.markup.GutterIconRenderer; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.xml.XmlTag; import com.intellij.ui.ColorUtil; import com.intellij.util.NotNullFunction; import com.intellij.util.NullableFunction; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import icons.DevkitIcons; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.PropertyKey; import org.jetbrains.idea.devkit.DevKitBundle; import org.jetbrains.idea.devkit.util.PointableCandidate; import java.text.MessageFormat; import java.util.Collection; import java.util.List; class LineMarkerInfoHelper { private static final NotNullFunction<PointableCandidate, Collection<? extends PsiElement>> CONVERTER = candidate -> ContainerUtil.createMaybeSingletonList(candidate.pointer.getElement()); private static final NotNullFunction<PointableCandidate, Collection<? extends GotoRelatedItem>> RELATED_ITEM_PROVIDER = candidate -> GotoRelatedItem.createItems(ContainerUtil.createMaybeSingletonList(candidate.pointer.getElement()), "DevKit"); private static final NullableFunction<PointableCandidate, String> EXTENSION_NAMER = createNamer("line.marker.tooltip.extension.declaration", XmlTag::getName); private static final NullableFunction<PointableCandidate, String> EXTENSION_POINT_NAMER = createNamer("line.marker.tooltip.extension.point.declaration", tag -> { String name = tag.getAttributeValue("name"); if (StringUtil.isEmpty(name)) { // shouldn't happen, just for additional safety name = "Extension Point"; } return name; }); private static final String MODULE_SUFFIX_PATTERN = " <font color='" + ColorUtil.toHex(UIUtil.getInactiveTextColor()) + "'>[{0}]</font>"; private LineMarkerInfoHelper() { } @NotNull static RelatedItemLineMarkerInfo<PsiElement> createExtensionLineMarkerInfo(@NotNull List<? extends PointableCandidate> targets, @NotNull PsiElement element) { return createPluginLineMarkerInfo(targets, element, "Choose Extension", EXTENSION_NAMER); } @NotNull static RelatedItemLineMarkerInfo<PsiElement> createExtensionPointLineMarkerInfo(@NotNull List<? extends PointableCandidate> targets, @NotNull PsiElement element) { return createPluginLineMarkerInfo(targets, element, "Choose Extension Point", EXTENSION_POINT_NAMER); } @NotNull private static RelatedItemLineMarkerInfo<PsiElement> createPluginLineMarkerInfo(@NotNull List<? extends PointableCandidate> targets, @NotNull PsiElement element, String popup, NullableFunction<PointableCandidate, String> namer) { return NavigationGutterIconBuilder .create(DevkitIcons.Gutter.Plugin, CONVERTER, RELATED_ITEM_PROVIDER) .setTargets(targets) .setPopupTitle(popup) .setNamer(namer) .setAlignment(GutterIconRenderer.Alignment.RIGHT) .createLineMarkerInfo(element); } @NotNull private static NullableFunction<PointableCandidate, String> createNamer(@PropertyKey(resourceBundle = DevKitBundle.BUNDLE) String tooltipPatternPropertyName, NotNullFunction<? super XmlTag, String> nameProvider) { return target -> { XmlTag tag = target.pointer.getElement(); if (tag == null) { // shouldn't happen throw new NullPointerException("Null element for pointable candidate: " + target); } PsiFile file = tag.getContainingFile(); String path = file.getVirtualFile().getPath(); String fileDisplayName = file.getName(); Module module = ModuleUtilCore.findModuleForPsiElement(file); if (module != null) { fileDisplayName += MessageFormat.format(MODULE_SUFFIX_PATTERN, module.getName()); } return DevKitBundle.message(tooltipPatternPropertyName, path, String.valueOf(tag.getTextRange().getStartOffset()), nameProvider.fun(tag), fileDisplayName); }; } }
apache-2.0
ChiralBehaviors/Kramer
explorer/src/main/java/com/chiralbehaviors/layout/explorer/AutoLayoutExplorer.java
1749
/** * Copyright (c) 2016 Chiral Behaviors, LLC, 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.chiralbehaviors.layout.explorer; import java.io.IOException; import com.chiralbehaviors.utils.Utils; import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; /** * A class to allow me to explore the autolayout. I hate UIs. * * @author hhildebrand * */ public class AutoLayoutExplorer extends Application { public static void main(String[] args) { launch(args); } public void initRootLayout(Stage primaryStage) throws IOException { QueryState queryState = new QueryState(); queryState.setTargetURL("http://localhost:5000/api/workspace/pNi_Y_WJVqO-vMMjaicSNw"); queryState.setQuery(Utils.getDocument(getClass().getResourceAsStream("/testQuery.gql"))); queryState.setSelection("workspaces"); AutoLayoutController controller = new AutoLayoutController(queryState); primaryStage.setScene(new Scene(controller.getRoot(), 800, 800)); primaryStage.show(); } @Override public void start(Stage primaryStage) throws IOException { initRootLayout(primaryStage); } }
apache-2.0
w4tson/blackfriar
blackfriar-web/src/test/java/com/blackfriar/controllers/GithubControllerTest.java
2123
package com.blackfriar.controllers; import com.blackfriar.config.TestConfig; import com.blackfriar.github.GithubClient; import com.blackfriar.github.dto.GithubUser; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.hateoas.MediaTypes; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.hamcrest.CoreMatchers.is; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @WebAppConfiguration @ContextConfiguration(classes = { TestConfig.class, GithubController.class}) public class GithubControllerTest { @MockBean GithubClient githubClient; @Autowired private WebApplicationContext ctx; private MockMvc mockMvc; @Before public void setup() { mockMvc = MockMvcBuilders.webAppContextSetup(this.ctx).build(); } @Test public void getUser() throws Exception { when(githubClient.getUser("bfb")).thenReturn(new GithubUser("bfb", "london")); this.mockMvc.perform(MockMvcRequestBuilders .get("/api/github/user/bfb") .accept(MediaTypes.HAL_JSON)) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.login", is("bfb"))) .andExpect(jsonPath("$.location", is("london"))); } }
apache-2.0
djays123/KTrack
src/main/java/ktrack/ui/DogsList.java
757
package ktrack.ui; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.wicketstuff.annotation.mount.MountPath; import ktrack.repository.DogNamesRepository; import ktrack.repository.DogRepository; import ktrack.ui.panels.DogListPanel; @MountPath("/dogs") public class DogsList extends BaseAuthenticatedPage { @SpringBean private DogRepository dogRepository; @SpringBean private DogNamesRepository dogNamesRepository; /** * The default constructor. * * @param pageParams */ public DogsList(PageParameters pageParams) { super(pageParams); add(new DogListPanel("dog-list-panel", null).setRenderBodyOnly(true)); } }
apache-2.0
voyagersearch/quickstart-java
src/main/java/voyager/quickstart/placefinder/XmlStreamPlacefinder.java
11882
package voyager.quickstart.placefinder; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.SAXParserFactory; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.apache.commons.lang.StringEscapeUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.solr.common.util.XMLErrorLogger; import org.apache.solr.util.EmptyEntityResolver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import voyager.api.placefinder.PlaceResult; import voyager.api.placefinder.PlaceSearch; import voyager.api.placefinder.Placefinder; import voyager.api.placefinder.PlacefinderFactory; import voyager.api.placefinder.PlacefinderSettings; import voyager.common.http.VoyagerHttpClient; import com.google.common.base.Charsets; import com.google.common.base.Strings; import com.google.common.hash.HashCode; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; import com.spatial4j.core.context.SpatialContext; import com.spatial4j.core.context.jts.JtsSpatialContext; public class XmlStreamPlacefinder extends Placefinder implements ResponseHandler<List<PlaceResult>> { static final Logger log = LoggerFactory.getLogger(XmlStreamPlacefinder.class); static final XMLErrorLogger xmllog = new XMLErrorLogger(log); @Component public static class Factory implements PlacefinderFactory { public static final String URL = "url"; public static final String NODE = "node"; public static final String LAT = "lat"; public static final String LON = "lon"; public static final String PLACE_NAME = "place_name"; public static final String PLACE_NAME_EXT = "place_name_ext"; @Override public String getName() { return "XmlStream"; } @Override public String getTitle() { return "Get place from XML Request"; } @Override public String getDescription() { return "This placefinder will parse XML results from the configured URL. Note the {query} in the URL template setting"; } @Override public PlacefinderSettings createInitialSettings() { PlacefinderSettings settings = new PlacefinderSettings().type(getName()).threshold(0.4f).enabled(false); settings.put(URL, "http://geonames.nga.mil/nameswfs/service.svc/get?SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=GEONAMES&FILTER=%3CFilter%20xmlns%3D%22http%3A%2F%2Fwww.opengis.net%2Fogc%22%3E%3CAnd%3E%3CPropertyIsLike%20wildCard%3D%22*%22%20singleChar%3D%22_%22%20escapeChar%3D%22%5C%22%3E%3CPropertyName%3ENAME%3C%2FPropertyName%3E%3CLiteral%3E{query}*%3C%2FLiteral%3E%3C%2FPropertyIsLike%3E%3CPropertyIsLike%20wildCard%3D%22*%22%20singleChar%3D%22_%22%20escapeChar%3D%22%5C%22%3E%3CPropertyName%3EFEATURE_DESIGNATION_CODE%3C%2FPropertyName%3E%3CLiteral%3EPPL*%3C%2FLiteral%3E%3C%2FPropertyIsLike%3E%3C%2FAnd%3E%3C%2FFilter%3E"); settings.put(NODE, "GEONAMES"); settings.put(LAT, "LATITUDE_DD"); settings.put(LON, "LONGITUDE_DD"); settings.put(PLACE_NAME, "NAME"); settings.put(PLACE_NAME_EXT, "PRIMARY_ADMIN_DIVISION"); return settings; } @Override public XmlStreamPlacefinder create(PlacefinderSettings settings) { return new XmlStreamPlacefinder(settings); } } protected static final SpatialContext CTX = JtsSpatialContext.GEO; final XMLInputFactory inputFactory; final SAXParserFactory saxFactory; protected final String param_url; protected final String param_node; protected final String param_lat; protected final String param_lon; protected final String param_place_name; protected final String param_place_name_ext; public XmlStreamPlacefinder(PlacefinderSettings settings) { super(settings); param_url = (String)settings.get(Factory.URL); //, "http://geonames.nga.mil/nameswfs/service.svc/get?SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=GEONAMES&FILTER=%3CFilter%20xmlns%3D%22http%3A%2F%2Fwww.opengis.net%2Fogc%22%3E%3CAnd%3E%3CPropertyIsLike%20wildCard%3D%22*%22%20singleChar%3D%22_%22%20escapeChar%3D%22%5C%22%3E%3CPropertyName%3ENAME%3C%2FPropertyName%3E%3CLiteral%3E{query}*%3C%2FLiteral%3E%3C%2FPropertyIsLike%3E%3CPropertyIsLike%20wildCard%3D%22*%22%20singleChar%3D%22_%22%20escapeChar%3D%22%5C%22%3E%3CPropertyName%3EFEATURE_DESIGNATION_CODE%3C%2FPropertyName%3E%3CLiteral%3EPPL*%3C%2FLiteral%3E%3C%2FPropertyIsLike%3E%3C%2FAnd%3E%3C%2FFilter%3E"); param_node = (String)settings.get(Factory.NODE); //, "GEONAMES"); param_lat = (String)settings.get(Factory.LAT); //, "LATITUDE_DD"); param_lon = (String)settings.get(Factory.LON); //, "LONGITUDE_DD"); param_place_name = (String)settings.get(Factory.PLACE_NAME); //, "NAME"); param_place_name_ext = (String)settings.get(Factory.PLACE_NAME_EXT); //, "PRIMARY_ADMIN_DIVISION"); // Init StAX parser: inputFactory = XMLInputFactory.newInstance(); EmptyEntityResolver.configureXMLInputFactory(inputFactory); inputFactory.setXMLReporter(xmllog); try { // The java 1.6 bundled stax parser (sjsxp) does not currently have a thread-safe // XMLInputFactory, as that implementation tries to cache and reuse the // XMLStreamReader. Setting the parser-specific "reuse-instance" property to false // prevents this. // All other known open-source stax parsers (and the bea ref impl) // have thread-safe factories. inputFactory.setProperty("reuse-instance", Boolean.FALSE); } catch (IllegalArgumentException ex) { // Other implementations will likely throw this exception since "reuse-instance" // isimplementation specific. log.debug("Unable to set the 'reuse-instance' property for the input chain: " + inputFactory); } // Init SAX parser (for XSL): saxFactory = SAXParserFactory.newInstance(); saxFactory.setNamespaceAware(false); EmptyEntityResolver.configureSAXParserFactory(saxFactory); } @Override public boolean matches(CharSequence text) { return true; // do this for everything } @Override public List<PlaceResult> find(PlaceSearch search) throws Exception { HttpClient httpclient = VoyagerHttpClient.getInstance().getHttpClient(); HttpGet httpget = getMethod(search); return httpclient.execute(httpget, this); } protected HttpGet getMethod(PlaceSearch search) { String url = param_url.replace("{query}", StringEscapeUtils.escapeJavaScript(search.text.toString())); System.out.println("SEND:"+url); return new HttpGet(url); } @Override public List<PlaceResult> handleResponse(HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); String enc = null; try { enc = entity.getContentEncoding().getValue(); } catch(Exception ex) {} return find(entity.getContent(), enc); } else { throw new ClientProtocolException("Unexpected response status: " + status); } } public final class NodeInfo { boolean inside = false; public Map<String, String> attrs = new HashMap<String, String>(); public Map<String, String> children = new HashMap<String, String>(); public void clear() { attrs.clear(); children.clear(); } @Override public String toString() { return "NodeInfo["+attrs+":"+children+"]"; } } public List<PlaceResult> find(InputStream is, String charset) throws IOException { List<PlaceResult> results = new ArrayList<PlaceResult>(10); XMLStreamReader parser = null; final StringBuilder text = new StringBuilder(); final NodeInfo element = new NodeInfo(); element.inside = false; try { parser = (charset == null) ? inputFactory.createXMLStreamReader(is) : inputFactory.createXMLStreamReader(is, charset); while (true) { int event = parser.next(); switch (event) { case XMLStreamConstants.END_DOCUMENT: parser.close(); return results; case XMLStreamConstants.START_ELEMENT: { String currTag = parser.getLocalName(); text.setLength(0); if (currTag.equals(param_node)) { if(element.inside) { throw new IllegalStateException("can not have nested elements"); } element.inside = true; element.clear(); for (int i = 0; i < parser.getAttributeCount(); i++) { String k = parser.getAttributeLocalName(i); String v = parser.getAttributeValue(i); element.attrs.put(k, v); } } else { if(!element.inside) { System.out.println("START:"+currTag + " :: " + element); } } break;} // Add everything to the text case XMLStreamConstants.SPACE: case XMLStreamConstants.CDATA: case XMLStreamConstants.CHARACTERS: text.append(parser.getText()); break; case XMLStreamConstants.END_ELEMENT: { String currTag = parser.getLocalName(); if (currTag.equals(param_node)) { if(!element.inside) { throw new IllegalStateException("can not have nested elements"); } element.inside = false; PlaceResult r = toPlaceResult(element); if(r!=null) { System.out.println( "ADD: "+r.toString() ); results.add(r); } } else if(text.length()>0) { String val = text.toString().trim(); if(val.length()>0) { element.children.put(currTag, val); } } break; } } } } catch(XMLStreamException ex) { throw new IOException(ex); } finally { if (parser != null) { try { parser.close(); } catch (XMLStreamException e) { throw new IOException(e); } } } } public PlaceResult toPlaceResult(NodeInfo info) { String lat = info.children.remove(param_lat); String lon = info.children.remove(param_lon); String name = info.children.remove(param_place_name); String name_ext = info.children.remove(param_place_name_ext); if(lat!=null&&lon!=null&&name!=null) { try { String id = info.attrs.get("id"); if(Strings.isNullOrEmpty(id)) { HashFunction hf = Hashing.sha1(); HashCode hc = hf.newHasher() .putString(info.toString(), Charsets.UTF_8) .hash(); id = hc.toString(); } PlaceResult p = new PlaceResult(id, 1.0f, getName()); p.shape(CTX.makePoint(Double.parseDouble(lon), Double.parseDouble(lat))); if(name_ext!=null) { name += " ("+name_ext+")"; } p.name(name); for(Map.Entry<String, String> entry : info.children.entrySet()) { p.attr(entry.getKey(), entry.getValue()); } return p; } catch(Exception ex) { log.warn("Error reading place: {}", info, ex ); } } return null; } }
apache-2.0
letconex/MMT
src/api-rest/src/main/java/eu/modernmt/rest/actions/translation/GetContextVector.java
5434
package eu.modernmt.rest.actions.translation; import eu.modernmt.context.ContextAnalyzerException; import eu.modernmt.facade.ModernMT; import eu.modernmt.io.FileProxy; import eu.modernmt.lang.LanguagePair; import eu.modernmt.model.ContextVector; import eu.modernmt.persistence.PersistenceException; import eu.modernmt.rest.actions.util.ContextUtils; import eu.modernmt.rest.framework.*; import eu.modernmt.rest.framework.actions.ObjectAction; import eu.modernmt.rest.framework.routing.Route; import eu.modernmt.rest.model.ContextVectorResult; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import java.io.*; import java.util.Locale; import java.util.Map; /** * Created by davide on 15/12/15. */ @Route(aliases = "context-vector", method = HttpMethod.GET) public class GetContextVector extends ObjectAction<ContextVectorResult> { private static File copy(FileProxy source) throws IOException { File destination = File.createTempFile("mmt-context", "txt"); InputStream input = null; OutputStream output = null; try { input = source.getInputStream(); output = new FileOutputStream(destination, false); IOUtils.copyLarge(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } return destination; } @Override protected ContextVectorResult execute(RESTRequest req, Parameters _params) throws ContextAnalyzerException, PersistenceException, IOException { Params params = (Params) _params; Map<Locale, ContextVector> contexts; File temp = null; try { if (params.text != null) { contexts = ModernMT.translation.getContextVectors(params.text, params.limit, params.source, params.targets); } else { boolean gzipped = params.compression != null; File file; if (params.localFile != null) { if (gzipped) temp = file = copy(FileProxy.wrap(params.localFile, true)); else file = params.localFile; } else { temp = file = copy(new ParameterFileProxy(params.content, gzipped)); } contexts = ModernMT.translation.getContextVectors(file, params.limit, params.source, params.targets); } } finally { if (temp != null) FileUtils.deleteQuietly(temp); } ContextUtils.resolve(contexts.values()); return new ContextVectorResult(params.source, contexts, params.backwardCompatible); } @Override protected Parameters getParameters(RESTRequest req) throws Parameters.ParameterParsingException { return new Params(req); } public enum FileCompression { GZIP } public static class Params extends Parameters { public static final int DEFAULT_LIMIT = 10; public final Locale source; public final Locale[] targets; public final int limit; public final String text; public final File localFile; public final FileParameter content; public final FileCompression compression; public final boolean backwardCompatible; public Params(RESTRequest req) throws ParameterParsingException { super(req); this.limit = getInt("limit", DEFAULT_LIMIT); Locale sourceLanguage = getLocale("source", null); Locale[] targetLanguages = getLocaleArray("targets", null); if (sourceLanguage == null && targetLanguages == null) { LanguagePair engineDirection = ModernMT.getNode().getEngine().getLanguages().asSingleLanguagePair(); if (engineDirection != null) { this.source = engineDirection.source; this.targets = new Locale[]{engineDirection.target}; this.backwardCompatible = true; } else { throw new ParameterParsingException("source"); } } else if (sourceLanguage == null) { throw new ParameterParsingException("source"); } else if (targetLanguages == null) { throw new ParameterParsingException("targets"); } else { this.source = sourceLanguage; this.targets = targetLanguages; this.backwardCompatible = false; } FileParameter content; String localFile; if ((content = req.getFile("content")) != null) { this.text = null; this.localFile = null; this.content = content; this.compression = getEnum("compression", FileCompression.class, null); } else if ((localFile = getString("local_file", false, null)) != null) { this.text = null; this.localFile = new File(localFile); this.content = null; this.compression = getEnum("compression", FileCompression.class, null); } else { this.text = getString("text", false); this.localFile = null; this.content = null; this.compression = null; } } } }
apache-2.0
xmruibi/Android_Chipotle
LibWizardPager/src/co/juliansuarez/libwizardpager/wizard/model/BranchPage.java
2783
package co.juliansuarez.libwizardpager.wizard.model; import java.util.ArrayList; import java.util.List; import android.support.v4.app.Fragment; import android.text.TextUtils; import co.juliansuarez.libwizardpager.wizard.ui.SingleChoiceFragment; /** * A page representing a branching point in the wizard. Depending on which choice is selected, the * next set of steps in the wizard may change. */ public class BranchPage extends SingleFixedChoicePage { private List<Branch> mBranches = new ArrayList<Branch>(); public BranchPage(ModelCallbacks callbacks, String title) { super(callbacks, title); } @Override public Page findByKey(String key) { if (getKey().equals(key)) { return this; } for (Branch branch : mBranches) { Page found = branch.childPageList.findByKey(key); if (found != null) { return found; } } return null; } @Override public void flattenCurrentPageSequence(ArrayList<Page> destination) { super.flattenCurrentPageSequence(destination); for (Branch branch : mBranches) { if (branch.choice.equals(mData.getString(Page.SIMPLE_DATA_KEY))) { branch.childPageList.flattenCurrentPageSequence(destination); break; } } } public BranchPage addBranch(String choice, Page... childPages) { PageList childPageList = new PageList(childPages); for (Page page : childPageList) { page.setParentKey(choice); } mBranches.add(new Branch(choice, childPageList)); return this; } @Override public Fragment createFragment() { return SingleChoiceFragment.create(getKey()); } public String getOptionAt(int position) { return mBranches.get(position).choice; } public int getOptionCount() { return mBranches.size(); } @Override public void getReviewItems(ArrayList<ReviewItem> dest) { dest.add(new ReviewItem(getTitle(), mData.getString(SIMPLE_DATA_KEY), getKey())); } @Override public boolean isCompleted() { return !TextUtils.isEmpty(mData.getString(SIMPLE_DATA_KEY)); } @Override public void notifyDataChanged() { mCallbacks.onPageTreeChanged(); super.notifyDataChanged(); } public BranchPage setValue(String value) { mData.putString(SIMPLE_DATA_KEY, value); return this; } private static class Branch { public String choice; public PageList childPageList; private Branch(String choice, PageList childPageList) { this.choice = choice; this.childPageList = childPageList; } } }
apache-2.0
Solomon1732/java-utilities
JavaUtils/src/main/java/com/sol/factory/GenericFactory.java
3428
/******************************************************************************* * Copyright (c) 2016 Shlomi Reuveni. * * 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.sol.factory; import java.util.HashMap; import java.util.Objects; import java.util.Optional; import java.util.function.Function; /** * This is a generic factory class. It is possible to use it as-is, but it's * recommended to wrap it inside a specific {@code Factory} class. * While it is possible to use this class for factories that do not require * input, it is recommended to use {@link GenericSupplier}. * @author Shlomi Reuveni * @version %I%, %G% * @since Apr 22 2016 * @param <K> - key that is associated with the instance function * @param <T> - input type of the function * @param <R> - output type of the function */ public final class GenericFactory<K, T, R> { //The hashmap containing the functions private final HashMap<K, Function<T, R>> factory = new HashMap<>(); /** * Associates the specified function with the specified key in this factory. * If the factory previously contained a mapping for the key, the old function * is replaced. * This class does not accept null values for mappings. * @param key - key with which the specified function is to be associated * @param function - function to be associated with the specified key * @return An {@link Optional} object containing the previous value * associated with key, or {@code null} if this is the first mapping of the * key. * @throws NullPointerException in case the key and/or the function is * {@code null} */ public Optional<Function<T, R>> put(final K key, final Function<T, R> function) throws NullPointerException { Objects.requireNonNull(function); Objects.requireNonNull(key); return Optional.ofNullable(factory.put(key, function)); } /** * Removes the mapping for the specified key from this map if present. * @param key - key whose mapping is to be removed from the factory * @return An {@link Optional} object containing the previous value * associated with key, or {@code null} if there was no mapping for key. * @throws NullPointerException if the key is {@code null} */ public Optional<Function<T, R>> remove(final K key) throws NullPointerException { Objects.requireNonNull(key); return Optional.ofNullable(factory.remove(key)); } /** * Get a new instance of the object produced by the stored function. * @param key - key associated with the instance function * @param input - input of the function * @return a new instance of the object produced by the stored function. * @throws NullPointerException if the key is {@code null} */ public R newInstance(final K key, final T input) throws NullPointerException { return factory.get(Objects.requireNonNull(key)).apply(input); } }
apache-2.0
YoungDigitalPlanet/empiria.player
src/main/java/eu/ydp/empiria/player/client/module/tutor/view/TutorViewImpl.java
4095
/* * Copyright 2017 Young Digital Planet S.A. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.ydp.empiria.player.client.module.tutor.view; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Style; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiTemplate; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import eu.ydp.gwtutil.client.animation.AnimationEndHandler; import eu.ydp.gwtutil.client.event.factory.Command; import eu.ydp.gwtutil.client.event.factory.UserInteractionHandlerFactory; import eu.ydp.gwtutil.client.util.events.animation.AnimationEndEvent; import eu.ydp.gwtutil.client.util.geom.Size; public class TutorViewImpl implements TutorView { private static final String DIMENSIONS_UNIT = "px"; private static TutorViewUiBinder uiBinder = GWT.create(TutorViewUiBinder.class); @UiTemplate("TutorViewImpl.ui.xml") interface TutorViewUiBinder extends UiBinder<Widget, TutorViewImpl> { } @UiField FlowPanel container; @UiField FlowPanel content; private final UserInteractionHandlerFactory userInteractionHandlerFactory; @Inject public TutorViewImpl(UserInteractionHandlerFactory userInteractionHandlerFactory) { this.userInteractionHandlerFactory = userInteractionHandlerFactory; } @Override public void setAnimationLeft(int left) { Style style = content.getElement().getStyle(); style.setProperty("backgroundPosition", left + DIMENSIONS_UNIT); } @Override public void setAnimationStyleName(String styleName, Size size) { clearAllStyles(); content.setStyleName(styleName); setSizeOfContent(size); } private void clearAllStyles() { content.getElement().setAttribute("style", ""); } @Override public Widget asWidget() { return container; } @Override public void bindUi() { uiBinder.createAndBindUi(this); } @Override public void setBackgroundImage(String src, Size size) { Style style = content.getElement().getStyle(); String srcWithUrlInside = "url(" + src + ")"; style.setBackgroundImage(srcWithUrlInside); style.setProperty("backgroundPosition", 0 + DIMENSIONS_UNIT); setSizeOfContent(size); } @Override public void removeAnimationStyleName(String styleName) { content.removeStyleName(styleName); } @Override public HandlerRegistration addAnimationEndHandler(final AnimationEndHandler animationEndHandler) { return content.addDomHandler(new eu.ydp.gwtutil.client.util.events.animation.AnimationEndHandler() { @Override public void onAnimationEnd(AnimationEndEvent event) { animationEndHandler.onEnd(); } }, AnimationEndEvent.getType()); } private void setSizeOfContent(Size size) { String width = size.getWidth() + DIMENSIONS_UNIT; String height = size.getHeight() + DIMENSIONS_UNIT; content.setWidth(width); content.setHeight(height); } @Override public void addClickHandler(Command command) { userInteractionHandlerFactory.applyUserClickHandler(command, container); } }
apache-2.0
elusive-code/TServer
TServer-base/src/main/java/com/elusive_code/tserver/util/StreamRedirector.java
1117
package com.elusive_code.tserver.util; import org.apache.commons.io.IOUtils; import java.io.*; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Vladislav Dolgikh */ public class StreamRedirector implements Runnable { private static Logger log = Logger.getLogger(StreamRedirector.class.getName()); private BufferedInputStream from; private BufferedOutputStream to; public StreamRedirector(InputStream from, OutputStream to) { this.from = new BufferedInputStream(from); this.to = new BufferedOutputStream(to); } private boolean isOpened() { try { from.available(); return true; } catch (IOException ex) { return false; } } @Override public void run() { try { while (true) { IOUtils.copyLarge(from,to); } } catch (EOFException ex){ } catch (IOException ex){ log.log(Level.SEVERE,"Error during stream redirect",ex); }finally { IOUtils.closeQuietly(to); } } }
apache-2.0
ymn/lorsource
src/main/java/ru/org/linux/tag/TagRequest.java
1484
/* * Copyright 1998-2015 Linux.org.ru * 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 ru.org.linux.tag; public class TagRequest { public static class Change { private String tagName; private String oldTagName; public String getTagName() { return tagName; } public void setTagName(String tagName) { this.tagName = tagName; } public String getOldTagName() { return oldTagName; } public void setOldTagName(String oldTagName) { this.oldTagName = oldTagName; } } public static class Delete { private String tagName; private String oldTagName; public String getTagName() { return tagName; } public void setTagName(String tagName) { this.tagName = tagName; } public String getOldTagName() { return oldTagName; } public void setOldTagName(String oldTagName) { this.oldTagName = oldTagName; } } }
apache-2.0
vjanmey/EpicMudfia
com/planet_ink/coffee_mud/core/database/MOBloader.java
53352
package com.planet_ink.coffee_mud.core.database; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.CMSecurity.SecFlag; import com.planet_ink.coffee_mud.core.CMSecurity.SecGroup; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.core.database.DBConnector.DBPreparedBatchEntry; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.Clan.MemberRecord; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.sql.*; import java.util.*; import java.util.Map.Entry; /* * Copyright 2000-2014 Bo Zimmerman 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. */ public class MOBloader { protected DBConnector DB=null; public MOBloader(DBConnector newDB) { DB=newDB; } protected Room emptyRoom=null; public String DBReadUserOnly(MOB mob) { if(mob.Name().length()==0) return null; String locID=null; DBConnection D=null; try { D=DB.DBFetch(); ResultSet R=D.query("SELECT * FROM CMCHAR WHERE CMUSERID='"+mob.Name()+"'"); if(R.next()) { final CharStats stats=mob.baseCharStats(); final CharState state=mob.baseState(); final PlayerStats pstats=(PlayerStats)CMClass.getCommon("DefaultPlayerStats"); mob.setPlayerStats(pstats); final String username=DBConnections.getRes(R,"CMUSERID"); final String password=DBConnections.getRes(R,"CMPASS"); mob.setName(username); pstats.setPassword(password); stats.setMyClasses(DBConnections.getRes(R,"CMCLAS")); stats.setStat(CharStats.STAT_STRENGTH,CMath.s_int(DBConnections.getRes(R,"CMSTRE"))); stats.setMyRace(CMClass.getRace(DBConnections.getRes(R,"CMRACE"))); stats.setStat(CharStats.STAT_DEXTERITY,CMath.s_int(DBConnections.getRes(R,"CMDEXT"))); stats.setStat(CharStats.STAT_CONSTITUTION,CMath.s_int(DBConnections.getRes(R,"CMCONS"))); stats.setStat(CharStats.STAT_GENDER,DBConnections.getRes(R,"CMGEND").charAt(0)); stats.setStat(CharStats.STAT_WISDOM,CMath.s_int(DBConnections.getRes(R,"CMWISD"))); stats.setStat(CharStats.STAT_INTELLIGENCE,CMath.s_int(DBConnections.getRes(R,"CMINTE"))); stats.setStat(CharStats.STAT_CHARISMA,CMath.s_int(DBConnections.getRes(R,"CMCHAR"))); state.setHitPoints(CMath.s_int(DBConnections.getRes(R,"CMHITP"))); stats.setMyLevels(DBConnections.getRes(R,"CMLEVL")); int level=0; for(int i=0;i<mob.baseCharStats().numClasses();i++) level+=stats.getClassLevel(mob.baseCharStats().getMyClass(i)); mob.basePhyStats().setLevel(level); state.setMana(CMath.s_int(DBConnections.getRes(R,"CMMANA"))); state.setMovement(CMath.s_int(DBConnections.getRes(R,"CMMOVE"))); mob.setDescription(DBConnections.getRes(R,"CMDESC")); final int align=(CMath.s_int(DBConnections.getRes(R,"CMALIG"))); if((CMLib.factions().getFaction(CMLib.factions().AlignID())!=null)&&(align>=0)) CMLib.factions().setAlignmentOldRange(mob,align); mob.setExperience(CMath.s_int(DBConnections.getRes(R,"CMEXPE"))); //mob.setExpNextLevel(CMath.s_int(DBConnections.getRes(R,"CMEXLV"))); mob.setWorshipCharID(DBConnections.getRes(R,"CMWORS")); mob.setPractices(CMath.s_int(DBConnections.getRes(R,"CMPRAC"))); mob.setTrains(CMath.s_int(DBConnections.getRes(R,"CMTRAI"))); mob.setAgeMinutes(CMath.s_long(DBConnections.getRes(R,"CMAGEH"))); mob.setMoney(CMath.s_int(DBConnections.getRes(R,"CMGOLD"))); mob.setWimpHitPoint(CMath.s_int(DBConnections.getRes(R,"CMWIMP"))); mob.setQuestPoint(CMath.s_int(DBConnections.getRes(R,"CMQUES"))); String roomID=DBConnections.getRes(R,"CMROID"); if(roomID==null) roomID=""; final int x=roomID.indexOf("||"); if(x>=0) { locID=roomID.substring(x+2); mob.setLocation(CMLib.map().getRoom(locID)); roomID=roomID.substring(0,x); } mob.setStartRoom(CMLib.map().getRoom(roomID)); pstats.setLastDateTime(CMath.s_long(DBConnections.getRes(R,"CMDATE"))); pstats.setChannelMask((int)DBConnections.getLongRes(R,"CMCHAN")); mob.basePhyStats().setAttackAdjustment(CMath.s_int(DBConnections.getRes(R,"CMATTA"))); mob.basePhyStats().setArmor(CMath.s_int(DBConnections.getRes(R,"CMAMOR"))); mob.basePhyStats().setDamage(CMath.s_int(DBConnections.getRes(R,"CMDAMG"))); mob.setBitmap(CMath.s_int(DBConnections.getRes(R,"CMBTMP"))); mob.setLiegeID(DBConnections.getRes(R,"CMLEIG")); mob.basePhyStats().setHeight((int)DBConnections.getLongRes(R,"CMHEIT")); mob.basePhyStats().setWeight((int)DBConnections.getLongRes(R,"CMWEIT")); pstats.setPrompt(DBConnections.getRes(R,"CMPRPT")); final String colorStr=DBConnections.getRes(R,"CMCOLR"); if((colorStr!=null)&&(colorStr.length()>0)&&(!colorStr.equalsIgnoreCase("NULL"))) pstats.setColorStr(colorStr); pstats.setLastIP(DBConnections.getRes(R,"CMLSIP")); mob.setClan("", Integer.MIN_VALUE); // delete all sequence pstats.setEmail(DBConnections.getRes(R,"CMEMAL")); final String buf=DBConnections.getRes(R,"CMPFIL"); pstats.setXML(buf); stats.setNonBaseStatsFromString(DBConnections.getRes(R,"CMSAVE")); List<String> V9=CMParms.parseSemicolons(CMLib.xml().returnXMLValue(buf,"TATTS"),true); for(final Enumeration<MOB.Tattoo> e=mob.tattoos();e.hasMoreElements();) mob.delTattoo(e.nextElement()); for(int v=0;v<V9.size();v++) mob.addTattoo(parseTattoo(V9.get(v))); V9=CMParms.parseSemicolons(CMLib.xml().returnXMLValue(buf,"EDUS"),true); mob.delAllExpertises(); for(int v=0;v<V9.size();v++) mob.addExpertise(V9.get(v)); if(pstats.getBirthday()==null) stats.setStat(CharStats.STAT_AGE, pstats.initializeBirthday((int)Math.round(CMath.div(mob.getAgeMinutes(),60.0)),stats.getMyRace())); mob.setImage(CMLib.xml().returnXMLValue(buf,"IMG")); final List<XMLLibrary.XMLpiece> CleanXML=CMLib.xml().parseAllXML(DBConnections.getRes(R,"CMMXML")); R.close(); if(pstats.getSavedPose().length()>0) mob.setDisplayText(pstats.getSavedPose()); CMLib.coffeeMaker().setFactionFromXML(mob,CleanXML); if((CMProps.getIntVar(CMProps.Int.COMMONACCOUNTSYSTEM)>1)&&(pstats.getAccount()==null)) { // yes, this can happen when you wiggle in and out of the account system. for(final Enumeration<PlayerAccount> a = CMLib.players().accounts(); a.hasMoreElements();) { final PlayerAccount pA=a.nextElement(); if(pA.findPlayer(mob.Name())!=null) { pstats.setAccount(pA); break; } } } } R.close(); R=D.query("SELECT * FROM CMCHCL WHERE CMUSERID='"+mob.Name()+"'"); while(R.next()) { final String clanID=DBConnections.getRes(R,"CMCLAN"); final int clanRole = this.BuildClanMemberRole(R); final Clan C=CMLib.clans().getClan(clanID); if(C!=null) mob.setClan(C.clanID(), clanRole); } } catch(final Exception sqle) { Log.errOut("MOB",sqle); } finally { DB.DBDone(D); } return locID; } public void DBRead(MOB mob) { if(mob.Name().length()==0) return; if(emptyRoom==null) emptyRoom=CMClass.getLocale("StdRoom"); final int oldDisposition=mob.basePhyStats().disposition(); mob.basePhyStats().setDisposition(PhyStats.IS_NOT_SEEN|PhyStats.IS_SNEAKING); mob.phyStats().setDisposition(PhyStats.IS_NOT_SEEN|PhyStats.IS_SNEAKING); CMLib.players().addPlayer(mob); final String oldLocID=DBReadUserOnly(mob); mob.recoverPhyStats(); mob.recoverCharStats(); Room oldLoc=mob.location(); boolean inhab=false; if(oldLoc!=null) inhab=oldLoc.isInhabitant(mob); mob.setLocation(emptyRoom); DBConnection D=null; // now grab the items try { D=DB.DBFetch(); final ResultSet R=D.query("SELECT * FROM CMCHIT WHERE CMUSERID='"+mob.Name()+"'"); final Hashtable<String,Item> itemNums=new Hashtable<String,Item>(); final Hashtable<Item,String> itemLocs=new Hashtable<Item,String>(); while(R.next()) { final String itemNum=DBConnections.getRes(R,"CMITNM"); final String itemID=DBConnections.getRes(R,"CMITID"); final Item newItem=CMClass.getItem(itemID); if(newItem==null) Log.errOut("MOB","Couldn't find item '"+itemID+"'"); else { itemNums.put(itemNum,newItem); boolean addToMOB=true; String text=DBConnections.getResQuietly(R,"CMITTX"); int roomX; if(text.startsWith("<ROOM") && ((roomX=text.indexOf("/>"))>=0)) { final String roomXML=text.substring(0,roomX+2); text=text.substring(roomX+2); newItem.setMiscText(text); final List<XMLLibrary.XMLpiece> xml=CMLib.xml().parseAllXML(roomXML); if((xml!=null)&&(xml.size()>0)) { final String roomID=xml.get(0).parms.get("ID"); final long expirationDate=CMath.s_long(xml.get(0).parms.get("EXPIRE")); if(roomID.startsWith("SPACE.") && (newItem instanceof SpaceShip)) { CMLib.map().addObjectToSpace((SpaceShip)newItem,CMParms.toLongArray(CMParms.parseCommas(roomID.substring(6), true))); addToMOB=false; } else { final Room itemR=CMLib.map().getRoom(roomID); if(itemR!=null) { if((newItem instanceof SpaceShip)&&(itemR instanceof LocationRoom)) ((SpaceShip)newItem).dockHere((LocationRoom)itemR); else itemR.addItem(newItem); newItem.setExpirationDate(expirationDate); addToMOB=false; } } } } else { newItem.setMiscText(text); } if((oldLoc==null)&&(oldLocID!=null) &&(newItem instanceof SpaceShip)) { final Area area=((SpaceShip)newItem).getShipArea(); if(area != null) oldLoc=area.getRoom(oldLocID); } final String loc=DBConnections.getResQuietly(R,"CMITLO"); if(loc.length()>0) { final Item container=itemNums.get(loc); if(container instanceof Container) newItem.setContainer((Container)container); else itemLocs.put(newItem,loc); } newItem.wearAt((int)DBConnections.getLongRes(R,"CMITWO")); newItem.setUsesRemaining((int)DBConnections.getLongRes(R,"CMITUR")); newItem.basePhyStats().setLevel((int)DBConnections.getLongRes(R,"CMITLV")); newItem.basePhyStats().setAbility((int)DBConnections.getLongRes(R,"CMITAB")); newItem.basePhyStats().setHeight((int)DBConnections.getLongRes(R,"CMHEIT")); newItem.recoverPhyStats(); if(addToMOB) mob.addItem(newItem); else mob.playerStats().getExtItems().addItem(newItem); } } for(final Enumeration<Item> e=itemLocs.keys();e.hasMoreElements();) { final Item keyItem=e.nextElement(); final String location=itemLocs.get(keyItem); final Item container=itemNums.get(location); if(container instanceof Container) { keyItem.setContainer((Container)container); keyItem.recoverPhyStats(); container.recoverPhyStats(); } } } catch(final Exception sqle) { Log.errOut("MOB",sqle); } finally { DB.DBDone(D); } D=null; if(oldLoc!=null) { mob.setLocation(oldLoc); if(inhab&&(!oldLoc.isInhabitant(mob))) oldLoc.addInhabitant(mob); } // now grab the abilities try { D=DB.DBFetch(); final ResultSet R=D.query("SELECT * FROM CMCHAB WHERE CMUSERID='"+mob.Name()+"'"); while(R.next()) { final String abilityID=DBConnections.getRes(R,"CMABID"); int proficiency=(int)DBConnections.getLongRes(R,"CMABPF"); if((proficiency==Integer.MIN_VALUE)||(proficiency==Integer.MIN_VALUE+1)) { if(abilityID.equalsIgnoreCase("ScriptingEngine")) { if(CMClass.getCommon("DefaultScriptingEngine")==null) Log.errOut("MOB","Couldn't find scripting engine!"); else { final String xml=DBConnections.getRes(R,"CMABTX"); if(xml.length()>0) CMLib.coffeeMaker().setGenScripts(mob,CMLib.xml().parseAllXML(xml),true); } } else { final Behavior newBehavior=CMClass.getBehavior(abilityID); if(newBehavior==null) Log.errOut("MOB","Couldn't find behavior '"+abilityID+"'"); else { newBehavior.setParms(DBConnections.getRes(R,"CMABTX")); mob.addBehavior(newBehavior); } } } else { final Ability newAbility=CMClass.getAbility(abilityID); if(newAbility==null) Log.errOut("MOB","Couldn't find ability '"+abilityID+"'"); else { if((proficiency<0)||(proficiency==Integer.MAX_VALUE)) { if(proficiency==Integer.MAX_VALUE) { newAbility.setProficiency(CMLib.ableMapper().getMaxProficiency(newAbility.ID())); mob.addNonUninvokableEffect(newAbility); newAbility.setMiscText(DBConnections.getRes(R,"CMABTX")); }else { proficiency=proficiency+200; newAbility.setProficiency(proficiency); newAbility.setMiscText(DBConnections.getRes(R,"CMABTX")); final Ability newAbility2=(Ability)newAbility.copyOf(); mob.addNonUninvokableEffect(newAbility); mob.addAbility(newAbility2); } }else { newAbility.setProficiency(proficiency); newAbility.setMiscText(DBConnections.getRes(R,"CMABTX")); mob.addAbility(newAbility); } } } } } catch(final Exception sqle) { Log.errOut("MOB",sqle); } finally { DB.DBDone(D); } D=null; mob.basePhyStats().setDisposition(oldDisposition); mob.recoverCharStats(); mob.recoverPhyStats(); mob.recoverMaxState(); mob.resetToMaxState(); if(mob.baseCharStats()!=null) { mob.baseCharStats().getCurrentClass().startCharacter(mob,false,true); final int oldWeight=mob.basePhyStats().weight(); final int oldHeight=mob.basePhyStats().height(); mob.baseCharStats().getMyRace().startRacing(mob,true); if(oldWeight>0) mob.basePhyStats().setWeight(oldWeight); if(oldHeight>0) mob.basePhyStats().setHeight(oldHeight); } mob.recoverCharStats(); mob.recoverPhyStats(); mob.recoverMaxState(); mob.resetToMaxState(); CMLib.threads().suspendResumeRecurse(mob, false, true); // wont add if same name already exists } public List<String> getUserList() { DBConnection D=null; final Vector<String> V=new Vector<String>(); try { D=DB.DBFetch(); final ResultSet R=D.query("SELECT * FROM CMCHAR"); if(R!=null) while(R.next()) { final String username=DBConnections.getRes(R,"CMUSERID"); V.addElement(username); } } catch(final Exception sqle) { Log.errOut("MOB",sqle); } finally { DB.DBDone(D); } return V; } protected PlayerLibrary.ThinPlayer parseThinUser(ResultSet R) { try { final PlayerLibrary.ThinPlayer thisUser=new PlayerLibrary.ThinPlayer(); thisUser.name=DBConnections.getRes(R,"CMUSERID"); String cclass=DBConnections.getRes(R,"CMCLAS"); final int x=cclass.lastIndexOf(';'); CharClass C=null; if((x>0)&&(x<cclass.length()-2)) { C=CMClass.getCharClass(cclass.substring(x+1)); if(C!=null) cclass=C.name(); } thisUser.charClass=(cclass); final String rrace=DBConnections.getRes(R,"CMRACE"); final Race R2=CMClass.getRace(rrace); if(R2!=null) thisUser.race=(R2.name()); else thisUser.race=rrace; final List<String> lvls=CMParms.parseSemicolons(DBConnections.getRes(R,"CMLEVL"), true); thisUser.level=0; for(final String lvl : lvls) thisUser.level+=CMath.s_int(lvl); thisUser.age=(int)DBConnections.getLongRes(R,"CMAGEH"); final MOB M=CMLib.players().getPlayer(thisUser.name); if((M!=null)&&(M.lastTickedDateTime()>0)) thisUser.last=M.lastTickedDateTime(); else thisUser.last=DBConnections.getLongRes(R,"CMDATE"); final String lsIP=DBConnections.getRes(R,"CMLSIP"); thisUser.email=DBConnections.getRes(R,"CMEMAL"); thisUser.ip=lsIP; thisUser.exp=CMath.s_int(DBConnections.getRes(R,"CMEXPE")); thisUser.expLvl=CMath.s_int(DBConnections.getRes(R,"CMEXLV")); return thisUser; }catch(final Exception e) { Log.errOut("MOBloader",e); } return null; } public PlayerLibrary.ThinPlayer getThinUser(String name) { DBConnection D=null; PlayerLibrary.ThinPlayer thisUser=null; try { D=DB.DBFetch(); final ResultSet R=D.query("SELECT * FROM CMCHAR WHERE CMUSERID='"+name+"'"); if(R!=null) while(R.next()) thisUser=parseThinUser(R); } catch(final Exception sqle) { Log.errOut("MOB",sqle); } finally { DB.DBDone(D); } return thisUser; } public List<PlayerLibrary.ThinPlayer> getExtendedUserList() { DBConnection D=null; final Vector<PlayerLibrary.ThinPlayer> allUsers=new Vector<PlayerLibrary.ThinPlayer>(); try { D=DB.DBFetch(); final ResultSet R=D.query("SELECT * FROM CMCHAR"); if(R!=null) while(R.next()) { final PlayerLibrary.ThinPlayer thisUser=parseThinUser(R); if(thisUser != null) allUsers.addElement(thisUser); } } catch(final Exception sqle) { Log.errOut("MOB",sqle); } finally { DB.DBDone(D); } return allUsers; } public MOB.Tattoo parseTattoo(String tattoo) { if(tattoo==null) return new MOB.Tattoo(""); int tickDown = 0; if((tattoo.length()>0) &&(Character.isDigit(tattoo.charAt(0)))) { final int x=tattoo.indexOf(' '); if((x>0) &&(CMath.isNumber(tattoo.substring(0,x).trim()))) { tickDown=CMath.s_int(tattoo.substring(0,x)); tattoo=tattoo.substring(x+1).trim(); } } return new MOB.Tattoo(tattoo, tickDown); } public List<PlayerLibrary.ThinPlayer> vassals(MOB mob, String liegeID) { DBConnection D=null; List<PlayerLibrary.ThinPlayer> list=new ArrayList<PlayerLibrary.ThinPlayer>(); try { D=DB.DBFetch(); final ResultSet R=D.query("SELECT * FROM CMCHAR WHERE CMLEIG='"+liegeID+"'"); if(R!=null) while(R.next()) list.add(this.parseThinUser(R)); } catch(final Exception sqle) { Log.errOut("MOB",sqle); } finally { DB.DBDone(D); } return list; } public DVector worshippers(String deityID) { DBConnection D=null; final DVector DV=new DVector(4); try { D=DB.DBFetch(); final ResultSet R=D.query("SELECT * FROM CMCHAR WHERE CMWORS='"+deityID+"'"); if(R!=null) while(R.next()) { final String username=DBConnections.getRes(R,"CMUSERID"); String cclass=DBConnections.getRes(R,"CMCLAS"); final int x=cclass.lastIndexOf(';'); if((x>0)&&(x<cclass.length()-2)) cclass=CMClass.getCharClass(cclass.substring(x+1)).name(); final String race=(CMClass.getRace(DBConnections.getRes(R,"CMRACE"))).name(); final List<String> lvls=CMParms.parseSemicolons(DBConnections.getRes(R,"CMLEVL"), true); int level=0; for(final String lvl : lvls) level+=CMath.s_int(lvl); DV.addElement(username, cclass, ""+level, race); } } catch(final Exception sqle) { Log.errOut("MOB",sqle); } finally { DB.DBDone(D); } return DV; } public List<MOB> DBScanFollowers(MOB mob) { DBConnection D=null; final Vector<MOB> V=new Vector<MOB>(); // now grab the followers try { D=DB.DBFetch(); final ResultSet R=D.query("SELECT * FROM CMCHFO WHERE CMUSERID='"+mob.Name()+"'"); while(R.next()) { final String MOBID=DBConnections.getRes(R,"CMFOID"); final MOB newMOB=CMClass.getMOB(MOBID); if(newMOB==null) Log.errOut("MOB","Couldn't find MOB '"+MOBID+"'"); else { newMOB.setMiscText(DBConnections.getResQuietly(R,"CMFOTX")); newMOB.basePhyStats().setLevel(((int)DBConnections.getLongRes(R,"CMFOLV"))); newMOB.basePhyStats().setAbility((int)DBConnections.getLongRes(R,"CMFOAB")); newMOB.basePhyStats().setRejuv(PhyStats.NO_REJUV); newMOB.recoverPhyStats(); newMOB.recoverCharStats(); newMOB.recoverMaxState(); newMOB.resetToMaxState(); V.addElement(newMOB); } } } catch(final Exception sqle) { Log.errOut("MOB",sqle); } finally { DB.DBDone(D); } return V; } public void DBReadFollowers(MOB mob, boolean bringToLife) { Room location=mob.location(); if(location==null) location=mob.getStartRoom(); final List<MOB> V=DBScanFollowers(mob); for(int v=0;v<V.size();v++) { final MOB newMOB=V.get(v); final Room room=(location==null)?newMOB.getStartRoom():location; newMOB.setStartRoom(room); newMOB.setLocation(room); newMOB.setFollowing(mob); if((newMOB.getStartRoom()!=null) &&(CMLib.law().doesHavePriviledgesHere(mob,newMOB.getStartRoom())) &&((newMOB.location()==null) ||(!CMLib.law().doesHavePriviledgesHere(mob,newMOB.location())))) newMOB.setLocation(newMOB.getStartRoom()); if(bringToLife) { newMOB.bringToLife(mob.location(),true); mob.location().showOthers(newMOB,null,CMMsg.MSG_OK_ACTION,CMLib.lang()._("<S-NAME> appears!")); } } } public void DBUpdateEmail(MOB mob) { final PlayerStats pstats=mob.playerStats(); if(pstats==null) return; DB.update("UPDATE CMCHAR SET CMEMAL='"+pstats.getEmail()+"' WHERE CMUSERID='"+mob.Name()+"'"); } private int BuildClanMemberRole(ResultSet R) { return (int)DBConnections.getLongRes(R,"CMCLRO"); } private MemberRecord BuildClanMemberRecord(ResultSet R) { final String username=DB.getRes(R,"CMUSERID"); final int clanRole = BuildClanMemberRole(R); int mobpvps=0; int playerpvps=0; final String stats=DB.getRes(R,"CMCLSTS"); if(stats!=null) { final String[] splitstats=stats.split(";"); if(splitstats.length>0) mobpvps=CMath.s_int(splitstats[0]); if(splitstats.length>1) playerpvps=CMath.s_int(splitstats[1]); } return new Clan.MemberRecord(username,clanRole,mobpvps,playerpvps); } public MemberRecord DBGetClanMember(String clan, String name) { DBConnection D=null; try { D=DB.DBFetch(); final ResultSet R=D.query("SELECT * FROM CMCHCL where CMCLAN='"+clan+"' and CMUSERID='"+name+"'"); if(R!=null) while(R.next()) { return BuildClanMemberRecord(R); } } catch(final Exception sqle) { Log.errOut("MOB",sqle); } finally { DB.DBDone(D); } return null; } public List<Clan.MemberRecord> DBClanMembers(String clan) { final List<Clan.MemberRecord> members = new Vector<Clan.MemberRecord>(); DBConnection D=null; try { D=DB.DBFetch(); final ResultSet R=D.query("SELECT * FROM CMCHCL where CMCLAN='"+clan+"'"); if(R!=null) while(R.next()) { members.add(BuildClanMemberRecord(R)); } } catch(final Exception sqle) { Log.errOut("MOB",sqle); } finally { DB.DBDone(D); } return members; } public void DBUpdateClanMembership(String name, String clan, int role) { final MOB M=CMLib.players().getPlayer(name); if(M!=null) { M.setClan(clan, role); } DBConnection D=null; try { D=DB.DBFetch(); if(role<0) DB.update("DELETE FROM CMCHCL WHERE CMUSERID='"+name+"' AND CMCLAN='"+clan+"'"); else { final ResultSet R=D.query("SELECT * FROM CMCHCL where CMCLAN='"+clan+"' and CMUSERID='"+name+"'"); if((R!=null) && (R.next())) { final int clanRole = BuildClanMemberRole(R); R.close(); if(clanRole == role) return; D.update("UPDATE CMCHCL SET CMCLRO="+role+" where CMCLAN='"+clan+"' and CMUSERID='"+name+"'", 0); } else { D.update("INSERT INTO CMCHCL (CMUSERID, CMCLAN, CMCLRO, CMCLSTS) values ('"+name+"','"+clan+"',"+role+",'0;0')",0); } } } catch(final Exception sqle) { Log.errOut("MOB",sqle); } finally { DB.DBDone(D); } } public void DBUpdateClanKills(String clan, String name, int adjMobKills, int adjPlayerKills) { if(((adjMobKills==0)&&(adjPlayerKills==0)) ||(clan==null) ||(name==null)) return; DBConnection D=null; try { D=DB.DBFetch(); final ResultSet R=D.query("SELECT * FROM CMCHCL where CMCLAN='"+clan+"' and CMUSERID='"+name+"'"); MemberRecord M=null; if(R!=null) { if(R.next()) { M=BuildClanMemberRecord(R); R.close(); M.mobpvps+=adjMobKills; M.playerpvps+=adjPlayerKills; final String newStats=M.mobpvps+";"+M.playerpvps; D.update("UPDATE CMCHCL SET CMCLSTS='"+newStats+"' where CMCLAN='"+clan+"' and CMUSERID='"+name+"'", 0); } } } catch(final Exception sqle) { Log.errOut("MOB",sqle); } finally { DB.DBDone(D); } } public void DBUpdate(MOB mob) { DBUpdateJustMOB(mob); final PlayerStats pStats = mob.playerStats(); if((mob.Name().length()==0)||(pStats==null)) return; DBUpdateItems(mob); DBUpdateAbilities(mob); pStats.setLastUpdated(System.currentTimeMillis()); final PlayerAccount account = pStats.getAccount(); if(account != null) { DBUpdateAccount(account); account.setLastUpdated(System.currentTimeMillis()); } } public void DBUpdatePassword(String name, String password) { name=CMStrings.capitalizeAndLower(name); DB.update("UPDATE CMCHAR SET CMPASS='"+password+"' WHERE CMUSERID='"+name.replace('\'', 'n')+"'"); } private String getPlayerStatsXML(MOB mob) { final PlayerStats pstats=mob.playerStats(); if(pstats==null) return ""; final StringBuilder pfxml=new StringBuilder(pstats.getXML()); if(mob.tattoos().hasMoreElements()) { pfxml.append("<TATTS>"); for(final Enumeration<MOB.Tattoo> e=mob.tattoos();e.hasMoreElements();) pfxml.append(e.nextElement().toString()+";"); pfxml.append("</TATTS>"); } if(mob.expertises().hasMoreElements()) { pfxml.append("<EDUS>"); for(final Enumeration<String> x=mob.expertises();x.hasMoreElements();) pfxml.append(x.nextElement()).append(';'); pfxml.append("</EDUS>"); } pfxml.append(CMLib.xml().convertXMLtoTag("IMG",mob.rawImage())); return pfxml.toString(); } public void DBUpdateJustPlayerStats(MOB mob) { if(mob.Name().length()==0) { DBCreateCharacter(mob); return; } final PlayerStats pstats=mob.playerStats(); if(pstats==null) return; final String pfxml=getPlayerStatsXML(mob); DB.updateWithClobs("UPDATE CMCHAR SET CMPFIL=? WHERE CMUSERID='"+mob.Name()+"'", pfxml.toString()); } public void DBUpdateJustMOB(MOB mob) { if(mob.Name().length()==0) { DBCreateCharacter(mob); return; } final PlayerStats pstats=mob.playerStats(); if(pstats==null) return; final String strStartRoomID=(mob.getStartRoom()!=null)?CMLib.map().getExtendedRoomID(mob.getStartRoom()):""; String strOtherRoomID=(mob.location()!=null)?CMLib.map().getExtendedRoomID(mob.location()):""; if((mob.location()!=null) &&(mob.location().getArea()!=null) &&(CMath.bset(mob.location().getArea().flags(),Area.FLAG_INSTANCE_PARENT) ||CMath.bset(mob.location().getArea().flags(),Area.FLAG_INSTANCE_CHILD))) strOtherRoomID=strStartRoomID; final String pfxml=getPlayerStatsXML(mob); final StringBuilder cleanXML=new StringBuilder(); cleanXML.append(CMLib.coffeeMaker().getFactionXML(mob)); DB.updateWithClobs( "UPDATE CMCHAR SET CMPASS='"+pstats.getPasswordStr()+"'" +", CMCLAS='"+mob.baseCharStats().getMyClassesStr()+"'" +", CMSTRE="+mob.baseCharStats().getStat(CharStats.STAT_STRENGTH) +", CMRACE='"+mob.baseCharStats().getMyRace().ID()+"'" +", CMDEXT="+mob.baseCharStats().getStat(CharStats.STAT_DEXTERITY) +", CMCONS="+mob.baseCharStats().getStat(CharStats.STAT_CONSTITUTION) +", CMGEND='"+((char)mob.baseCharStats().getStat(CharStats.STAT_GENDER))+"'" +", CMWISD="+mob.baseCharStats().getStat(CharStats.STAT_WISDOM) +", CMINTE="+mob.baseCharStats().getStat(CharStats.STAT_INTELLIGENCE) +", CMCHAR="+mob.baseCharStats().getStat(CharStats.STAT_CHARISMA) +", CMHITP="+mob.baseState().getHitPoints() +", CMLEVL='"+mob.baseCharStats().getMyLevelsStr()+"'" +", CMMANA="+mob.baseState().getMana() +", CMMOVE="+mob.baseState().getMovement() +", CMALIG=-1" +", CMEXPE="+mob.getExperience() +", CMEXLV="+mob.getExpNextLevel() +", CMWORS='"+mob.getWorshipCharID()+"'" +", CMPRAC="+mob.getPractices() +", CMTRAI="+mob.getTrains() +", CMAGEH="+mob.getAgeMinutes() +", CMGOLD="+mob.getMoney() +", CMWIMP="+mob.getWimpHitPoint() +", CMQUES="+mob.getQuestPoint() +", CMROID='"+strStartRoomID+"||"+strOtherRoomID+"'" +", CMDATE='"+pstats.getLastDateTime()+"'" +", CMCHAN="+pstats.getChannelMask() +", CMATTA="+mob.basePhyStats().attackAdjustment() +", CMAMOR="+mob.basePhyStats().armor() +", CMDAMG="+mob.basePhyStats().damage() +", CMBTMP="+mob.getBitmap() +", CMLEIG='"+mob.getLiegeID()+"'" +", CMHEIT="+mob.basePhyStats().height() +", CMWEIT="+mob.basePhyStats().weight() +", CMPRPT=?" +", CMCOLR=?" +", CMLSIP='"+pstats.getLastIP()+"'" +", CMEMAL=?" +", CMPFIL=?" +", CMSAVE=?" +", CMMXML=?" +", CMDESC=?" +" WHERE CMUSERID='"+mob.Name()+"'" ,new String[][]{{pstats.getPrompt(),pstats.getColorStr(),pstats.getEmail(), pfxml,mob.baseCharStats().getNonBaseStatsAsString(),cleanXML.toString(),mob.description()}}); final List<String> clanStatements=new LinkedList<String>(); DBConnection D=null; try { D=DB.DBFetch(); final ResultSet R=D.query("SELECT * FROM CMCHCL WHERE CMUSERID='"+mob.Name()+"'"); final Set<String> savedClans=new HashSet<String>(); if(R!=null) { while(R.next()) { final String clanID=DB.getRes(R,"CMCLAN"); final Pair<Clan,Integer> role=mob.getClanRole(clanID); if(role==null) clanStatements.add("DELETE FROM CMCHCL WHERE CMUSERID='"+mob.Name()+"' AND CMCLAN='"+clanID+"'"); else { final MemberRecord M=BuildClanMemberRecord(R); if(role.second.intValue()!=M.role) clanStatements.add("UPDATE CMCHCL SET CMCLRO="+role+" where CMCLAN='"+clanID+"' and CMUSERID='"+mob.Name()+"'"); } savedClans.add(clanID.toUpperCase()); } R.close(); } for(final Pair<Clan,Integer> p : mob.clans()) if(!savedClans.contains(p.first.clanID().toUpperCase())) clanStatements.add("INSERT INTO CMCHCL (CMUSERID, CMCLAN, CMCLRO, CMCLSTS) values ('"+mob.Name()+"','"+p.first.clanID()+"',"+p.second.intValue()+",'0;0')"); } catch(final Exception sqle) { Log.errOut("MOB",sqle); } finally { DB.DBDone(D); } if(clanStatements.size()>0) DB.update(clanStatements.toArray(new String[0])); } protected String getDBItemUpdateString(final MOB mob, final Item thisItem) { CMLib.catalog().updateCatalogIntegrity(thisItem); final String container=((thisItem.container()!=null)?(""+thisItem.container()):""); return "INSERT INTO CMCHIT (CMUSERID, CMITNM, CMITID, CMITTX, CMITLO, CMITWO, " +"CMITUR, CMITLV, CMITAB, CMHEIT" +") values ('"+mob.Name()+"','"+(thisItem)+"','"+thisItem.ID()+"',?,'"+container+"',"+thisItem.rawWornCode()+"," +thisItem.usesRemaining()+","+thisItem.basePhyStats().level()+","+thisItem.basePhyStats().ability()+"," +thisItem.basePhyStats().height()+")"; } private List<DBPreparedBatchEntry> getDBItemUpdateStrings(MOB mob) { final HashSet<String> done=new HashSet<String>(); final List<DBPreparedBatchEntry> strings=new LinkedList<DBPreparedBatchEntry>(); for(int i=0;i<mob.numItems();i++) { final Item thisItem=mob.getItem(i); if((thisItem!=null)&&(!done.contains(""+thisItem))&&(thisItem.isSavable())) { CMLib.catalog().updateCatalogIntegrity(thisItem); final String sql=getDBItemUpdateString(mob,thisItem); strings.add(new DBPreparedBatchEntry(sql,thisItem.text()+" ")); done.add(""+thisItem); } } final PlayerStats pStats=mob.playerStats(); if(pStats !=null) { final ItemCollection coll=pStats.getExtItems(); final List<Item> finalCollection=new LinkedList<Item>(); final List<Item> extraItems=new LinkedList<Item>(); for(int i=coll.numItems()-1;i>=0;i--) { final Item thisItem=coll.getItem(i); if((thisItem!=null)&&(!thisItem.amDestroyed())) { final Item cont=thisItem.ultimateContainer(null); if(cont.owner() instanceof Room) finalCollection.add(thisItem); } } for(final Item thisItem : finalCollection) { if(thisItem instanceof Container) { final List<Item> contents=((Container)thisItem).getContents(); for(final Item I : contents) if(!finalCollection.contains(I)) extraItems.add(I); } } finalCollection.addAll(extraItems); for(final Item thisItem : finalCollection) { if(!done.contains(""+thisItem)) { CMLib.catalog().updateCatalogIntegrity(thisItem); final Item cont=thisItem.ultimateContainer(null); final String sql=getDBItemUpdateString(mob,thisItem); final String roomID=((cont.owner()==null)&&(thisItem instanceof SpaceShip)&&(CMLib.map().isObjectInSpace((SpaceShip)thisItem)))? ("SPACE."+CMParms.toStringList(((SpaceShip)thisItem).coordinates())):CMLib.map().getExtendedRoomID((Room)cont.owner()); final String text="<ROOM ID=\""+roomID+"\" EXPIRE="+thisItem.expirationDate()+" />"+thisItem.text(); strings.add(new DBPreparedBatchEntry(sql,text)); done.add(""+thisItem); } } } return strings; } public void DBUpdateItems(MOB mob) { if(mob.Name().length()==0) return; final List<DBPreparedBatchEntry> statements=new LinkedList<DBPreparedBatchEntry>(); statements.add(new DBPreparedBatchEntry("DELETE FROM CMCHIT WHERE CMUSERID='"+mob.Name()+"'")); statements.addAll(getDBItemUpdateStrings(mob)); DB.updateWithClobs(statements); } protected List<Pair<String,Integer>>[][] DBFindPrideWinners(int topThisMany, short scanCPUPercent, boolean players) { @SuppressWarnings("unchecked") final List<Pair<String,Integer>>[][] top=new Vector[TimeClock.TimePeriod.values().length][AccountStats.PrideStat.values().length]; for(int x=0;x<top.length;x++) for(int y=0;y<top[x].length;y++) top[x][y]=new Vector<Pair<String,Integer>>(topThisMany+1); DBConnection D=null; final long msWait=Math.round(1000.0 * CMath.div(scanCPUPercent, 100)); final long sleepAmount=1000 - msWait; try { long nextWaitAfter=System.currentTimeMillis() + msWait; final long now=System.currentTimeMillis(); D=DB.DBFetch(); ResultSet R; if(players) R=D.query("SELECT CMUSERID,CMPFIL FROM CMCHAR"); else R=D.query("SELECT CMANAM,CMAXML FROM CMACCT"); while((R!=null)&&(R.next())) { final String userID=DB.getRes(R, players?"CMUSERID":"CMANAM"); String pxml; final MOB M=CMLib.players().getPlayer(userID); if((M!=null)&&(M.playerStats()!=null)) pxml=M.playerStats().getXML(); else if(players) pxml=DB.getRes(R, "CMPFIL"); else pxml=DB.getRes(R, "CMAXML"); final String[] pridePeriods=CMLib.xml().returnXMLValue(pxml, "NEXTPRIDEPERIODS").split(","); final String[] prideStats=CMLib.xml().returnXMLValue(pxml, "PRIDESTATS").split(";"); final Pair<Long,int[]>[] allData = CMLib.players().parsePrideStats(pridePeriods, prideStats); for(final TimeClock.TimePeriod period : TimeClock.TimePeriod.values()) { if(allData.length > period.ordinal()) { final Pair<Long,int[]> p=allData[period.ordinal()]; final List<Pair<String,Integer>>[] topPeriods=top[period.ordinal()]; if((period==TimeClock.TimePeriod.ALLTIME)||(now < p.first.longValue())) { for(final AccountStats.PrideStat pride : AccountStats.PrideStat.values()) { if((p.second.length>pride.ordinal())&&(p.second[pride.ordinal()]>0)) { final int val=p.second[pride.ordinal()]; final List<Pair<String,Integer>> topPrides=topPeriods[pride.ordinal()]; final int oldSize=topPrides.size(); for(int i=0;i<topPrides.size();i++) if(val >= topPrides.get(i).second.intValue()) { topPrides.add(i, new Pair<String,Integer>(userID,Integer.valueOf(val))); while(topPrides.size()>topThisMany) topPrides.remove(topPrides.size()-1); break; } if((oldSize==topPrides.size())&&(topPrides.size()<topThisMany)) topPrides.add(new Pair<String,Integer>(userID,Integer.valueOf(val))); } } } } } if((sleepAmount>0)&&(System.currentTimeMillis() > nextWaitAfter)) { CMLib.s_sleep(sleepAmount); nextWaitAfter=System.currentTimeMillis() + msWait; } } } catch(final Exception sqle) { Log.errOut("MOB",sqle); } finally { DB.DBDone(D); } return top; } public List<Pair<String,Integer>>[][] DBScanPridePlayerWinners(int topThisMany, short scanCPUPercent) { return DBFindPrideWinners(topThisMany,scanCPUPercent,true); } public List<Pair<String,Integer>>[][] DBScanPrideAccountWinners(int topThisMany, short scanCPUPercent) { return DBFindPrideWinners(topThisMany,scanCPUPercent,false); } // this method is unused, but is a good idea of how to collect riders, followers, carts, etc. protected void addFollowerDependent(PhysicalAgent P, DVector list, String parent) { if(P==null) return; if(list.contains(P)) return; if((P instanceof MOB) &&((!((MOB)P).isMonster())||(((MOB)P).isPossessing()))) return; CMLib.catalog().updateCatalogIntegrity(P); final String myCode=""+(list.size()-1); list.addElement(P,CMClass.classID(P)+"#"+myCode+parent); if(P instanceof Rideable) { final Rideable R=(Rideable)P; for(int r=0;r<R.numRiders();r++) addFollowerDependent(R.fetchRider(r),list,"@"+myCode+"R"); } if(P instanceof Container) { final Container C=(Container)P; final List<Item> contents=C.getContents(); for(int c=0;c<contents.size();c++) addFollowerDependent(contents.get(c),list,"@"+myCode+"C"); } } public void DBUpdateFollowers(MOB mob) { if((mob==null)||(mob.Name().length()==0)) return; final List<DBPreparedBatchEntry> statements=new LinkedList<DBPreparedBatchEntry>(); statements.add(new DBPreparedBatchEntry("DELETE FROM CMCHFO WHERE CMUSERID='"+mob.Name()+"'")); for(int f=0;f<mob.numFollowers();f++) { final MOB thisMOB=mob.fetchFollower(f); if((thisMOB!=null)&&(thisMOB.isMonster())&&(!thisMOB.isPossessing())) { CMLib.catalog().updateCatalogIntegrity(thisMOB); final String sql="INSERT INTO CMCHFO (CMUSERID, CMFONM, CMFOID, CMFOTX, CMFOLV, CMFOAB" +") values ('"+mob.Name()+"',"+f+",'"+CMClass.classID(thisMOB)+"',?," +thisMOB.basePhyStats().level()+","+thisMOB.basePhyStats().ability()+")"; statements.add(new DBPreparedBatchEntry(sql,thisMOB.text()+" ")); } } DB.updateWithClobs(statements); } public void DBNameChange(String oldName, String newName) { if((oldName==null) ||(oldName.trim().length()==0) ||(oldName.indexOf('\'')>=0) ||(newName==null) ||(newName.trim().length()==0) ||(newName.indexOf('\'')>=0)) return; DB.update("UPDATE CMCHAB SET CMUSERID='"+newName+"' WHERE CMUSERID='"+oldName+"'"); DB.update("UPDATE CMCHAR SET CMUSERID='"+newName+"' WHERE CMUSERID='"+oldName+"'"); DB.update("UPDATE CMCHAR SET CMWORS='"+newName+"' WHERE CMWORS='"+oldName+"'"); DB.update("UPDATE CMCHAR SET CMLEIG='"+newName+"' WHERE CMLEIG='"+oldName+"'"); DB.update("UPDATE CMCHCL SET CMUSERID='"+newName+"' WHERE CMUSERID='"+oldName+"'"); DB.update("UPDATE CMCHFO SET CMUSERID='"+newName+"' WHERE CMUSERID='"+oldName+"'"); DB.update("UPDATE CMCHIT SET CMUSERID='"+newName+"' WHERE CMUSERID='"+oldName+"'"); DB.update("UPDATE CMJRNL SET CMFROM='"+newName+"' WHERE CMFROM='"+oldName+"'"); DB.update("UPDATE CMJRNL SET CMTONM='"+newName+"' WHERE CMTONM='"+oldName+"'"); DB.update("UPDATE CMPDAT SET CMPLID='"+newName+"' WHERE CMPLID='"+oldName+"'"); } public void DBDelete(MOB mob, boolean deleteAssets) { if(mob.Name().length()==0) return; final List<String> channels=CMLib.channels().getFlaggedChannelNames(ChannelsLibrary.ChannelFlag.PLAYERPURGES); for(int i=0;i<channels.size();i++) CMLib.commands().postChannel(channels.get(i),mob.clans(),mob.Name()+" has just been deleted.",true); CMLib.coffeeTables().bump(mob,CoffeeTableRow.STAT_PURGES); DB.update("DELETE FROM CMCHAR WHERE CMUSERID='"+mob.Name()+"'"); DB.update("DELETE FROM CMCHCL WHERE CMUSERID='"+mob.Name()+"'"); mob.delAllItems(false); for(int i=0;i<mob.numItems();i++) { final Item I=mob.getItem(i); if(I!=null) I.setContainer(null); } mob.delAllItems(false); DBUpdateItems(mob); while(mob.numFollowers()>0) { final MOB follower=mob.fetchFollower(0); if(follower!=null) follower.setFollowing(null); } if(deleteAssets) { DBUpdateFollowers(mob); } mob.delAllAbilities(); DBUpdateAbilities(mob); if(deleteAssets) { CMLib.database().DBDeletePlayerJournals(mob.Name()); CMLib.database().DBDeletePlayerData(mob.Name()); } final PlayerStats pstats = mob.playerStats(); if(pstats!=null) { final PlayerAccount account = pstats.getAccount(); if(account != null) { account.delPlayer(mob); DBUpdateAccount(account); account.setLastUpdated(System.currentTimeMillis()); } } if(deleteAssets) { for(int q=0;q<CMLib.quests().numQuests();q++) { final Quest Q=CMLib.quests().fetchQuest(q); if(Q.wasWinner(mob.Name())) Q.declareWinner("-"+mob.Name()); } } } public void DBUpdateAbilities(MOB mob) { if(mob.Name().length()==0) return; final List<DBPreparedBatchEntry> statements=new LinkedList<DBPreparedBatchEntry>(); statements.add(new DBPreparedBatchEntry("DELETE FROM CMCHAB WHERE CMUSERID='"+mob.Name()+"'")); final HashSet<String> H=new HashSet<String>(); for(int a=0;a<mob.numAbilities();a++) { final Ability thisAbility=mob.fetchAbility(a); if((thisAbility!=null)&&(thisAbility.isSavable())) { int proficiency=thisAbility.proficiency(); final Ability effectA=mob.fetchEffect(thisAbility.ID()); if(effectA!=null) { if((effectA.isSavable())&&(!effectA.canBeUninvoked())&&(!effectA.isAutoInvoked())) proficiency=proficiency-200; } H.add(thisAbility.ID()); final String sql="INSERT INTO CMCHAB (CMUSERID, CMABID, CMABPF,CMABTX" +") values ('"+mob.Name()+"','"+thisAbility.ID()+"',"+proficiency+",?)"; statements.add(new DBPreparedBatchEntry(sql,thisAbility.text())); } } for(final Enumeration<Ability> a=mob.personalEffects();a.hasMoreElements();) { final Ability A=a.nextElement(); if((A!=null)&&(!H.contains(A.ID()))&&(A.isSavable())&&(!A.canBeUninvoked())) { final String sql="INSERT INTO CMCHAB (CMUSERID, CMABID, CMABPF,CMABTX" +") values ('"+mob.Name()+"','"+A.ID()+"',"+Integer.MAX_VALUE+",?)"; statements.add(new DBPreparedBatchEntry(sql,A.text())); } } for(final Enumeration<Behavior> e=mob.behaviors();e.hasMoreElements();) { final Behavior B=e.nextElement(); if((B!=null)&&(B.isSavable())) { final String sql="INSERT INTO CMCHAB (CMUSERID, CMABID, CMABPF,CMABTX" +") values ('"+mob.Name()+"','"+B.ID()+"',"+(Integer.MIN_VALUE+1)+",?" +")"; statements.add(new DBPreparedBatchEntry(sql,B.getParms())); } } final String scriptStuff = CMLib.coffeeMaker().getGenScripts(mob,true); if(scriptStuff.length()>0) { final String sql="INSERT INTO CMCHAB (CMUSERID, CMABID, CMABPF,CMABTX" +") values ('"+mob.Name()+"','ScriptingEngine',"+(Integer.MIN_VALUE+1)+",?" +")"; statements.add(new DBPreparedBatchEntry(sql,scriptStuff)); } DB.updateWithClobs(statements); } public void DBCreateCharacter(MOB mob) { if(mob.Name().length()==0) return; final PlayerStats pstats=mob.playerStats(); if(pstats==null) return; DB.update("INSERT INTO CMCHAR (CMUSERID, CMPASS, CMCLAS, CMRACE, CMGEND " +") VALUES ('"+mob.Name()+"','"+pstats.getPasswordStr()+"','"+mob.baseCharStats().getMyClassesStr() +"','"+mob.baseCharStats().getMyRace().ID()+"','"+((char)mob.baseCharStats().getStat(CharStats.STAT_GENDER)) +"')"); final PlayerAccount account = pstats.getAccount(); if(account != null) { account.addNewPlayer(mob); DBUpdateAccount(account); account.setLastUpdated(System.currentTimeMillis()); } } public void DBUpdateAccount(PlayerAccount account) { if(account == null) return; final String characters = CMParms.toSemicolonList(account.getPlayers()); DB.updateWithClobs("UPDATE CMACCT SET CMPASS='"+account.getPasswordStr()+"', CMCHRS=?, CMAXML=? WHERE CMANAM='"+account.getAccountName()+"'", new String[][]{{characters,account.getXML()}}); } public void DBDeleteAccount(PlayerAccount account) { if(account == null) return; DB.update("DELETE FROM CMACCT WHERE CMANAM='"+account.getAccountName()+"'"); } public void DBCreateAccount(PlayerAccount account) { if(account == null) return; account.setAccountName(CMStrings.capitalizeAndLower(account.getAccountName())); final String characters = CMParms.toSemicolonList(account.getPlayers()); DB.updateWithClobs("INSERT INTO CMACCT (CMANAM, CMPASS, CMCHRS, CMAXML) " +"VALUES ('"+account.getAccountName()+"','"+account.getPasswordStr()+"',?,?)",new String[][]{{characters,account.getXML()}}); } public PlayerAccount MakeAccount(String username, ResultSet R) throws SQLException { PlayerAccount account = null; account = (PlayerAccount)CMClass.getCommon("DefaultPlayerAccount"); final String password=DB.getRes(R,"CMPASS"); final String chrs=DB.getRes(R,"CMCHRS"); final String xml=DB.getRes(R,"CMAXML"); final Vector<String> names = new Vector<String>(); if(chrs!=null) names.addAll(CMParms.parseSemicolons(chrs,true)); account.setAccountName(CMStrings.capitalizeAndLower(username)); account.setPassword(password); account.setPlayerNames(names); account.setXML(xml); return account; } public PlayerAccount DBReadAccount(String Login) { DBConnection D=null; PlayerAccount account = null; try { // why in the hell is this a memory scan? // case insensitivity from databases configured almost // certainly by amateurs is the answer. That, and fakedb // doesn't understand 'LIKE' D=DB.DBFetch(); final ResultSet R=D.query("SELECT * FROM CMACCT WHERE CMANAM='"+CMStrings.replaceAll(CMStrings.capitalizeAndLower(Login),"\'", "n")+"'"); if(R!=null) while(R.next()) { final String username=DB.getRes(R,"CMANAM"); if(Login.equalsIgnoreCase(username)) account = MakeAccount(username,R); } } catch(final Exception sqle) { Log.errOut("MOB",sqle); } finally { DB.DBDone(D); } return account; } public List<PlayerAccount> DBListAccounts(String mask) { DBConnection D=null; PlayerAccount account = null; final Vector<PlayerAccount> accounts = new Vector<PlayerAccount>(); if(mask!=null) mask=mask.toLowerCase(); try { // why in the hell is this a memory scan? // case insensitivity from databases configured almost // certainly by amateurs is the answer. That, and fakedb // doesn't understand 'LIKE' D=DB.DBFetch(); final ResultSet R=D.query("SELECT * FROM CMACCT"); if(R!=null) while(R.next()) { final String username=DB.getRes(R,"CMANAM"); if((mask==null)||(mask.length()==0)||(username.toLowerCase().indexOf(mask)>=0)) { account = MakeAccount(username,R); accounts.add(account); } } } catch(final Exception sqle) { Log.errOut("MOB",sqle); } finally { DB.DBDone(D); } return accounts; } public List<String> DBExpiredCharNameSearch(Set<String> skipNames) { DBConnection D=null; String buf=null; final List<String> expiredPlayers = new ArrayList<String>(); final long now=System.currentTimeMillis(); try { D=DB.DBFetch(); final ResultSet R=D.query("SELECT * FROM CMCHAR"); if(R!=null) while(R.next()) { final String username=DB.getRes(R,"CMUSERID"); if((skipNames!=null)&&(skipNames.contains(username))) continue; buf=DBConnections.getRes(R,"CMPFIL"); final String secGrps=CMLib.xml().restoreAngleBrackets(CMLib.xml().returnXMLValue(buf,"SECGRPS")); final SecGroup g=CMSecurity.instance().createGroup("", CMParms.parseSemicolons(secGrps,true)); if(g.contains(SecFlag.NOEXPIRE, false)) continue; long expiration; if(CMLib.xml().returnXMLValue(buf,"ACCTEXP").length()>0) expiration=CMath.s_long(CMLib.xml().returnXMLValue(buf,"ACCTEXP")); else { final Calendar C=Calendar.getInstance(); C.add(Calendar.DATE,CMProps.getIntVar(CMProps.Int.TRIALDAYS)); expiration=C.getTimeInMillis(); } if(now>=expiration) expiredPlayers.add(username); } } catch(final Exception sqle) { Log.errOut("MOB",sqle); } finally { DB.DBDone(D); } return expiredPlayers; } public PlayerLibrary.ThinnerPlayer DBUserSearch(String Login) { DBConnection D=null; String buf=null; PlayerLibrary.ThinnerPlayer thinPlayer = null; try { // why in the hell is this a memory scan? // case insensitivity from databases configured almost // certainly by amateurs is the answer. That, and fakedb // doesn't understand 'LIKE' D=DB.DBFetch(); final ResultSet R=D.query("SELECT * FROM CMCHAR WHERE CMUSERID='"+CMStrings.capitalizeAndLower(Login).replace('\'', 'n')+"'"); if(R!=null) while(R.next()) { final String username=DB.getRes(R,"CMUSERID"); thinPlayer = new PlayerLibrary.ThinnerPlayer(); final String password=DB.getRes(R,"CMPASS"); final String email=DB.getRes(R,"CMEMAL"); thinPlayer.name=username; thinPlayer.password=password; thinPlayer.email=email; // Acct Exp Code buf=DBConnections.getRes(R,"CMPFIL"); } } catch(final Exception sqle) { Log.errOut("MOB",sqle); } finally { DB.DBDone(D); } if((buf!=null)&&(thinPlayer!=null)) { PlayerAccount acct = null; thinPlayer.accountName = CMLib.xml().returnXMLValue(buf,"ACCOUNT"); if((thinPlayer.accountName!=null)&&(thinPlayer.accountName.length()>0)) acct = CMLib.players().getLoadAccount(thinPlayer.accountName); if((acct != null)&&(CMProps.getIntVar(CMProps.Int.COMMONACCOUNTSYSTEM)>1)) thinPlayer.expiration=acct.getAccountExpiration(); else if(CMLib.xml().returnXMLValue(buf,"ACCTEXP").length()>0) thinPlayer.expiration=CMath.s_long(CMLib.xml().returnXMLValue(buf,"ACCTEXP")); else { final Calendar C=Calendar.getInstance(); C.add(Calendar.DATE,CMProps.getIntVar(CMProps.Int.TRIALDAYS)); thinPlayer.expiration=C.getTimeInMillis(); } } return thinPlayer; } public String[] DBFetchEmailData(String name) { final String[] data=new String[2]; for(final Enumeration<MOB> e=CMLib.players().players();e.hasMoreElements();) { final MOB M=e.nextElement(); if((M.Name().equalsIgnoreCase(name))&&(M.playerStats()!=null)) { data[0]=M.playerStats().getEmail(); data[1]=""+((M.getBitmap()&MOB.ATT_AUTOFORWARD)==MOB.ATT_AUTOFORWARD); return data; } } DBConnection D=null; try { D=DB.DBFetch(); final ResultSet R=D.query("SELECT * FROM CMCHAR WHERE CMUSERID='"+name.replace('\'', 'n')+"'"); if(R!=null) while(R.next()) { // String username=DB.getRes(R,"CMUSERID"); final int btmp=CMath.s_int(DB.getRes(R,"CMBTMP")); final String temail=DB.getRes(R,"CMEMAL"); data[0]=temail; data[1]=""+((btmp&MOB.ATT_AUTOFORWARD)==MOB.ATT_AUTOFORWARD); return data; } } catch(final Exception sqle) { Log.errOut("MOB",sqle); } finally { DB.DBDone(D); } return null; } public String DBPlayerEmailSearch(String email) { DBConnection D=null; for(final Enumeration<MOB> e=CMLib.players().players();e.hasMoreElements();) { final MOB M=e.nextElement(); if((M.playerStats()!=null)&&(M.playerStats().getEmail().equalsIgnoreCase(email))) return M.Name(); } try { D=DB.DBFetch(); email=DB.injectionClean(email.trim()); ResultSet R=D.query("SELECT * FROM CMCHAR WHERE CMEMAL='"+email+"'"); if(((R==null)||(!R.next()))&&(!CMStrings.isLowerCase(email))) R=D.query("SELECT * FROM CMCHAR WHERE CMEMAL='"+email.toLowerCase()+"'"); if((R==null)||(!R.next())) R=D.query("SELECT * FROM CMCHAR WHERE CMEMAL LIKE '"+email+"'"); if((R==null)||(!R.next())) R=D.query("SELECT * FROM CMCHAR"); if(R!=null) while(R.next()) { final String username=DB.getRes(R,"CMUSERID"); final String temail=DB.getRes(R,"CMEMAL"); if(temail.equalsIgnoreCase(email)) { return username; } } } catch(final Exception sqle) { Log.errOut("MOB",sqle); } finally { DB.DBDone(D); } return null; } }
apache-2.0
veniosg/Dir
app/src/androidTest/java/com/veniosg/dir/test/acceptance/SettingsActivityTest.java
286
package com.veniosg.dir.test.acceptance; import android.support.test.filters.LargeTest; import android.support.test.runner.AndroidJUnit4; import org.junit.Ignore; import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) @LargeTest @Ignore public class SettingsActivityTest { }
apache-2.0
youngwookim/presto
presto-hive/src/main/java/io/prestosql/plugin/hive/HivePageSourceProvider.java
19087
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.plugin.hive; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import io.prestosql.plugin.hive.HdfsEnvironment.HdfsContext; import io.prestosql.plugin.hive.HiveSplit.BucketConversion; import io.prestosql.spi.connector.ColumnHandle; import io.prestosql.spi.connector.ConnectorPageSource; import io.prestosql.spi.connector.ConnectorPageSourceProvider; import io.prestosql.spi.connector.ConnectorSession; import io.prestosql.spi.connector.ConnectorSplit; import io.prestosql.spi.connector.ConnectorTableHandle; import io.prestosql.spi.connector.ConnectorTransactionHandle; import io.prestosql.spi.connector.RecordCursor; import io.prestosql.spi.connector.RecordPageSource; import io.prestosql.spi.predicate.TupleDomain; import io.prestosql.spi.type.Type; import io.prestosql.spi.type.TypeManager; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.joda.time.DateTimeZone; import javax.inject.Inject; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.OptionalInt; import java.util.Properties; import java.util.Set; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Maps.uniqueIndex; import static io.prestosql.plugin.hive.HiveColumnHandle.ColumnType.PARTITION_KEY; import static io.prestosql.plugin.hive.HiveColumnHandle.ColumnType.REGULAR; import static io.prestosql.plugin.hive.HiveColumnHandle.ColumnType.SYNTHESIZED; import static io.prestosql.plugin.hive.HivePageSourceProvider.ColumnMapping.toColumnHandles; import static io.prestosql.plugin.hive.HiveUtil.getPrefilledColumnValue; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; public class HivePageSourceProvider implements ConnectorPageSourceProvider { private final DateTimeZone hiveStorageTimeZone; private final HdfsEnvironment hdfsEnvironment; private final Set<HiveRecordCursorProvider> cursorProviders; private final TypeManager typeManager; private final Set<HivePageSourceFactory> pageSourceFactories; @Inject public HivePageSourceProvider( HiveConfig hiveConfig, HdfsEnvironment hdfsEnvironment, Set<HiveRecordCursorProvider> cursorProviders, Set<HivePageSourceFactory> pageSourceFactories, TypeManager typeManager) { requireNonNull(hiveConfig, "hiveConfig is null"); this.hiveStorageTimeZone = hiveConfig.getDateTimeZone(); this.hdfsEnvironment = requireNonNull(hdfsEnvironment, "hdfsEnvironment is null"); this.cursorProviders = ImmutableSet.copyOf(requireNonNull(cursorProviders, "cursorProviders is null")); this.pageSourceFactories = ImmutableSet.copyOf(requireNonNull(pageSourceFactories, "pageSourceFactories is null")); this.typeManager = requireNonNull(typeManager, "typeManager is null"); } @Override public ConnectorPageSource createPageSource(ConnectorTransactionHandle transaction, ConnectorSession session, ConnectorSplit split, ConnectorTableHandle table, List<ColumnHandle> columns) { List<HiveColumnHandle> hiveColumns = columns.stream() .map(HiveColumnHandle.class::cast) .collect(toList()); HiveSplit hiveSplit = (HiveSplit) split; Path path = new Path(hiveSplit.getPath()); Configuration configuration = hdfsEnvironment.getConfiguration(new HdfsContext(session, hiveSplit.getDatabase(), hiveSplit.getTable()), path); Optional<ConnectorPageSource> pageSource = createHivePageSource( cursorProviders, pageSourceFactories, configuration, session, path, hiveSplit.getBucketNumber(), hiveSplit.getStart(), hiveSplit.getLength(), hiveSplit.getFileSize(), hiveSplit.getSchema(), hiveSplit.getEffectivePredicate(), hiveColumns, hiveSplit.getPartitionKeys(), hiveStorageTimeZone, typeManager, hiveSplit.getColumnCoercions(), hiveSplit.getBucketConversion(), hiveSplit.isS3SelectPushdownEnabled()); if (pageSource.isPresent()) { return pageSource.get(); } throw new RuntimeException("Could not find a file reader for split " + hiveSplit); } public static Optional<ConnectorPageSource> createHivePageSource( Set<HiveRecordCursorProvider> cursorProviders, Set<HivePageSourceFactory> pageSourceFactories, Configuration configuration, ConnectorSession session, Path path, OptionalInt bucketNumber, long start, long length, long fileSize, Properties schema, TupleDomain<HiveColumnHandle> effectivePredicate, List<HiveColumnHandle> hiveColumns, List<HivePartitionKey> partitionKeys, DateTimeZone hiveStorageTimeZone, TypeManager typeManager, Map<Integer, HiveType> columnCoercions, Optional<BucketConversion> bucketConversion, boolean s3SelectPushdownEnabled) { List<ColumnMapping> columnMappings = ColumnMapping.buildColumnMappings( partitionKeys, hiveColumns, bucketConversion.map(BucketConversion::getBucketColumnHandles).orElse(ImmutableList.of()), columnCoercions, path, bucketNumber); List<ColumnMapping> regularAndInterimColumnMappings = ColumnMapping.extractRegularAndInterimColumnMappings(columnMappings); Optional<BucketAdaptation> bucketAdaptation = bucketConversion.map(conversion -> { Map<Integer, ColumnMapping> hiveIndexToBlockIndex = uniqueIndex(regularAndInterimColumnMappings, columnMapping -> columnMapping.getHiveColumnHandle().getHiveColumnIndex()); int[] bucketColumnIndices = conversion.getBucketColumnHandles().stream() .mapToInt(columnHandle -> hiveIndexToBlockIndex.get(columnHandle.getHiveColumnIndex()).getIndex()) .toArray(); List<HiveType> bucketColumnHiveTypes = conversion.getBucketColumnHandles().stream() .map(columnHandle -> hiveIndexToBlockIndex.get(columnHandle.getHiveColumnIndex()).getHiveColumnHandle().getHiveType()) .collect(toImmutableList()); return new BucketAdaptation(bucketColumnIndices, bucketColumnHiveTypes, conversion.getTableBucketCount(), conversion.getPartitionBucketCount(), bucketNumber.getAsInt()); }); for (HivePageSourceFactory pageSourceFactory : pageSourceFactories) { Optional<? extends ConnectorPageSource> pageSource = pageSourceFactory.createPageSource( configuration, session, path, start, length, fileSize, schema, toColumnHandles(regularAndInterimColumnMappings, true), effectivePredicate, hiveStorageTimeZone); if (pageSource.isPresent()) { return Optional.of( new HivePageSource( columnMappings, bucketAdaptation, hiveStorageTimeZone, typeManager, pageSource.get())); } } for (HiveRecordCursorProvider provider : cursorProviders) { // GenericHiveRecordCursor will automatically do the coercion without HiveCoercionRecordCursor boolean doCoercion = !(provider instanceof GenericHiveRecordCursorProvider); Optional<RecordCursor> cursor = provider.createRecordCursor( configuration, session, path, start, length, fileSize, schema, toColumnHandles(regularAndInterimColumnMappings, doCoercion), effectivePredicate, hiveStorageTimeZone, typeManager, s3SelectPushdownEnabled); if (cursor.isPresent()) { RecordCursor delegate = cursor.get(); if (bucketAdaptation.isPresent()) { delegate = new HiveBucketAdapterRecordCursor( bucketAdaptation.get().getBucketColumnIndices(), bucketAdaptation.get().getBucketColumnHiveTypes(), bucketAdaptation.get().getTableBucketCount(), bucketAdaptation.get().getPartitionBucketCount(), bucketAdaptation.get().getBucketToKeep(), typeManager, delegate); } // Need to wrap RcText and RcBinary into a wrapper, which will do the coercion for mismatch columns if (doCoercion) { delegate = new HiveCoercionRecordCursor(regularAndInterimColumnMappings, typeManager, delegate); } HiveRecordCursor hiveRecordCursor = new HiveRecordCursor( columnMappings, hiveStorageTimeZone, typeManager, delegate); List<Type> columnTypes = hiveColumns.stream() .map(input -> typeManager.getType(input.getTypeSignature())) .collect(toList()); return Optional.of(new RecordPageSource(columnTypes, hiveRecordCursor)); } } return Optional.empty(); } public static class ColumnMapping { private final ColumnMappingKind kind; private final HiveColumnHandle hiveColumnHandle; private final Optional<String> prefilledValue; /** * ordinal of this column in the underlying page source or record cursor */ private final OptionalInt index; private final Optional<HiveType> coercionFrom; public static ColumnMapping regular(HiveColumnHandle hiveColumnHandle, int index, Optional<HiveType> coerceFrom) { checkArgument(hiveColumnHandle.getColumnType() == REGULAR); return new ColumnMapping(ColumnMappingKind.REGULAR, hiveColumnHandle, Optional.empty(), OptionalInt.of(index), coerceFrom); } public static ColumnMapping prefilled(HiveColumnHandle hiveColumnHandle, String prefilledValue, Optional<HiveType> coerceFrom) { checkArgument(hiveColumnHandle.getColumnType() == PARTITION_KEY || hiveColumnHandle.getColumnType() == SYNTHESIZED); return new ColumnMapping(ColumnMappingKind.PREFILLED, hiveColumnHandle, Optional.of(prefilledValue), OptionalInt.empty(), coerceFrom); } public static ColumnMapping interim(HiveColumnHandle hiveColumnHandle, int index) { checkArgument(hiveColumnHandle.getColumnType() == REGULAR); return new ColumnMapping(ColumnMappingKind.INTERIM, hiveColumnHandle, Optional.empty(), OptionalInt.of(index), Optional.empty()); } private ColumnMapping(ColumnMappingKind kind, HiveColumnHandle hiveColumnHandle, Optional<String> prefilledValue, OptionalInt index, Optional<HiveType> coerceFrom) { this.kind = requireNonNull(kind, "kind is null"); this.hiveColumnHandle = requireNonNull(hiveColumnHandle, "hiveColumnHandle is null"); this.prefilledValue = requireNonNull(prefilledValue, "prefilledValue is null"); this.index = requireNonNull(index, "index is null"); this.coercionFrom = requireNonNull(coerceFrom, "coerceFrom is null"); } public ColumnMappingKind getKind() { return kind; } public String getPrefilledValue() { checkState(kind == ColumnMappingKind.PREFILLED); return prefilledValue.get(); } public HiveColumnHandle getHiveColumnHandle() { return hiveColumnHandle; } public int getIndex() { checkState(kind == ColumnMappingKind.REGULAR || kind == ColumnMappingKind.INTERIM); return index.getAsInt(); } public Optional<HiveType> getCoercionFrom() { return coercionFrom; } /** * @param columns columns that need to be returned to engine * @param requiredInterimColumns columns that are needed for processing, but shouldn't be returned to engine (may overlaps with columns) * @param columnCoercions map from hive column index to hive type * @param bucketNumber empty if table is not bucketed, a number within [0, # bucket in table) otherwise */ public static List<ColumnMapping> buildColumnMappings( List<HivePartitionKey> partitionKeys, List<HiveColumnHandle> columns, List<HiveColumnHandle> requiredInterimColumns, Map<Integer, HiveType> columnCoercions, Path path, OptionalInt bucketNumber) { Map<String, HivePartitionKey> partitionKeysByName = uniqueIndex(partitionKeys, HivePartitionKey::getName); int regularIndex = 0; Set<Integer> regularColumnIndices = new HashSet<>(); ImmutableList.Builder<ColumnMapping> columnMappings = ImmutableList.builder(); for (HiveColumnHandle column : columns) { Optional<HiveType> coercionFrom = Optional.ofNullable(columnCoercions.get(column.getHiveColumnIndex())); if (column.getColumnType() == REGULAR) { checkArgument(regularColumnIndices.add(column.getHiveColumnIndex()), "duplicate hiveColumnIndex in columns list"); columnMappings.add(regular(column, regularIndex, coercionFrom)); regularIndex++; } else { columnMappings.add(prefilled( column, getPrefilledColumnValue(column, partitionKeysByName.get(column.getName()), path, bucketNumber), coercionFrom)); } } for (HiveColumnHandle column : requiredInterimColumns) { checkArgument(column.getColumnType() == REGULAR); if (regularColumnIndices.contains(column.getHiveColumnIndex())) { continue; // This column exists in columns. Do not add it again. } // If coercion does not affect bucket number calculation, coercion doesn't need to be applied here. // Otherwise, read of this partition should not be allowed. // (Alternatively, the partition could be read as an unbucketed partition. This is not implemented.) columnMappings.add(interim(column, regularIndex)); regularIndex++; } return columnMappings.build(); } public static List<ColumnMapping> extractRegularAndInterimColumnMappings(List<ColumnMapping> columnMappings) { return columnMappings.stream() .filter(columnMapping -> columnMapping.getKind() == ColumnMappingKind.REGULAR || columnMapping.getKind() == ColumnMappingKind.INTERIM) .collect(toImmutableList()); } public static List<HiveColumnHandle> toColumnHandles(List<ColumnMapping> regularColumnMappings, boolean doCoercion) { return regularColumnMappings.stream() .map(columnMapping -> { HiveColumnHandle columnHandle = columnMapping.getHiveColumnHandle(); if (!doCoercion || !columnMapping.getCoercionFrom().isPresent()) { return columnHandle; } return new HiveColumnHandle( columnHandle.getName(), columnMapping.getCoercionFrom().get(), columnMapping.getCoercionFrom().get().getTypeSignature(), columnHandle.getHiveColumnIndex(), columnHandle.getColumnType(), Optional.empty()); }) .collect(toList()); } } public enum ColumnMappingKind { REGULAR, PREFILLED, INTERIM, } public static class BucketAdaptation { private final int[] bucketColumnIndices; private final List<HiveType> bucketColumnHiveTypes; private final int tableBucketCount; private final int partitionBucketCount; private final int bucketToKeep; public BucketAdaptation(int[] bucketColumnIndices, List<HiveType> bucketColumnHiveTypes, int tableBucketCount, int partitionBucketCount, int bucketToKeep) { this.bucketColumnIndices = bucketColumnIndices; this.bucketColumnHiveTypes = bucketColumnHiveTypes; this.tableBucketCount = tableBucketCount; this.partitionBucketCount = partitionBucketCount; this.bucketToKeep = bucketToKeep; } public int[] getBucketColumnIndices() { return bucketColumnIndices; } public List<HiveType> getBucketColumnHiveTypes() { return bucketColumnHiveTypes; } public int getTableBucketCount() { return tableBucketCount; } public int getPartitionBucketCount() { return partitionBucketCount; } public int getBucketToKeep() { return bucketToKeep; } } }
apache-2.0
palantir/atlasdb
atlasdb-cassandra/src/main/java/com/palantir/atlasdb/keyvalue/cassandra/CassandraLogHelper.java
3357
/* * (c) Copyright 2018 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.atlasdb.keyvalue.cassandra; import com.google.common.collect.Multimap; import com.google.common.collect.Range; import com.google.common.collect.RangeMap; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.apache.cassandra.thrift.TokenRange; import org.immutables.value.Value; public final class CassandraLogHelper { private CassandraLogHelper() { // Utility class. } public static HostAndIpAddress host(InetSocketAddress host) { return HostAndIpAddress.fromAddress(host); } static Collection<HostAndIpAddress> collectionOfHosts(Collection<InetSocketAddress> hosts) { return hosts.stream().map(CassandraLogHelper::host).collect(Collectors.toSet()); } static List<String> tokenRangesToHost(Multimap<Set<TokenRange>, InetSocketAddress> tokenRangesToHost) { return tokenRangesToHost.entries().stream() .map(entry -> String.format("host %s has range %s", entry.getKey().toString(), host(entry.getValue()))) .collect(Collectors.toList()); } public static List<String> tokenMap(RangeMap<LightweightOppToken, List<InetSocketAddress>> tokenMap) { return tokenMap.asMapOfRanges().entrySet().stream() .map(rangeListToHostEntry -> String.format( "range from %s to %s is on host %s", getLowerEndpoint(rangeListToHostEntry.getKey()), getUpperEndpoint(rangeListToHostEntry.getKey()), CassandraLogHelper.collectionOfHosts(rangeListToHostEntry.getValue()))) .collect(Collectors.toList()); } private static String getLowerEndpoint(Range<LightweightOppToken> range) { if (!range.hasLowerBound()) { return "(no lower bound)"; } return range.lowerEndpoint().toString(); } private static String getUpperEndpoint(Range<LightweightOppToken> range) { if (!range.hasUpperBound()) { return "(no upper bound)"; } return range.upperEndpoint().toString(); } @Value.Immutable interface HostAndIpAddress { String host(); Optional<String> ipAddress(); static HostAndIpAddress fromAddress(InetSocketAddress address) { return ImmutableHostAndIpAddress.builder() .host(address.getHostString()) .ipAddress(Optional.ofNullable(address.getAddress()).map(InetAddress::getHostAddress)) .build(); } } }
apache-2.0
eliabruni/ludwig
src/com/s2m/ludwig/core/cooccur/Cooccurs.java
1800
package com.s2m.ludwig.core.cooccur; import com.carrotsearch.hppc.LongIntOpenHashMap; import com.carrotsearch.hppc.LongObjectOpenHashMap; import com.carrotsearch.hppc.ObjectArrayList; /************************************************************************* * * Description * ------- * * * Remarks * ------- * * *************************************************************************/ public class Cooccurs { /** * Retain all the cooccur counts. */ private ObjectArrayList<LongObjectOpenHashMap<LongIntOpenHashMap>> cooccurs; /********************************************************************************** * Constructors **********************************************************************************/ public Cooccurs() { cooccurs = new ObjectArrayList<LongObjectOpenHashMap<LongIntOpenHashMap>>(); } /********************************************************************************** * Main methods **********************************************************************************/ /** * */ public void addCooccurMap(LongObjectOpenHashMap<LongIntOpenHashMap> cooccur) { cooccurs.add(cooccur); } /** * * @param TP * @return */ public LongObjectOpenHashMap<LongIntOpenHashMap> getCooccur(int TP) { return cooccurs.get(TP); } /** * * @param TP */ public void removeTP(int TP) { // TODO: put a check here, to be sure there is the TP inside cooccurs, before removing. cooccurs.remove(TP); } /** * * @param TP */ public void insertTP(int TP) { cooccurs.insert(TP, new LongObjectOpenHashMap<LongIntOpenHashMap>()); } /** * * A wrapper around removeTP(int TP) and insertTP(int TP). * * @param int TP */ public void resetTP(int TP) { removeTP(TP); insertTP(TP); } }
apache-2.0
DreamSunny/Subway
subwaylib/src/main/java/com/infrastructure/image/DiskLruCache.java
33896
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.infrastructure.image; import java.io.BufferedInputStream; import java.io.BufferedWriter; import java.io.Closeable; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Array; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** ****************************************************************************** * Taken from the JB source code, can be found in: * libcore/luni/src/main/java/libcore/io/DiskLruCache.java * or direct link: * https://android.googlesource.com/platform/libcore/+/android-4.1.1_r1/luni/src/main/java/libcore/io/DiskLruCache.java ****************************************************************************** * * A cache that uses a bounded amount of space on a filesystem. Each cache * entry has a string key and a fixed number of values. Values are byte * sequences, accessible as streams or files. Each value must be between {@code * 0} and {@code Integer.MAX_VALUE} bytes in length. * * <p>The cache stores its data in a directory on the filesystem. This * directory must be exclusive to the cache; the cache may delete or overwrite * files from its directory. It is an error for multiple processes to use the * same cache directory at the same time. * * <p>This cache limits the number of bytes that it will store on the * filesystem. When the number of stored bytes exceeds the limit, the cache will * remove entries in the background until the limit is satisfied. The limit is * not strict: the cache may temporarily exceed it while waiting for files to be * deleted. The limit does not include filesystem overhead or the cache * journal so space-sensitive applications should set a conservative limit. * * <p>Clients call {@link #edit} to create or update the values of an entry. An * entry may have only one editor at one time; if a value is not available to be * edited then {@link #edit} will return null. * <ul> * <li>When an entry is being <strong>created</strong> it is necessary to * supply a full set of values; the empty value should be used as a * placeholder if necessary. * <li>When an entry is being <strong>edited</strong>, it is not necessary * to supply data for every value; values default to their previous * value. * </ul> * Every {@link #edit} call must be matched by a call to {@link Editor#commit} * or {@link Editor#abort}. Committing is atomic: a read observes the full set * of values as they were before or after the commit, but never a mix of values. * * <p>Clients call {@link #get} to read a snapshot of an entry. The read will * observe the value at the time that {@link #get} was called. Updates and * removals after the call do not impact ongoing reads. * * <p>This class is tolerant of some I/O errors. If files are missing from the * filesystem, the corresponding entries will be dropped from the cache. If * an error occurs while writing a cache value, the edit will fail silently. * Callers should handle other problems by catching {@code IOException} and * responding appropriately. */ public final class DiskLruCache implements Closeable { static final String JOURNAL_FILE = "journal"; static final String JOURNAL_FILE_TMP = "journal.tmp"; static final String MAGIC = "libcore.io.DiskLruCache"; static final String VERSION_1 = "1"; static final long ANY_SEQUENCE_NUMBER = -1; private static final String CLEAN = "CLEAN"; private static final String DIRTY = "DIRTY"; private static final String REMOVE = "REMOVE"; private static final String READ = "READ"; private static final Charset UTF_8 = Charset.forName("UTF-8"); private static final int IO_BUFFER_SIZE = 8 * 1024; /* * This cache uses a journal file named "journal". A typical journal file * looks like this: * libcore.io.DiskLruCache * 1 * 100 * 2 * * CLEAN 3400330d1dfc7f3f7f4b8d4d803dfcf6 832 21054 * DIRTY 335c4c6028171cfddfbaae1a9c313c52 * CLEAN 335c4c6028171cfddfbaae1a9c313c52 3934 2342 * REMOVE 335c4c6028171cfddfbaae1a9c313c52 * DIRTY 1ab96a171faeeee38496d8b330771a7a * CLEAN 1ab96a171faeeee38496d8b330771a7a 1600 234 * READ 335c4c6028171cfddfbaae1a9c313c52 * READ 3400330d1dfc7f3f7f4b8d4d803dfcf6 * * The first five lines of the journal form its header. They are the * constant string "libcore.io.DiskLruCache", the disk cache's version, * the application's version, the value count, and a blank line. * * Each of the subsequent lines in the file is a record of the state of a * cache entry. Each line contains space-separated values: a state, a key, * and optional state-specific values. * o DIRTY lines track that an entry is actively being created or updated. * Every successful DIRTY action should be followed by a CLEAN or REMOVE * action. DIRTY lines without a matching CLEAN or REMOVE indicate that * temporary files may need to be deleted. * o CLEAN lines track a cache entry that has been successfully published * and may be read. A publish line is followed by the lengths of each of * its values. * o READ lines track accesses for LRU. * o REMOVE lines track entries that have been deleted. * * The journal file is appended to as cache operations occur. The journal may * occasionally be compacted by dropping redundant lines. A temporary file named * "journal.tmp" will be used during compaction; that file should be deleted if * it exists when the cache is opened. */ private final File directory; private final File journalFile; private final File journalFileTmp; private final int appVersion; private final long maxSize; private final int valueCount; private long size = 0; private Writer journalWriter; private final LinkedHashMap<String, Entry> lruEntries = new LinkedHashMap<String, Entry>(0, 0.75f, true); private int redundantOpCount; /** * To differentiate between old and current snapshots, each entry is given * a sequence number each time an edit is committed. A snapshot is stale if * its sequence number is not equal to its entry's sequence number. */ private long nextSequenceNumber = 0; /* From java.util.Arrays */ @SuppressWarnings("unchecked") private static <T> T[] copyOfRange(T[] original, int start, int end) { final int originalLength = original.length; // For exception priority compatibility. if (start > end) { throw new IllegalArgumentException(); } if (start < 0 || start > originalLength) { throw new ArrayIndexOutOfBoundsException(); } final int resultLength = end - start; final int copyLength = Math.min(resultLength, originalLength - start); final T[] result = (T[]) Array .newInstance(original.getClass().getComponentType(), resultLength); System.arraycopy(original, start, result, 0, copyLength); return result; } /** * Returns the remainder of 'reader' as a string, closing it when done. */ public static String readFully(Reader reader) throws IOException { try { StringWriter writer = new StringWriter(); char[] buffer = new char[1024]; int count; while ((count = reader.read(buffer)) != -1) { writer.write(buffer, 0, count); } return writer.toString(); } finally { reader.close(); } } /** * Returns the ASCII characters up to but not including the next "\r\n", or * "\n". * * @throws EOFException if the stream is exhausted before the next newline * character. */ public static String readAsciiLine(InputStream in) throws IOException { // TODO: support UTF-8 here instead StringBuilder result = new StringBuilder(80); while (true) { int c = in.read(); if (c == -1) { throw new EOFException(); } else if (c == '\n') { break; } result.append((char) c); } int length = result.length(); if (length > 0 && result.charAt(length - 1) == '\r') { result.setLength(length - 1); } return result.toString(); } /** * Closes 'closeable', ignoring any checked exceptions. Does nothing if 'closeable' is null. */ public static void closeQuietly(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (RuntimeException rethrown) { throw rethrown; } catch (Exception ignored) { } } } /** * Recursively delete everything in {@code dir}. */ // TODO: this should specify paths as Strings rather than as Files public static void deleteContents(File dir) throws IOException { File[] files = dir.listFiles(); if (files == null) { throw new IllegalArgumentException("not a directory: " + dir); } for (File file : files) { if (file.isDirectory()) { deleteContents(file); } if (!file.delete()) { throw new IOException("failed to delete file: " + file); } } } /** This cache uses a single background thread to evict entries. */ private final ExecutorService executorService = new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); private final Callable<Void> cleanupCallable = new Callable<Void>() { @Override public Void call() throws Exception { synchronized (DiskLruCache.this) { if (journalWriter == null) { return null; // closed } trimToSize(); if (journalRebuildRequired()) { rebuildJournal(); redundantOpCount = 0; } } return null; } }; private DiskLruCache(File directory, int appVersion, int valueCount, long maxSize) { this.directory = directory; this.appVersion = appVersion; this.journalFile = new File(directory, JOURNAL_FILE); this.journalFileTmp = new File(directory, JOURNAL_FILE_TMP); this.valueCount = valueCount; this.maxSize = maxSize; } /** * Opens the cache in {@code directory}, creating a cache if none exists * there. * * @param directory a writable directory * @param appVersion * @param valueCount the number of values per cache entry. Must be positive. * @param maxSize the maximum number of bytes this cache should use to store * @throws IOException if reading or writing the cache directory fails */ public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize) throws IOException { if (maxSize <= 0) { throw new IllegalArgumentException("maxSize <= 0"); } if (valueCount <= 0) { throw new IllegalArgumentException("valueCount <= 0"); } // prefer to pick up where we left off DiskLruCache cache = new DiskLruCache(directory, appVersion, valueCount, maxSize); if (cache.journalFile.exists()) { try { cache.readJournal(); cache.processJournal(); cache.journalWriter = new BufferedWriter(new FileWriter(cache.journalFile, true), IO_BUFFER_SIZE); return cache; } catch (IOException journalIsCorrupt) { // System.logW("DiskLruCache " + directory + " is corrupt: " // + journalIsCorrupt.getMessage() + ", removing"); cache.delete(); } } // create a new empty cache directory.mkdirs(); cache = new DiskLruCache(directory, appVersion, valueCount, maxSize); cache.rebuildJournal(); return cache; } private void readJournal() throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(journalFile), IO_BUFFER_SIZE); try { String magic = readAsciiLine(in); String version = readAsciiLine(in); String appVersionString = readAsciiLine(in); String valueCountString = readAsciiLine(in); String blank = readAsciiLine(in); if (!MAGIC.equals(magic) || !VERSION_1.equals(version) || !Integer.toString(appVersion).equals(appVersionString) || !Integer.toString(valueCount).equals(valueCountString) || !"".equals(blank)) { throw new IOException("unexpected journal header: [" + magic + ", " + version + ", " + valueCountString + ", " + blank + "]"); } while (true) { try { readJournalLine(readAsciiLine(in)); } catch (EOFException endOfJournal) { break; } } } finally { closeQuietly(in); } } private void readJournalLine(String line) throws IOException { String[] parts = line.split(" "); if (parts.length < 2) { throw new IOException("unexpected journal line: " + line); } String key = parts[1]; if (parts[0].equals(REMOVE) && parts.length == 2) { lruEntries.remove(key); return; } Entry entry = lruEntries.get(key); if (entry == null) { entry = new Entry(key); lruEntries.put(key, entry); } if (parts[0].equals(CLEAN) && parts.length == 2 + valueCount) { entry.readable = true; entry.currentEditor = null; entry.setLengths(copyOfRange(parts, 2, parts.length)); } else if (parts[0].equals(DIRTY) && parts.length == 2) { entry.currentEditor = new Editor(entry); } else if (parts[0].equals(READ) && parts.length == 2) { // this work was already done by calling lruEntries.get() } else { throw new IOException("unexpected journal line: " + line); } } /** * Computes the initial size and collects garbage as a part of opening the * cache. Dirty entries are assumed to be inconsistent and will be deleted. */ private void processJournal() throws IOException { deleteIfExists(journalFileTmp); for (Iterator<Entry> i = lruEntries.values().iterator(); i.hasNext(); ) { Entry entry = i.next(); if (entry.currentEditor == null) { for (int t = 0; t < valueCount; t++) { size += entry.lengths[t]; } } else { entry.currentEditor = null; for (int t = 0; t < valueCount; t++) { deleteIfExists(entry.getCleanFile(t)); deleteIfExists(entry.getDirtyFile(t)); } i.remove(); } } } /** * Creates a new journal that omits redundant information. This replaces the * current journal if it exists. */ private synchronized void rebuildJournal() throws IOException { if (journalWriter != null) { journalWriter.close(); } Writer writer = new BufferedWriter(new FileWriter(journalFileTmp), IO_BUFFER_SIZE); writer.write(MAGIC); writer.write("\n"); writer.write(VERSION_1); writer.write("\n"); writer.write(Integer.toString(appVersion)); writer.write("\n"); writer.write(Integer.toString(valueCount)); writer.write("\n"); writer.write("\n"); for (Entry entry : lruEntries.values()) { if (entry.currentEditor != null) { writer.write(DIRTY + ' ' + entry.key + '\n'); } else { writer.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n'); } } writer.close(); journalFileTmp.renameTo(journalFile); journalWriter = new BufferedWriter(new FileWriter(journalFile, true), IO_BUFFER_SIZE); } private static void deleteIfExists(File file) throws IOException { // try { // Libcore.os.remove(file.getPath()); // } catch (ErrnoException errnoException) { // if (errnoException.errno != OsConstants.ENOENT) { // throw errnoException.rethrowAsIOException(); // } // } if (file.exists() && !file.delete()) { throw new IOException(); } } /** * Returns a snapshot of the entry named {@code key}, or null if it doesn't * exist is not currently readable. If a value is returned, it is moved to * the head of the LRU queue. */ public synchronized Snapshot get(String key) throws IOException { checkNotClosed(); validateKey(key); Entry entry = lruEntries.get(key); if (entry == null) { return null; } if (!entry.readable) { return null; } /* * Open all streams eagerly to guarantee that we see a single published * snapshot. If we opened streams lazily then the streams could come * from different edits. */ InputStream[] ins = new InputStream[valueCount]; try { for (int i = 0; i < valueCount; i++) { ins[i] = new FileInputStream(entry.getCleanFile(i)); } } catch (FileNotFoundException e) { // a file must have been deleted manually! return null; } redundantOpCount++; journalWriter.append(READ + ' ' + key + '\n'); if (journalRebuildRequired()) { executorService.submit(cleanupCallable); } return new Snapshot(key, entry.sequenceNumber, ins); } /** * Returns an editor for the entry named {@code key}, or null if another * edit is in progress. */ public Editor edit(String key) throws IOException { return edit(key, ANY_SEQUENCE_NUMBER); } private synchronized Editor edit(String key, long expectedSequenceNumber) throws IOException { checkNotClosed(); validateKey(key); Entry entry = lruEntries.get(key); if (expectedSequenceNumber != ANY_SEQUENCE_NUMBER && (entry == null || entry.sequenceNumber != expectedSequenceNumber)) { return null; // snapshot is stale } if (entry == null) { entry = new Entry(key); lruEntries.put(key, entry); } else if (entry.currentEditor != null) { return null; // another edit is in progress } Editor editor = new Editor(entry); entry.currentEditor = editor; // flush the journal before creating files to prevent file leaks journalWriter.write(DIRTY + ' ' + key + '\n'); journalWriter.flush(); return editor; } /** * Returns the directory where this cache stores its data. */ public File getDirectory() { return directory; } /** * Returns the maximum number of bytes that this cache should use to store * its data. */ public long maxSize() { return maxSize; } /** * Returns the number of bytes currently being used to store the values in * this cache. This may be greater than the max size if a background * deletion is pending. */ public synchronized long size() { return size; } private synchronized void completeEdit(Editor editor, boolean success) throws IOException { Entry entry = editor.entry; if (entry.currentEditor != editor) { throw new IllegalStateException(); } // if this edit is creating the entry for the first time, every index must have a value if (success && !entry.readable) { for (int i = 0; i < valueCount; i++) { if (!entry.getDirtyFile(i).exists()) { editor.abort(); throw new IllegalStateException("edit didn't create file " + i); } } } for (int i = 0; i < valueCount; i++) { File dirty = entry.getDirtyFile(i); if (success) { if (dirty.exists()) { File clean = entry.getCleanFile(i); dirty.renameTo(clean); long oldLength = entry.lengths[i]; long newLength = clean.length(); entry.lengths[i] = newLength; size = size - oldLength + newLength; } } else { deleteIfExists(dirty); } } redundantOpCount++; entry.currentEditor = null; if (entry.readable | success) { entry.readable = true; journalWriter.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n'); if (success) { entry.sequenceNumber = nextSequenceNumber++; } } else { lruEntries.remove(entry.key); journalWriter.write(REMOVE + ' ' + entry.key + '\n'); } if (size > maxSize || journalRebuildRequired()) { executorService.submit(cleanupCallable); } } /** * We only rebuild the journal when it will halve the size of the journal * and eliminate at least 2000 ops. */ private boolean journalRebuildRequired() { final int REDUNDANT_OP_COMPACT_THRESHOLD = 2000; return redundantOpCount >= REDUNDANT_OP_COMPACT_THRESHOLD && redundantOpCount >= lruEntries.size(); } /** * Drops the entry for {@code key} if it exists and can be removed. Entries * actively being edited cannot be removed. * * @return true if an entry was removed. */ public synchronized boolean remove(String key) throws IOException { checkNotClosed(); validateKey(key); Entry entry = lruEntries.get(key); if (entry == null || entry.currentEditor != null) { return false; } for (int i = 0; i < valueCount; i++) { File file = entry.getCleanFile(i); if (!file.delete()) { throw new IOException("failed to delete " + file); } size -= entry.lengths[i]; entry.lengths[i] = 0; } redundantOpCount++; journalWriter.append(REMOVE + ' ' + key + '\n'); lruEntries.remove(key); if (journalRebuildRequired()) { executorService.submit(cleanupCallable); } return true; } /** * Returns true if this cache has been closed. */ public boolean isClosed() { return journalWriter == null; } private void checkNotClosed() { if (journalWriter == null) { throw new IllegalStateException("cache is closed"); } } /** * Force buffered operations to the filesystem. */ public synchronized void flush() throws IOException { checkNotClosed(); trimToSize(); journalWriter.flush(); } /** * Closes this cache. Stored values will remain on the filesystem. */ public synchronized void close() throws IOException { if (journalWriter == null) { return; // already closed } for (Entry entry : new ArrayList<Entry>(lruEntries.values())) { if (entry.currentEditor != null) { entry.currentEditor.abort(); } } trimToSize(); journalWriter.close(); journalWriter = null; } private void trimToSize() throws IOException { while (size > maxSize) { // Map.Entry<String, Entry> toEvict = lruEntries.eldest(); final Map.Entry<String, Entry> toEvict = lruEntries.entrySet().iterator().next(); remove(toEvict.getKey()); } } /** * Closes the cache and deletes all of its stored values. This will delete * all files in the cache directory including files that weren't created by * the cache. */ public void delete() throws IOException { close(); deleteContents(directory); } private void validateKey(String key) { if (key.contains(" ") || key.contains("\n") || key.contains("\r")) { throw new IllegalArgumentException( "keys must not contain spaces or newlines: \"" + key + "\""); } } private static String inputStreamToString(InputStream in) throws IOException { return readFully(new InputStreamReader(in, UTF_8)); } /** * A snapshot of the values for an entry. */ public final class Snapshot implements Closeable { private final String key; private final long sequenceNumber; private final InputStream[] ins; private Snapshot(String key, long sequenceNumber, InputStream[] ins) { this.key = key; this.sequenceNumber = sequenceNumber; this.ins = ins; } /** * Returns an editor for this snapshot's entry, or null if either the * entry has changed since this snapshot was created or if another edit * is in progress. */ public Editor edit() throws IOException { return DiskLruCache.this.edit(key, sequenceNumber); } /** * Returns the unbuffered stream with the value for {@code index}. */ public InputStream getInputStream(int index) { return ins[index]; } /** * Returns the string value for {@code index}. */ public String getString(int index) throws IOException { return inputStreamToString(getInputStream(index)); } @Override public void close() { for (InputStream in : ins) { closeQuietly(in); } } } /** * Edits the values for an entry. */ public final class Editor { private final Entry entry; private boolean hasErrors; private Editor(Entry entry) { this.entry = entry; } /** * Returns an unbuffered input stream to read the last committed value, * or null if no value has been committed. */ public InputStream newInputStream(int index) throws IOException { synchronized (DiskLruCache.this) { if (entry.currentEditor != this) { throw new IllegalStateException(); } if (!entry.readable) { return null; } return new FileInputStream(entry.getCleanFile(index)); } } /** * Returns the last committed value as a string, or null if no value * has been committed. */ public String getString(int index) throws IOException { InputStream in = newInputStream(index); return in != null ? inputStreamToString(in) : null; } /** * Returns a new unbuffered output stream to write the value at * {@code index}. If the underlying output stream encounters errors * when writing to the filesystem, this edit will be aborted when * {@link #commit} is called. The returned output stream does not throw * IOExceptions. */ public OutputStream newOutputStream(int index) throws IOException { synchronized (DiskLruCache.this) { if (entry.currentEditor != this) { throw new IllegalStateException(); } return new FaultHidingOutputStream(new FileOutputStream(entry.getDirtyFile(index))); } } /** * Sets the value at {@code index} to {@code value}. */ public void set(int index, String value) throws IOException { Writer writer = null; try { writer = new OutputStreamWriter(newOutputStream(index), UTF_8); writer.write(value); } finally { closeQuietly(writer); } } /** * Commits this edit so it is visible to readers. This releases the * edit lock so another edit may be started on the same key. */ public void commit() throws IOException { if (hasErrors) { completeEdit(this, false); remove(entry.key); // the previous entry is stale } else { completeEdit(this, true); } } /** * Aborts this edit. This releases the edit lock so another edit may be * started on the same key. */ public void abort() throws IOException { completeEdit(this, false); } private class FaultHidingOutputStream extends FilterOutputStream { private FaultHidingOutputStream(OutputStream out) { super(out); } @Override public void write(int oneByte) { try { out.write(oneByte); } catch (IOException e) { hasErrors = true; } } @Override public void write(byte[] buffer, int offset, int length) { try { out.write(buffer, offset, length); } catch (IOException e) { hasErrors = true; } } @Override public void close() { try { out.close(); } catch (IOException e) { hasErrors = true; } } @Override public void flush() { try { out.flush(); } catch (IOException e) { hasErrors = true; } } } } private final class Entry { private final String key; /** Lengths of this entry's files. */ private final long[] lengths; /** True if this entry has ever been published */ private boolean readable; /** The ongoing edit or null if this entry is not being edited. */ private Editor currentEditor; /** The sequence number of the most recently committed edit to this entry. */ private long sequenceNumber; private Entry(String key) { this.key = key; this.lengths = new long[valueCount]; } public String getLengths() throws IOException { StringBuilder result = new StringBuilder(); for (long size : lengths) { result.append(' ').append(size); } return result.toString(); } /** * Set lengths using decimal numbers like "10123". */ private void setLengths(String[] strings) throws IOException { if (strings.length != valueCount) { throw invalidLengths(strings); } try { for (int i = 0; i < strings.length; i++) { lengths[i] = Long.parseLong(strings[i]); } } catch (NumberFormatException e) { throw invalidLengths(strings); } } private IOException invalidLengths(String[] strings) throws IOException { throw new IOException("unexpected journal line: " + Arrays.toString(strings)); } public File getCleanFile(int i) { return new File(directory, key + "." + i); } public File getDirtyFile(int i) { return new File(directory, key + "." + i + ".tmp"); } } }
apache-2.0
taimos/dvalin
interconnect/metamodel/src/main/java/de/taimos/dvalin/interconnect/model/metamodel/memberdef/INamedMemberDef.java
247
package de.taimos.dvalin.interconnect.model.metamodel.memberdef; /** * Copyright 2022 Cinovo AG<br> * <br> * * @author psigloch */ public interface INamedMemberDef { /** * @return the members name */ String getName(); }
apache-2.0
Yiiinsh/x-pipe
core/src/main/java/com/ctrip/xpipe/payload/StringInOutPayload.java
1088
package com.ctrip.xpipe.payload; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import java.nio.charset.Charset; import com.ctrip.xpipe.api.codec.Codec; import io.netty.buffer.ByteBuf; /** * @author wenchao.meng * * 2016年4月26日 下午7:02:09 */ public class StringInOutPayload extends AbstractInOutPayload{ private String message; private Charset charset; public StringInOutPayload(String message){ this(message, Codec.defaultCharset); } public StringInOutPayload(String message, Charset charset) { this.message = message; this.charset = charset; } @Override protected int doIn(ByteBuf byteBuf) throws IOException { throw new UnsupportedOperationException("unsupported in"); } @Override protected long doOut(WritableByteChannel writableByteChannel) throws IOException { return writableByteChannel.write(ByteBuffer.wrap(message.getBytes(charset))); } @Override protected void doTruncate(int reduceLen) throws IOException { throw new UnsupportedOperationException(); } }
apache-2.0
SingingTree/hapi-fhir
hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/builder/predicate/CompositeUniqueSearchParameterPredicateBuilder.java
1731
package ca.uhn.fhir.jpa.search.builder.predicate; /*- * #%L * HAPI FHIR JPA Server * %% * Copyright (C) 2014 - 2021 Smile CDR, 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. * #L% */ import ca.uhn.fhir.interceptor.model.RequestPartitionId; import ca.uhn.fhir.jpa.search.builder.sql.SearchQueryBuilder; import com.healthmarketscience.sqlbuilder.BinaryCondition; import com.healthmarketscience.sqlbuilder.Condition; import com.healthmarketscience.sqlbuilder.dbspec.basic.DbColumn; public class CompositeUniqueSearchParameterPredicateBuilder extends BaseSearchParamPredicateBuilder { private final DbColumn myColumnString; /** * Constructor */ public CompositeUniqueSearchParameterPredicateBuilder(SearchQueryBuilder theSearchSqlBuilder) { super(theSearchSqlBuilder, theSearchSqlBuilder.addTable("HFJ_IDX_CMP_STRING_UNIQ")); myColumnString = getTable().addColumn("IDX_STRING"); } public Condition createPredicateIndexString(RequestPartitionId theRequestPartitionId, String theIndexString) { BinaryCondition predicate = BinaryCondition.equalTo(myColumnString, generatePlaceholder(theIndexString)); return combineWithRequestPartitionIdPredicate(theRequestPartitionId, predicate); } }
apache-2.0
glowroot/glowroot
agent/embedded/src/test/java/org/glowroot/agent/embedded/util/CappedDatabaseTest.java
5634
/* * Copyright 2012-2018 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.glowroot.agent.embedded.util; import java.io.File; import java.io.IOException; import java.io.Reader; import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import com.google.common.base.Ticker; import com.google.common.io.ByteSource; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static com.google.common.base.Charsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; public class CappedDatabaseTest { private File tempFile; private ScheduledExecutorService scheduledExecutor; private CappedDatabase cappedDatabase; @BeforeEach public void onBefore() throws IOException { tempFile = File.createTempFile("glowroot-test-", ".capped.db"); scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); cappedDatabase = new CappedDatabase(tempFile, 1, scheduledExecutor, Ticker.systemTicker()); } @AfterEach public void onAfter() throws IOException { scheduledExecutor.shutdownNow(); cappedDatabase.close(); tempFile.delete(); } @Test public void shouldWrite() throws Exception { // given String text = "0123456789"; // when long cappedId = cappedDatabase.write(ByteSource.wrap(text.getBytes(UTF_8)), "test"); // then String text2 = cappedDatabase.read(cappedId).read(); assertThat(text2).isEqualTo(text); } @Test public void shouldReadOneByteAtATime() throws Exception { // given String text = "0123456789"; // when long cappedId = cappedDatabase.write(ByteSource.wrap(text.getBytes(UTF_8)), "test"); // then Reader in = cappedDatabase.read(cappedId).openStream(); assertThat((char) in.read()).isEqualTo('0'); assertThat((char) in.read()).isEqualTo('1'); assertThat((char) in.read()).isEqualTo('2'); assertThat((char) in.read()).isEqualTo('3'); assertThat((char) in.read()).isEqualTo('4'); assertThat((char) in.read()).isEqualTo('5'); assertThat((char) in.read()).isEqualTo('6'); assertThat((char) in.read()).isEqualTo('7'); assertThat((char) in.read()).isEqualTo('8'); assertThat((char) in.read()).isEqualTo('9'); assertThat(in.read()).isEqualTo(-1); } @Test public void shouldWrap() throws Exception { // given // use random text so that the lzf compressed text is also large and forces wrapping Random random = new Random(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 600; i++) { sb.append((char) ('a' + random.nextInt(26))); } String text = sb.toString(); cappedDatabase.write(ByteSource.wrap(text.getBytes(UTF_8)), "test"); // when long cappedId = cappedDatabase.write(ByteSource.wrap(text.getBytes(UTF_8)), "test"); // then String text2 = cappedDatabase.read(cappedId).read(); assertThat(text2).isEqualTo(text); } @Test public void shouldWrapAndKeepGoing() throws Exception { // given // use random text so that the lzf compressed text is also large and forces wrapping Random random = new Random(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 600; i++) { sb.append((char) ('a' + random.nextInt(26))); } String text = sb.toString(); cappedDatabase.write(ByteSource.wrap(text.getBytes(UTF_8)), "test"); cappedDatabase.write(ByteSource.wrap(text.getBytes(UTF_8)), "test"); // when long cappedId = cappedDatabase.write(ByteSource.wrap(text.getBytes(UTF_8)), "test"); // then String text2 = cappedDatabase.read(cappedId).read(); assertThat(text2).isEqualTo(text); } @Test public void shouldWrapOverOldBlocks() throws Exception { // given // use random text so that the lzf compressed text is also large and forces wrapping Random random = new Random(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 600; i++) { sb.append((char) ('a' + random.nextInt(26))); } String text = sb.toString(); long cappedId = cappedDatabase.write(ByteSource.wrap(text.getBytes(UTF_8)), "test"); cappedDatabase.write(ByteSource.wrap(text.getBytes(UTF_8)), "test"); // when cappedDatabase.write(ByteSource.wrap(text.getBytes(UTF_8)), "test"); // then String exceptionClassName = null; try { cappedDatabase.read(cappedId).read(); } catch (Exception e) { exceptionClassName = e.getClass().getName(); } assertThat(exceptionClassName).isEqualTo("org.glowroot.agent.embedded.util.CappedDatabase" + "$CappedBlockRolledOverMidReadException"); } }
apache-2.0
ernellsoftware/JavaStreamProcessor
JavaStreamProcessor/src/se/ernell/java/streamprocessor/Score.java
9032
package se.ernell.java.streamprocessor; /* * Copyright (C) 2012 Robert Andersson <http://www.ernell.se> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.HashMap; /** * Score (Singleton class) * * @author rob@ernell.se * */ public class Score { private static Score instance; protected Score() { } public static Score getInstance() { if (instance == null) instance = new Score(); return instance; } /** Score definitions (new in v2.109) */ public enum Game { ENGLISH_SCRABBLE, ENGLISH_WORDFEUD, ENGLISH_WORDS4FRIENDS, SWEDISH_WORDFEUD }; public static HashMap<Character, Integer> score_table; public static Game active_game; static { score_table = setscore_ENGLISH_SCRABBLE(); } public static int getScore(char[] word, int len) { int points = 0; int temp = 0; try { // do loopcount backwards??? for (int i = 0; i < len; i++) { temp = score_table.get(word[i]); // if (temp > 0) points += temp; } } catch (NullPointerException e) { e.printStackTrace(); } return points; } public static String getGameString() { return active_game.toString(); } public static Game getGame() { return active_game; } /** * * @param score_table * Use the public constants 'SCORE_<LANG>_<GAME>' * @return A score table ( HashMap<Character, Integer> ) */ public static void setScoreTable(Game score_game) { active_game = score_game; // debug // System.out.println("setScoreTable: " + active_game.toString()); switch (score_game) { case ENGLISH_SCRABBLE: score_table = setscore_ENGLISH_SCRABBLE(); break; case ENGLISH_WORDFEUD: score_table = setscore_ENGLISH_WORDFEUD(); break; case SWEDISH_WORDFEUD: score_table = setscore_SWEDISH_WORDFEUD(); break; case ENGLISH_WORDS4FRIENDS: score_table = setscore_ENGLISH_WORDS4FRIENDS(); break; default: score_table = setscore_ENGLISH_SCRABBLE(); break; } } /** English - Wordfeud */ private static HashMap<Character, Integer> setscore_ENGLISH_WORDFEUD() { HashMap<Character, Integer> score_hashmap = new HashMap<Character, Integer>(); score_hashmap.clear(); score_hashmap.put('A', Integer.valueOf(1)); score_hashmap.put('B', Integer.valueOf(4)); score_hashmap.put('C', Integer.valueOf(4)); score_hashmap.put('D', Integer.valueOf(2)); score_hashmap.put('E', Integer.valueOf(1)); score_hashmap.put('F', Integer.valueOf(4)); score_hashmap.put('G', Integer.valueOf(3)); score_hashmap.put('H', Integer.valueOf(4)); score_hashmap.put('I', Integer.valueOf(1)); score_hashmap.put('J', Integer.valueOf(10)); score_hashmap.put('K', Integer.valueOf(5)); score_hashmap.put('L', Integer.valueOf(1)); score_hashmap.put('M', Integer.valueOf(3)); score_hashmap.put('N', Integer.valueOf(1)); score_hashmap.put('O', Integer.valueOf(1)); score_hashmap.put('P', Integer.valueOf(4)); score_hashmap.put('Q', Integer.valueOf(10)); score_hashmap.put('R', Integer.valueOf(1)); score_hashmap.put('S', Integer.valueOf(1)); score_hashmap.put('T', Integer.valueOf(1)); score_hashmap.put('U', Integer.valueOf(2)); score_hashmap.put('V', Integer.valueOf(4)); score_hashmap.put('W', Integer.valueOf(4)); score_hashmap.put('X', Integer.valueOf(8)); score_hashmap.put('Y', Integer.valueOf(4)); score_hashmap.put('Z', Integer.valueOf(10)); score_hashmap.put('Å', Integer.valueOf(0)); score_hashmap.put('Ä', Integer.valueOf(0)); score_hashmap.put('Ö', Integer.valueOf(0)); return score_hashmap; } /** English - Words 4 Friends */ private static HashMap<Character, Integer> setscore_ENGLISH_WORDS4FRIENDS() { HashMap<Character, Integer> score_hashmap = new HashMap<Character, Integer>(); score_hashmap.clear(); score_hashmap.put('A', Integer.valueOf(1)); score_hashmap.put('B', Integer.valueOf(4)); score_hashmap.put('C', Integer.valueOf(4)); score_hashmap.put('D', Integer.valueOf(2)); score_hashmap.put('E', Integer.valueOf(1)); score_hashmap.put('F', Integer.valueOf(4)); score_hashmap.put('G', Integer.valueOf(3)); score_hashmap.put('H', Integer.valueOf(3)); score_hashmap.put('I', Integer.valueOf(1)); score_hashmap.put('J', Integer.valueOf(10)); score_hashmap.put('K', Integer.valueOf(5)); score_hashmap.put('L', Integer.valueOf(2)); score_hashmap.put('M', Integer.valueOf(4)); score_hashmap.put('N', Integer.valueOf(2)); score_hashmap.put('O', Integer.valueOf(1)); score_hashmap.put('P', Integer.valueOf(4)); score_hashmap.put('Q', Integer.valueOf(10)); score_hashmap.put('R', Integer.valueOf(1)); score_hashmap.put('S', Integer.valueOf(1)); score_hashmap.put('T', Integer.valueOf(1)); score_hashmap.put('U', Integer.valueOf(2)); score_hashmap.put('V', Integer.valueOf(5)); score_hashmap.put('W', Integer.valueOf(4)); score_hashmap.put('X', Integer.valueOf(8)); score_hashmap.put('Y', Integer.valueOf(3)); score_hashmap.put('Z', Integer.valueOf(10)); score_hashmap.put('Å', Integer.valueOf(0)); score_hashmap.put('Ä', Integer.valueOf(0)); score_hashmap.put('Ö', Integer.valueOf(0)); return score_hashmap; } /** English - Scrabble */ private static HashMap<Character, Integer> setscore_ENGLISH_SCRABBLE() { HashMap<Character, Integer> score_hashmap = new HashMap<Character, Integer>(); score_hashmap.clear(); score_hashmap.put('A', Integer.valueOf(1)); score_hashmap.put('B', Integer.valueOf(3)); score_hashmap.put('C', Integer.valueOf(3)); score_hashmap.put('D', Integer.valueOf(2)); score_hashmap.put('E', Integer.valueOf(1)); score_hashmap.put('F', Integer.valueOf(4)); score_hashmap.put('G', Integer.valueOf(2)); score_hashmap.put('H', Integer.valueOf(4)); score_hashmap.put('I', Integer.valueOf(1)); score_hashmap.put('J', Integer.valueOf(8)); score_hashmap.put('K', Integer.valueOf(5)); score_hashmap.put('L', Integer.valueOf(1)); score_hashmap.put('M', Integer.valueOf(3)); score_hashmap.put('N', Integer.valueOf(1)); score_hashmap.put('O', Integer.valueOf(1)); score_hashmap.put('P', Integer.valueOf(3)); score_hashmap.put('Q', Integer.valueOf(10)); score_hashmap.put('R', Integer.valueOf(1)); score_hashmap.put('S', Integer.valueOf(1)); score_hashmap.put('T', Integer.valueOf(1)); score_hashmap.put('U', Integer.valueOf(1)); score_hashmap.put('V', Integer.valueOf(4)); score_hashmap.put('W', Integer.valueOf(4)); score_hashmap.put('X', Integer.valueOf(8)); score_hashmap.put('Y', Integer.valueOf(4)); score_hashmap.put('Z', Integer.valueOf(10)); score_hashmap.put('Å', Integer.valueOf(0)); score_hashmap.put('Ä', Integer.valueOf(0)); score_hashmap.put('Ö', Integer.valueOf(0)); return score_hashmap; } /** English - Scrabble */ private static HashMap<Character, Integer> setscore_SWEDISH_WORDFEUD() { HashMap<Character, Integer> score_hashmap = new HashMap<Character, Integer>(); score_hashmap.clear(); score_hashmap.put('A', Integer.valueOf(1)); score_hashmap.put('B', Integer.valueOf(3)); score_hashmap.put('C', Integer.valueOf(3)); score_hashmap.put('D', Integer.valueOf(2)); score_hashmap.put('E', Integer.valueOf(1)); score_hashmap.put('F', Integer.valueOf(4)); score_hashmap.put('G', Integer.valueOf(2)); score_hashmap.put('H', Integer.valueOf(4)); score_hashmap.put('I', Integer.valueOf(1)); score_hashmap.put('J', Integer.valueOf(8)); score_hashmap.put('K', Integer.valueOf(5)); score_hashmap.put('L', Integer.valueOf(1)); score_hashmap.put('M', Integer.valueOf(3)); score_hashmap.put('N', Integer.valueOf(1)); score_hashmap.put('O', Integer.valueOf(1)); score_hashmap.put('P', Integer.valueOf(3)); score_hashmap.put('Q', Integer.valueOf(10)); score_hashmap.put('R', Integer.valueOf(1)); score_hashmap.put('S', Integer.valueOf(1)); score_hashmap.put('T', Integer.valueOf(1)); score_hashmap.put('U', Integer.valueOf(1)); score_hashmap.put('V', Integer.valueOf(4)); score_hashmap.put('W', Integer.valueOf(4)); score_hashmap.put('X', Integer.valueOf(8)); score_hashmap.put('Y', Integer.valueOf(4)); score_hashmap.put('Z', Integer.valueOf(10)); score_hashmap.put('Å', Integer.valueOf(0)); score_hashmap.put('Ä', Integer.valueOf(0)); score_hashmap.put('Ö', Integer.valueOf(0)); return score_hashmap; } }
apache-2.0
ranadas/conceptandpractices
JpaSpring4/src/main/java/com/rdas/db/EmailSubjectRepository.java
250
package com.rdas.db; import org.springframework.data.jpa.repository.JpaRepository; import com.rdas.model.EmailSubject; /** * Created by rdas on 10/02/2015. */ public interface EmailSubjectRepository extends JpaRepository<EmailSubject, Long> { }
artistic-2.0
leechwin/jslint-eclipse
com.googlecode.jslint4java.eclipse/src/com/googlecode/jslint4java/eclipse/builder/JSLintBuilder.java
7084
package com.googlecode.jslint4java.eclipse.builder; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStreamReader; import java.util.Map; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IResourceDeltaVisitor; import org.eclipse.core.resources.IResourceVisitor; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import com.googlecode.jslint4java.Issue; import com.googlecode.jslint4java.JSLint; import com.googlecode.jslint4java.JSLintResult; import com.googlecode.jslint4java.eclipse.JSLintLog; import com.googlecode.jslint4java.eclipse.JSLintPlugin; public class JSLintBuilder extends IncrementalProjectBuilder { private class JSLintDeltaVisitor implements IResourceDeltaVisitor { private final IProgressMonitor monitor; public JSLintDeltaVisitor(IProgressMonitor monitor) { this.monitor = monitor; } public boolean visit(IResourceDelta delta) throws CoreException { IResource resource = delta.getResource(); switch (delta.getKind()) { case IResourceDelta.ADDED: // handle added resource logProgress(monitor, resource); checkJavaScript(resource); break; case IResourceDelta.REMOVED: // handle removed resource break; case IResourceDelta.CHANGED: // handle changed resource logProgress(monitor, resource); checkJavaScript(resource); break; } // return true to continue visiting children. return true; } } private class JSLintResourceVisitor implements IResourceVisitor { private final IProgressMonitor monitor; public JSLintResourceVisitor(IProgressMonitor monitor) { this.monitor = monitor; } public boolean visit(IResource resource) { logProgress(monitor, resource); checkJavaScript(resource); // return true to continue visiting children. return true; } } // NB! Must match plugin.xml declaration. public static final String BUILDER_ID = JSLintPlugin.PLUGIN_ID + ".builder.jsLintBuilder"; // NB! Must match plugin.xml declaration. public static final String MARKER_TYPE = JSLintPlugin.PLUGIN_ID + ".javaScriptLintProblem"; private final JSLintProvider lintProvider = new JSLintProvider(); private final Excluder excluder = new Excluder(); public JSLintBuilder() { lintProvider.init(); excluder.init(); } private void addMarker(IFile file, Issue issue) { try { IMarker m = file.createMarker(MARKER_TYPE); if (m.exists()) { m.setAttribute(IMarker.MESSAGE, issue.getMessage()); m.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING); m.setAttribute(IMarker.LINE_NUMBER, issue.getLine()); m.setAttribute(IMarker.SOURCE_ID, "jslint4java"); } } catch (CoreException e) { JSLintLog.error(e); } } @Override protected IProject[] build(final int kind, @SuppressWarnings("rawtypes") Map args, IProgressMonitor monitor) throws CoreException { ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { if (kind == FULL_BUILD) { fullBuild(monitor); } else { IResourceDelta delta = getDelta(getProject()); if (delta == null) { fullBuild(monitor); } else { incrementalBuild(delta, monitor); } } } }, monitor); return null; } private void checkJavaScript(IResource resource) { if (!(resource instanceof IFile)) { return; } IFile file = (IFile) resource; if (!isJavaScript(file)) { return; } // Clear out any existing problems. deleteMarkers(file); if (excluded(file)) { return; } BufferedReader reader = null; try { JSLint lint = lintProvider.getJsLint(); // TODO: this should react to changes in the prefs pane instead. reader = new BufferedReader(new InputStreamReader(file.getContents(), file.getCharset())); JSLintResult result = lint.lint(file.getFullPath().toString(), reader); for (Issue issue : result.getIssues()) { addMarker(file, issue); } } catch (IOException e) { JSLintLog.error(e); } catch (CoreException e) { JSLintLog.error(e); } finally { close(reader); } } /** * Is {@code file} explicitly excluded? Check against a list of regexes in the <i>exclude_path_regexes</i> preference. */ private boolean excluded(IFile file) { return excluder.isExcluded(file); } private boolean isJavaScript(IFile file) { return file.getName().endsWith(".js"); } private void close(Closeable close) { if (close == null) { return; } try { close.close(); } catch (IOException e) { } } private void deleteMarkers(IFile file) { try { file.deleteMarkers(MARKER_TYPE, false, IResource.DEPTH_ZERO); } catch (CoreException e) { JSLintLog.error(e); } } private void fullBuild(final IProgressMonitor monitor) throws CoreException { try { startProgress(monitor); getProject().accept(new JSLintResourceVisitor(monitor)); } catch (CoreException e) { JSLintLog.error(e); } finally { monitor.done(); } } private void incrementalBuild(IResourceDelta delta, IProgressMonitor monitor) throws CoreException { try { startProgress(monitor); delta.accept(new JSLintDeltaVisitor(monitor)); } finally { monitor.done(); } } private void startProgress(IProgressMonitor monitor) { monitor.beginTask("jslint4java", IProgressMonitor.UNKNOWN); } private void logProgress(IProgressMonitor monitor, IResource resource) { monitor.subTask("Linting " + resource.getName()); } }
bsd-2-clause
jcodec/jcodec
streaming/main/java/org/jcodec/movtool/streaming/VirtualMovie.java
3054
package org.jcodec.movtool.streaming; import java.lang.IllegalStateException; import java.lang.System; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * This class is part of JCodec ( www.jcodec.org ) This software is distributed * under FreeBSD License * * Virtual movie. A movie constructed on-the-fly from virtual track data. * * Generic muxing * * @author The JCodec project * */ public abstract class VirtualMovie { public MovieSegment[] chunks; public MovieSegment _headerChunk; protected long _size; protected VirtualTrack[] tracks; public VirtualMovie(VirtualTrack[] virtualTracks) throws IOException { this.tracks = virtualTracks; } protected void muxTracks() throws IOException { List<MovieSegment> chch = new ArrayList<MovieSegment>(); VirtualPacket[] heads = new VirtualPacket[tracks.length], tails = new VirtualPacket[tracks.length]; for (int curChunk = 1;; curChunk++) { int min = -1; for (int i = 0; i < heads.length; i++) { if (heads[i] == null) { heads[i] = tracks[i].nextPacket(); if (heads[i] == null) continue; } min = min == -1 || heads[i].getPts() < heads[min].getPts() ? i : min; } if (min == -1) break; chch.add(packetChunk(tracks[min], heads[min], curChunk, min, _size)); if (heads[min].getDataLen() >= 0) _size += heads[min].getDataLen(); else System.err.println("WARN: Negative frame data len!!!"); tails[min] = heads[min]; heads[min] = tracks[min].nextPacket(); } _headerChunk = headerChunk(chch, tracks, _size); _size += _headerChunk.getDataLen(); chunks = chch.toArray(new MovieSegment[0]); } protected abstract MovieSegment packetChunk(VirtualTrack track, VirtualPacket pkt, int chunkNo, int trackNo, long pos); protected abstract MovieSegment headerChunk(List<MovieSegment> chunks, VirtualTrack[] tracks, long dataSize) throws IOException; public void close() throws IOException { for (VirtualTrack virtualTrack : tracks) { virtualTrack.close(); } } public MovieSegment getPacketAt(long position) throws IOException { if (position >= 0 && position < _headerChunk.getDataLen()) return _headerChunk; for (int i = 0; i < chunks.length - 1; i++) { if (chunks[i + 1].getPos() > position) return chunks[i]; } if (position < _size) return chunks[chunks.length - 1]; return null; } public MovieSegment getPacketByNo(int no) { if (no > chunks.length) return null; if (no == 0) return _headerChunk; return chunks[no - 1]; } public long size() { return _size; } }
bsd-2-clause
licehammer/perun
perun-core/src/main/java/cz/metacentrum/perun/core/impl/modules/attributes/urn_perun_member_resource_attribute_def_def_dataLimit.java
8377
package cz.metacentrum.perun.core.impl.modules.attributes; import cz.metacentrum.perun.core.api.Attribute; import cz.metacentrum.perun.core.api.AttributeDefinition; import cz.metacentrum.perun.core.api.AttributesManager; import cz.metacentrum.perun.core.api.Member; import cz.metacentrum.perun.core.api.Resource; import cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException; import cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException; import cz.metacentrum.perun.core.api.exceptions.InternalErrorException; import cz.metacentrum.perun.core.api.exceptions.MemberResourceMismatchException; import cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException; import cz.metacentrum.perun.core.api.exceptions.WrongAttributeValueException; import cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException; import cz.metacentrum.perun.core.impl.PerunSessionImpl; import cz.metacentrum.perun.core.implApi.modules.attributes.ResourceMemberAttributesModuleAbstract; import cz.metacentrum.perun.core.implApi.modules.attributes.ResourceMemberAttributesModuleImplApi; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author Michal Stava stavamichal@gmail.com */ public class urn_perun_member_resource_attribute_def_def_dataLimit extends ResourceMemberAttributesModuleAbstract implements ResourceMemberAttributesModuleImplApi { private static final String A_R_defaultDataLimit = AttributesManager.NS_RESOURCE_ATTR_DEF + ":defaultDataLimit"; private static final String A_R_defaultDataQuota = AttributesManager.NS_RESOURCE_ATTR_DEF + ":defaultDataQuota"; private static final String A_MR_dataQuota = AttributesManager.NS_MEMBER_RESOURCE_ATTR_DEF + ":dataQuota"; Pattern numberPattern = Pattern.compile("[0-9]+(\\.|,)?[0-9]*"); Pattern letterPattern = Pattern.compile("[A-Z]"); long K = 1024; long M = K * 1024; long G = M * 1024; long T = G * 1024; long P = T * 1024; long E = P * 1024; @Override public void checkAttributeValue(PerunSessionImpl perunSession, Resource resource, Member member, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException { Attribute attrDataQuota = null; String dataQuota = null; String dataLimit = null; String dataQuotaNumber = null; String dataQuotaLetter = null; String dataLimitNumber = null; String dataLimitLetter = null; //Get attrDataQuota attribute try { attrDataQuota = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, resource, member, A_MR_dataQuota); } catch (AttributeNotExistsException ex) { throw new ConsistencyErrorException("Attribute with dataQuota from member " + member.getId() + " and resource " + resource.getId() + " could not obtained.", ex); } catch (MemberResourceMismatchException ex) { throw new InternalErrorException(ex); } //Get dataLimit value if (attribute.getValue() == null) { try { attribute = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, resource, A_R_defaultDataLimit); } catch (AttributeNotExistsException ex) { throw new ConsistencyErrorException("Attribute with defaultDataLimit from resource " + resource.getId() + " could not obtained.", ex); } } if (attribute.getValue() != null) { dataLimit = (String) attribute.getValue(); Matcher numberMatcher = numberPattern.matcher(dataLimit); Matcher letterMatcher = letterPattern.matcher(dataLimit); numberMatcher.find(); letterMatcher.find(); try { dataLimitNumber = dataLimit.substring(numberMatcher.start(), numberMatcher.end()); } catch (IllegalStateException ex) { dataLimitNumber = null; } try { dataLimitLetter = dataLimit.substring(letterMatcher.start(), letterMatcher.end()); } catch (IllegalStateException ex) { dataLimitLetter = "G"; } } BigDecimal limitNumber; if(dataLimitNumber != null) limitNumber = new BigDecimal(dataLimitNumber.replace(',', '.').toString()); else limitNumber = new BigDecimal("0"); if (limitNumber != null && limitNumber.compareTo(BigDecimal.valueOf(0)) < 0) { throw new WrongAttributeValueException(attribute, resource, member, attribute + " cant be less than 0."); } //Get dataQuota value if (attrDataQuota == null || attrDataQuota.getValue() == null) { try { attrDataQuota = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, resource, A_R_defaultDataQuota); } catch (AttributeNotExistsException ex) { throw new ConsistencyErrorException("Attribute with defaultDataQuota from resource " + resource.getId() + " could not obtained.", ex); } } if (attrDataQuota != null && attrDataQuota.getValue() != null) { dataQuota = (String) attrDataQuota.getValue(); Matcher numberMatcher = numberPattern.matcher(dataQuota); Matcher letterMatcher = letterPattern.matcher(dataQuota); numberMatcher.find(); letterMatcher.find(); try { dataQuotaNumber = dataQuota.substring(numberMatcher.start(), numberMatcher.end()); } catch (IllegalStateException ex) { dataQuotaNumber = null; } try { dataQuotaLetter = dataQuota.substring(letterMatcher.start(), letterMatcher.end()); } catch (IllegalStateException ex) { dataQuotaLetter = "G"; } } BigDecimal quotaNumber; if(dataQuotaNumber != null) quotaNumber = new BigDecimal(dataQuotaNumber.replace(',', '.')); else quotaNumber = new BigDecimal("0"); if (quotaNumber != null && quotaNumber.compareTo(BigDecimal.valueOf(0)) < 0) { throw new WrongReferenceAttributeValueException(attribute, attrDataQuota, resource, member, resource, null, attrDataQuota + " cant be less than 0."); } //Compare dataLimit with dataQuota if (quotaNumber == null || quotaNumber.compareTo(BigDecimal.valueOf(0)) == 0) { if (limitNumber != null && limitNumber.compareTo(BigDecimal.valueOf(0)) != 0) { throw new WrongReferenceAttributeValueException(attribute, attrDataQuota, resource, member, resource, null, "Try to set limited limit, but there is still set unlimited Quota."); } } else if ((quotaNumber != null && quotaNumber.compareTo(BigDecimal.valueOf(0)) != 0) && (limitNumber != null && limitNumber.compareTo(BigDecimal.valueOf(0)) != 0)) { if(dataLimitLetter.equals("K")) limitNumber = limitNumber.multiply(BigDecimal.valueOf(K)); else if(dataLimitLetter.equals("M")) limitNumber = limitNumber.multiply(BigDecimal.valueOf(M)); else if(dataLimitLetter.equals("T")) limitNumber = limitNumber.multiply(BigDecimal.valueOf(T)); else if(dataLimitLetter.equals("P")) limitNumber = limitNumber.multiply(BigDecimal.valueOf(P)); else if(dataLimitLetter.equals("E")) limitNumber = limitNumber.multiply(BigDecimal.valueOf(E)); else limitNumber = limitNumber.multiply(BigDecimal.valueOf(G)); if(dataQuotaLetter.equals("K")) quotaNumber = quotaNumber.multiply(BigDecimal.valueOf(K)); else if(dataQuotaLetter.equals("M")) quotaNumber = quotaNumber.multiply(BigDecimal.valueOf(M)); else if(dataQuotaLetter.equals("T")) quotaNumber = quotaNumber.multiply(BigDecimal.valueOf(T)); else if(dataQuotaLetter.equals("P")) quotaNumber = quotaNumber.multiply(BigDecimal.valueOf(P)); else if(dataQuotaLetter.equals("E")) quotaNumber = quotaNumber.multiply(BigDecimal.valueOf(E)); else quotaNumber = quotaNumber.multiply(BigDecimal.valueOf(G)); if (limitNumber.compareTo(quotaNumber) < 0) { throw new WrongReferenceAttributeValueException(attribute, attrDataQuota, resource, member, resource, null, attribute + " must be more than or equals to " + attrDataQuota); } } } @Override public AttributeDefinition getAttributeDefinition() { AttributeDefinition attr = new AttributeDefinition(); attr.setNamespace(AttributesManager.NS_MEMBER_RESOURCE_ATTR_DEF); attr.setFriendlyName("dataLimit"); attr.setDisplayName("Data limit"); attr.setType(String.class.getName()); attr.setDescription("Hard quota including units (M, G, T, ...), G is default."); return attr; } @Override public List<String> getDependencies() { List<String> dependecies = new ArrayList<String>(); dependecies.add(A_R_defaultDataLimit); dependecies.add(A_R_defaultDataQuota); return dependecies; } }
bsd-2-clause
linkedin/LiTr
litr-filters/src/main/java/com/linkedin/android/litr/filter/video/gl/GammaFilter.java
2880
/* * Copyright 2018 Masayuki Suda * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.linkedin.android.litr.filter.video.gl; import androidx.annotation.Nullable; import com.linkedin.android.litr.filter.Transform; import com.linkedin.android.litr.filter.video.gl.parameter.ShaderParameter; import com.linkedin.android.litr.filter.video.gl.parameter.Uniform1f; /** * Frame render filter that adjusts the gamma of video pixels */ public class GammaFilter extends VideoFrameRenderFilter { private static final String FRAGMENT_SHADER = "#extension GL_OES_EGL_image_external : require\n" + "precision mediump float;" + "varying vec2 vTextureCoord;\n" + "uniform samplerExternalOES sTexture;\n" + "uniform lowp float gamma;\n" + "void main()\n" + "{\n" + "lowp vec4 textureColor = texture2D(sTexture, vTextureCoord);\n" + "gl_FragColor = vec4(pow(textureColor.rgb, vec3(gamma)), textureColor.w);\n" + "}"; /** * Create the instance of frame render filter * @param gamma gamma adjustment value */ public GammaFilter(float gamma) { this(gamma, null); } /** * Create frame render filter with source video frame, then scale, then position and then rotate the bitmap around its center as specified. * @param gamma gamma adjustment value * @param transform {@link Transform} that defines positioning of source video frame within target video frame */ public GammaFilter(float gamma, @Nullable Transform transform) { super(DEFAULT_VERTEX_SHADER, FRAGMENT_SHADER, new ShaderParameter[] { new Uniform1f("gamma", gamma) }, transform); } }
bsd-2-clause
alpha-asp/Alpha
alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/solver/ThreeColouringTestWithRandom.java
9392
/** * Copyright (c) 2017 Siemens AG * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1) Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package at.ac.tuwien.kr.alpha.core.solver; import static at.ac.tuwien.kr.alpha.core.test.util.TestUtils.buildSolverForRegressionTest; import static at.ac.tuwien.kr.alpha.core.test.util.TestUtils.runWithTimeout; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Random; import org.junit.jupiter.api.Disabled; import at.ac.tuwien.kr.alpha.api.AnswerSet; import at.ac.tuwien.kr.alpha.api.Solver; import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; import at.ac.tuwien.kr.alpha.api.programs.Predicate; import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; import at.ac.tuwien.kr.alpha.api.terms.Term; import at.ac.tuwien.kr.alpha.commons.Predicates; import at.ac.tuwien.kr.alpha.commons.atoms.Atoms; import at.ac.tuwien.kr.alpha.commons.terms.Terms; import at.ac.tuwien.kr.alpha.core.parser.ProgramParserImpl; import at.ac.tuwien.kr.alpha.core.programs.InputProgram; /** * Tests {@link AbstractSolver} using some three-coloring test cases, as described in: * Lefèvre, Claire; Béatrix, Christopher; Stéphan, Igor; Garcia, Laurent (2017): * ASPeRiX, a first-order forward chaining approach for answer set computing. * In Theory and Practice of Logic Programming, pp. 1-45. DOI: * 10.1017/S1471068416000569 */ public class ThreeColouringTestWithRandom { private static final long DEBUG_TIMEOUT_FACTOR = 5; @RegressionTest public void testN3(RegressionTestConfig cfg) { long timeout = 3000L; runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(3, false, 0, cfg)); } @RegressionTest public void testN4(RegressionTestConfig cfg) { long timeout = 4000L; runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(4, false, 0, cfg)); } @RegressionTest @Disabled("disabled to save resources during CI") public void testN5(RegressionTestConfig cfg) { long timeout = 5000L; runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(5, false, 0, cfg)); } @RegressionTest @Disabled("disabled to save resources during CI") public void testN6(RegressionTestConfig cfg) { long timeout = 6000L; runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(6, false, 0, cfg)); } @RegressionTest @Disabled("disabled to save resources during CI") public void testN7(RegressionTestConfig cfg) { long timeout = 7000L; runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(7, false, 0, cfg)); } @RegressionTest @Disabled("disabled to save resources during CI") public void testN8(RegressionTestConfig cfg) { long timeout = 8000L; runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(8, false, 0, cfg)); } @RegressionTest @Disabled("disabled to save resources during CI") public void testN9(RegressionTestConfig cfg) { long timeout = 9000L; runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(9, false, 0, cfg)); } @RegressionTest @Disabled("disabled to save resources during CI") public void testN10(RegressionTestConfig cfg) { long timeout = 10000L; runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(10, false, 0, cfg)); } @RegressionTest @Disabled("disabled to save resources during CI") public void testN10Random0(RegressionTestConfig cfg) { long timeout = 10000L; runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(10, true, 0, cfg)); } @RegressionTest @Disabled("disabled to save resources during CI") public void testN10Random1(RegressionTestConfig cfg) { long timeout = 10000L; runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(10, true, 1, cfg)); } @RegressionTest @Disabled("disabled to save resources during CI") public void testN10Random2(RegressionTestConfig cfg) { long timeout = 10000L; runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(10, true, 2, cfg)); } @RegressionTest @Disabled("disabled to save resources during CI") public void testN10Random3(RegressionTestConfig cfg) { long timeout = 10000L; runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(10, true, 3, cfg)); } @RegressionTest @Disabled("disabled to save resources during CI") public void testN19(RegressionTestConfig cfg) { long timeout = 60000L; runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(19, false, 0, cfg)); } @RegressionTest @Disabled("disabled to save resources during CI") public void testN19Random0(RegressionTestConfig cfg) { long timeout = 60000L; runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(19, true, 0, cfg)); } @RegressionTest @Disabled("disabled to save resources during CI") public void testN19Random1(RegressionTestConfig cfg) { long timeout = 60000L; runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(19, true, 1, cfg)); } @RegressionTest @Disabled("disabled to save resources during CI") public void testN19Random2(RegressionTestConfig cfg) { long timeout = 60000L; runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(19, true, 2, cfg)); } @RegressionTest @Disabled("disabled to save resources during CI") public void testN19Random3(RegressionTestConfig cfg) { long timeout = 60000L; runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(19, true, 3, cfg)); } @RegressionTest @Disabled("disabled to save resources during CI") public void testN101(RegressionTestConfig cfg) { long timeout = 10000L; runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(101, false, 0, cfg)); } private void testThreeColouring(int n, boolean shuffle, int seed, RegressionTestConfig cfg) { ASPCore2Program tmpPrg = new ProgramParserImpl() .parse("col(V,C) :- v(V), c(C), not ncol(V,C)." + "ncol(V,C) :- col(V,D), c(C), C != D." + ":- e(V,U), col(V,C), col(U,C)."); InputProgram.Builder prgBuilder = InputProgram.builder().accumulate(tmpPrg); prgBuilder.addFacts(createColors("1", "2", "3")); prgBuilder.addFacts(createVertices(n)); prgBuilder.addFacts(createEdges(n, shuffle, seed)); InputProgram program = prgBuilder.build(); Solver solver = buildSolverForRegressionTest(program, cfg); @SuppressWarnings("unused") Optional<AnswerSet> answerSet = solver.stream().findAny(); // System.out.println(answerSet); // TODO: check correctness of answer set } private List<Atom> createColors(String... colours) { List<Atom> facts = new ArrayList<>(colours.length); for (String colour : colours) { List<Term> terms = new ArrayList<>(1); terms.add(Terms.newConstant(colour)); facts.add(Atoms.newBasicAtom(Predicates.getPredicate("c", 1), terms)); } return facts; } private List<Atom> createVertices(int n) { List<Atom> facts = new ArrayList<>(n); for (int i = 1; i <= n; i++) { facts.add(fact("v", i)); } return facts; } /** * * @param n * @param shuffle if true, the vertex indices are shuffled with the given seed * @param seed * @return */ private List<Atom> createEdges(int n, boolean shuffle, int seed) { List<Atom> facts = new ArrayList<>(n); List<Integer> indices = new ArrayList<>(); for (int i = 1; i <= n; i++) { indices.add(i); } if (shuffle) { Collections.shuffle(indices, new Random(seed)); } for (int i = 1; i < n; i++) { facts.add(fact("e", indices.get(0), indices.get(i))); } for (int i = 1; i < n - 1; i++) { facts.add(fact("e", indices.get(i), indices.get(i + 1))); } facts.add(fact("e", indices.get(1), indices.get(n - 1))); return facts; } private Atom fact(String predicateName, int... iTerms) { List<Term> terms = new ArrayList<>(iTerms.length); Predicate predicate = Predicates.getPredicate(predicateName, iTerms.length); for (int i : iTerms) { terms.add(Terms.newConstant(i)); } return Atoms.newBasicAtom(predicate, terms); } }
bsd-2-clause
zhangjunfang/eclipse-dir
eCardCity2.0/ecardcity-om/src/main/java/cn/newcapec/function/ecardcity/om/biz/impl/BaseEmployeeServiceImpl.java
3841
/** * 系统名称 :城市一卡通综合管理平台 * 开发组织 :城市一卡通事业部 * 版权所属 :新开普电子股份有限公司 * (C) Copyright Corporation 2014 All Rights Reserved. * 本内容仅限于郑州新开普电子股份有限公司内部使用,版权保护,未经过授权拷贝使用将追究法律责任 */ package cn.newcapec.function.ecardcity.om.biz.impl; import java.util.List; import java.util.Map; import net.sf.json.JSONArray; import org.hibernate.criterion.Order; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import cn.newcapec.framework.core.utils.pagesUtils.Page; import cn.newcapec.function.ecardcity.om.biz.BaseEmployeeService; import cn.newcapec.function.ecardcity.om.dao.BaseEmployeeDao; import cn.newcapec.function.ecardcity.om.model.BaseEmployee; import cn.newcapec.function.ecardcity.om.model.NetSiteBank; import cn.newcapec.function.ecardcity.om.utils.KeyValue; /** * @author wj * @category 操作员服务实现 * @version 1.0 * @date 2014年5月13日 下午5:06:43 */ @Service("BaseEmployeeService") @Transactional @SuppressWarnings("all") public class BaseEmployeeServiceImpl implements BaseEmployeeService { @Autowired private BaseEmployeeDao objDao ; /* (non-Javadoc) * @see cn.newcapec.framework.core.biz.BaseService#get(java.lang.String) */ @Override @Transactional(readOnly=true,propagation = Propagation.NOT_SUPPORTED) public BaseEmployee get(String arg0) { return objDao.get(arg0); } /* (non-Javadoc) * @see cn.newcapec.framework.core.biz.BaseService#removeUnused(java.lang.String) */ @Override public void removeUnused(String arg0) { objDao.delete(get(arg0)); } /* (non-Javadoc) * @see cn.newcapec.framework.core.biz.BaseService#saveOrUpdate(java.lang.Object) */ @Override public void saveOrUpdate(BaseEmployee arg0) { objDao.saveOrUpdate(arg0); } /* (non-Javadoc) * @see cn.newcapec.function.ecardcity.om.biz.BaseEmployeeService#getPage(java.util.Map) */ @Override @Transactional(readOnly=true,propagation = Propagation.NOT_SUPPORTED) public Page<?> getPage(Map<String, Object> paramMap) { return objDao.getPage(paramMap); } /* (non-Javadoc) * @see cn.newcapec.function.ecardcity.om.biz.BaseEmployeeService#getList(java.util.Map) */ @Override @Transactional(readOnly=true,propagation = Propagation.NOT_SUPPORTED) public List<?> getList(Map<String, Object> paramMap) { return (List<Map<String, Object>>) objDao.getListByAttr(paramMap, BaseEmployee.class,null); } /* (non-Javadoc) * @see cn.newcapec.function.ecardcity.om.biz.BaseEmployeeService#isExists(cn.newcapec.function.ecardcity.om.utils.KeyValue[]) */ @Override @Transactional(readOnly=true,propagation = Propagation.NOT_SUPPORTED) public boolean isExists(KeyValue[] keyValueArr) { return objDao.isExistsByAttr(BaseEmployee.class, keyValueArr); } /* (non-Javadoc) * @see cn.newcapec.function.ecardcity.om.biz.BaseEmployeeService#delete(java.lang.String[]) */ @Override public void delete(String[] ids) { objDao.delete(ids); } /* (non-Javadoc) * @see cn.newcapec.function.ecardcity.om.biz.BaseEmployeeService#getUsersFliterEployee(JSONArray) */ @Override public JSONArray getUsersFliterEployee(JSONArray users) { return objDao.getUsersFliterEployee(users); } /* (non-Javadoc) * @see cn.newcapec.function.ecardcity.om.biz.BaseEmployeeService#getMaxEmpID() */ @Override public int getMaxEmpID() { return objDao.getMaxEmpID(); } }
bsd-2-clause
javafunk/funk
funk-core/src/main/java/org/javafunk/funk/iterators/ChainedIterator.java
3389
/* * Copyright (C) 2011-Present Funk committers. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. */ package org.javafunk.funk.iterators; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import java.util.Iterator; import java.util.NoSuchElementException; import static org.javafunk.funk.Literals.iteratorBuilderWith; import static org.javafunk.funk.Literals.iteratorWith; public class ChainedIterator<T> implements Iterator<T> { private Iterator<? extends Iterator<? extends T>> iteratorsIterator; private Iterator<? extends T> currentIterator; public ChainedIterator(Iterator<? extends Iterator<? extends T>> iteratorsIterator) { this.iteratorsIterator = iteratorsIterator; if (this.iteratorsIterator.hasNext()) { currentIterator = this.iteratorsIterator.next(); } } @Override public boolean hasNext() { if (currentIterator == null) { return false; } if (currentIterator.hasNext()) { return true; } else { while (iteratorsIterator.hasNext()) { currentIterator = iteratorsIterator.next(); if (currentIterator.hasNext()) { return true; } } } return false; } @Override public T next() { if (hasNext()) { return currentIterator.next(); } else { throw new NoSuchElementException(); } } @Override public void remove() { currentIterator.remove(); } @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) .append("currentIterator", currentIterator) .append("remainingIterators", iteratorsIterator) .toString(); } public ChainedIterator( Iterator<? extends T> i1, Iterator<? extends T> i2) { this(iteratorWith(i1, i2)); } public ChainedIterator( Iterator<? extends T> i1, Iterator<? extends T> i2, Iterator<? extends T> i3) { this(iteratorWith(i1, i2, i3)); } public ChainedIterator( Iterator<? extends T> i1, Iterator<? extends T> i2, Iterator<? extends T> i3, Iterator<? extends T> i4) { this(iteratorWith(i1, i2, i3, i4)); } public ChainedIterator( Iterator<? extends T> i1, Iterator<? extends T> i2, Iterator<? extends T> i3, Iterator<? extends T> i4, Iterator<? extends T> i5) { this(iteratorWith(i1, i2, i3, i4, i5)); } public ChainedIterator( Iterator<? extends T> i1, Iterator<? extends T> i2, Iterator<? extends T> i3, Iterator<? extends T> i4, Iterator<? extends T> i5, Iterator<? extends T> i6) { this(iteratorWith(i1, i2, i3, i4, i5, i6)); } public ChainedIterator( Iterator<? extends T> i1, Iterator<? extends T> i2, Iterator<? extends T> i3, Iterator<? extends T> i4, Iterator<? extends T> i5, Iterator<? extends T> i6, Iterator<? extends T>... i7on) { this(iteratorBuilderWith(i1, i2, i3, i4, i5, i6).and(i7on).build()); } }
bsd-2-clause
swiezy/BPMN_temporal_logic_generator
Core/src/main/java/pl/edu/agh/kis/core/utilities/Utils.java
2165
/* * Copyright (c) 2015, pl.edu.agh * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package pl.edu.agh.kis.core.utilities; import java.io.File; /** * * @author Jakub Piotrowski * Filters only image types files */ public class Utils { public final static String jpeg = "jpeg"; public final static String jpg = "jpg"; public final static String gif = "gif"; public final static String tiff = "tiff"; public final static String tif = "tif"; public final static String png = "png"; public final static String bpmn = "bpmn"; /* * Get the extension of a file. */ public static String getExtension(File f) { String ext = null; String s = f.getName(); int i = s.lastIndexOf('.'); if (i > 0 && i < s.length() - 1) { ext = s.substring(i + 1).toLowerCase(); } return ext; } }
bsd-2-clause
wono/LoS
src/monsters/humans/Human.java
677
/* * * * * * * * * * * * * * * * * * * * * * * * * JAVA, ABSTRACT : HUMAN * * * last modified: 2014/06/10 * * first wrote: 2014/06/09 * * * * wono (wonho lim: wono@live.com) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * **/ package monsters.humans; import monsters.Monster; public abstract class Human extends Monster { }
bsd-2-clause
imagej/imagej-ops
src/main/java/net/imagej/ops/lookup/LookupByName.java
2030
/* * #%L * ImageJ2 software for multidimensional image processing and analysis. * %% * Copyright (C) 2014 - 2021 ImageJ2 developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package net.imagej.ops.lookup; import net.imagej.ops.Op; import net.imagej.ops.Ops; import net.imagej.ops.special.function.AbstractUnaryFunctionOp; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; /** * Implementation of "op" that finds the op by name. * * @author Curtis Rueden */ @Plugin(type = Ops.Lookup.class) public class LookupByName extends AbstractUnaryFunctionOp<String, Op> implements Ops.Lookup { @Parameter private Object[] args; @Override public Op calculate(final String input) { return ops().op(input, args); } }
bsd-2-clause
jkwatson/jotify
gui/src/main/java/nl/pascaldevink/jotify/gui/swing/plaf/JotifyPreviousNextButtonUI.java
1938
package nl.pascaldevink.jotify.gui.swing.plaf; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import javax.swing.AbstractButton; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.plaf.basic.BasicButtonUI; public class JotifyPreviousNextButtonUI extends BasicButtonUI { public static final int BUTTON_PREVIOUS = 0; public static final int BUTTON_NEXT = 1; private Image imageNormal; private Image imagePressed; private Image imageDisabled; public JotifyPreviousNextButtonUI(int type){ /* Load button images (25x25 pixels). */ if(type == BUTTON_PREVIOUS){ this.imageNormal = new ImageIcon(JotifyPlayButtonUI.class.getResource("images/previous_button.png")).getImage(); this.imagePressed = new ImageIcon(JotifyPlayButtonUI.class.getResource("images/previous_button_pressed.png")).getImage(); this.imageDisabled = new ImageIcon(JotifyPlayButtonUI.class.getResource("images/previous_button_disabled.png")).getImage(); } else{ this.imageNormal = new ImageIcon(JotifyPlayButtonUI.class.getResource("images/next_button.png")).getImage(); this.imagePressed = new ImageIcon(JotifyPlayButtonUI.class.getResource("images/next_button_pressed.png")).getImage(); this.imageDisabled = new ImageIcon(JotifyPlayButtonUI.class.getResource("images/next_button_disabled.png")).getImage(); } } public void paint(Graphics graphics, JComponent component){ /* Get button and 2D graphics. */ AbstractButton button = (AbstractButton)component; Graphics2D graphics2D = (Graphics2D)graphics; Image image = null; /* Select button image based on status. */ if(!button.getModel().isEnabled()){ image = this.imageDisabled; } else if(button.getModel().isPressed()){ image = this.imagePressed; } else{ image = this.imageNormal; } /* Draw button. */ graphics2D.drawImage(image, 0, 0, null); } }
bsd-2-clause
robertocapuano/jink
jink/src/main/java/debug/model/classobject/SnapshotState.java
2034
/* * Copyright (c) 2014, Roberto Capuano <roberto@2think.it> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package debug.model.classobject; import com.sun.jdi.*; import java.util.*; import debug.model.*; import debug.model.monitor.*; import debug.model.classloader.*; /** ** ObjectReference non pi� valido, quindi non interrogabile. ** Come suo surrogato abbiamo una shallow-copy. ** Rappresenta il this della precedente invocazione di dmetodo. */ public class SnapshotState extends debug.model.object.SnapshotState implements ClassState { SnapshotState( LiveState liveState ) throws StateException, OperationException { super( liveState ); } public boolean isRunnable() throws StateException { throw new StateException(); } }
bsd-2-clause
balcirakpeter/perun
perun-core/src/main/java/cz/metacentrum/perun/core/bl/VosManagerBl.java
17656
package cz.metacentrum.perun.core.bl; import cz.metacentrum.perun.core.api.BanOnVo; import cz.metacentrum.perun.core.api.Candidate; import cz.metacentrum.perun.core.api.ExtSource; import cz.metacentrum.perun.core.api.Facility; import cz.metacentrum.perun.core.api.Group; import cz.metacentrum.perun.core.api.Host; import cz.metacentrum.perun.core.api.Member; import cz.metacentrum.perun.core.api.MemberCandidate; import cz.metacentrum.perun.core.api.PerunSession; import cz.metacentrum.perun.core.api.Resource; import cz.metacentrum.perun.core.api.RichUser; import cz.metacentrum.perun.core.api.User; import cz.metacentrum.perun.core.api.Vo; import cz.metacentrum.perun.core.api.exceptions.AlreadyAdminException; import cz.metacentrum.perun.core.api.exceptions.BanNotExistsException; import cz.metacentrum.perun.core.api.exceptions.GroupNotAdminException; import cz.metacentrum.perun.core.api.exceptions.InternalErrorException; import cz.metacentrum.perun.core.api.exceptions.MemberNotExistsException; import cz.metacentrum.perun.core.api.exceptions.UserNotAdminException; import cz.metacentrum.perun.core.api.exceptions.UserNotExistsException; import cz.metacentrum.perun.core.api.exceptions.VoExistsException; import cz.metacentrum.perun.core.api.exceptions.VoNotExistsException; import java.util.Date; import java.util.List; import java.util.Optional; /** * <p>VOs manager can create, delete, update and find VO.</p> * <p/> * <p>You must get an instance of VosManager from Perun:</p> * <pre> * PerunSession ps; * //... * VosManager vm = ps.getPerun().getVosManager(); * </pre> * * @author Michal Prochazka * @author Slavek Licehammer * @see PerunSession */ public interface VosManagerBl { /** * Get list of all Vos. * * @param perunSession * @throws InternalErrorException * @return List of VOs or empty ArrayList<Vo> */ List<Vo> getVos(PerunSession perunSession); /** * Delete VO. * * @param perunSession * @param vo * @throws InternalErrorException */ void deleteVo(PerunSession perunSession, Vo vo); /** * Delete VO. * * @param perunSession * @param vo * @param forceDelete force the deletion of the VO, regardless there are any existing entities associated with the VO (they will be deleted) * @throws InternalErrorException */ void deleteVo(PerunSession perunSession, Vo vo, boolean forceDelete); /** * Create new VO. * * @param perunSession * @param vo vo object with prefilled voShortName and voName * @return newly created VO * @throws VoExistsException * @throws InternalErrorException */ Vo createVo(PerunSession perunSession, Vo vo) throws VoExistsException; /** * Updates VO. * * @param perunSession * @param vo * @return returns updated VO * @throws InternalErrorException */ Vo updateVo(PerunSession perunSession, Vo vo); /** * Find existing VO by short name (short name is unique). * * @param perunSession * @param shortName short name of VO which you find (for example "KZCU") * @return VO with requested shortName or throws if the VO with specified shortName doesn't exist * @throws InternalErrorException */ Vo getVoByShortName(PerunSession perunSession, String shortName) throws VoNotExistsException; /** * Finds existing VO by id. * * @param perunSession * @param id * @return VO with requested id or throws if the VO with specified id doesn't exist * @throws InternalErrorException */ Vo getVoById(PerunSession perunSession, int id) throws VoNotExistsException; /** * Finds existing VOs by ids. * * @param perunSession * @param ids * @return VOs with requested ids * @throws InternalErrorException */ List<Vo> getVosByIds(PerunSession perunSession, List<Integer> ids); /** * Finds users, who can join the Vo. * * @param perunSession * @param vo * @param searchString depends on the extSource of the VO, could by part of the name, email or something like that. * @param maxNumOfResults limit the maximum number of returned entries * @return list of candidates who match the searchString * @throws InternalErrorException */ List<Candidate> findCandidates(PerunSession perunSession, Vo vo, String searchString, int maxNumOfResults); /** * Finds users, who can join the Vo. * * @param perunSession * @param vo vo to be used * @param searchString depends on the extSource of the VO, could by part of the name, email or something like that. * @return list of candidates who match the searchString * @throws InternalErrorException */ List<Candidate> findCandidates(PerunSession perunSession, Vo vo, String searchString); /** * Finds users, who can join the group in Vo. * * @param sess * @param group group to be used * @param searchString depends on the extSource of the Group, could by part of the name, email or something like that. * @return list of candidates who match the searchString * @throws InternalErrorException */ List<Candidate> findCandidates(PerunSession sess, Group group, String searchString); /** * Finds MemberCandidates who can join the Vo. * * @param sess session * @param vo vo to be used * @param attrNames name of attributes to be searched * @param searchString depends on the extSource of the Vo, could by part of the name, email or something like that. * @return list of memberCandidates who match the searchString * @throws InternalErrorException internal error */ List<MemberCandidate> getCompleteCandidates(PerunSession sess, Vo vo, List<String> attrNames, String searchString); /** * Finds MemberCandidates who can join the Group. If the given vo is not null, it searches only * users who belong to this Vo or who have ues in any of given extSources. * * @param sess session * @param vo vo if vo is null, users are searched in whole perun, otherwise users are searched in members of given vo and in users with ues in any of given extSources * @param group group to be used * @param attrNames name of attributes to be searched * @param searchString depends on the extSource of the Vo, could by part of the name, email or something like that. * @param extSources extSources used to find candidates and possibly users * @return list of memberCandidates who match the searchString */ List<MemberCandidate> getCompleteCandidates(PerunSession sess, Vo vo, Group group, List<String> attrNames, String searchString, List<ExtSource> extSources); /** * Get list of all user administrators for supported role and specific vo. * * If onlyDirectAdmins is true, return only direct users of the group for supported role. * * Supported roles: VOOBSERVER, TOPGROUPCREATOR, VOADMIN * * @param perunSession * @param vo * @param role supported role * @param onlyDirectAdmins if true, get only direct user administrators (if false, get both direct and indirect) * * @return list of all user administrators of the given vo for supported role * * @throws InternalErrorException */ List<User> getAdmins(PerunSession perunSession, Vo vo, String role, boolean onlyDirectAdmins); /** * Get list of all richUser administrators for the vo and supported role with specific attributes. * * Supported roles: VOOBSERVER, TOPGROUPCREATOR, VOADMIN * * If "onlyDirectAdmins" is "true", return only direct users of the vo for supported role with specific attributes. * If "allUserAttributes" is "true", do not specify attributes through list and return them all in objects richUser. Ignoring list of specific attributes. * * @param perunSession * @param vo * * @param specificAttributes list of specified attributes which are needed in object richUser * @param allUserAttributes if true, get all possible user attributes and ignore list of specificAttributes (if false, get only specific attributes) * @param onlyDirectAdmins if true, get only direct user administrators (if false, get both direct and indirect) * * @return list of RichUser administrators for the vo and supported role with attributes * * @throws InternalErrorException * @throws UserNotExistsException */ List<RichUser> getRichAdmins(PerunSession perunSession, Vo vo, String role, List<String> specificAttributes, boolean allUserAttributes, boolean onlyDirectAdmins) throws UserNotExistsException; /** * Get list of group administrators of the given VO. * * Supported roles: VOOBSERVER, TOPGROUPCREATOR, VOADMIN * * @param perunSession * @param vo * @param role * * @return List of groups, who are administrators of the Vo with supported role. Returns empty list if there is no VO group admin. * * @throws InternalErrorException */ List<Group> getAdminGroups(PerunSession perunSession, Vo vo, String role); /** * Get list of Vo administrators. * If some group is administrator of the VO, all members are included in the list. * * @param perunSession * @param vo * @return List of users, who are administrators of the Vo. Returns empty list if there is no VO admin. * @throws InternalErrorException */ @Deprecated List<User> getAdmins(PerunSession perunSession, Vo vo); /** * Gets list of direct user administrators of the VO. * 'Direct' means, there aren't included users, who are members of group administrators, in the returned list. * * @param perunSession * @param vo * * @throws InternalErrorException */ @Deprecated List<User> getDirectAdmins(PerunSession perunSession, Vo vo); /** * Get list of group administrators of the given VO. * * @param perunSession * @param vo * @return List of groups, who are administrators of the Vo. Returns empty list if there is no VO group admin. * @throws InternalErrorException */ @Deprecated List<Group> getAdminGroups(PerunSession perunSession, Vo vo); /** * Get list of Vo administrators like RichUsers without attributes. * * @param perunSession * @param vo * @return List of users, who are administrators of the Vo. Returns empty list if there is no VO admin. * @throws InternalErrorException */ @Deprecated List<RichUser> getRichAdmins(PerunSession perunSession, Vo vo); /** * Get list of Vo administrators directly assigned to VO like RichUsers without attributes. * * @param perunSession * @param vo * @return List of users, who are administrators of the Vo. Returns empty list if there is no VO admin. * @throws InternalErrorException */ @Deprecated List<RichUser> getDirectRichAdmins(PerunSession perunSession, Vo vo); /** * Get list of Vo administrators like RichUsers with attributes. * * @param perunSession * @param vo * @return List of users, who are administrators of the Vo. Returns empty list if there is no VO admin. * @throws InternalErrorException * @throws UserNotExistsException */ @Deprecated List<RichUser> getRichAdminsWithAttributes(PerunSession perunSession, Vo vo) throws UserNotExistsException; /** * Get list of Vo administrators with specific attributes. * From list of specificAttributes get all Users Attributes and find those for every RichAdmin (only, other attributes are not searched) * * @param perunSession * @param vo * @param specificAttributes * @return list of RichUsers with specific attributes. * @throws InternalErrorException */ @Deprecated List<RichUser> getRichAdminsWithSpecificAttributes(PerunSession perunSession, Vo vo, List<String> specificAttributes); /** * Get list of Vo administrators, which are directly assigned (not by group membership) with specific attributes. * From list of specificAttributes get all Users Attributes and find those for every RichAdmin (only, other attributes are not searched) * * @param perunSession * @param vo * @param specificAttributes * @return list of RichUsers with specific attributes. * @throws InternalErrorException */ @Deprecated List<RichUser> getDirectRichAdminsWithSpecificAttributes(PerunSession perunSession, Vo vo, List<String> specificAttributes); /** * Returns list of vos connected with a group * * @param sess * @param group * @return list of vos connected with group * @throws InternalErrorException */ List<Vo> getVosByPerunBean(PerunSession sess, Group group) throws VoNotExistsException; /** * Returns list of vos connected with a member * * @param sess * @param member * @return list of vos connected with member * @throws InternalErrorException */ List<Vo> getVosByPerunBean(PerunSession sess, Member member); /** * Returns list of vos connected with a resource * * @param sess * @param resource * @return list of vos connected with resource * @throws InternalErrorException */ List<Vo> getVosByPerunBean(PerunSession sess, Resource resource) throws VoNotExistsException; /** * Returns list of vos connected with a user * * @param sess * @param user * @return list of vos connected with user * @throws InternalErrorException */ List<Vo> getVosByPerunBean(PerunSession sess, User user); /** * Returns list of vos connected with a host * * @param sess * @param host * @return list of vos connected with host * @throws InternalErrorException */ List<Vo> getVosByPerunBean(PerunSession sess, Host host); /** * Returns list of vos connected with a facility * * @param sess * @param facility * @return list of vos connected with facility * @throws InternalErrorException */ List<Vo> getVosByPerunBean(PerunSession sess, Facility facility); void checkVoExists(PerunSession sess, Vo vo) throws VoNotExistsException; /** * Get count of all vos. * * @param perunSession * * @return count of all vos * * @throws InternalErrorException */ int getVosCount(PerunSession perunSession); /** * Check whether a user is in a role for a given VO, possibly checking also user's groups. * @param session session * @param user user * @param role role * @param vo virtual organization * @param checkGroups check also groups of the user whether they have the role * @return true if user is directly in role for the vo, or if "checkGroups" flag is set and at least one of the groups is in the role * @throws InternalErrorException exception */ boolean isUserInRoleForVo(PerunSession session, User user, String role, Vo vo, boolean checkGroups); /** * Handles a user that lost a role. * * @param sess perun session * @param user user * @param vo virtual organization * @param role role of user in VO * @throws InternalErrorException */ void handleUserLostVoRole(PerunSession sess, User user, Vo vo, String role); /** * Handles a group that lost a role. * * @param sess perun session * @param group group * @param vo virtual organization * @param role role of group in VO * @throws InternalErrorException */ void handleGroupLostVoRole(PerunSession sess, Group group, Vo vo, String role); /** * Set given ban. * * @param sess session * @param banOnVo ban information, memberId, voId, validity and description are needed * @return created ban object */ BanOnVo setBan(PerunSession sess, BanOnVo banOnVo) throws MemberNotExistsException; /** * Get ban by its id. * * @param sess session * @param banId ban id * @return ban object * @throws BanNotExistsException if ban with given id is not found */ BanOnVo getBanById(PerunSession sess, int banId) throws BanNotExistsException; /** * Get ban for given member, if it exists. * * @param sess session * @param memberId member id * @return ban object, or null if there is no ban for given member */ Optional<BanOnVo> getBanForMember(PerunSession sess, int memberId); /** * Get list of all bans for vo with given id. * * @param sess session * @param voId vo id * @return list of bans for given vo */ List<BanOnVo> getBansForVo(PerunSession sess, int voId); /** * Update ban information. Only description and validity are updated. * * @param sess session * @param banOnVo updated ban * @return updated ban object */ BanOnVo updateBan(PerunSession sess, BanOnVo banOnVo); /** * Removes ban with given id. * * @param sess session * @param banId ban id * @throws BanNotExistsException if there is no ban with given id */ void removeBan(PerunSession sess, int banId) throws BanNotExistsException; /** * Removes ban for member with given id. * * @param sess session * @param memberId member id * @throws BanNotExistsException if there is no ban for member with given id */ void removeBanForMember(PerunSession sess, int memberId) throws BanNotExistsException; /** * Information if there is a ban for member with given id. * * @param sess session * @param memberId member id * @return true, if member with given id is banned, false otherwise */ boolean isMemberBanned(PerunSession sess, int memberId); /** * For the given vo, creates sponsored members for each sponsored user who is a member * of the given vo. Original sponsors of the users will be set to the sponsored members. * * @param sess session * @param vo vo where members will be converted */ void convertSponsoredUsers(PerunSession sess, Vo vo); /** * For the given vo, creates sponsored members for each sponsored user who is a member * of the given vo. The sponsored members will be sponsored by the given user, not by its * original sponsors. * * @param sess session * @param vo vo where members will be converted * @param newSponsor user, who will be set as a sponsor to the sponsored members */ void convertSponsoredUsersWithNewSponsor(PerunSession sess, Vo vo, User newSponsor); }
bsd-2-clause
msetteducati/StarbucksSimulation
src/pa5_EC/Customer.java
1960
package pa5_EC; /** * Project 5: Starbucks Simulation * * Purpose: Store the fields relevant to a customer * * @author MichaelSetteducati * */ public class Customer { /** * Instance variable stores name of Customer */ private String name; /** * Instance variable stores arrival time of Customer */ private int arrivalTime; /** * Instance variable stores serviceTime required for customer */ private int serviceTime; /** * Constructor for Customer * * @param name Name of customer * @param arrivalTime ArrivalTime of customer * @param serviceTime Time required to prepare customer's drink */ public Customer(String name, int serviceTime, int arrivalTime) { this.name = name; this.arrivalTime = arrivalTime; this.serviceTime = serviceTime; } /** * Getter method for Name * * @return Name of customer */ public String getName() { return name; } /** * Getter method for arrivalTime * * @return ArrivalTime of customer */ public int getArrivalTime() { return arrivalTime; } /** * Getter method for serviceTime * * @return ServiceTime required for this customer */ public int getServiceTime() { return serviceTime; } /** * toString method for customer returns a String representation of Customer in the following format: * <Name> - <ServiceTime> (<ArrivalTime>) * * @return String representation of Customer */ public String toString(){ return this.name + " - (serviceTime: " + this.serviceTime + ") (arrivalTime: " + this.getArrivalTime() + ")"; } /** * Equals method overrides the default equals method for Object * * @return True if this customer equals o, false otherwise */ @Override public boolean equals(Object o) { if(!(o instanceof Customer)) return false; else if(this.name.equals( ( (Customer) o).getName() ) ) //If names are the same, customer is the same return true; return false; } }
bsd-2-clause
kfricilone/runelite
runescape-client/src/main/java/class199.java
1285
import java.util.Iterator; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("ga") public class class199 implements Iterator { @ObfuscatedName("w") @ObfuscatedSignature( signature = "Lgt;" ) CombatInfoList field2429; @ObfuscatedName("m") @ObfuscatedSignature( signature = "Lgl;" ) Node field2428; @ObfuscatedName("q") @ObfuscatedSignature( signature = "Lgl;" ) Node field2430; @ObfuscatedSignature( signature = "(Lgt;)V" ) class199(CombatInfoList var1) { this.field2430 = null; this.field2429 = var1; this.field2428 = this.field2429.node.next; this.field2430 = null; } public void remove() { if(this.field2430 == null) { throw new IllegalStateException(); } else { this.field2430.unlink(); this.field2430 = null; } } public Object next() { Node var1 = this.field2428; if(var1 == this.field2429.node) { var1 = null; this.field2428 = null; } else { this.field2428 = var1.next; } this.field2430 = var1; return var1; } public boolean hasNext() { return this.field2429.node != this.field2428; } }
bsd-2-clause
kruss/Juggernaut
src/ui/panel/SchedulerPanel.java
6767
package ui.panel; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Date; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumnModel; import core.ISystemComponent; import core.runtime.LaunchManager; import core.runtime.ScheduleManager; import core.runtime.LaunchManager.LaunchInfo; import core.runtime.logger.ILogProvider; import core.runtime.logger.Logger; import util.DateTools; import util.IChangeListener; import util.UiTools; public class SchedulerPanel extends JPanel implements ISystemComponent, IChangeListener { private static final long serialVersionUID = 1L; private LaunchManager launchManager; private ScheduleManager scheduleManager; private JScrollPane launchPanel; private JTable launchTable; private DefaultTableModel tableModel; private LoggerConsole logingConsole; private JButton triggerScheduler; private JButton stopLaunch; private ArrayList<LaunchInfo> launches; public SchedulerPanel( LaunchManager launchManager, ScheduleManager scheduleManager, Logger logger) { this.launchManager = launchManager; this.scheduleManager = scheduleManager; launches = new ArrayList<LaunchInfo>(); tableModel = new DefaultTableModel(){ private static final long serialVersionUID = 1L; public Object getValueAt(int row, int column){ try{ return super.getValueAt(row, column); }catch(Exception e){ return null; } } }; tableModel.addColumn("Launch"); tableModel.addColumn("Trigger"); tableModel.addColumn("Start"); tableModel.addColumn("Progress"); tableModel.addColumn("Status"); launchTable = new JTable(tableModel){ private static final long serialVersionUID = 1L; @Override public boolean isCellEditable(int row, int col){ return false; } }; launchTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); launchTable.setRowSelectionAllowed(true); launchTable.setColumnSelectionAllowed(false); TableColumnModel columnModel = launchTable.getColumnModel(); columnModel.getColumn(0).setMinWidth(150); columnModel.getColumn(1).setMinWidth(200); columnModel.getColumn(2).setMinWidth(150); columnModel.getColumn(2).setMaxWidth(150); columnModel.getColumn(3).setMinWidth(100); columnModel.getColumn(3).setMaxWidth(100); columnModel.getColumn(4).setMinWidth(150); columnModel.getColumn(4).setMaxWidth(150); triggerScheduler = new JButton(" Trigger "); triggerScheduler.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ triggerScheduler(); } }); stopLaunch = new JButton(" Stop "); stopLaunch.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ stopLaunch(); } }); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS)); buttonPanel.add(triggerScheduler); buttonPanel.add(stopLaunch); launchPanel = new JScrollPane(launchTable); JPanel topPanel = new JPanel(new BorderLayout()); topPanel.add(launchPanel, BorderLayout.CENTER); topPanel.add(buttonPanel, BorderLayout.EAST); logingConsole = new LoggerConsole(); JSplitPane centerPanel = new JSplitPane( JSplitPane.VERTICAL_SPLIT, topPanel, logingConsole); centerPanel.setDividerLocation(200); setLayout(new BorderLayout()); add(centerPanel, BorderLayout.CENTER); launchTable.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e){ adjustSelection(); } }); launchTable.addKeyListener(new KeyListener(){ @Override public void keyPressed(KeyEvent e) {} @Override public void keyReleased(KeyEvent e) { adjustSelection(); } @Override public void keyTyped(KeyEvent e) {} }); launchManager.addListener(this); scheduleManager.addListener(this); } @Override public void init() throws Exception { initUI(); adjustSelection(); } @Override public void shutdown() throws Exception {} private void clearUI() { launchTable.clearSelection(); for(int i=tableModel.getRowCount()-1; i>=0; i--){ tableModel.removeRow(i); } } private void initUI() { for(LaunchInfo launch : launches){ Object[] rowData = { launch.name, launch.trigger, launch.start != null ? DateTools.getTextDate(launch.start) : "", launch.progress+" %", launch.status.toString() }; tableModel.addRow(rowData); } setSchedulerUpdate(); } private void setSchedulerUpdate() { Date updated = scheduleManager.getUpdated(); String info = updated != null ? "Scheduler: "+DateTools.getTextDate(updated) : "Scheduler: idle"; launchPanel.setToolTipText(info); launchTable.setToolTipText(info); } private void refreshUI(LaunchInfo selected) { clearUI(); initUI(); if(selected != null){ for(int i=0; i<launches.size(); i++){ if(launches.get(i).id.equals(selected.id)){ launchTable.changeSelection(i, -1, false, false); break; } } } adjustSelection(); } private void adjustSelection() { LaunchInfo selected = getSelectedLaunch(); if(selected != null){ stopLaunch.setEnabled(true); ILogProvider provider = launchManager.getLoggingProvider(selected.id); if(provider != logingConsole.getProvider()){ logingConsole.deregister(); logingConsole.clearConsole(); logingConsole.initConsole(provider.getBuffer()); provider.addListener(logingConsole); } }else{ stopLaunch.setEnabled(false); logingConsole.deregister(); logingConsole.clearConsole(); } } @Override public void changed(Object object) { if(object == launchManager){ LaunchInfo selected = getSelectedLaunch(); launches = launchManager.getLaunchInfo(); refreshUI(selected); }else if(object == scheduleManager){ setSchedulerUpdate(); } } private LaunchInfo getSelectedLaunch() { LaunchInfo selected = null; int index = launchTable.getSelectedRow(); if(index >=0){ selected = launches.get(index); } return selected; } public void triggerScheduler(){ scheduleManager.triggerScheduler(0); } public void stopLaunch(){ LaunchInfo selected = getSelectedLaunch(); if(selected != null && UiTools.confirmDialog("Stop launch [ "+selected.name+" ]?")){ launchManager.stopLaunch(selected.id); } } }
bsd-2-clause
yumix/growslowly
src/main/java/jp/yumix/mail/session/qualifier/Sonet.java
614
package jp.yumix.mail.session.qualifier; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.inject.Qualifier; /** * @author Yumi Hiraoka - yumix at outlook.com * */ @Qualifier @Target({TYPE, METHOD, FIELD, PARAMETER}) @Retention(RUNTIME) public @interface Sonet { }
bsd-2-clause
milot-mirdita/GeMuDB
Vendor/NCBI eutils/src/gov/nih/nlm/ncbi/www/soap/eutils/efetch_gene/Value_type83.java
24041
/** * Value_type83.java * * This file was auto-generated from WSDL * by the Apache Axis2 version: 1.6.2 Built on : Apr 17, 2012 (05:34:40 IST) */ package gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene; /** * Value_type83 bean class */ @SuppressWarnings({"unchecked","unused"}) public class Value_type83 implements org.apache.axis2.databinding.ADBBean{ public static final javax.xml.namespace.QName MY_QNAME = new javax.xml.namespace.QName( "http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene", "value_type83", "ns1"); /** * field for Value_type83 */ protected java.lang.String localValue_type83 ; private static java.util.HashMap _table_ = new java.util.HashMap(); // Constructor protected Value_type83(java.lang.String value, boolean isRegisterValue) { localValue_type83 = value; if (isRegisterValue){ _table_.put(localValue_type83, this); } } public static final java.lang.String _value1 = org.apache.axis2.databinding.utils.ConverterUtil.convertToString("not-set"); public static final java.lang.String _value2 = org.apache.axis2.databinding.utils.ConverterUtil.convertToString("virtual"); public static final java.lang.String _value3 = org.apache.axis2.databinding.utils.ConverterUtil.convertToString("raw"); public static final java.lang.String _value4 = org.apache.axis2.databinding.utils.ConverterUtil.convertToString("seg"); public static final java.lang.String _value5 = org.apache.axis2.databinding.utils.ConverterUtil.convertToString("const"); public static final java.lang.String _value6 = org.apache.axis2.databinding.utils.ConverterUtil.convertToString("ref"); public static final java.lang.String _value7 = org.apache.axis2.databinding.utils.ConverterUtil.convertToString("consen"); public static final java.lang.String _value8 = org.apache.axis2.databinding.utils.ConverterUtil.convertToString("map"); public static final java.lang.String _value9 = org.apache.axis2.databinding.utils.ConverterUtil.convertToString("delta"); public static final java.lang.String _value10 = org.apache.axis2.databinding.utils.ConverterUtil.convertToString("other"); public static final Value_type83 value1 = new Value_type83(_value1,true); public static final Value_type83 value2 = new Value_type83(_value2,true); public static final Value_type83 value3 = new Value_type83(_value3,true); public static final Value_type83 value4 = new Value_type83(_value4,true); public static final Value_type83 value5 = new Value_type83(_value5,true); public static final Value_type83 value6 = new Value_type83(_value6,true); public static final Value_type83 value7 = new Value_type83(_value7,true); public static final Value_type83 value8 = new Value_type83(_value8,true); public static final Value_type83 value9 = new Value_type83(_value9,true); public static final Value_type83 value10 = new Value_type83(_value10,true); public java.lang.String getValue() { return localValue_type83;} public boolean equals(java.lang.Object obj) {return (obj == this);} public int hashCode() { return toString().hashCode();} public java.lang.String toString() { return localValue_type83.toString(); } /** * * @param parentQName * @param factory * @return org.apache.axiom.om.OMElement */ public org.apache.axiom.om.OMElement getOMElement ( final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{ org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this,MY_QNAME); return factory.createOMElement(dataSource,MY_QNAME); } public void serialize(final javax.xml.namespace.QName parentQName, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ serialize(parentQName,xmlWriter,false); } public void serialize(final javax.xml.namespace.QName parentQName, javax.xml.stream.XMLStreamWriter xmlWriter, boolean serializeType) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ //We can safely assume an element has only one type associated with it java.lang.String namespace = parentQName.getNamespaceURI(); java.lang.String _localName = parentQName.getLocalPart(); writeStartElement(null, namespace, _localName, xmlWriter); // add the type details if this is used in a simple type if (serializeType){ java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene"); if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){ writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", namespacePrefix+":value_type83", xmlWriter); } else { writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", "value_type83", xmlWriter); } } if (localValue_type83==null){ throw new org.apache.axis2.databinding.ADBException("value_type83 cannot be null !!"); }else{ xmlWriter.writeCharacters(localValue_type83); } xmlWriter.writeEndElement(); } private static java.lang.String generatePrefix(java.lang.String namespace) { if(namespace.equals("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene")){ return "ns1"; } return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } /** * Utility method to write an element start tag. */ private void writeStartElement(java.lang.String prefix, java.lang.String namespace, java.lang.String localPart, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String writerPrefix = xmlWriter.getPrefix(namespace); if (writerPrefix != null) { xmlWriter.writeStartElement(namespace, localPart); } else { if (namespace.length() == 0) { prefix = ""; } else if (prefix == null) { prefix = generatePrefix(namespace); } xmlWriter.writeStartElement(prefix, localPart, namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } } /** * Util method to write an attribute with the ns prefix */ private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } xmlWriter.writeAttribute(namespace,attName,attValue); } /** * Util method to write an attribute without the ns prefix */ private void writeAttribute(java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (namespace.equals("")) { xmlWriter.writeAttribute(attName,attValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace,attName,attValue); } } /** * Util method to write an attribute without the ns prefix */ private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName, javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String attributeNamespace = qname.getNamespaceURI(); java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix = registerPrefix(xmlWriter, attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue = attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue = qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attributeValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attributeValue); } } /** * method to handle Qnames */ private void writeQName(javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String namespaceURI = qname.getNamespaceURI(); if (namespaceURI != null) { java.lang.String prefix = xmlWriter.getPrefix(namespaceURI); if (prefix == null) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } else { // i.e this is the default namespace xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } private void writeQNames(javax.xml.namespace.QName[] qnames, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (qnames != null) { // we have to store this data until last moment since it is not possible to write any // namespace data after writing the charactor data java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer(); java.lang.String namespaceURI = null; java.lang.String prefix = null; for (int i = 0; i < qnames.length; i++) { if (i > 0) { stringToWrite.append(" "); } namespaceURI = qnames[i].getNamespaceURI(); if (namespaceURI != null) { prefix = xmlWriter.getPrefix(namespaceURI); if ((prefix == null) || (prefix.length() == 0)) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } xmlWriter.writeCharacters(stringToWrite.toString()); } } /** * Register a namespace prefix */ private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); javax.xml.namespace.NamespaceContext nsContext = xmlWriter.getNamespaceContext(); while (true) { java.lang.String uri = nsContext.getNamespaceURI(prefix); if (uri == null || uri.length() == 0) { break; } prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } return prefix; } /** * databinding method to get an XML representation of this object * */ public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException{ //We can safely assume an element has only one type associated with it return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(MY_QNAME, new java.lang.Object[]{ org.apache.axis2.databinding.utils.reader.ADBXMLStreamReader.ELEMENT_TEXT, org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localValue_type83) }, null); } /** * Factory class that keeps the parse method */ public static class Factory{ public static Value_type83 fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { Value_type83 enumeration = (Value_type83) _table_.get(value); if ((enumeration == null) && !((value == null) || (value.equals("")))) { throw new java.lang.IllegalArgumentException(); } return enumeration; } public static Value_type83 fromString(java.lang.String value,java.lang.String namespaceURI) throws java.lang.IllegalArgumentException { try { return fromValue(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(value)); } catch (java.lang.Exception e) { throw new java.lang.IllegalArgumentException(); } } public static Value_type83 fromString(javax.xml.stream.XMLStreamReader xmlStreamReader, java.lang.String content) { if (content.indexOf(":") > -1){ java.lang.String prefix = content.substring(0,content.indexOf(":")); java.lang.String namespaceUri = xmlStreamReader.getNamespaceContext().getNamespaceURI(prefix); return Value_type83.Factory.fromString(content,namespaceUri); } else { return Value_type83.Factory.fromString(content,""); } } /** * static method to create the object * Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable * If this object is not an element, it is a complex type and the reader is at the event just after the outer start element * Postcondition: If this object is an element, the reader is positioned at its end element * If this object is a complex type, the reader is positioned at the end element of its outer element */ public static Value_type83 parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{ Value_type83 object = null; // initialize a hash map to keep values java.util.Map attributeMap = new java.util.HashMap(); java.util.List extraAttributeList = new java.util.ArrayList<org.apache.axiom.om.OMAttribute>(); int event; java.lang.String nillableValue = null; java.lang.String prefix =""; java.lang.String namespaceuri =""; try { while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); // Note all attributes that were handled. Used to differ normal attributes // from anyAttributes. java.util.Vector handledAttributes = new java.util.Vector(); while(!reader.isEndElement()) { if (reader.isStartElement() || reader.hasText()){ nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","nil"); if ("true".equals(nillableValue) || "1".equals(nillableValue)){ throw new org.apache.axis2.databinding.ADBException("The element: "+"value_type83" +" cannot be null"); } java.lang.String content = reader.getElementText(); if (content.indexOf(":") > 0) { // this seems to be a Qname so find the namespace and send prefix = content.substring(0, content.indexOf(":")); namespaceuri = reader.getNamespaceURI(prefix); object = Value_type83.Factory.fromString(content,namespaceuri); } else { // this seems to be not a qname send and empty namespace incase of it is // check is done in fromString method object = Value_type83.Factory.fromString(content,""); } } else { reader.next(); } } // end of while loop } catch (javax.xml.stream.XMLStreamException e) { throw new java.lang.Exception(e); } return object; } }//end of factory class }
bsd-2-clause
atomashpolskiy/link-rest
link-rest/src/main/java/com/nhl/link/rest/annotation/listener/UpdateServerParamsApplied.java
601
package com.nhl.link.rest.annotation.listener; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.Target; import com.nhl.link.rest.runtime.processor.update.ApplyUpdateServerParamsStage; /** * A chain listener annotation for methods to be invoked after * {@link ApplyUpdateServerParamsStage} execution. * * @since 1.19 */ @Target({ METHOD }) @Retention(RUNTIME) @Inherited public @interface UpdateServerParamsApplied { }
bsd-2-clause
mrduongnv/jcodec
src/main/java/org/jcodec/api/SequenceEncoder.java
3203
package org.jcodec.api; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import org.jcodec.codecs.h264.H264Encoder; import org.jcodec.codecs.h264.H264Utils; import org.jcodec.common.NIOUtils; import org.jcodec.common.SeekableByteChannel; import org.jcodec.common.model.ColorSpace; import org.jcodec.common.model.Picture; import org.jcodec.containers.mp4.Brand; import org.jcodec.containers.mp4.MP4Packet; import org.jcodec.containers.mp4.TrackType; import org.jcodec.containers.mp4.muxer.FramesMP4MuxerTrack; import org.jcodec.containers.mp4.muxer.MP4Muxer; import org.jcodec.scale.ColorUtil; import org.jcodec.scale.Transform; /** * This class is part of JCodec ( www.jcodec.org ) This software is distributed * under FreeBSD License * * @author The JCodec project * */ public class SequenceEncoder { private SeekableByteChannel ch; private Picture toEncode; private Transform transform; private H264Encoder encoder; private ArrayList<ByteBuffer> spsList; private ArrayList<ByteBuffer> ppsList; private FramesMP4MuxerTrack outTrack; private ByteBuffer _out; private int frameNo; private MP4Muxer muxer; public SequenceEncoder(File out) throws IOException { this.ch = NIOUtils.writableFileChannel(out); // Muxer that will store the encoded frames muxer = new MP4Muxer(ch, Brand.MP4); // Add video track to muxer outTrack = muxer.addTrack(TrackType.VIDEO, 25); // Allocate a buffer big enough to hold output frames _out = ByteBuffer.allocate(1920 * 1080 * 6); // Create an instance of encoder encoder = new H264Encoder(); // Transform to convert between RGB and YUV transform = ColorUtil.getTransform(ColorSpace.RGB, encoder.getSupportedColorSpaces()[0]); // Encoder extra data ( SPS, PPS ) to be stored in a special place of // MP4 spsList = new ArrayList<ByteBuffer>(); ppsList = new ArrayList<ByteBuffer>(); } public void encodeNativeFrame(Picture pic) throws IOException { if (toEncode == null) { toEncode = Picture.create(pic.getWidth(), pic.getHeight(), encoder.getSupportedColorSpaces()[0]); } // Perform conversion transform.transform(pic, toEncode); // Encode image into H.264 frame, the result is stored in '_out' buffer _out.clear(); ByteBuffer result = encoder.encodeFrame(toEncode, _out); // Based on the frame above form correct MP4 packet spsList.clear(); ppsList.clear(); H264Utils.wipePS(result, spsList, ppsList); H264Utils.encodeMOVPacket(result); // Add packet to video track outTrack.addFrame(new MP4Packet(result, frameNo, 25, 1, frameNo, true, null, frameNo, 0)); frameNo++; } public void finish() throws IOException { // Push saved SPS/PPS to a special storage in MP4 outTrack.addSampleEntry(H264Utils.createMOVSampleEntry(spsList, ppsList, 4)); // Write MP4 header and finalize recording muxer.writeHeader(); NIOUtils.closeQuietly(ch); } }
bsd-2-clause
cliniome/pki
secureClient/src/main/java/sa/com/is/Account.java
70938
package sa.com.is; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap; import android.content.ContentResolver; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.util.Log; import sa.com.is.activity.setup.AccountSetupCheckSettings.CheckDirection; import sa.com.is.helper.Utility; import sa.com.is.Folder.FolderClass; import sa.com.is.filter.Base64; import sa.com.is.store.RemoteStore; import sa.com.is.store.StoreConfig; import sa.com.is.mailstore.StorageManager; import sa.com.is.mailstore.StorageManager.StorageProvider; import sa.com.is.mailstore.LocalStore; import sa.com.is.provider.EmailProvider; import sa.com.is.provider.EmailProvider.StatsColumns; import sa.com.is.search.ConditionsTreeNode; import sa.com.is.search.LocalSearch; import sa.com.is.search.SqlQueryBuilder; import sa.com.is.search.SearchSpecification.Attribute; import sa.com.is.search.SearchSpecification.SearchCondition; import sa.com.is.search.SearchSpecification.SearchField; import sa.com.is.ssl.LocalKeyStore; import sa.com.is.view.ColorChip; import com.larswerkman.colorpicker.ColorPicker; /** * Account stores all of the settings for a single account defined by the user. It is able to save * and delete itself given a Preferences to work with. Each account is defined by a UUID. */ public class Account implements BaseAccount, StoreConfig { /** * Default value for the inbox folder (never changes for POP3 and IMAP) */ public static final String INBOX = "INBOX"; /** * This local folder is used to store messages to be sent. */ public static final String OUTBOX = "K9MAIL_INTERNAL_OUTBOX"; public void setSignedEmail(boolean signedEmail) { this.signedEmail = signedEmail; } public void setEncryptedEmail(boolean encryptedEmail) { this.encryptedEmail = encryptedEmail; } public enum Expunge { EXPUNGE_IMMEDIATELY, EXPUNGE_MANUALLY, EXPUNGE_ON_POLL } public enum DeletePolicy { NEVER(0), SEVEN_DAYS(1), ON_DELETE(2), MARK_AS_READ(3); public final int setting; DeletePolicy(int setting) { this.setting = setting; } public String preferenceString() { return Integer.toString(setting); } public static DeletePolicy fromInt(int initialSetting) { for (DeletePolicy policy: values()) { if (policy.setting == initialSetting) { return policy; } } throw new IllegalArgumentException("DeletePolicy " + initialSetting + " unknown"); } } public static final MessageFormat DEFAULT_MESSAGE_FORMAT = MessageFormat.HTML; public static final boolean DEFAULT_MESSAGE_FORMAT_AUTO = false; public static final boolean DEFAULT_MESSAGE_READ_RECEIPT = false; public static final QuoteStyle DEFAULT_QUOTE_STYLE = QuoteStyle.PREFIX; public static final String DEFAULT_QUOTE_PREFIX = ">"; public static final boolean DEFAULT_QUOTED_TEXT_SHOWN = true; public static final boolean DEFAULT_REPLY_AFTER_QUOTE = false; public static final boolean DEFAULT_STRIP_SIGNATURE = true; public static final int DEFAULT_REMOTE_SEARCH_NUM_RESULTS = 25; public static final String ACCOUNT_DESCRIPTION_KEY = "description"; public static final String STORE_URI_KEY = "storeUri"; public static final String TRANSPORT_URI_KEY = "transportUri"; public static final String IDENTITY_NAME_KEY = "name"; public static final String IDENTITY_EMAIL_KEY = "email"; public static final String IDENTITY_DESCRIPTION_KEY = "description"; private boolean signedEmail; private boolean encryptedEmail; /* * http://developer.android.com/design/style/color.html * Note: Order does matter, it's the order in which they will be picked. */ public static final Integer[] PREDEFINED_COLORS = new Integer[] { Color.parseColor("#0099CC"), // blue Color.parseColor("#669900"), // green Color.parseColor("#FF8800"), // orange Color.parseColor("#CC0000"), // red Color.parseColor("#9933CC") // purple }; public enum SortType { SORT_DATE(R.string.sort_earliest_first, R.string.sort_latest_first, false), SORT_ARRIVAL(R.string.sort_earliest_first, R.string.sort_latest_first, false), SORT_SUBJECT(R.string.sort_subject_alpha, R.string.sort_subject_re_alpha, true), SORT_SENDER(R.string.sort_sender_alpha, R.string.sort_sender_re_alpha, true), SORT_UNREAD(R.string.sort_unread_first, R.string.sort_unread_last, true), SORT_FLAGGED(R.string.sort_flagged_first, R.string.sort_flagged_last, true), SORT_ATTACHMENT(R.string.sort_attach_first, R.string.sort_unattached_first, true); private int ascendingToast; private int descendingToast; private boolean defaultAscending; SortType(int ascending, int descending, boolean ndefaultAscending) { ascendingToast = ascending; descendingToast = descending; defaultAscending = ndefaultAscending; } public int getToast(boolean ascending) { return (ascending) ? ascendingToast : descendingToast; } public boolean isDefaultAscending() { return defaultAscending; } } public static final SortType DEFAULT_SORT_TYPE = SortType.SORT_DATE; public static final boolean DEFAULT_SORT_ASCENDING = false; public static final String NO_OPENPGP_PROVIDER = ""; private DeletePolicy mDeletePolicy = DeletePolicy.NEVER; private final String mUuid; private String mStoreUri; /** * Storage provider ID, used to locate and manage the underlying DB/file * storage */ private String mLocalStorageProviderId; private String mTransportUri; private String mDescription; private String mAlwaysBcc; private int mAutomaticCheckIntervalMinutes; private int mDisplayCount; private int mChipColor; private long mLastAutomaticCheckTime; private long mLatestOldMessageSeenTime; private boolean mNotifyNewMail; private FolderMode mFolderNotifyNewMailMode; private boolean mNotifySelfNewMail; private String mInboxFolderName; private String mDraftsFolderName; private String mSentFolderName; private String mTrashFolderName; private String mArchiveFolderName; private String mSpamFolderName; private String mAutoExpandFolderName; private FolderMode mFolderDisplayMode; private FolderMode mFolderSyncMode; private FolderMode mFolderPushMode; private FolderMode mFolderTargetMode; private int mAccountNumber; private boolean mPushPollOnConnect; private boolean mNotifySync; private SortType mSortType; private Map<SortType, Boolean> mSortAscending = new HashMap<SortType, Boolean>(); private ShowPictures mShowPictures; private boolean mIsSignatureBeforeQuotedText; private Expunge mExpungePolicy = Expunge.EXPUNGE_IMMEDIATELY; private int mMaxPushFolders; private int mIdleRefreshMinutes; private boolean goToUnreadMessageSearch; private final Map<NetworkType, Boolean> compressionMap = new ConcurrentHashMap<NetworkType, Boolean>(); private Searchable searchableFolders; private boolean subscribedFoldersOnly; private int maximumPolledMessageAge; private int maximumAutoDownloadMessageSize=10485760; // Tracks if we have sent a notification for this account for // current set of fetched messages private boolean mRingNotified; private MessageFormat mMessageFormat; private boolean mMessageFormatAuto; private boolean mMessageReadReceipt; private QuoteStyle mQuoteStyle; private String mQuotePrefix; private boolean mDefaultQuotedTextShown; private boolean mReplyAfterQuote; private boolean mStripSignature; private boolean mSyncRemoteDeletions; private String mCryptoApp; private long mCryptoKey; private boolean mMarkMessageAsReadOnView; private boolean mAlwaysShowCcBcc; private boolean mAllowRemoteSearch; private boolean mRemoteSearchFullText; private int mRemoteSearchNumResults; private ColorChip mUnreadColorChip; private ColorChip mReadColorChip; private ColorChip mFlaggedUnreadColorChip; private ColorChip mFlaggedReadColorChip; /** * Indicates whether this account is enabled, i.e. ready for use, or not. * * <p> * Right now newly imported accounts are disabled if the settings file didn't contain a * password for the incoming and/or outgoing server. * </p> */ private boolean mEnabled; /** * Name of the folder that was last selected for a copy or move operation. * * Note: For now this value isn't persisted. So it will be reset when * K-9 Mail is restarted. */ private String lastSelectedFolderName = null; private List<Identity> identities; private NotificationSetting mNotificationSetting = new NotificationSetting(); public enum FolderMode { NONE, ALL, FIRST_CLASS, FIRST_AND_SECOND_CLASS, NOT_SECOND_CLASS } public enum ShowPictures { NEVER, ALWAYS, ONLY_FROM_CONTACTS } public enum Searchable { ALL, DISPLAYABLE, NONE } public enum QuoteStyle { PREFIX, HEADER } public enum MessageFormat { TEXT, HTML, AUTO } protected Account(Context context) { mUuid = UUID.randomUUID().toString(); mLocalStorageProviderId = StorageManager.getInstance(context).getDefaultProviderId(); mAutomaticCheckIntervalMinutes = -1; mIdleRefreshMinutes = 24; mPushPollOnConnect = true; mDisplayCount = K9.DEFAULT_VISIBLE_LIMIT; mAccountNumber = -1; mNotifyNewMail = true; mFolderNotifyNewMailMode = FolderMode.ALL; mNotifySync = true; mNotifySelfNewMail = true; mFolderDisplayMode = FolderMode.NOT_SECOND_CLASS; mFolderSyncMode = FolderMode.FIRST_CLASS; mFolderPushMode = FolderMode.FIRST_CLASS; mFolderTargetMode = FolderMode.NOT_SECOND_CLASS; mSortType = DEFAULT_SORT_TYPE; mSortAscending.put(DEFAULT_SORT_TYPE, DEFAULT_SORT_ASCENDING); mShowPictures = ShowPictures.NEVER; mIsSignatureBeforeQuotedText = false; mExpungePolicy = Expunge.EXPUNGE_IMMEDIATELY; mAutoExpandFolderName = INBOX; mInboxFolderName = INBOX; mMaxPushFolders = 10; mChipColor = pickColor(context); goToUnreadMessageSearch = false; subscribedFoldersOnly = false; maximumPolledMessageAge = -1; maximumAutoDownloadMessageSize = 32768; mMessageFormat = DEFAULT_MESSAGE_FORMAT; mMessageFormatAuto = DEFAULT_MESSAGE_FORMAT_AUTO; mMessageReadReceipt = DEFAULT_MESSAGE_READ_RECEIPT; mQuoteStyle = DEFAULT_QUOTE_STYLE; mQuotePrefix = DEFAULT_QUOTE_PREFIX; mDefaultQuotedTextShown = DEFAULT_QUOTED_TEXT_SHOWN; mReplyAfterQuote = DEFAULT_REPLY_AFTER_QUOTE; mStripSignature = DEFAULT_STRIP_SIGNATURE; mSyncRemoteDeletions = true; mCryptoApp = NO_OPENPGP_PROVIDER; mCryptoKey = 0; mAllowRemoteSearch = false; mRemoteSearchFullText = false; mRemoteSearchNumResults = DEFAULT_REMOTE_SEARCH_NUM_RESULTS; mEnabled = true; mMarkMessageAsReadOnView = true; mAlwaysShowCcBcc = false; searchableFolders = Searchable.ALL; identities = new ArrayList<Identity>(); Identity identity = new Identity(); identity.setSignatureUse(true); identity.setSignature(context.getString(R.string.default_signature)); identity.setDescription(context.getString(R.string.default_identity_description)); identities.add(identity); mNotificationSetting = new NotificationSetting(); mNotificationSetting.setVibrate(false); mNotificationSetting.setVibratePattern(0); mNotificationSetting.setVibrateTimes(5); mNotificationSetting.setRing(true); mNotificationSetting.setRingtone("content://settings/system/notification_sound"); mNotificationSetting.setLedColor(mChipColor); cacheChips(); } /* * Pick a nice Android guidelines color if we haven't used them all yet. */ private int pickColor(Context context) { List<Account> accounts = Preferences.getPreferences(context).getAccounts(); List<Integer> availableColors = new ArrayList<Integer>(PREDEFINED_COLORS.length); Collections.addAll(availableColors, PREDEFINED_COLORS); for (Account account : accounts) { Integer color = account.getChipColor(); if (availableColors.contains(color)) { availableColors.remove(color); if (availableColors.isEmpty()) { break; } } } return (availableColors.isEmpty()) ? ColorPicker.getRandomColor() : availableColors.get(0); } protected Account(Preferences preferences, String uuid) { this.mUuid = uuid; loadAccount(preferences); } /** * Load stored settings for this account. */ private synchronized void loadAccount(Preferences preferences) { SharedPreferences prefs = preferences.getPreferences(); mStoreUri = Base64.decode(prefs.getString(mUuid + ".storeUri", null)); mLocalStorageProviderId = prefs.getString(mUuid + ".localStorageProvider", StorageManager.getInstance(K9.app).getDefaultProviderId()); mTransportUri = Base64.decode(prefs.getString(mUuid + ".transportUri", null)); mDescription = prefs.getString(mUuid + ".description", null); mAlwaysBcc = prefs.getString(mUuid + ".alwaysBcc", mAlwaysBcc); mAutomaticCheckIntervalMinutes = prefs.getInt(mUuid + ".automaticCheckIntervalMinutes", -1); mIdleRefreshMinutes = prefs.getInt(mUuid + ".idleRefreshMinutes", 24); mPushPollOnConnect = prefs.getBoolean(mUuid + ".pushPollOnConnect", true); mDisplayCount = prefs.getInt(mUuid + ".displayCount", K9.DEFAULT_VISIBLE_LIMIT); if (mDisplayCount < 0) { mDisplayCount = K9.DEFAULT_VISIBLE_LIMIT; } mLastAutomaticCheckTime = prefs.getLong(mUuid + ".lastAutomaticCheckTime", 0); mLatestOldMessageSeenTime = prefs.getLong(mUuid + ".latestOldMessageSeenTime", 0); mNotifyNewMail = prefs.getBoolean(mUuid + ".notifyNewMail", false); mFolderNotifyNewMailMode = Preferences.getEnumStringPref(prefs, mUuid + ".folderNotifyNewMailMode", FolderMode.ALL); mNotifySelfNewMail = prefs.getBoolean(mUuid + ".notifySelfNewMail", true); mNotifySync = prefs.getBoolean(mUuid + ".notifyMailCheck", false); mDeletePolicy = DeletePolicy.fromInt(prefs.getInt(mUuid + ".deletePolicy", DeletePolicy.NEVER.setting)); mInboxFolderName = prefs.getString(mUuid + ".inboxFolderName", INBOX); mDraftsFolderName = prefs.getString(mUuid + ".draftsFolderName", "Drafts"); mSentFolderName = prefs.getString(mUuid + ".sentFolderName", "Sent"); mTrashFolderName = prefs.getString(mUuid + ".trashFolderName", "Trash"); mArchiveFolderName = prefs.getString(mUuid + ".archiveFolderName", "Archive"); mSpamFolderName = prefs.getString(mUuid + ".spamFolderName", "Spam"); mExpungePolicy = Preferences.getEnumStringPref(prefs, mUuid + ".expungePolicy", Expunge.EXPUNGE_IMMEDIATELY); mSyncRemoteDeletions = prefs.getBoolean(mUuid + ".syncRemoteDeletions", true); mMaxPushFolders = prefs.getInt(mUuid + ".maxPushFolders", 10); goToUnreadMessageSearch = prefs.getBoolean(mUuid + ".goToUnreadMessageSearch", false); subscribedFoldersOnly = prefs.getBoolean(mUuid + ".subscribedFoldersOnly", false); maximumPolledMessageAge = prefs.getInt(mUuid + ".maximumPolledMessageAge", -1); maximumAutoDownloadMessageSize = prefs.getInt(mUuid + ".maximumAutoDownloadMessageSize", 32768); mMessageFormat = Preferences.getEnumStringPref(prefs, mUuid + ".messageFormat", DEFAULT_MESSAGE_FORMAT); mMessageFormatAuto = prefs.getBoolean(mUuid + ".messageFormatAuto", DEFAULT_MESSAGE_FORMAT_AUTO); if (mMessageFormatAuto && mMessageFormat == MessageFormat.TEXT) { mMessageFormat = MessageFormat.AUTO; } mMessageReadReceipt = prefs.getBoolean(mUuid + ".messageReadReceipt", DEFAULT_MESSAGE_READ_RECEIPT); mQuoteStyle = Preferences.getEnumStringPref(prefs, mUuid + ".quoteStyle", DEFAULT_QUOTE_STYLE); mQuotePrefix = prefs.getString(mUuid + ".quotePrefix", DEFAULT_QUOTE_PREFIX); mDefaultQuotedTextShown = prefs.getBoolean(mUuid + ".defaultQuotedTextShown", DEFAULT_QUOTED_TEXT_SHOWN); mReplyAfterQuote = prefs.getBoolean(mUuid + ".replyAfterQuote", DEFAULT_REPLY_AFTER_QUOTE); mStripSignature = prefs.getBoolean(mUuid + ".stripSignature", DEFAULT_STRIP_SIGNATURE); for (NetworkType type : NetworkType.values()) { Boolean useCompression = prefs.getBoolean(mUuid + ".useCompression." + type, true); compressionMap.put(type, useCompression); } mAutoExpandFolderName = prefs.getString(mUuid + ".autoExpandFolderName", INBOX); mAccountNumber = prefs.getInt(mUuid + ".accountNumber", 0); mChipColor = prefs.getInt(mUuid + ".chipColor", ColorPicker.getRandomColor()); mSortType = Preferences.getEnumStringPref(prefs, mUuid + ".sortTypeEnum", SortType.SORT_DATE); mSortAscending.put(mSortType, prefs.getBoolean(mUuid + ".sortAscending", false)); mShowPictures = Preferences.getEnumStringPref(prefs, mUuid + ".showPicturesEnum", ShowPictures.NEVER); mNotificationSetting.setVibrate(prefs.getBoolean(mUuid + ".vibrate", false)); mNotificationSetting.setVibratePattern(prefs.getInt(mUuid + ".vibratePattern", 0)); mNotificationSetting.setVibrateTimes(prefs.getInt(mUuid + ".vibrateTimes", 5)); mNotificationSetting.setRing(prefs.getBoolean(mUuid + ".ring", true)); mNotificationSetting.setRingtone(prefs.getString(mUuid + ".ringtone", "content://settings/system/notification_sound")); mNotificationSetting.setLed(prefs.getBoolean(mUuid + ".led", true)); mNotificationSetting.setLedColor(prefs.getInt(mUuid + ".ledColor", mChipColor)); mFolderDisplayMode = Preferences.getEnumStringPref(prefs, mUuid + ".folderDisplayMode", FolderMode.NOT_SECOND_CLASS); mFolderSyncMode = Preferences.getEnumStringPref(prefs, mUuid + ".folderSyncMode", FolderMode.FIRST_CLASS); mFolderPushMode = Preferences.getEnumStringPref(prefs, mUuid + ".folderPushMode", FolderMode.FIRST_CLASS); mFolderTargetMode = Preferences.getEnumStringPref(prefs, mUuid + ".folderTargetMode", FolderMode.NOT_SECOND_CLASS); searchableFolders = Preferences.getEnumStringPref(prefs, mUuid + ".searchableFolders", Searchable.ALL); mIsSignatureBeforeQuotedText = prefs.getBoolean(mUuid + ".signatureBeforeQuotedText", false); identities = loadIdentities(prefs); String cryptoApp = prefs.getString(mUuid + ".cryptoApp", NO_OPENPGP_PROVIDER); setCryptoApp(cryptoApp); mAllowRemoteSearch = prefs.getBoolean(mUuid + ".allowRemoteSearch", false); mRemoteSearchFullText = prefs.getBoolean(mUuid + ".remoteSearchFullText", false); mRemoteSearchNumResults = prefs.getInt(mUuid + ".remoteSearchNumResults", DEFAULT_REMOTE_SEARCH_NUM_RESULTS); mEnabled = prefs.getBoolean(mUuid + ".enabled", true); mMarkMessageAsReadOnView = prefs.getBoolean(mUuid + ".markMessageAsReadOnView", true); mAlwaysShowCcBcc = prefs.getBoolean(mUuid + ".alwaysShowCcBcc", false); cacheChips(); // Use email address as account description if necessary if (mDescription == null) { mDescription = getEmail(); } } protected synchronized void delete(Preferences preferences) { // Get the list of account UUIDs String[] uuids = preferences.getPreferences().getString("accountUuids", "").split(","); // Create a list of all account UUIDs excluding this account List<String> newUuids = new ArrayList<String>(uuids.length); for (String uuid : uuids) { if (!uuid.equals(mUuid)) { newUuids.add(uuid); } } SharedPreferences.Editor editor = preferences.getPreferences().edit(); // Only change the 'accountUuids' value if this account's UUID was listed before if (newUuids.size() < uuids.length) { String accountUuids = Utility.combine(newUuids.toArray(), ','); editor.putString("accountUuids", accountUuids); } editor.remove(mUuid + ".storeUri"); editor.remove(mUuid + ".transportUri"); editor.remove(mUuid + ".description"); editor.remove(mUuid + ".name"); editor.remove(mUuid + ".email"); editor.remove(mUuid + ".alwaysBcc"); editor.remove(mUuid + ".automaticCheckIntervalMinutes"); editor.remove(mUuid + ".pushPollOnConnect"); editor.remove(mUuid + ".idleRefreshMinutes"); editor.remove(mUuid + ".lastAutomaticCheckTime"); editor.remove(mUuid + ".latestOldMessageSeenTime"); editor.remove(mUuid + ".notifyNewMail"); editor.remove(mUuid + ".notifySelfNewMail"); editor.remove(mUuid + ".deletePolicy"); editor.remove(mUuid + ".draftsFolderName"); editor.remove(mUuid + ".sentFolderName"); editor.remove(mUuid + ".trashFolderName"); editor.remove(mUuid + ".archiveFolderName"); editor.remove(mUuid + ".spamFolderName"); editor.remove(mUuid + ".autoExpandFolderName"); editor.remove(mUuid + ".accountNumber"); editor.remove(mUuid + ".vibrate"); editor.remove(mUuid + ".vibratePattern"); editor.remove(mUuid + ".vibrateTimes"); editor.remove(mUuid + ".ring"); editor.remove(mUuid + ".ringtone"); editor.remove(mUuid + ".folderDisplayMode"); editor.remove(mUuid + ".folderSyncMode"); editor.remove(mUuid + ".folderPushMode"); editor.remove(mUuid + ".folderTargetMode"); editor.remove(mUuid + ".signatureBeforeQuotedText"); editor.remove(mUuid + ".expungePolicy"); editor.remove(mUuid + ".syncRemoteDeletions"); editor.remove(mUuid + ".maxPushFolders"); editor.remove(mUuid + ".searchableFolders"); editor.remove(mUuid + ".chipColor"); editor.remove(mUuid + ".led"); editor.remove(mUuid + ".ledColor"); editor.remove(mUuid + ".goToUnreadMessageSearch"); editor.remove(mUuid + ".subscribedFoldersOnly"); editor.remove(mUuid + ".maximumPolledMessageAge"); editor.remove(mUuid + ".maximumAutoDownloadMessageSize"); editor.remove(mUuid + ".messageFormatAuto"); editor.remove(mUuid + ".quoteStyle"); editor.remove(mUuid + ".quotePrefix"); editor.remove(mUuid + ".sortTypeEnum"); editor.remove(mUuid + ".sortAscending"); editor.remove(mUuid + ".showPicturesEnum"); editor.remove(mUuid + ".replyAfterQuote"); editor.remove(mUuid + ".stripSignature"); editor.remove(mUuid + ".cryptoApp"); editor.remove(mUuid + ".cryptoAutoSignature"); editor.remove(mUuid + ".cryptoAutoEncrypt"); editor.remove(mUuid + ".enabled"); editor.remove(mUuid + ".markMessageAsReadOnView"); editor.remove(mUuid + ".alwaysShowCcBcc"); editor.remove(mUuid + ".allowRemoteSearch"); editor.remove(mUuid + ".remoteSearchFullText"); editor.remove(mUuid + ".remoteSearchNumResults"); editor.remove(mUuid + ".defaultQuotedTextShown"); editor.remove(mUuid + ".displayCount"); editor.remove(mUuid + ".inboxFolderName"); editor.remove(mUuid + ".localStorageProvider"); editor.remove(mUuid + ".messageFormat"); editor.remove(mUuid + ".messageReadReceipt"); editor.remove(mUuid + ".notifyMailCheck"); for (NetworkType type : NetworkType.values()) { editor.remove(mUuid + ".useCompression." + type.name()); } deleteIdentities(preferences.getPreferences(), editor); // TODO: Remove preference settings that may exist for individual // folders in the account. editor.commit(); } public static int findNewAccountNumber(List<Integer> accountNumbers) { int newAccountNumber = -1; Collections.sort(accountNumbers); for (int accountNumber : accountNumbers) { if (accountNumber > newAccountNumber + 1) { break; } newAccountNumber = accountNumber; } newAccountNumber++; return newAccountNumber; } public static List<Integer> getExistingAccountNumbers(Preferences preferences) { List<Account> accounts = preferences.getAccounts(); List<Integer> accountNumbers = new ArrayList<Integer>(accounts.size()); for (Account a : accounts) { accountNumbers.add(a.getAccountNumber()); } return accountNumbers; } public static int generateAccountNumber(Preferences preferences) { List<Integer> accountNumbers = getExistingAccountNumbers(preferences); return findNewAccountNumber(accountNumbers); } public void move(Preferences preferences, boolean moveUp) { String[] uuids = preferences.getPreferences().getString("accountUuids", "").split(","); SharedPreferences.Editor editor = preferences.getPreferences().edit(); String[] newUuids = new String[uuids.length]; if (moveUp) { for (int i = 0; i < uuids.length; i++) { if (i > 0 && uuids[i].equals(mUuid)) { newUuids[i] = newUuids[i-1]; newUuids[i-1] = mUuid; } else { newUuids[i] = uuids[i]; } } } else { for (int i = uuids.length - 1; i >= 0; i--) { if (i < uuids.length - 1 && uuids[i].equals(mUuid)) { newUuids[i] = newUuids[i+1]; newUuids[i+1] = mUuid; } else { newUuids[i] = uuids[i]; } } } String accountUuids = Utility.combine(newUuids, ','); editor.putString("accountUuids", accountUuids); editor.commit(); preferences.loadAccounts(); } public synchronized void save(Preferences preferences) { SharedPreferences.Editor editor = preferences.getPreferences().edit(); if (!preferences.getPreferences().getString("accountUuids", "").contains(mUuid)) { /* * When the account is first created we assign it a unique account number. The * account number will be unique to that account for the lifetime of the account. * So, we get all the existing account numbers, sort them ascending, loop through * the list and check if the number is greater than 1 + the previous number. If so * we use the previous number + 1 as the account number. This refills gaps. * mAccountNumber starts as -1 on a newly created account. It must be -1 for this * algorithm to work. * * I bet there is a much smarter way to do this. Anyone like to suggest it? */ List<Account> accounts = preferences.getAccounts(); int[] accountNumbers = new int[accounts.size()]; for (int i = 0; i < accounts.size(); i++) { accountNumbers[i] = accounts.get(i).getAccountNumber(); } Arrays.sort(accountNumbers); for (int accountNumber : accountNumbers) { if (accountNumber > mAccountNumber + 1) { break; } mAccountNumber = accountNumber; } mAccountNumber++; String accountUuids = preferences.getPreferences().getString("accountUuids", ""); accountUuids += (accountUuids.length() != 0 ? "," : "") + mUuid; editor.putString("accountUuids", accountUuids); } editor.putString(mUuid + ".storeUri", Base64.encode(mStoreUri)); editor.putString(mUuid + ".localStorageProvider", mLocalStorageProviderId); editor.putString(mUuid + ".transportUri", Base64.encode(mTransportUri)); editor.putString(mUuid + ".description", mDescription); editor.putString(mUuid + ".alwaysBcc", mAlwaysBcc); editor.putInt(mUuid + ".automaticCheckIntervalMinutes", mAutomaticCheckIntervalMinutes); editor.putInt(mUuid + ".idleRefreshMinutes", mIdleRefreshMinutes); editor.putBoolean(mUuid + ".pushPollOnConnect", mPushPollOnConnect); editor.putInt(mUuid + ".displayCount", mDisplayCount); editor.putLong(mUuid + ".lastAutomaticCheckTime", mLastAutomaticCheckTime); editor.putLong(mUuid + ".latestOldMessageSeenTime", mLatestOldMessageSeenTime); editor.putBoolean(mUuid + ".notifyNewMail", mNotifyNewMail); editor.putString(mUuid + ".folderNotifyNewMailMode", mFolderNotifyNewMailMode.name()); editor.putBoolean(mUuid + ".notifySelfNewMail", mNotifySelfNewMail); editor.putBoolean(mUuid + ".notifyMailCheck", mNotifySync); editor.putInt(mUuid + ".deletePolicy", mDeletePolicy.setting); editor.putString(mUuid + ".inboxFolderName", mInboxFolderName); editor.putString(mUuid + ".draftsFolderName", mDraftsFolderName); editor.putString(mUuid + ".sentFolderName", mSentFolderName); editor.putString(mUuid + ".trashFolderName", mTrashFolderName); editor.putString(mUuid + ".archiveFolderName", mArchiveFolderName); editor.putString(mUuid + ".spamFolderName", mSpamFolderName); editor.putString(mUuid + ".autoExpandFolderName", mAutoExpandFolderName); editor.putInt(mUuid + ".accountNumber", mAccountNumber); editor.putString(mUuid + ".sortTypeEnum", mSortType.name()); editor.putBoolean(mUuid + ".sortAscending", mSortAscending.get(mSortType)); editor.putString(mUuid + ".showPicturesEnum", mShowPictures.name()); editor.putString(mUuid + ".folderDisplayMode", mFolderDisplayMode.name()); editor.putString(mUuid + ".folderSyncMode", mFolderSyncMode.name()); editor.putString(mUuid + ".folderPushMode", mFolderPushMode.name()); editor.putString(mUuid + ".folderTargetMode", mFolderTargetMode.name()); editor.putBoolean(mUuid + ".signatureBeforeQuotedText", this.mIsSignatureBeforeQuotedText); editor.putString(mUuid + ".expungePolicy", mExpungePolicy.name()); editor.putBoolean(mUuid + ".syncRemoteDeletions", mSyncRemoteDeletions); editor.putInt(mUuid + ".maxPushFolders", mMaxPushFolders); editor.putString(mUuid + ".searchableFolders", searchableFolders.name()); editor.putInt(mUuid + ".chipColor", mChipColor); editor.putBoolean(mUuid + ".goToUnreadMessageSearch", goToUnreadMessageSearch); editor.putBoolean(mUuid + ".subscribedFoldersOnly", subscribedFoldersOnly); editor.putInt(mUuid + ".maximumPolledMessageAge", maximumPolledMessageAge); editor.putInt(mUuid + ".maximumAutoDownloadMessageSize", maximumAutoDownloadMessageSize); if (MessageFormat.AUTO.equals(mMessageFormat)) { // saving MessageFormat.AUTO as is to the database will cause downgrades to crash on // startup, so we save as MessageFormat.TEXT instead with a separate flag for auto. editor.putString(mUuid + ".messageFormat", Account.MessageFormat.TEXT.name()); mMessageFormatAuto = true; } else { editor.putString(mUuid + ".messageFormat", mMessageFormat.name()); mMessageFormatAuto = false; } editor.putBoolean(mUuid + ".messageFormatAuto", mMessageFormatAuto); editor.putBoolean(mUuid + ".messageReadReceipt", mMessageReadReceipt); editor.putString(mUuid + ".quoteStyle", mQuoteStyle.name()); editor.putString(mUuid + ".quotePrefix", mQuotePrefix); editor.putBoolean(mUuid + ".defaultQuotedTextShown", mDefaultQuotedTextShown); editor.putBoolean(mUuid + ".replyAfterQuote", mReplyAfterQuote); editor.putBoolean(mUuid + ".stripSignature", mStripSignature); editor.putString(mUuid + ".cryptoApp", mCryptoApp); editor.putLong(mUuid + ".cryptoKey", mCryptoKey); editor.putBoolean(mUuid + ".allowRemoteSearch", mAllowRemoteSearch); editor.putBoolean(mUuid + ".remoteSearchFullText", mRemoteSearchFullText); editor.putInt(mUuid + ".remoteSearchNumResults", mRemoteSearchNumResults); editor.putBoolean(mUuid + ".enabled", mEnabled); editor.putBoolean(mUuid + ".markMessageAsReadOnView", mMarkMessageAsReadOnView); editor.putBoolean(mUuid + ".alwaysShowCcBcc", mAlwaysShowCcBcc); editor.putBoolean(mUuid + ".vibrate", mNotificationSetting.shouldVibrate()); editor.putInt(mUuid + ".vibratePattern", mNotificationSetting.getVibratePattern()); editor.putInt(mUuid + ".vibrateTimes", mNotificationSetting.getVibrateTimes()); editor.putBoolean(mUuid + ".ring", mNotificationSetting.shouldRing()); editor.putString(mUuid + ".ringtone", mNotificationSetting.getRingtone()); editor.putBoolean(mUuid + ".led", mNotificationSetting.isLed()); editor.putInt(mUuid + ".ledColor", mNotificationSetting.getLedColor()); for (NetworkType type : NetworkType.values()) { Boolean useCompression = compressionMap.get(type); if (useCompression != null) { editor.putBoolean(mUuid + ".useCompression." + type, useCompression); } } saveIdentities(preferences.getPreferences(), editor); editor.commit(); } public void resetVisibleLimits() { try { getLocalStore().resetVisibleLimits(getDisplayCount()); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to reset visible limits", e); } } /** * @param context * @return <code>null</code> if not available * @throws MessagingException * @see {@link #isAvailable(Context)} */ public AccountStats getStats(Context context) throws MessagingException { if (!isAvailable(context)) { return null; } AccountStats stats = new AccountStats(); ContentResolver cr = context.getContentResolver(); Uri uri = Uri.withAppendedPath(EmailProvider.CONTENT_URI, "account/" + getUuid() + "/stats"); String[] projection = { StatsColumns.UNREAD_COUNT, StatsColumns.FLAGGED_COUNT }; // Create LocalSearch instance to exclude special folders (Trash, Drafts, Spam, Outbox, // Sent) and limit the search to displayable folders. LocalSearch search = new LocalSearch(); excludeSpecialFolders(search); limitToDisplayableFolders(search); // Use the LocalSearch instance to create a WHERE clause to query the content provider StringBuilder query = new StringBuilder(); List<String> queryArgs = new ArrayList<String>(); ConditionsTreeNode conditions = search.getConditions(); SqlQueryBuilder.buildWhereClause(this, conditions, query, queryArgs); String selection = query.toString(); String[] selectionArgs = queryArgs.toArray(new String[0]); Cursor cursor = cr.query(uri, projection, selection, selectionArgs, null); try { if (cursor.moveToFirst()) { stats.unreadMessageCount = cursor.getInt(0); stats.flaggedMessageCount = cursor.getInt(1); } } finally { cursor.close(); } LocalStore localStore = getLocalStore(); if (K9.measureAccounts()) { stats.size = localStore.getSize(); } return stats; } public synchronized void setChipColor(int color) { mChipColor = color; cacheChips(); } public synchronized void cacheChips() { mReadColorChip = new ColorChip(mChipColor, true, ColorChip.CIRCULAR); mUnreadColorChip = new ColorChip(mChipColor, false, ColorChip.CIRCULAR); mFlaggedReadColorChip = new ColorChip(mChipColor, true, ColorChip.STAR); mFlaggedUnreadColorChip = new ColorChip(mChipColor, false, ColorChip.STAR); } public synchronized int getChipColor() { return mChipColor; } public ColorChip generateColorChip(boolean messageRead, boolean toMe, boolean ccMe, boolean fromMe, boolean messageFlagged) { ColorChip chip; if (messageRead) { if (messageFlagged) { chip = mFlaggedReadColorChip; } else { chip = mReadColorChip; } } else { if (messageFlagged) { chip = mFlaggedUnreadColorChip; } else { chip = mUnreadColorChip; } } return chip; } @Override public String getUuid() { return mUuid; } public Uri getContentUri() { return Uri.parse("content://accounts/" + getUuid()); } public synchronized String getStoreUri() { return mStoreUri; } public synchronized void setStoreUri(String storeUri) { this.mStoreUri = storeUri; } public synchronized String getTransportUri() { return mTransportUri; } public synchronized void setTransportUri(String transportUri) { this.mTransportUri = transportUri; } @Override public synchronized String getDescription() { return mDescription; } @Override public synchronized void setDescription(String description) { this.mDescription = description; } public synchronized String getName() { return identities.get(0).getName(); } public synchronized void setName(String name) { identities.get(0).setName(name); } public synchronized boolean getSignatureUse() { return identities.get(0).getSignatureUse(); } public synchronized void setSignatureUse(boolean signatureUse) { identities.get(0).setSignatureUse(signatureUse); } public synchronized String getSignature() { return identities.get(0).getSignature(); } public synchronized void setSignature(String signature) { identities.get(0).setSignature(signature); } @Override public synchronized String getEmail() { return identities.get(0).getEmail(); } @Override public synchronized void setEmail(String email) { identities.get(0).setEmail(email); } public synchronized String getAlwaysBcc() { return mAlwaysBcc; } public synchronized void setAlwaysBcc(String alwaysBcc) { this.mAlwaysBcc = alwaysBcc; } /* Have we sent a new mail notification on this account */ public boolean isRingNotified() { return mRingNotified; } public void setRingNotified(boolean ringNotified) { mRingNotified = ringNotified; } public String getLocalStorageProviderId() { return mLocalStorageProviderId; } public void setLocalStorageProviderId(String id) { if (!mLocalStorageProviderId.equals(id)) { boolean successful = false; try { switchLocalStorage(id); successful = true; } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Switching local storage provider from " + mLocalStorageProviderId + " to " + id + " failed.", e); } finally { // if migration to/from SD-card failed once, it will fail again. if (!successful) { return; } } mLocalStorageProviderId = id; } } /** * Returns -1 for never. */ public synchronized int getAutomaticCheckIntervalMinutes() { return mAutomaticCheckIntervalMinutes; } /** * @param automaticCheckIntervalMinutes or -1 for never. */ public synchronized boolean setAutomaticCheckIntervalMinutes(int automaticCheckIntervalMinutes) { int oldInterval = this.mAutomaticCheckIntervalMinutes; this.mAutomaticCheckIntervalMinutes = automaticCheckIntervalMinutes; return (oldInterval != automaticCheckIntervalMinutes); } public synchronized int getDisplayCount() { return mDisplayCount; } public synchronized void setDisplayCount(int displayCount) { if (displayCount != -1) { this.mDisplayCount = displayCount; } else { this.mDisplayCount = K9.DEFAULT_VISIBLE_LIMIT; } resetVisibleLimits(); } public synchronized long getLastAutomaticCheckTime() { return mLastAutomaticCheckTime; } public synchronized void setLastAutomaticCheckTime(long lastAutomaticCheckTime) { this.mLastAutomaticCheckTime = lastAutomaticCheckTime; } public synchronized long getLatestOldMessageSeenTime() { return mLatestOldMessageSeenTime; } public synchronized void setLatestOldMessageSeenTime(long latestOldMessageSeenTime) { this.mLatestOldMessageSeenTime = latestOldMessageSeenTime; } public synchronized boolean isNotifyNewMail() { return mNotifyNewMail; } public synchronized void setNotifyNewMail(boolean notifyNewMail) { this.mNotifyNewMail = notifyNewMail; } public synchronized FolderMode getFolderNotifyNewMailMode() { return mFolderNotifyNewMailMode; } public synchronized void setFolderNotifyNewMailMode(FolderMode folderNotifyNewMailMode) { this.mFolderNotifyNewMailMode = folderNotifyNewMailMode; } public synchronized DeletePolicy getDeletePolicy() { return mDeletePolicy; } public synchronized void setDeletePolicy(DeletePolicy deletePolicy) { this.mDeletePolicy = deletePolicy; } public boolean isSpecialFolder(String folderName) { return (folderName != null && (folderName.equalsIgnoreCase(getInboxFolderName()) || folderName.equals(getTrashFolderName()) || folderName.equals(getDraftsFolderName()) || folderName.equals(getArchiveFolderName()) || folderName.equals(getSpamFolderName()) || folderName.equals(getOutboxFolderName()) || folderName.equals(getSentFolderName()) || folderName.equals(getErrorFolderName()))); } public synchronized String getDraftsFolderName() { return mDraftsFolderName; } public synchronized void setDraftsFolderName(String name) { mDraftsFolderName = name; } /** * Checks if this account has a drafts folder set. * @return true if account has a drafts folder set. */ public synchronized boolean hasDraftsFolder() { return !K9.FOLDER_NONE.equalsIgnoreCase(mDraftsFolderName); } public synchronized String getSentFolderName() { return mSentFolderName; } public synchronized String getErrorFolderName() { return K9.ERROR_FOLDER_NAME; } public synchronized void setSentFolderName(String name) { mSentFolderName = name; } /** * Checks if this account has a sent folder set. * @return true if account has a sent folder set. */ public synchronized boolean hasSentFolder() { return !K9.FOLDER_NONE.equalsIgnoreCase(mSentFolderName); } public synchronized String getTrashFolderName() { return mTrashFolderName; } public synchronized void setTrashFolderName(String name) { mTrashFolderName = name; } /** * Checks if this account has a trash folder set. * @return true if account has a trash folder set. */ public synchronized boolean hasTrashFolder() { return !K9.FOLDER_NONE.equalsIgnoreCase(mTrashFolderName); } public synchronized String getArchiveFolderName() { return mArchiveFolderName; } public synchronized void setArchiveFolderName(String archiveFolderName) { mArchiveFolderName = archiveFolderName; } /** * Checks if this account has an archive folder set. * @return true if account has an archive folder set. */ public synchronized boolean hasArchiveFolder() { return !K9.FOLDER_NONE.equalsIgnoreCase(mArchiveFolderName); } public synchronized String getSpamFolderName() { return mSpamFolderName; } public synchronized void setSpamFolderName(String name) { mSpamFolderName = name; } /** * Checks if this account has a spam folder set. * @return true if account has a spam folder set. */ public synchronized boolean hasSpamFolder() { return !K9.FOLDER_NONE.equalsIgnoreCase(mSpamFolderName); } public synchronized String getOutboxFolderName() { return OUTBOX; } public synchronized String getAutoExpandFolderName() { return mAutoExpandFolderName; } public synchronized void setAutoExpandFolderName(String name) { mAutoExpandFolderName = name; } public synchronized int getAccountNumber() { return mAccountNumber; } public synchronized FolderMode getFolderDisplayMode() { return mFolderDisplayMode; } public synchronized boolean setFolderDisplayMode(FolderMode displayMode) { FolderMode oldDisplayMode = mFolderDisplayMode; mFolderDisplayMode = displayMode; return oldDisplayMode != displayMode; } public synchronized FolderMode getFolderSyncMode() { return mFolderSyncMode; } public synchronized boolean setFolderSyncMode(FolderMode syncMode) { FolderMode oldSyncMode = mFolderSyncMode; mFolderSyncMode = syncMode; if (syncMode == FolderMode.NONE && oldSyncMode != FolderMode.NONE) { return true; } if (syncMode != FolderMode.NONE && oldSyncMode == FolderMode.NONE) { return true; } return false; } public synchronized FolderMode getFolderPushMode() { return mFolderPushMode; } public synchronized boolean setFolderPushMode(FolderMode pushMode) { FolderMode oldPushMode = mFolderPushMode; mFolderPushMode = pushMode; return pushMode != oldPushMode; } public synchronized boolean isShowOngoing() { return mNotifySync; } public synchronized void setShowOngoing(boolean showOngoing) { this.mNotifySync = showOngoing; } public synchronized SortType getSortType() { return mSortType; } public synchronized void setSortType(SortType sortType) { mSortType = sortType; } public synchronized boolean isSortAscending(SortType sortType) { if (mSortAscending.get(sortType) == null) { mSortAscending.put(sortType, sortType.isDefaultAscending()); } return mSortAscending.get(sortType); } public synchronized void setSortAscending(SortType sortType, boolean sortAscending) { mSortAscending.put(sortType, sortAscending); } public synchronized ShowPictures getShowPictures() { return mShowPictures; } public synchronized void setShowPictures(ShowPictures showPictures) { mShowPictures = showPictures; } public synchronized FolderMode getFolderTargetMode() { return mFolderTargetMode; } public synchronized void setFolderTargetMode(FolderMode folderTargetMode) { mFolderTargetMode = folderTargetMode; } public synchronized boolean isSignatureBeforeQuotedText() { return mIsSignatureBeforeQuotedText; } public synchronized void setSignatureBeforeQuotedText(boolean mIsSignatureBeforeQuotedText) { this.mIsSignatureBeforeQuotedText = mIsSignatureBeforeQuotedText; } public synchronized boolean isNotifySelfNewMail() { return mNotifySelfNewMail; } public synchronized void setNotifySelfNewMail(boolean notifySelfNewMail) { mNotifySelfNewMail = notifySelfNewMail; } public synchronized Expunge getExpungePolicy() { return mExpungePolicy; } public synchronized void setExpungePolicy(Expunge expungePolicy) { mExpungePolicy = expungePolicy; } public synchronized int getMaxPushFolders() { return mMaxPushFolders; } public synchronized boolean setMaxPushFolders(int maxPushFolders) { int oldMaxPushFolders = mMaxPushFolders; mMaxPushFolders = maxPushFolders; return oldMaxPushFolders != maxPushFolders; } public LocalStore getLocalStore() throws MessagingException { return LocalStore.getInstance(this, K9.app); } public Store getRemoteStore() throws MessagingException { return RemoteStore.getInstance(K9.app, this); } // It'd be great if this actually went into the store implementation // to get this, but that's expensive and not easily accessible // during initialization public boolean isSearchByDateCapable() { return (getStoreUri().startsWith("imap")); } @Override public synchronized String toString() { return mDescription; } public synchronized void setCompression(NetworkType networkType, boolean useCompression) { compressionMap.put(networkType, useCompression); } public synchronized boolean useCompression(NetworkType networkType) { Boolean useCompression = compressionMap.get(networkType); if (useCompression == null) { return true; } return useCompression; } @Override public boolean equals(Object o) { if (o instanceof Account) { return ((Account)o).mUuid.equals(mUuid); } return super.equals(o); } @Override public int hashCode() { return mUuid.hashCode(); } private synchronized List<Identity> loadIdentities(SharedPreferences prefs) { List<Identity> newIdentities = new ArrayList<Identity>(); int ident = 0; boolean gotOne = false; do { gotOne = false; String name = prefs.getString(mUuid + "." + IDENTITY_NAME_KEY + "." + ident, null); String email = prefs.getString(mUuid + "." + IDENTITY_EMAIL_KEY + "." + ident, null); boolean signatureUse = prefs.getBoolean(mUuid + ".signatureUse." + ident, true); String signature = prefs.getString(mUuid + ".signature." + ident, null); String description = prefs.getString(mUuid + "." + IDENTITY_DESCRIPTION_KEY + "." + ident, null); final String replyTo = prefs.getString(mUuid + ".replyTo." + ident, null); if (email != null) { Identity identity = new Identity(); identity.setName(name); identity.setEmail(email); identity.setSignatureUse(signatureUse); identity.setSignature(signature); identity.setDescription(description); identity.setReplyTo(replyTo); newIdentities.add(identity); gotOne = true; } ident++; } while (gotOne); if (newIdentities.isEmpty()) { String name = prefs.getString(mUuid + ".name", null); String email = prefs.getString(mUuid + ".email", null); boolean signatureUse = prefs.getBoolean(mUuid + ".signatureUse", true); String signature = prefs.getString(mUuid + ".signature", null); Identity identity = new Identity(); identity.setName(name); identity.setEmail(email); identity.setSignatureUse(signatureUse); identity.setSignature(signature); identity.setDescription(email); newIdentities.add(identity); } return newIdentities; } private synchronized void deleteIdentities(SharedPreferences prefs, SharedPreferences.Editor editor) { int ident = 0; boolean gotOne = false; do { gotOne = false; String email = prefs.getString(mUuid + "." + IDENTITY_EMAIL_KEY + "." + ident, null); if (email != null) { editor.remove(mUuid + "." + IDENTITY_NAME_KEY + "." + ident); editor.remove(mUuid + "." + IDENTITY_EMAIL_KEY + "." + ident); editor.remove(mUuid + ".signatureUse." + ident); editor.remove(mUuid + ".signature." + ident); editor.remove(mUuid + "." + IDENTITY_DESCRIPTION_KEY + "." + ident); editor.remove(mUuid + ".replyTo." + ident); gotOne = true; } ident++; } while (gotOne); } private synchronized void saveIdentities(SharedPreferences prefs, SharedPreferences.Editor editor) { deleteIdentities(prefs, editor); int ident = 0; for (Identity identity : identities) { editor.putString(mUuid + "." + IDENTITY_NAME_KEY + "." + ident, identity.getName()); editor.putString(mUuid + "." + IDENTITY_EMAIL_KEY + "." + ident, identity.getEmail()); editor.putBoolean(mUuid + ".signatureUse." + ident, identity.getSignatureUse()); editor.putString(mUuid + ".signature." + ident, identity.getSignature()); editor.putString(mUuid + "." + IDENTITY_DESCRIPTION_KEY + "." + ident, identity.getDescription()); editor.putString(mUuid + ".replyTo." + ident, identity.getReplyTo()); ident++; } } public synchronized List<Identity> getIdentities() { return identities; } public synchronized void setIdentities(List<Identity> newIdentities) { identities = new ArrayList<Identity>(newIdentities); } public synchronized Identity getIdentity(int i) { if (i < identities.size()) { return identities.get(i); } throw new IllegalArgumentException("Identity with index " + i + " not found"); } public boolean isAnIdentity(Address[] addrs) { if (addrs == null) { return false; } for (Address addr : addrs) { if (findIdentity(addr) != null) { return true; } } return false; } public boolean isAnIdentity(Address addr) { return findIdentity(addr) != null; } public synchronized Identity findIdentity(Address addr) { for (Identity identity : identities) { String email = identity.getEmail(); if (email != null && email.equalsIgnoreCase(addr.getAddress())) { return identity; } } return null; } public synchronized Searchable getSearchableFolders() { return searchableFolders; } public synchronized void setSearchableFolders(Searchable searchableFolders) { this.searchableFolders = searchableFolders; } public synchronized int getIdleRefreshMinutes() { return mIdleRefreshMinutes; } public synchronized void setIdleRefreshMinutes(int idleRefreshMinutes) { mIdleRefreshMinutes = idleRefreshMinutes; } public synchronized boolean isPushPollOnConnect() { return mPushPollOnConnect; } public synchronized void setPushPollOnConnect(boolean pushPollOnConnect) { mPushPollOnConnect = pushPollOnConnect; } /** * Are we storing out localStore on the SD-card instead of the local device * memory?<br/> * Only to be called durin initial account-setup!<br/> * Side-effect: changes {@link #mLocalStorageProviderId}. * * @param newStorageProviderId * Never <code>null</code>. * @throws MessagingException */ public void switchLocalStorage(final String newStorageProviderId) throws MessagingException { if (!mLocalStorageProviderId.equals(newStorageProviderId)) { getLocalStore().switchLocalStorage(newStorageProviderId); } } public synchronized boolean goToUnreadMessageSearch() { return goToUnreadMessageSearch; } public synchronized void setGoToUnreadMessageSearch(boolean goToUnreadMessageSearch) { this.goToUnreadMessageSearch = goToUnreadMessageSearch; } public synchronized boolean subscribedFoldersOnly() { return subscribedFoldersOnly; } public synchronized void setSubscribedFoldersOnly(boolean subscribedFoldersOnly) { this.subscribedFoldersOnly = subscribedFoldersOnly; } public synchronized int getMaximumPolledMessageAge() { return maximumPolledMessageAge; } public synchronized void setMaximumPolledMessageAge(int maximumPolledMessageAge) { this.maximumPolledMessageAge = maximumPolledMessageAge; } public synchronized int getMaximumAutoDownloadMessageSize() { return maximumAutoDownloadMessageSize; } public synchronized void setMaximumAutoDownloadMessageSize(int maximumAutoDownloadMessageSize) { this.maximumAutoDownloadMessageSize = maximumAutoDownloadMessageSize; } public Date getEarliestPollDate() { int age = getMaximumPolledMessageAge(); if (age >= 0) { Calendar now = Calendar.getInstance(); now.set(Calendar.HOUR_OF_DAY, 0); now.set(Calendar.MINUTE, 0); now.set(Calendar.SECOND, 0); now.set(Calendar.MILLISECOND, 0); if (age < 28) { now.add(Calendar.DATE, age * -1); } else switch (age) { case 28: now.add(Calendar.MONTH, -1); break; case 56: now.add(Calendar.MONTH, -2); break; case 84: now.add(Calendar.MONTH, -3); break; case 168: now.add(Calendar.MONTH, -6); break; case 365: now.add(Calendar.YEAR, -1); break; } return now.getTime(); } return null; } public MessageFormat getMessageFormat() { return mMessageFormat; } public void setMessageFormat(MessageFormat messageFormat) { this.mMessageFormat = messageFormat; } public synchronized boolean isMessageReadReceiptAlways() { return mMessageReadReceipt; } public synchronized void setMessageReadReceipt(boolean messageReadReceipt) { mMessageReadReceipt = messageReadReceipt; } public QuoteStyle getQuoteStyle() { return mQuoteStyle; } public void setQuoteStyle(QuoteStyle quoteStyle) { this.mQuoteStyle = quoteStyle; } public synchronized String getQuotePrefix() { return mQuotePrefix; } public synchronized void setQuotePrefix(String quotePrefix) { mQuotePrefix = quotePrefix; } public synchronized boolean isDefaultQuotedTextShown() { return mDefaultQuotedTextShown; } public synchronized void setDefaultQuotedTextShown(boolean shown) { mDefaultQuotedTextShown = shown; } public synchronized boolean isReplyAfterQuote() { return mReplyAfterQuote; } public synchronized void setReplyAfterQuote(boolean replyAfterQuote) { mReplyAfterQuote = replyAfterQuote; } public synchronized boolean isStripSignature() { return mStripSignature; } public synchronized void setStripSignature(boolean stripSignature) { mStripSignature = stripSignature; } public String getCryptoApp() { return mCryptoApp; } public void setCryptoApp(String cryptoApp) { if (cryptoApp == null || cryptoApp.equals("apg")) { mCryptoApp = NO_OPENPGP_PROVIDER; } else { mCryptoApp = cryptoApp; } } public long getCryptoKey() { return mCryptoKey; } public void setCryptoKey(long keyId) { mCryptoKey = keyId; } public boolean allowRemoteSearch() { return mAllowRemoteSearch; } public void setAllowRemoteSearch(boolean val) { mAllowRemoteSearch = val; } public int getRemoteSearchNumResults() { return mRemoteSearchNumResults; } public void setRemoteSearchNumResults(int val) { mRemoteSearchNumResults = (val >= 0 ? val : 0); } public String getInboxFolderName() { return mInboxFolderName; } public void setInboxFolderName(String name) { this.mInboxFolderName = name; } public synchronized boolean syncRemoteDeletions() { return mSyncRemoteDeletions; } public synchronized void setSyncRemoteDeletions(boolean syncRemoteDeletions) { mSyncRemoteDeletions = syncRemoteDeletions; } public synchronized String getLastSelectedFolderName() { return lastSelectedFolderName; } public synchronized void setLastSelectedFolderName(String folderName) { lastSelectedFolderName = folderName; } public synchronized String getOpenPgpProvider() { if (!isOpenPgpProviderConfigured()) { return null; } return getCryptoApp(); } public synchronized boolean isOpenPgpProviderConfigured() { return !NO_OPENPGP_PROVIDER.equals(getCryptoApp()); } public synchronized NotificationSetting getNotificationSetting() { return mNotificationSetting; } /** * @return <code>true</code> if our {@link StorageProvider} is ready. (e.g. * card inserted) */ public boolean isAvailable(Context context) { String localStorageProviderId = getLocalStorageProviderId(); if (localStorageProviderId == null) { return true; // defaults to internal memory } return StorageManager.getInstance(context).isReady(localStorageProviderId); } public synchronized boolean isEnabled() { return mEnabled; } public synchronized void setEnabled(boolean enabled) { mEnabled = enabled; } public synchronized boolean isMarkMessageAsReadOnView() { return mMarkMessageAsReadOnView; } public synchronized void setMarkMessageAsReadOnView(boolean value) { mMarkMessageAsReadOnView = value; } public synchronized boolean isAlwaysShowCcBcc() { return mAlwaysShowCcBcc; } public synchronized void setAlwaysShowCcBcc(boolean show) { mAlwaysShowCcBcc = show; } public boolean isRemoteSearchFullText() { return false; // Temporarily disabled //return mRemoteSearchFullText; } @Override public boolean isSignedEmail() { return this.signedEmail; } @Override public boolean isEncryptedEmail() { return this.encryptedEmail; } public void setRemoteSearchFullText(boolean val) { mRemoteSearchFullText = val; } /** * Modify the supplied {@link LocalSearch} instance to limit the search to displayable folders. * * <p> * This method uses the current folder display mode to decide what folders to include/exclude. * </p> * * @param search * The {@code LocalSearch} instance to modify. * * @see #getFolderDisplayMode() */ public void limitToDisplayableFolders(LocalSearch search) { final Account.FolderMode displayMode = getFolderDisplayMode(); switch (displayMode) { case FIRST_CLASS: { // Count messages in the INBOX and non-special first class folders search.and(SearchField.DISPLAY_CLASS, FolderClass.FIRST_CLASS.name(), Attribute.EQUALS); break; } case FIRST_AND_SECOND_CLASS: { // Count messages in the INBOX and non-special first and second class folders search.and(SearchField.DISPLAY_CLASS, FolderClass.FIRST_CLASS.name(), Attribute.EQUALS); // TODO: Create a proper interface for creating arbitrary condition trees SearchCondition searchCondition = new SearchCondition(SearchField.DISPLAY_CLASS, Attribute.EQUALS, FolderClass.SECOND_CLASS.name()); ConditionsTreeNode root = search.getConditions(); if (root.mRight != null) { root.mRight.or(searchCondition); } else { search.or(searchCondition); } break; } case NOT_SECOND_CLASS: { // Count messages in the INBOX and non-special non-second-class folders search.and(SearchField.DISPLAY_CLASS, FolderClass.SECOND_CLASS.name(), Attribute.NOT_EQUALS); break; } default: case ALL: { // Count messages in the INBOX and non-special folders break; } } } /** * Modify the supplied {@link LocalSearch} instance to exclude special folders. * * <p> * Currently the following folders are excluded: * <ul> * <li>Trash</li> * <li>Drafts</li> * <li>Spam</li> * <li>Outbox</li> * <li>Sent</li> * </ul> * The Inbox will always be included even if one of the special folders is configured to point * to the Inbox. * </p> * * @param search * The {@code LocalSearch} instance to modify. */ public void excludeSpecialFolders(LocalSearch search) { excludeSpecialFolder(search, getTrashFolderName()); excludeSpecialFolder(search, getDraftsFolderName()); excludeSpecialFolder(search, getSpamFolderName()); excludeSpecialFolder(search, getOutboxFolderName()); excludeSpecialFolder(search, getSentFolderName()); excludeSpecialFolder(search, getErrorFolderName()); search.or(new SearchCondition(SearchField.FOLDER, Attribute.EQUALS, getInboxFolderName())); } /** * Modify the supplied {@link LocalSearch} instance to exclude "unwanted" folders. * * <p> * Currently the following folders are excluded: * <ul> * <li>Trash</li> * <li>Spam</li> * <li>Outbox</li> * </ul> * The Inbox will always be included even if one of the special folders is configured to point * to the Inbox. * </p> * * @param search * The {@code LocalSearch} instance to modify. */ public void excludeUnwantedFolders(LocalSearch search) { excludeSpecialFolder(search, getTrashFolderName()); excludeSpecialFolder(search, getSpamFolderName()); excludeSpecialFolder(search, getOutboxFolderName()); search.or(new SearchCondition(SearchField.FOLDER, Attribute.EQUALS, getInboxFolderName())); } private void excludeSpecialFolder(LocalSearch search, String folderName) { if (!K9.FOLDER_NONE.equals(folderName)) { search.and(SearchField.FOLDER, folderName, Attribute.NOT_EQUALS); } } /** * Add a new certificate for the incoming or outgoing server to the local key store. */ public void addCertificate(CheckDirection direction, X509Certificate certificate) throws CertificateException { Uri uri; if (direction == CheckDirection.INCOMING) { uri = Uri.parse(getStoreUri()); } else { uri = Uri.parse(getTransportUri()); } LocalKeyStore localKeyStore = LocalKeyStore.getInstance(); localKeyStore.addCertificate(uri.getHost(), uri.getPort(), certificate); } /** * Examine the existing settings for an account. If the old host/port is different from the * new host/port, then try and delete any (possibly non-existent) certificate stored for the * old host/port. */ public void deleteCertificate(String newHost, int newPort, CheckDirection direction) { Uri uri; if (direction == CheckDirection.INCOMING) { uri = Uri.parse(getStoreUri()); } else { uri = Uri.parse(getTransportUri()); } String oldHost = uri.getHost(); int oldPort = uri.getPort(); if (oldPort == -1) { // This occurs when a new account is created return; } if (!newHost.equals(oldHost) || newPort != oldPort) { LocalKeyStore localKeyStore = LocalKeyStore.getInstance(); localKeyStore.deleteCertificate(oldHost, oldPort); } } /** * Examine the settings for the account and attempt to delete (possibly non-existent) * certificates for the incoming and outgoing servers. */ public void deleteCertificates() { LocalKeyStore localKeyStore = LocalKeyStore.getInstance(); String storeUri = getStoreUri(); if (storeUri != null) { Uri uri = Uri.parse(storeUri); localKeyStore.deleteCertificate(uri.getHost(), uri.getPort()); } String transportUri = getTransportUri(); if (transportUri != null) { Uri uri = Uri.parse(transportUri); localKeyStore.deleteCertificate(uri.getHost(), uri.getPort()); } } }
bsd-3-clause
NCIP/national-biomedical-image-archive
docs/analysis_and_design/5.1/CedaraAIMMapingTo3_0/code/com/altova/types/DateTime.java
4666
/*L * Copyright SAIC, Ellumen and RSNA (CTP) * * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/national-biomedical-image-archive/LICENSE.txt for details. */ // DateTime.java // This file contains generated code and will be overwritten when you rerun code generation. package com.altova.types; import java.util.Calendar; public class DateTime extends CalendarBase { // construction public DateTime() { } public DateTime(DateTime newvalue) { year = newvalue.year; month = newvalue.month; day = newvalue.day; hour = newvalue.hour; minute = newvalue.minute; second = newvalue.second; partsecond = newvalue.partsecond; hasTZ = newvalue.hasTZ; offsetTZ = newvalue.offsetTZ; } public DateTime(int newyear, int newmonth, int newday, int newhour, int newminute, int newsecond, double newpartsecond, int newoffsetTZ) { setInternalValues( newyear, newmonth, newday, newhour, newminute, newsecond, newpartsecond, CalendarBase.TZ_OFFSET, newoffsetTZ); } public DateTime(int newyear, int newmonth, int newday, int newhour, int newminute, int newsecond, double newpartsecond) { setInternalValues( newyear, newmonth, newday, newhour, newminute, newsecond, newpartsecond, CalendarBase.TZ_MISSING, 0); } public DateTime(int newyear, int newmonth, int newday) { setInternalValues( newyear, newmonth, newday, 0, 0, 0, 0.0, CalendarBase.TZ_MISSING, 0 ); } public DateTime(Calendar newvalue) { year = newvalue.get( Calendar.YEAR ); month = newvalue.get( Calendar.MONTH ) + 1; day = newvalue.get( Calendar.DAY_OF_MONTH ); hour = newvalue.get( Calendar.HOUR_OF_DAY ); minute = newvalue.get( Calendar.MINUTE ); second = newvalue.get( Calendar.SECOND ); setMillisecond( newvalue.get( Calendar.MILLISECOND ) ); hasTZ = TZ_MISSING; } public int getYear() { return year; } public void setYear( int nYear ) { year = nYear; } public int getMonth() { return month; } public void setMonth( int nMonth ) { month = nMonth; } public int getDay() { return day; } public void setDay( int nDay ) { day = nDay; } public int getHour() { return hour; } public void setHour( int nHour ) { hour = nHour; } public int getMinute() { return minute; } public void setMinute( int nMinute ) { minute = nMinute; } public int getSecond() { return second; } public void setSecond( int nSecond ) { second = nSecond; } public double getPartSecond() { return partsecond; } public void setPartSecond( double nPartSecond ) { partsecond = nPartSecond; } public int getMillisecond() { return (int)java.lang.Math.round(partsecond*1000.0); } public int hasTimezone() { return hasTZ; } public void setHasTimezone( int nHasTZ ) { hasTZ = nHasTZ; } public int getTimezoneOffset() { if( hasTZ != TZ_OFFSET ) return 0; return offsetTZ; } public void setTimezoneOffset( int nOffsetTZ ) { offsetTZ = nOffsetTZ; } public Calendar getValue() { Calendar cal = Calendar.getInstance(); cal.set( year, month-1, day, hour, minute, second); cal.set( Calendar.MILLISECOND, getMillisecond() ); // hasTZ = TZ_OFFSET; // necessary, because Calendar object always has timezone. cal.set(Calendar.ZONE_OFFSET, offsetTZ * 60000); //cal.setTimeZone( (TimeZone)new SimpleTimeZone(offsetTZ * 60000, "") ); return cal; } public static DateTime parse(String s) { String newvalue = s.trim(); DateTime dt = new DateTime(); if (!dt.parseDateTime(newvalue, DateTimePart_Date | DateTimePart_Time)) if (!dt.parseDateTime(newvalue, DateTimePart_Date)) if (!dt.parseDateTime(newvalue, DateTimePart_Year | DateTimePart_Month)) if (!dt.parseDateTime(newvalue, DateTimePart_Year)) if (!dt.parseDateTime(newvalue, DateTimePart_Month | DateTimePart_Day)) if (!dt.parseDateTime(newvalue, DateTimePart_Month)) if (!dt.parseDateTime(newvalue, DateTimePart_Day)) if (!dt.parseDateTime(newvalue, DateTimePart_Time)) throw new StringParseException(newvalue + " cannot be converted to a dateTime value", 0); return dt; } public String toString() { StringBuffer s = new StringBuffer(); s.append( toDateString() ); s.append("T"); s.append( toTimeString() ); return s.toString(); } public static DateTime now() { Calendar cal = Calendar.getInstance(); int tzofs = (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / (60 * 1000); DateTime ret = new DateTime(cal); ret.setTimezoneOffset( tzofs ); ret.setHasTimezone( tzofs == 0 ? TZ_UTC : TZ_OFFSET ); return ret; } }
bsd-3-clause
magirtopcu/mopub-android-sdk
mopub-sdk/src/test/java/com/mopub/mobileads/BaseWebViewTest.java
4529
/* * Copyright (c) 2010-2013, MoPub Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of 'MoPub Inc.' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mopub.mobileads; import android.app.Activity; import android.os.Build; import android.view.ViewGroup; import android.webkit.WebSettings; import com.mopub.mobileads.test.support.SdkTestRunner; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.shadows.ShadowWebView; import static com.mopub.common.util.VersionCode.ECLAIR_MR1; import static com.mopub.common.util.VersionCode.FROYO; import static com.mopub.common.util.VersionCode.JELLY_BEAN_MR2; import static org.fest.assertions.api.Assertions.assertThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.robolectric.Robolectric.shadowOf; @RunWith(SdkTestRunner.class) public class BaseWebViewTest { private Activity context; private BaseWebView subject; @Before public void setup() { context = new Activity(); } @Test public void beforeFroyo_shouldDisablePluginsByDefault() throws Exception { Robolectric.Reflection.setFinalStaticField(Build.VERSION.class, "SDK_INT", ECLAIR_MR1.getApiLevel()); subject = new BaseWebView(context); WebSettings webSettings = subject.getSettings(); assertThat(webSettings.getPluginsEnabled()).isFalse(); subject.enablePlugins(true); assertThat(webSettings.getPluginsEnabled()).isTrue(); } @Test public void froyoAndAfter_shouldDisablePluginsByDefault() throws Exception { Robolectric.Reflection.setFinalStaticField(Build.VERSION.class, "SDK_INT", FROYO.getApiLevel()); subject = new BaseWebView(context); WebSettings webSettings = subject.getSettings(); assertThat(webSettings.getPluginState()).isEqualTo(WebSettings.PluginState.OFF); subject.enablePlugins(true); assertThat(webSettings.getPluginState()).isEqualTo(WebSettings.PluginState.ON); } @Test public void jellyBeanMr2AndAfter_shouldPass() throws Exception { Robolectric.Reflection.setFinalStaticField(Build.VERSION.class, "SDK_INT", JELLY_BEAN_MR2.getApiLevel()); subject = new BaseWebView(context); subject.enablePlugins(true); // pass } @Test public void destroy_shouldRemoveSelfFromParent_beforeCallingDestroy() throws Exception { subject = new BaseWebView(context); ViewGroup parent = mock(ViewGroup.class); ShadowWebView shadow = shadowOf(subject); shadow.setMyParent(parent); subject.destroy(); verify(parent).removeView(eq(subject)); assertThat(shadow.wasDestroyCalled()).isTrue(); } @Test public void destroy_shouldSetTheCorrectStateVariable() { subject = new BaseWebView(context); assertThat(subject.mIsDestroyed).isFalse(); subject.destroy(); assertThat(subject.mIsDestroyed).isTrue(); } }
bsd-3-clause
grassrootza/grassroot-platform
grassroot-services/src/main/java/za/org/grassroot/services/util/LogsAndNotificationsBroker.java
1664
package za.org.grassroot.services.util; import org.springframework.data.domain.Page; import org.springframework.data.jpa.domain.Specification; import za.org.grassroot.core.domain.ActionLog; import za.org.grassroot.core.domain.Notification; import za.org.grassroot.core.domain.User; import za.org.grassroot.core.domain.UserLog; import za.org.grassroot.core.domain.campaign.Campaign; import za.org.grassroot.core.domain.campaign.CampaignLog; import za.org.grassroot.core.domain.group.Membership; import za.org.grassroot.core.enums.ActionLogType; import za.org.grassroot.core.enums.CampaignLogType; import java.time.Instant; import java.util.Collection; import java.util.List; public interface LogsAndNotificationsBroker { void asyncStoreBundle(LogsAndNotificationsBundle bundle); void storeBundle(LogsAndNotificationsBundle bundle); long countNotifications(Specification<Notification> specifications); <T extends Notification> long countNotifications(Specification<T> specs, Class<T> notificationType); List<ActionLog> fetchMembershipLogs(Membership membership); <T extends ActionLog> long countLogs(Specification<T> specs, ActionLogType logType); long countCampaignLogs(Specification<CampaignLog> specs); List<PublicActivityLog> fetchMostRecentPublicLogs(Integer numberLogs); void updateCache(Collection<ActionLog> actionLogs); void abortNotificationSend(Specification specifications); Page<Notification> lastNotificationsSentToUser(User user, Integer numberToRetrieve, Instant sinceTime); void removeCampaignLog(User user, Campaign campaign, CampaignLogType logType); long countUserLogs(Specification<UserLog> userLogSpecification); }
bsd-3-clause
FuriKuri/aspgen
aspgen-generator/src/main/java/de/hbrs/aspgen/generator/container/AfterAdviceForParameterContainer.java
622
package de.hbrs.aspgen.generator.container; import de.hbrs.aspgen.api.ast.JavaMethod; public class AfterAdviceForParameterContainer extends AdviceForParameterContainer { @Override protected String getAdviceType(final JavaMethod javaMethod) { return "after"; } @Override protected String getAdditionalAdviceDeclartaation(final JavaMethod javaMethod) { if (javaMethod.getType().equals("void")) { return ""; } else { final String returnInfo = javaMethod.getType() + " returnValue"; return "returning(" + returnInfo + ") "; } } }
bsd-3-clause
gnanam336/ideal
bootstrapped/ideal/library/elements/immutable_composite_value.java
180
// Autogenerated from isource/library/elements.i package ideal.library.elements; public interface immutable_composite_value extends immutable_value, readonly_composite_value { }
bsd-3-clause
UrielCh/ovh-java-sdk
ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/hosting/web/localseo/OvhVisibilityCheckResponse.java
365
package net.minidev.ovh.api.hosting.web.localseo; /** * Struct describing the response for a visibility check request */ public class OvhVisibilityCheckResponse { /** * Is the searched location already managed ? * * canBeNull */ public Boolean alreadyManaged; /** * Searched location data * * canBeNull */ public OvhSearchData searchData; }
bsd-3-clause
lang010/acit
leetcode/1334.find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance.414311323.ac.java
4303
/* * @lc app=leetcode id=1334 lang=java * * [1334] Find the City With the Smallest Number of Neighbors at a Threshold Distance * * https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/description/ * * algorithms * Medium (46.34%) * Total Accepted: 17.2K * Total Submissions: 37.2K * Testcase Example: '4\n[[0,1,3],[1,2,1],[1,3,4],[2,3,1]]\n4' * * There are n cities numbered from 0 to n-1. Given the array edges where * edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted * edge between cities fromi and toi, and given the integer distanceThreshold. * * Return the city with the smallest number of cities that are reachable * through some path and whose distance is at most distanceThreshold, If there * are multiple such cities, return the city with the greatest number. * * Notice that the distance of a path connecting cities i and j is equal to the * sum of the edges' weights along that path. * * * Example 1: * * * * * Input: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = * 4 * Output: 3 * Explanation: The figure above describes the graph.  * The neighboring cities at a distanceThreshold = 4 for each city are: * City 0 -> [City 1, City 2]  * City 1 -> [City 0, City 2, City 3]  * City 2 -> [City 0, City 1, City 3]  * City 3 -> [City 1, City 2]  * Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we * have to return city 3 since it has the greatest number. * * * Example 2: * * * * * Input: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], * distanceThreshold = 2 * Output: 0 * Explanation: The figure above describes the graph.  * The neighboring cities at a distanceThreshold = 2 for each city are: * City 0 -> [City 1]  * City 1 -> [City 0, City 4]  * City 2 -> [City 3, City 4]  * City 3 -> [City 2, City 4] * City 4 -> [City 1, City 2, City 3]  * The city 0 has 1 neighboring city at a distanceThreshold = 2. * * * * Constraints: * * * 2 <= n <= 100 * 1 <= edges.length <= n * (n - 1) / 2 * edges[i].length == 3 * 0 <= fromi < toi < n * 1 <= weighti, distanceThreshold <= 10^4 * All pairs (fromi, toi) are distinct. * * */ class Solution { public int findTheCity(int n, int[][] edges, int distanceThreshold) { int[][] dist = new int[n][n]; for (int i = 0; i < n; i++) Arrays.fill(dist[i], Integer.MAX_VALUE/3); for (int i = 0; i < n; i++) dist[i][i] = 0; for (int[] e : edges) { dist[e[0]][e[1]] = e[2]; dist[e[1]][e[0]] = e[2]; } for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) for (int k = 0; k < n; k++) dist[j][k] = Math.min(dist[j][k], dist[j][i]+dist[i][k]); int ans = 0; int min = n; for (int i = 0; i < n; i++) { int cnt = 0; for (int j = 0; j < n; j++) if (dist[i][j] <= distanceThreshold) cnt++; if (min >= cnt) { min = cnt; ans = i; } } return ans; } public int findTheCity2(int n, int[][] edges, int distanceThreshold) { Map<Integer, Integer>[] map = new HashMap[n]; for (int i = 0; i < n; i++) map[i] = new HashMap<>(); for (int[] e : edges) { map[e[0]].put(e[1], e[2]); map[e[1]].put(e[0], e[2]); } int ans = n; int min = n; for (int i = 0; i < n; i++) { Map<Integer, Integer> cur = new HashMap<>(); PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[1] - a[1]); pq.offer(new int[] {i, distanceThreshold}); while (!pq.isEmpty()) { int[] p = pq.poll(); cur.put(p[0], p[1]); map[p[0]].forEach((k, v) -> { if (cur.getOrDefault(k, -1) < p[1] - v) pq.offer(new int[] {k, p[1]-v}); }); } if (min >= cur.size()) { ans = i; min = cur.size(); } } return ans; } }
bsd-3-clause
NCIP/cacore-sdk-pre411
SDK4/conf/system/package/remote-client/src/TestXMLClient.java
3619
/*L * Copyright Ekagra Software Technologies Ltd. * Copyright SAIC * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cacore-sdk-pre411/LICENSE.txt for details. */ import gov.nih.nci.system.applicationservice.ApplicationService; import gov.nih.nci.system.client.ApplicationServiceProvider; import gov.nih.nci.system.client.util.xml.Marshaller; import gov.nih.nci.system.client.util.xml.Unmarshaller; import gov.nih.nci.system.client.util.xml.XMLUtility; import gov.nih.nci.system.client.util.xml.caCOREMarshaller; import gov.nih.nci.system.client.util.xml.caCOREUnmarshaller; import java.io.File; import java.io.FileWriter; import java.util.Collection; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Source; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.w3c.dom.Document; public class TestXMLClient extends TestClient { public static void main(String args[]) { TestXMLClient client = new TestXMLClient(); try { client.testXMLUtility(); } catch(Exception e) { e.printStackTrace(); } } public void testXMLUtility() throws Exception { //Application Service retrieval for secured system //ApplicationService appService = ApplicationServiceProvider.getApplicationService("userId","password"); ApplicationService appService = ApplicationServiceProvider.getApplicationService(); Collection<Class> classList = getClasses(); Marshaller marshaller = new caCOREMarshaller("xml-mapping.xml", false); Unmarshaller unmarshaller = new caCOREUnmarshaller("unmarshaller-xml-mapping.xml", false); XMLUtility myUtil = new XMLUtility(marshaller, unmarshaller); for(Class klass:classList) { Object o = klass.newInstance(); System.out.println("Searching for "+klass.getName()); try { Collection results = appService.search(klass, o); for(Object obj : results) { File myFile = new File("./output/" + klass.getName() + "_test.xml"); FileWriter myWriter = new FileWriter(myFile); myUtil.toXML(obj, myWriter); myWriter.close(); printObject(obj, klass); DocumentBuilder parser = DocumentBuilderFactory .newInstance().newDocumentBuilder(); Document document = parser.parse(myFile); SchemaFactory factory = SchemaFactory .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { System.out.println("Validating " + klass.getName() + " against the schema......\n\n"); Source schemaFile = new StreamSource(Thread.currentThread().getContextClassLoader().getResourceAsStream(klass.getPackage().getName() + ".xsd")); Schema schema = factory.newSchema(schemaFile); Validator validator = schema.newValidator(); validator.validate(new DOMSource(document)); System.out.println(klass.getName() + " has been validated!!!\n\n"); } catch (Exception e) { System.out.println(klass.getName() + " has failed validation!!! Error reason is: \n\n" + e.getMessage()); } System.out.println("Un-marshalling " + klass.getName() + " from " + myFile.getName() +"......\n\n"); Object myObj = (Object) myUtil.fromXML(myFile); printObject(myObj, klass); break; } }catch(Exception e) { System.out.println("Exception caught: " + e.getMessage()); e.printStackTrace(); } //break; } } }
bsd-3-clause
seratch/java-time-backport
src/main/java/java/time/chrono/Chronology.java
39617
/* * Copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of JSR-310 nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package java.time.chrono; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectStreamException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.ServiceLoader; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.time.Clock; import java.time.DateTimeException; import java.time.Instant; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZoneId; import java.time.format.DateTimeFormatterBuilder; import java.time.format.ResolverStyle; import java.time.format.TextStyle; import java.time.jdk8.DefaultInterfaceTemporalAccessor; import java.time.jdk8.Jdk8Methods; import java.time.temporal.ChronoField; import java.time.temporal.Temporal; import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalField; import java.time.temporal.TemporalQueries; import java.time.temporal.TemporalQuery; import java.time.temporal.UnsupportedTemporalTypeException; import java.time.temporal.ValueRange; /** * A calendar system, used to organize and identify dates. * <p> * The main date and time API is built on the ISO calendar system. * This class operates behind the scenes to represent the general concept of a calendar system. * For example, the Japanese, Minguo, Thai Buddhist and others. * <p> * Most other calendar systems also operate on the shared concepts of year, month and day, * linked to the cycles of the Earth around the Sun, and the Moon around the Earth. * These shared concepts are defined by {@link ChronoField} and are availalbe * for use by any {@code Chronology} implementation: * <pre> * LocalDate isoDate = ... * ChronoLocalDate&lt;ThaiBuddhistChrono&gt; minguoDate = ... * int isoYear = isoDate.get(ChronoField.YEAR); * int thaiYear = thaiDate.get(ChronoField.YEAR); * </pre> * As shown, although the date objects are in different calendar systems, represented by different * {@code Chronology} instances, both can be queried using the same constant on {@code ChronoField}. * For a full discussion of the implications of this, see {@link ChronoLocalDate}. * In general, the advice is to use the known ISO-based {@code LocalDate}, rather than * {@code ChronoLocalDate}. * <p> * While a {@code Chronology} object typically uses {@code ChronoField} and is based on * an era, year-of-era, month-of-year, day-of-month model of a date, this is not required. * A {@code Chronology} instance may represent a totally different kind of calendar system, * such as the Mayan. * <p> * In practical terms, the {@code Chronology} instance also acts as a factory. * The {@link #of(String)} method allows an instance to be looked up by identifier, * while the {@link #ofLocale(Locale)} method allows lookup by locale. * <p> * The {@code Chronology} instance provides a set of methods to create {@code ChronoLocalDate} instances. * The date classes are used to manipulate specific dates. * <p><ul> * <li> {@link #dateNow() dateNow()} * <li> {@link #dateNow(Clock) dateNow(clock)} * <li> {@link #dateNow(ZoneId) dateNow(zone)} * <li> {@link #date(int, int, int) date(yearProleptic, month, day)} * <li> {@link #date(Era, int, int, int) date(era, yearOfEra, month, day)} * <li> {@link #dateYearDay(int, int) dateYearDay(yearProleptic, dayOfYear)} * <li> {@link #dateYearDay(Era, int, int) dateYearDay(era, yearOfEra, dayOfYear)} * <li> {@link #date(TemporalAccessor) date(TemporalAccessor)} * </ul><p> * * <p id="addcalendars">Adding New Calendars</p> * The set of available chronologies can be extended by applications. * Adding a new calendar system requires the writing of an implementation of * {@code Chronology}, {@code ChronoLocalDate} and {@code Era}. * The majority of the logic specific to the calendar system will be in * {@code ChronoLocalDate}. The {@code Chronology} subclass acts as a factory. * <p> * To permit the discovery of additional chronologies, the {@link java.util.ServiceLoader ServiceLoader} * is used. A file must be added to the {@code META-INF/services} directory with the * name 'java.bp.chrono.Chrono' listing the implementation classes. * See the ServiceLoader for more details on service loading. * For lookup by id or calendarType, the system provided calendars are found * first followed by application provided calendars. * <p> * Each chronology must define a chronology ID that is unique within the system. * If the chronology represents a calendar system defined by the * <em>Unicode Locale Data Markup Language (LDML)</em> specification then that * calendar type should also be specified. * * <h3>Specification for implementors</h3> * This class must be implemented with care to ensure other classes operate correctly. * All implementations that can be instantiated must be final, immutable and thread-safe. * Subclasses should be Serializable wherever possible. * <p> * In JDK 8, this is an interface with default methods. * Since there are no default methods in JDK 7, an abstract class is used. */ public abstract class Chronology implements Comparable<Chronology> { /** * Simulate JDK 8 method reference Chronology::from. */ public static final TemporalQuery<Chronology> FROM = new TemporalQuery<Chronology>() { @Override public Chronology queryFrom(TemporalAccessor temporal) { return Chronology.from(temporal); } }; /** * Map of available calendars by ID. */ private static final ConcurrentHashMap<String, Chronology> CHRONOS_BY_ID = new ConcurrentHashMap<String, Chronology>(); /** * Map of available calendars by calendar type. */ private static final ConcurrentHashMap<String, Chronology> CHRONOS_BY_TYPE = new ConcurrentHashMap<String, Chronology>(); /** * Access JDK 7 method if on JDK 7. */ private static final Method LOCALE_METHOD; static { Method method = null; try { method = Locale.class.getMethod("getUnicodeLocaleType", String.class); } catch (Throwable ex) { // ignore } LOCALE_METHOD = method; } //----------------------------------------------------------------------- /** * Obtains an instance of {@code Chronology} from a temporal object. * <p> * A {@code TemporalAccessor} represents some form of date and time information. * This factory converts the arbitrary temporal object to an instance of {@code Chronology}. * If the specified temporal object does not have a chronology, {@link IsoChronology} is returned. * <p> * The conversion will obtain the chronology using {@link TemporalQueries#chronology()}. * <p> * This method matches the signature of the functional interface {@link TemporalQuery} * allowing it to be used in queries via method reference, {@code Chrono::from}. * * @param temporal the temporal to convert, not null * @return the chronology, not null * @throws DateTimeException if unable to convert to an {@code Chronology} */ public static Chronology from(TemporalAccessor temporal) { Jdk8Methods.requireNonNull(temporal, "temporal"); Chronology obj = temporal.query(TemporalQueries.chronology()); return (obj != null ? obj : IsoChronology.INSTANCE); } //----------------------------------------------------------------------- /** * Obtains an instance of {@code Chronology} from a locale. * <p> * This returns a {@code Chronology} based on the specified locale, * typically returning {@code IsoChronology}. Other calendar systems * are only returned if they are explicitly selected within the locale. * <p> * The {@link Locale} class provide access to a range of information useful * for localizing an application. This includes the language and region, * such as "en-GB" for English as used in Great Britain. * <p> * The {@code Locale} class also supports an extension mechanism that * can be used to identify a calendar system. The mechanism is a form * of key-value pairs, where the calendar system has the key "ca". * For example, the locale "en-JP-u-ca-japanese" represents the English * language as used in Japan with the Japanese calendar system. * <p> * This method finds the desired calendar system by in a manner equivalent * to passing "ca" to {@link Locale#getUnicodeLocaleType(String)}. * If the "ca" key is not present, then {@code IsoChronology} is returned. * <p> * Note that the behavior of this method differs from the older * {@link java.util.Calendar#getInstance(Locale)} method. * If that method receives a locale of "th_TH" it will return {@code BuddhistCalendar}. * By contrast, this method will return {@code IsoChronology}. * Passing the locale "th-TH-u-ca-buddhist" into either method will * result in the Thai Buddhist calendar system and is therefore the * recommended approach going forward for Thai calendar system localization. * <p> * A similar, but simpler, situation occurs for the Japanese calendar system. * The locale "jp_JP_JP" has previously been used to access the calendar. * However, unlike the Thai locale, "ja_JP_JP" is automatically converted by * {@code Locale} to the modern and recommended form of "ja-JP-u-ca-japanese". * Thus, there is no difference in behavior between this method and * {@code Calendar#getInstance(Locale)}. * * @param locale the locale to use to obtain the calendar system, not null * @return the calendar system associated with the locale, not null * @throws DateTimeException if the locale-specified calendar cannot be found */ public static Chronology ofLocale(Locale locale) { init(); Jdk8Methods.requireNonNull(locale, "locale"); String type = "iso"; if (LOCALE_METHOD != null) { // JDK 7: locale.getUnicodeLocaleType("ca"); try { type = (String) LOCALE_METHOD.invoke(locale, "ca"); } catch (IllegalArgumentException ex) { // ignore } catch (IllegalAccessException ex) { // ignore } catch (InvocationTargetException ex) { // ignore } } else if (locale.equals(JapaneseChronology.LOCALE)) { type = "japanese"; } if (type == null || "iso".equals(type) || "iso8601".equals(type)) { return IsoChronology.INSTANCE; } else { Chronology chrono = CHRONOS_BY_TYPE.get(type); if (chrono == null) { throw new DateTimeException("Unknown calendar system: " + type); } return chrono; } } //----------------------------------------------------------------------- /** * Obtains an instance of {@code Chronology} from a chronology ID or * calendar system type. * <p> * This returns a chronology based on either the ID or the type. * The {@link #getId() chronology ID} uniquely identifies the chronology. * The {@link #getCalendarType() calendar system type} is defined by the LDML specification. * <p> * The chronology may be a system chronology or a chronology * provided by the application via ServiceLoader configuration. * <p> * Since some calendars can be customized, the ID or type typically refers * to the default customization. For example, the Gregorian calendar can have multiple * cutover dates from the Julian, but the lookup only provides the default cutover date. * * @param id the chronology ID or calendar system type, not null * @return the chronology with the identifier requested, not null * @throws DateTimeException if the chronology cannot be found */ public static Chronology of(String id) { init(); Chronology chrono = CHRONOS_BY_ID.get(id); if (chrono != null) { return chrono; } chrono = CHRONOS_BY_TYPE.get(id); if (chrono != null) { return chrono; } throw new DateTimeException("Unknown chronology: " + id); } /** * Returns the available chronologies. * <p> * Each returned {@code Chronology} is available for use in the system. * * @return the independent, modifiable set of the available chronology IDs, not null */ public static Set<Chronology> getAvailableChronologies() { init(); return new HashSet<Chronology>(CHRONOS_BY_ID.values()); } private static void init() { if (CHRONOS_BY_ID.isEmpty()) { register(IsoChronology.INSTANCE); register(ThaiBuddhistChronology.INSTANCE); register(MinguoChronology.INSTANCE); register(JapaneseChronology.INSTANCE); register(HijrahChronology.INSTANCE); CHRONOS_BY_ID.putIfAbsent("Hijrah", HijrahChronology.INSTANCE); CHRONOS_BY_TYPE.putIfAbsent("islamic", HijrahChronology.INSTANCE); ServiceLoader<Chronology> loader = ServiceLoader.load(Chronology.class, Chronology.class.getClassLoader()); for (Chronology chrono : loader) { CHRONOS_BY_ID.putIfAbsent(chrono.getId(), chrono); String type = chrono.getCalendarType(); if (type != null) { CHRONOS_BY_TYPE.putIfAbsent(type, chrono); } } } } private static void register(Chronology chrono) { CHRONOS_BY_ID.putIfAbsent(chrono.getId(), chrono); String type = chrono.getCalendarType(); if (type != null) { CHRONOS_BY_TYPE.putIfAbsent(type, chrono); } } //----------------------------------------------------------------------- /** * Creates an instance. */ protected Chronology() { } //----------------------------------------------------------------------- /** * Casts the {@code Temporal} to {@code ChronoLocalDate} with the same chronology. * * @param temporal a date-time to cast, not null * @return the date-time checked and cast to {@code ChronoLocalDate}, not null * @throws ClassCastException if the date-time cannot be cast to ChronoLocalDate * or the chronology is not equal this Chrono */ <D extends ChronoLocalDate> D ensureChronoLocalDate(Temporal temporal) { @SuppressWarnings("unchecked") D other = (D) temporal; if (this.equals(other.getChronology()) == false) { throw new ClassCastException("Chrono mismatch, expected: " + getId() + ", actual: " + other.getChronology().getId()); } return other; } /** * Casts the {@code Temporal} to {@code ChronoLocalDateTime} with the same chronology. * * @param temporal a date-time to cast, not null * @return the date-time checked and cast to {@code ChronoLocalDateTime}, not null * @throws ClassCastException if the date-time cannot be cast to ChronoLocalDateTimeImpl * or the chronology is not equal this Chrono */ <D extends ChronoLocalDate> ChronoLocalDateTimeImpl<D> ensureChronoLocalDateTime(Temporal temporal) { @SuppressWarnings("unchecked") ChronoLocalDateTimeImpl<D> other = (ChronoLocalDateTimeImpl<D>) temporal; if (this.equals(other.toLocalDate().getChronology()) == false) { throw new ClassCastException("Chrono mismatch, required: " + getId() + ", supplied: " + other.toLocalDate().getChronology().getId()); } return other; } /** * Casts the {@code Temporal} to {@code ChronoZonedDateTimeImpl} with the same chronology. * * @param temporal a date-time to cast, not null * @return the date-time checked and cast to {@code ChronoZonedDateTimeImpl}, not null * @throws ClassCastException if the date-time cannot be cast to ChronoZonedDateTimeImpl * or the chronology is not equal this Chrono */ <D extends ChronoLocalDate> ChronoZonedDateTimeImpl<D> ensureChronoZonedDateTime(Temporal temporal) { @SuppressWarnings("unchecked") ChronoZonedDateTimeImpl<D> other = (ChronoZonedDateTimeImpl<D>) temporal; if (this.equals(other.toLocalDate().getChronology()) == false) { throw new ClassCastException("Chrono mismatch, required: " + getId() + ", supplied: " + other.toLocalDate().getChronology().getId()); } return other; } //----------------------------------------------------------------------- /** * Gets the ID of the chronology. * <p> * The ID uniquely identifies the {@code Chronology}. * It can be used to lookup the {@code Chronology} using {@link #of(String)}. * * @return the chronology ID, not null * @see #getCalendarType() */ public abstract String getId(); /** * Gets the calendar type of the underlying calendar system. * <p> * The calendar type is an identifier defined by the * <em>Unicode Locale Data Markup Language (LDML)</em> specification. * It can be used to lookup the {@code Chronology} using {@link #of(String)}. * It can also be used as part of a locale, accessible via * {@link Locale#getUnicodeLocaleType(String)} with the key 'ca'. * * @return the calendar system type, null if the calendar is not defined by LDML * @see #getId() */ public abstract String getCalendarType(); //----------------------------------------------------------------------- /** * Obtains a local date in this chronology from the era, year-of-era, * month-of-year and day-of-month fields. * * @param era the era of the correct type for the chronology, not null * @param yearOfEra the chronology year-of-era * @param month the chronology month-of-year * @param dayOfMonth the chronology day-of-month * @return the local date in this chronology, not null * @throws DateTimeException if unable to create the date * @throws ClassCastException if the {@code era} is not of the correct type for the chronology */ public ChronoLocalDate date(Era era, int yearOfEra, int month, int dayOfMonth) { return date(prolepticYear(era, yearOfEra), month, dayOfMonth); } /** * Obtains a local date in this chronology from the proleptic-year, * month-of-year and day-of-month fields. * * @param prolepticYear the chronology proleptic-year * @param month the chronology month-of-year * @param dayOfMonth the chronology day-of-month * @return the local date in this chronology, not null * @throws DateTimeException if unable to create the date */ public abstract ChronoLocalDate date(int prolepticYear, int month, int dayOfMonth); /** * Obtains a local date in this chronology from the era, year-of-era and * day-of-year fields. * * @param era the era of the correct type for the chronology, not null * @param yearOfEra the chronology year-of-era * @param dayOfYear the chronology day-of-year * @return the local date in this chronology, not null * @throws DateTimeException if unable to create the date * @throws ClassCastException if the {@code era} is not of the correct type for the chronology */ public ChronoLocalDate dateYearDay(Era era, int yearOfEra, int dayOfYear) { return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear); } /** * Obtains a local date in this chronology from the proleptic-year and * day-of-year fields. * * @param prolepticYear the chronology proleptic-year * @param dayOfYear the chronology day-of-year * @return the local date in this chronology, not null * @throws DateTimeException if unable to create the date */ public abstract ChronoLocalDate dateYearDay(int prolepticYear, int dayOfYear); /** * Obtains a local date in this chronology from the epoch-day. * <p> * The definition of {@link ChronoField#EPOCH_DAY EPOCH_DAY} is the same * for all calendar systems, thus it can be used for conversion. * * @param epochDay the epoch day * @return the local date in this chronology, not null * @throws DateTimeException if unable to create the date */ public abstract ChronoLocalDate dateEpochDay(long epochDay); /** * Obtains a local date in this chronology from another temporal object. * <p> * This creates a date in this chronology based on the specified {@code TemporalAccessor}. * <p> * The standard mechanism for conversion between date types is the * {@link ChronoField#EPOCH_DAY local epoch-day} field. * * @param temporal the temporal object to convert, not null * @return the local date in this chronology, not null * @throws DateTimeException if unable to create the date */ public abstract ChronoLocalDate date(TemporalAccessor temporal); //----------------------------------------------------------------------- /** * Obtains the current local date in this chronology from the system clock in the default time-zone. * <p> * This will query the {@link Clock#systemDefaultZone() system clock} in the default * time-zone to obtain the current date. * <p> * Using this method will prevent the ability to use an alternate clock for testing * because the clock is hard-coded. * <p> * This implementation uses {@link #dateNow(Clock)}. * * @return the current local date using the system clock and default time-zone, not null * @throws DateTimeException if unable to create the date */ public ChronoLocalDate dateNow() { return dateNow(Clock.systemDefaultZone()); } /** * Obtains the current local date in this chronology from the system clock in the specified time-zone. * <p> * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date. * Specifying the time-zone avoids dependence on the default time-zone. * <p> * Using this method will prevent the ability to use an alternate clock for testing * because the clock is hard-coded. * * @param zone the zone ID to use, not null * @return the current local date using the system clock, not null * @throws DateTimeException if unable to create the date */ public ChronoLocalDate dateNow(ZoneId zone) { return dateNow(Clock.system(zone)); } /** * Obtains the current local date in this chronology from the specified clock. * <p> * This will query the specified clock to obtain the current date - today. * Using this method allows the use of an alternate clock for testing. * The alternate clock may be introduced using {@link Clock dependency injection}. * * @param clock the clock to use, not null * @return the current local date, not null * @throws DateTimeException if unable to create the date */ public ChronoLocalDate dateNow(Clock clock) { Jdk8Methods.requireNonNull(clock, "clock"); return date(LocalDate.now(clock)); } //----------------------------------------------------------------------- /** * Obtains a local date-time in this chronology from another temporal object. * <p> * This creates a date-time in this chronology based on the specified {@code TemporalAccessor}. * <p> * The date of the date-time should be equivalent to that obtained by calling * {@link #date(TemporalAccessor)}. * The standard mechanism for conversion between time types is the * {@link ChronoField#NANO_OF_DAY nano-of-day} field. * * @param temporal the temporal object to convert, not null * @return the local date-time in this chronology, not null * @throws DateTimeException if unable to create the date-time */ public ChronoLocalDateTime<?> localDateTime(TemporalAccessor temporal) { try { ChronoLocalDate date = date(temporal); return date.atTime(LocalTime.from(temporal)); } catch (DateTimeException ex) { throw new DateTimeException("Unable to obtain ChronoLocalDateTime from TemporalAccessor: " + temporal.getClass(), ex); } } /** * Obtains a zoned date-time in this chronology from another temporal object. * <p> * This creates a date-time in this chronology based on the specified {@code TemporalAccessor}. * <p> * This should obtain a {@code ZoneId} using {@link ZoneId#from(TemporalAccessor)}. * The date-time should be obtained by obtaining an {@code Instant}. * If that fails, the local date-time should be used. * * @param temporal the temporal object to convert, not null * @return the zoned date-time in this chronology, not null * @throws DateTimeException if unable to create the date-time */ @SuppressWarnings({ "rawtypes", "unchecked" }) public ChronoZonedDateTime<?> zonedDateTime(TemporalAccessor temporal) { try { ZoneId zone = ZoneId.from(temporal); try { Instant instant = Instant.from(temporal); return zonedDateTime(instant, zone); } catch (DateTimeException ex1) { ChronoLocalDateTime cldt = localDateTime(temporal); ChronoLocalDateTimeImpl cldtImpl = ensureChronoLocalDateTime(cldt); return ChronoZonedDateTimeImpl.ofBest(cldtImpl, zone, null); } } catch (DateTimeException ex) { throw new DateTimeException("Unable to obtain ChronoZonedDateTime from TemporalAccessor: " + temporal.getClass(), ex); } } /** * Obtains a zoned date-time in this chronology from an {@code Instant}. * <p> * This creates a zoned date-time with the same instant as that specified. * * @param instant the instant to create the date-time from, not null * @param zone the time-zone, not null * @return the zoned date-time, not null * @throws DateTimeException if the result exceeds the supported range */ public ChronoZonedDateTime<?> zonedDateTime(Instant instant, ZoneId zone) { ChronoZonedDateTime<? extends ChronoLocalDate> result = ChronoZonedDateTimeImpl.ofInstant(this, instant, zone); return result; } //----------------------------------------------------------------------- /** * Obtains a period for this chronology based on years, months and days. * <p> * This returns a period tied to this chronology using the specified * years, months and days. All supplied chronologies use periods * based on years, months and days, however the {@code ChronoPeriod} API * allows the period to be represented using other units. * <p> * The default implementation returns an implementation class suitable * for most calendar systems. It is based solely on the three units. * Normalization, addition and subtraction derive the number of months * in a year from the {@link #range(ChronoField)}. If the number of * months within a year is fixed, then the calculation approach for * addition, subtraction and normalization is slightly different. * <p> * If implementing an unusual calendar system that is not based on * years, months and days, or where you want direct control, then * the {@code ChronoPeriod} interface must be directly implemented. * <p> * The returned period is immutable and thread-safe. * * @param years the number of years, may be negative * @param months the number of years, may be negative * @param days the number of years, may be negative * @return the period in terms of this chronology, not null */ public ChronoPeriod period(int years, int months, int days) { return new ChronoPeriodImpl(this, years, months, days); } //----------------------------------------------------------------------- /** * Checks if the specified year is a leap year. * <p> * A leap-year is a year of a longer length than normal. * The exact meaning is determined by the chronology according to the following constraints. * <p><ul> * <li>a leap-year must imply a year-length longer than a non leap-year. * <li>a chronology that does not support the concept of a year must return false. * </ul><p> * * @param prolepticYear the proleptic-year to check, not validated for range * @return true if the year is a leap year */ public abstract boolean isLeapYear(long prolepticYear); /** * Calculates the proleptic-year given the era and year-of-era. * <p> * This combines the era and year-of-era into the single proleptic-year field. * * @param era the era of the correct type for the chronology, not null * @param yearOfEra the chronology year-of-era * @return the proleptic-year * @throws DateTimeException if unable to convert * @throws ClassCastException if the {@code era} is not of the correct type for the chronology */ public abstract int prolepticYear(Era era, int yearOfEra); /** * Creates the chronology era object from the numeric value. * <p> * The era is, conceptually, the largest division of the time-line. * Most calendar systems have a single epoch dividing the time-line into two eras. * However, some have multiple eras, such as one for the reign of each leader. * The exact meaning is determined by the chronology according to the following constraints. * <p> * The era in use at 1970-01-01 must have the value 1. * Later eras must have sequentially higher values. * Earlier eras must have sequentially lower values. * Each chronology must refer to an enum or similar singleton to provide the era values. * <p> * This method returns the singleton era of the correct type for the specified era value. * * @param eraValue the era value * @return the calendar system era, not null * @throws DateTimeException if unable to create the era */ public abstract Era eraOf(int eraValue); /** * Gets the list of eras for the chronology. * <p> * Most calendar systems have an era, within which the year has meaning. * If the calendar system does not support the concept of eras, an empty * list must be returned. * * @return the list of eras for the chronology, may be immutable, not null */ public abstract List<Era> eras(); //----------------------------------------------------------------------- /** * Gets the range of valid values for the specified field. * <p> * All fields can be expressed as a {@code long} integer. * This method returns an object that describes the valid range for that value. * <p> * Note that the result only describes the minimum and maximum valid values * and it is important not to read too much into them. For example, there * could be values within the range that are invalid for the field. * <p> * This method will return a result whether or not the chronology supports the field. * * @param field the field to get the range for, not null * @return the range of valid values for the field, not null * @throws DateTimeException if the range for the field cannot be obtained */ public abstract ValueRange range(ChronoField field); //----------------------------------------------------------------------- /** * Gets the textual representation of this chronology. * <p> * This returns the textual name used to identify the chronology. * The parameters control the style of the returned text and the locale. * * @param style the style of the text required, not null * @param locale the locale to use, not null * @return the text value of the chronology, not null */ public String getDisplayName(TextStyle style, Locale locale) { return new DateTimeFormatterBuilder().appendChronologyText(style).toFormatter(locale).format(new DefaultInterfaceTemporalAccessor() { @Override public boolean isSupported(TemporalField field) { return false; } @Override public long getLong(TemporalField field) { throw new UnsupportedTemporalTypeException("Unsupported field: " + field); } @SuppressWarnings("unchecked") @Override public <R> R query(TemporalQuery<R> query) { if (query == TemporalQueries.chronology()) { return (R) Chronology.this; } return super.query(query); } }); } //----------------------------------------------------------------------- /** * Resolves parsed {@code ChronoField} values into a date during parsing. * <p> * Most {@code TemporalField} implementations are resolved using the * resolve method on the field. By contrast, the {@code ChronoField} class * defines fields that only have meaning relative to the chronology. * As such, {@code ChronoField} date fields are resolved here in the * context of a specific chronology. * <p> * The default implementation, which explains typical resolve behaviour, * is provided in {@link AbstractChronology}. * * @param fieldValues the map of fields to values, which can be updated, not null * @param resolverStyle the requested type of resolve, not null * @return the resolved date, null if insufficient information to create a date * @throws DateTimeException if the date cannot be resolved, typically * because of a conflict in the input data */ public ChronoLocalDate resolveDate(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) { throw new UnsupportedOperationException("ThreeTen Backport does not support resolveDate"); } /** * Updates the map of field-values during resolution. * * @param field the field to update, not null * @param value the value to update, not null * @throws DateTimeException if a conflict occurs */ void updateResolveMap(Map<TemporalField, Long> fieldValues, ChronoField field, long value) { Long current = fieldValues.get(field); if (current != null && current.longValue() != value) { throw new DateTimeException("Invalid state, field: " + field + " " + current + " conflicts with " + field + " " + value); } fieldValues.put(field, value); } //----------------------------------------------------------------------- /** * Compares this chronology to another chronology. * <p> * The comparison order first by the chronology ID string, then by any * additional information specific to the subclass. * It is "consistent with equals", as defined by {@link Comparable}. * <p> * The default implementation compares the chronology ID. * Subclasses must compare any additional state that they store. * * @param other the other chronology to compare to, not null * @return the comparator value, negative if less, positive if greater */ @Override public int compareTo(Chronology other) { return getId().compareTo(other.getId()); } /** * Checks if this chronology is equal to another chronology. * <p> * The comparison is based on the entire state of the object. * <p> * The default implementation checks the type and calls {@link #compareTo(Chronology)}. * * @param obj the object to check, null returns false * @return true if this is equal to the other chronology */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof Chronology) { return compareTo((Chronology) obj) == 0; } return false; } /** * A hash code for this chronology. * <p> * The default implementation is based on the ID and class. * Subclasses should add any additional state that they store. * * @return a suitable hash code */ @Override public int hashCode() { return getClass().hashCode() ^ getId().hashCode(); } //----------------------------------------------------------------------- /** * Outputs this chronology as a {@code String}, using the ID. * * @return a string representation of this chronology, not null */ @Override public String toString() { return getId(); } //----------------------------------------------------------------------- private Object writeReplace() { return new Ser(Ser.CHRONO_TYPE, this); } /** * Defend against malicious streams. * @return never * @throws InvalidObjectException always */ private Object readResolve() throws ObjectStreamException { throw new InvalidObjectException("Deserialization via serialization delegate"); } void writeExternal(DataOutput out) throws IOException { out.writeUTF(getId()); } static Chronology readExternal(DataInput in) throws IOException { String id = in.readUTF(); return Chronology.of(id); } }
bsd-3-clause
erwin1/gluon-samples
pws-gluoncloudlink-whiteboard/webapp-mobile/src/main/java/com/gluonhq/cloudlink/sample/whiteboard/mobile/storage/WhiteboardRepository.java
1982
/* * Copyright (c) 2016, Gluon * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Gluon, any associated website, nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL GLUON BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.gluonhq.cloudlink.sample.whiteboard.mobile.storage; import com.gluonhq.cloudlink.sample.whiteboard.mobile.model.Item; import org.springframework.context.annotation.Profile; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository @Profile({"in-memory", "mysql", "postgres", "oracle"}) public interface WhiteboardRepository extends JpaRepository<Item, String> { }
bsd-3-clause
percolate/foam
Foam/foam/src/main/java/com/percolate/foam/Graphite.java
4316
package com.percolate.foam; import android.content.Context; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; /** * {@inheritDoc} */ class Graphite extends ServiceImpl implements EventTrackingService { String host; int port; String apiKey; Graphite(Context context) { super(context); } /** * {@inheritDoc} */ @Override public void enable(String url) { if(utils.isNotBlank(url) && url.contains(":") && url.split(":").length == 2) { String first = url.split(":")[0]; String second = url.split(":")[1]; if (first.contains("@")) { this.apiKey = first.split("@")[0]; this.host = first.split("@")[1]; } else { this.host = url.split(":")[0]; } try { this.port = Integer.parseInt(second); } catch (NumberFormatException ex) { utils.logIssue("Invalid port in Graphite URL [" + second + "]", ex); } } else { utils.logIssue("Invalid Graphite URL. Expecting \"[key@]host:port\" format.", null); } } /** * {@inheritDoc} */ @Override public boolean isEnabled() { return host != null && port != 0; } /** * {@inheritDoc} */ @Override public ServiceType getServiceType() { return ServiceType.GRAPHITE; } /** * Send data to graphite in the format "metric_path value timestamp\n". * Example: "com.myapp.activities.MainActivity 1 1429801333\n" * ApiKey will be appended to the metric_path as expected by hosted providers. * * {@inheritDoc} */ @Override public void logEvent(Context context, String event) { StringBuilder eventData = new StringBuilder(); if(utils.isNotBlank(apiKey)){ eventData.append(apiKey); eventData.append("."); } eventData.append(utils.getApplicationPackageName(context)); eventData.append("."); eventData.append(event); eventData.append(" 1 "); eventData.append(getTimeStamp()); eventData.append("\n"); sendData(eventData.toString()); } /** * Return unix epoch for the current time * @return Epoch in for the current time. */ long getTimeStamp() { return System.currentTimeMillis() / 1000L; } /** * Start new background thread to send data with. * * @param graphiteEvent Event data to send to graphite. */ void sendData(final String graphiteEvent) { new Thread(new Runnable() { @Override public void run() { sendUdpData(graphiteEvent); } }).start(); } /** * Send data to Graphite server. * * @param graphiteEvent Event data to send to graphite. */ void sendUdpData(String graphiteEvent) { Socket socket = null; try { socket = sendDataOverSocket(graphiteEvent); } catch (IOException ex) { utils.logIssue("Error sending graphite event [" + graphiteEvent + "] to [" + host + ":" + port + "].", ex); } finally { closeSocket(socket); } } /** * Create new {@link DataOutputStream} to send data over. * * @param graphiteEvent Event data to send to graphite. * @return created {@link Socket} object. Should be closed after calling this method. * @throws IOException propagates if there was a network issue. */ Socket sendDataOverSocket(String graphiteEvent) throws IOException { Socket socket = new Socket(host, port); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeBytes(graphiteEvent); dos.flush(); return socket; } /** * Close the given {@link} Socket object, checking for null * @param socket socket to close. */ void closeSocket(Socket socket) { if(socket != null) { try { socket.close(); } catch (Exception ex) { utils.logIssue("Could not close graphite socket [" + host + ":" + port + "].", ex); } } } }
bsd-3-clause
Prospect-Robotics/2016Robot
src/org/usfirst/frc2813/Robot2016/commands/arms/SafeArmsUp.java
1037
package org.usfirst.frc2813.Robot2016.commands.arms; import org.usfirst.frc2813.Robot2016.commands.shooter.ShooterToMiddle; import edu.wpi.first.wpilibj.command.CommandGroup; /** * */ public class SafeArmsUp extends CommandGroup { public SafeArmsUp() { // Add Commands here: // e.g. addSequential(new Command1()); // addSequential(new Command2()); // these will run in order. // To run multiple commands at the same time, // use addParallel() // e.g. addParallel(new Command1()); // addSequential(new Command2()); // Command1 and Command2 will run in parallel. // A command group will require all of the subsystems that each member // would require. // e.g. if Command1 requires chassis, and Command2 requires arm, // a CommandGroup containing them would require both the chassis and the // arm. addSequential(new ShooterToMiddle(), 2.5); addSequential(new ArmsUp()); } }
bsd-3-clause
pjreiniger/TempAllWpi
wpilibj/src/main/java/edu/wpi/first/wpilibj/SafePWM.java
2967
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2008-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; /** * Manages a PWM object. */ public class SafePWM extends PWM implements MotorSafety { private final MotorSafetyHelper m_safetyHelper; /** * Constructor for a SafePWM object taking a channel number. * * @param channel The channel number to be used for the underlying PWM object. 0-9 are on-board, * 10-19 are on the MXP port. */ public SafePWM(final int channel) { super(channel); m_safetyHelper = new MotorSafetyHelper(this); m_safetyHelper.setExpiration(0.0); m_safetyHelper.setSafetyEnabled(false); } /** * Set the expiration time for the PWM object. * * @param timeout The timeout (in seconds) for this motor object */ public void setExpiration(double timeout) { m_safetyHelper.setExpiration(timeout); } /** * Return the expiration time for the PWM object. * * @return The expiration time value. */ public double getExpiration() { return m_safetyHelper.getExpiration(); } /** * Check if the PWM object is currently alive or stopped due to a timeout. * * @return a bool value that is true if the motor has NOT timed out and should still be running. */ public boolean isAlive() { return m_safetyHelper.isAlive(); } /** * Stop the motor associated with this PWM object. This is called by the MotorSafetyHelper object * when it has a timeout for this PWM and needs to stop it from running. */ public void stopMotor() { disable(); } /** * Check if motor safety is enabled for this object. * * @return True if motor safety is enforced for this object */ public boolean isSafetyEnabled() { return m_safetyHelper.isSafetyEnabled(); } /** * Feed the MotorSafety timer. This method is called by the subclass motor whenever it updates its * speed, thereby resetting the timeout value. * * @deprecated Use {@link #feed()} instead. */ @Deprecated @SuppressWarnings("MethodName") public void Feed() { feed(); } /** * Feed the MotorSafety timer. This method is called by the subclass motor whenever it updates its * speed, thereby resetting the timeout value. */ public void feed() { m_safetyHelper.feed(); } public void setSafetyEnabled(boolean enabled) { m_safetyHelper.setSafetyEnabled(enabled); } public String getDescription() { return "PWM " + getChannel(); } public void disable() { setDisabled(); } }
bsd-3-clause
mural/spm
db4oj/src/main/java/com/db4o/internal/btree/algebra/BTreeRangeUnionUnion.java
1131
/* This file is part of the db4o object database http://www.db4o.com Copyright (C) 2004 - 2010 Versant Corporation http://www.versant.com db4o is free software; you can redistribute it and/or modify it under the terms of version 3 of the GNU General Public License as published by the Free Software Foundation. db4o is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ package com.db4o.internal.btree.algebra; import com.db4o.internal.btree.*; /** * @exclude */ public class BTreeRangeUnionUnion extends BTreeRangeUnionOperation { public BTreeRangeUnionUnion(BTreeRangeUnion union) { super(union); } protected BTreeRange execute(BTreeRangeUnion union) { return BTreeAlgebra.union(_union, union); } protected BTreeRange execute(BTreeRangeSingle single) { return BTreeAlgebra.union(_union, single); } }
bsd-3-clause
monnetproject/coal
main/src/main/java/eu/monnetproject/align/Aligner.java
1262
package eu.monnetproject.align; import eu.monnetproject.ontology.Ontology; /** * Interface for aligning two ontologies * * @author Dennis Spohr * */ public interface Aligner { /** * Aligns two ontologies and stores the results in <code>alignment</code>. * * @param srcOntology source ontology * @param tgtOntology target ontology * @param alignment the suggested alignment */ public void align(Alignment alignment); /** * Aligns two ontologies and stores the results in <code>alignment</code>. * * @param srcOntology source ontology * @param tgtOntology target ontology * @return the suggested alignment */ public Alignment align(Ontology srcOntology, Ontology tgtOntology); /** * Aligns two ontologies and stores the results in <code>alignment</code>. * * @param srcOntology source ontology * @param tgtOntology target ontology * @param k number of matches to return * @return the suggested alignment */ public Alignment align(Ontology srcOntology, Ontology tgtOntology, int k); int getProgress(); }
bsd-3-clause
NCIP/commons-module
software/washu-commons/src/test/java/edu/wustl/common/testdomain/Person.java
1954
/*L * Copyright Washington University in St. Louis, SemanticBits, Persistent Systems, Krishagni. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/commons-module/LICENSE.txt for details. */ package edu.wustl.common.testdomain; import java.util.Collection; import java.util.HashSet; /** * @author kalpana_thakur * */ public class Person { /** * Default Serial Version Id. */ private static final long serialVersionUID = 1L; /** * id. */ private Long identifier; /** * name. */ private String name; /** * The address of the site. */ private Address address; /** * person's order collection. */ private Collection<Object> orderCollection = new HashSet<Object>(); /** * @return collection of orders. */ public Collection<Object> getOrderCollection() { return orderCollection; } /** * @param orderCollection : */ public void setOrderCollection(Collection<Object> orderCollection) { this.orderCollection = orderCollection; } /** *@return person name. */ public String getName() { return name; } /** * @param name : name of person */ public void setName(String name) { this.name = name; } /** * @return : */ public Long getIdentifier() { return identifier; } /** * @param identifier : */ public void setIdentifier(Long identifier) { this.identifier = identifier; } /** * Returns the address. * @return Address */ public Address getAddress() { return address; } /** * Sets the address. * @param address address */ public void setAddress(Address address) { this.address = address; } /** * @return id. */ public Long getId() { // TODO Auto-generated method stub return getIdentifier(); } }
bsd-3-clause
MjAbuz/carrot2
core/carrot2-util-text/src-test/org/carrot2/text/preprocessing/filter/MinLengthLabelFilterTest.java
1633
/* * Carrot2 project. * * Copyright (C) 2002-2015, Dawid Weiss, Stanisław Osiński. * All rights reserved. * * Refer to the full license file "carrot2.LICENSE" * in the root folder of the repository checkout or at: * http://www.carrot2.org/carrot2.LICENSE */ package org.carrot2.text.preprocessing.filter; import org.carrot2.text.preprocessing.LabelFilterProcessor; import org.carrot2.text.preprocessing.LabelFilterTestBase; import org.junit.Test; /** * Test cases for {@link StopWordLabelFilter}. */ public class MinLengthLabelFilterTest extends LabelFilterTestBase { @Override protected void initializeFilters(LabelFilterProcessor filterProcessor) { filterProcessor.minLengthLabelFilter.enabled = true; } @Test public void testEmpty() { final int [] expectedLabelsFeatureIndex = new int [] {}; check(expectedLabelsFeatureIndex); } @Test public void testTooShortWords() { createDocuments("aa . aa", "b . b"); final int [] expectedLabelsFeatureIndex = new int [] {}; check(expectedLabelsFeatureIndex); } @Test public void testLongerWords() { createDocuments("abc . abc", "abcd . abcd"); final int [] expectedLabelsFeatureIndex = new int [] { 0, 1 }; check(expectedLabelsFeatureIndex); } @Test public void testShortPhrases() { createDocuments("a a . a a", "b b . b b"); final int [] expectedLabelsFeatureIndex = new int [] { 2, 3 }; check(expectedLabelsFeatureIndex, 0); } }
bsd-3-clause
JesseeMeadows/Fury-Fighter
src/test/TestAllSuite.java
798
import org.junit.runner.RunWith; import org.junit.runners.Suite.SuiteClasses; @RunWith(value=org.junit.runners.Suite.class) @SuiteClasses(value={ TestMillisecTimer.class, TestUtils.class, TestFlyerModel.class, TestEnemyBullet.class, TestInputResponder.class, TestScoreTable.class, TestInputHandler.class, TestSplashModel.class, TestTitleModel.class, TestGameOverModel.class, TestRingBullet.class, TestSoundManager.class, TestPlayerModel.class, TestWeaponPickup.class, TestModelController.class, TestPickup.class, TestBullet.class, TestEnemyModel.class, TestTitleView.class, TestPlayerView.class, TestLevelModel.class, TestBossModel.class, TestEnemyView.class, TestSplashView.class, }) public class TestAllSuite {}
bsd-3-clause
wandora-team/zmpp-wandora
src/org/zmpp/io/TranscriptOutputStream.java
3928
/* * $Id: TranscriptOutputStream.java 548 2008-03-15 07:18:10Z weiju $ * * Created on 11/08/2005 * Copyright 2005-2008 by Wei-ju Wu * This file is part of The Z-machine Preservation Project (ZMPP). * * ZMPP is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZMPP is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZMPP. If not, see <http://www.gnu.org/licenses/>. */ package org.zmpp.io; import java.io.BufferedWriter; import java.io.IOException; import java.io.Writer; import org.zmpp.encoding.ZsciiEncoding; /** * This class defines an output stream for transcript output (Stream 2). * * @author Wei-ju Wu * @version 1.0 */ public class TranscriptOutputStream implements OutputStream { private IOSystem iosys; private BufferedWriter output; private Writer transcriptWriter; private boolean enabled; private StringBuilder linebuffer; private ZsciiEncoding encoding; private boolean initialized; /** * Constructor. * * @param iosys the I/O system */ public TranscriptOutputStream(final IOSystem iosys, final ZsciiEncoding encoding) { super(); this.iosys = iosys; this.encoding = encoding; linebuffer = new StringBuilder(); } /** * {@inheritDoc} */ private void initFile() { if (!initialized && transcriptWriter == null) { transcriptWriter = iosys.getTranscriptWriter(); if (transcriptWriter != null) { output = new BufferedWriter(transcriptWriter); } initialized = true; } } /** * {@inheritDoc} */ public void print(final char zsciiChar, final boolean isInput) { //System.out.println("TRANSCRIPT: PRINT: '" + zsciiChar + "'"); initFile(); if (output != null) { if (zsciiChar == ZsciiEncoding.NEWLINE) { flush(); } else if (zsciiChar == ZsciiEncoding.DELETE) { linebuffer.deleteCharAt(linebuffer.length() - 1); } else { linebuffer.append(encoding.getUnicodeChar(zsciiChar)); } flush(); } } /** * {@inheritDoc} */ public void select(final boolean flag) { enabled = flag; } /** * {@inheritDoc} */ public boolean isSelected() { return enabled; } /** * {@inheritDoc} */ public void flush() { try { if (output != null) { output.write(linebuffer.toString()); output.write("\n"); linebuffer = new StringBuilder(); } } catch (IOException ex) { ex.printStackTrace(System.err); } } /** * {@inheritDoc} */ public void close() { if (output != null) { try { output.close(); output = null; } catch (Exception ex) { ex.printStackTrace(System.err); } } if (transcriptWriter != null) { try { transcriptWriter.close(); transcriptWriter = null; } catch (Exception ex) { ex.printStackTrace(System.err); } } initialized = false; } /** * {@inheritDoc} */ public void deletePrevious(final char zchar) { // transcript does not support deleting } }
bsd-3-clause
hashrock/JavaOutlineEditor
src/com/organic/maynard/outliner/model/propertycontainer/PropertyContainerUtil.java
13434
/** * Copyright (C) 2004 Maynard Demmon, maynard@organic.com * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the * following conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * - Neither the names "Java Outline Editor", "JOE" nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.organic.maynard.outliner.model.propertycontainer; import java.util.*; import java.lang.reflect.*; import com.organic.maynard.xml.XMLTools; import com.organic.maynard.xml.XMLProcessor; import org.xml.sax.*; /** * Holds static methods useful for working with PropertyContainer objects. */ public class PropertyContainerUtil { // XML Serialization private static final String ELEMENT_PROPERTY_CONTAINERS = "property_containers"; private static final String ELEMENT_PROPERTY_CONTAINER = "property_container"; private static final String ELEMENT_PROPERTY = "property"; private static final String ATTRIBUTE_CLASS = "class"; private static final String ATTRIBUTE_NAME = "name"; private static final String ATTRIBUTE_VALUE = "value"; public static List parseXML(String filepath) { PropertyContainerXMLParser parser = new PropertyContainerXMLParser(); try { parser.process(filepath); return parser.getPropertyContainerList(); } catch (Exception e) { e.printStackTrace(); return null; } } public static void writeXML( StringBuffer buf, List containers, int depth, String line_ending ) { if (containers != null) { HashMap attributes = new HashMap(); attributes.put(ATTRIBUTE_CLASS, containers.getClass().getName()); XMLTools.writeElementStart(buf, depth, false, line_ending, ELEMENT_PROPERTY_CONTAINERS, attributes); for (int i = 0; i < containers.size(); i++) { PropertyContainer container = (PropertyContainer) containers.get(i); PropertyContainerUtil.writeXML(buf, container, depth + 1, line_ending); } XMLTools.writeElementEnd(buf, depth, line_ending, ELEMENT_PROPERTY_CONTAINERS); } } public static void writeXML( StringBuffer buf, PropertyContainer container, int depth, String line_ending ) { if (container != null) { HashMap attributes = new HashMap(); attributes.put(ATTRIBUTE_CLASS, container.getClass().getName()); XMLTools.writeElementStart(buf, depth, false, line_ending, ELEMENT_PROPERTY_CONTAINER, attributes); Iterator it = container.getKeys(); while (it.hasNext()) { String key = (String) it.next(); Object property = container.getProperty(key); attributes = new HashMap(); attributes.put(ATTRIBUTE_NAME, key); if (property != null) { attributes.put(ATTRIBUTE_CLASS, property.getClass().getName()); attributes.put(ATTRIBUTE_VALUE, property.toString()); } XMLTools.writeElementStart(buf, depth + 1, true, line_ending, ELEMENT_PROPERTY, attributes); } XMLTools.writeElementEnd(buf, depth, line_ending, ELEMENT_PROPERTY_CONTAINER); } else { throw new IllegalArgumentException("Provided PropertyContainer was null."); } } // String Typed public static void setPropertyAsString(PropertyContainer container, String key, String value) { if (container != null) { container.setProperty(key, value); } else { throw new IllegalArgumentException("Provided PropertyContainer was null."); } } public static void setPropertyDefaultAsString(PropertyContainer container, String key, String default_value) { if (container != null) { container.setPropertyDefault(key, default_value); } else { throw new IllegalArgumentException("Provided PropertyContainer was null."); } } public static String getPropertyAsString(PropertyContainer container, String key) { if (container != null) { Object value = container.getProperty(key); return convertObjectToString(value); } else { throw new IllegalArgumentException("Provided PropertyContainer was null."); } } public static String getPropertyAsString(PropertyContainer container, String key, Object backup_value) { if (container != null) { Object value = container.getProperty(key, backup_value); return convertObjectToString(value); } else { throw new IllegalArgumentException("Provided PropertyContainer was null."); } } public static String getPropertyDefaultAsString(PropertyContainer container, String key) { if (container != null) { Object value = container.getPropertyDefault(key); return convertObjectToString(value); } else { throw new IllegalArgumentException("Provided PropertyContainer was null."); } } public static boolean propertyEqualsAsString(PropertyContainer container, String key, String test_value) { if (container != null) { return container.propertyEquals(key, test_value); } else { throw new IllegalArgumentException("Provided PropertyContainer was null."); } } public static String convertObjectToString(Object value) { if (value != null) { return value.toString(); } else { return null; } } // boolean typed public static void setPropertyAsBoolean(PropertyContainer container, String key, boolean value) { if (container != null) { container.setProperty(key, new Boolean(value)); } else { throw new IllegalArgumentException("Provided PropertyContainer was null."); } } public static void setPropertyDefaultAsBoolean(PropertyContainer container, String key, boolean default_value) { if (container != null) { container.setPropertyDefault(key, new Boolean(default_value)); } else { throw new IllegalArgumentException("Provided PropertyContainer was null."); } } public static boolean getPropertyAsBoolean(PropertyContainer container, String key) { if (container != null) { Object value = container.getProperty(key); return convertObjectToBoolean(value); } else { throw new IllegalArgumentException("Provided PropertyContainer was null."); } } public static boolean getPropertyAsBoolean(PropertyContainer container, String key, boolean backup_value) { if (container != null) { Object value = container.getProperty(key, new Boolean(backup_value)); return convertObjectToBoolean(value); } else { throw new IllegalArgumentException("Provided PropertyContainer was null."); } } public static boolean getPropertyDefaultAsBoolean(PropertyContainer container, String key) { if (container != null) { Object value = container.getPropertyDefault(key); return convertObjectToBoolean(value); } else { throw new IllegalArgumentException("Provided PropertyContainer was null."); } } public static boolean propertyEqualsAsBoolean(PropertyContainer container, String key, boolean test_value) { if (container != null) { try { boolean value = getPropertyAsBoolean(container, key); return value == test_value; } catch (NullPointerException npe) { return false; } } else { throw new IllegalArgumentException("Provided PropertyContainer was null."); } } /** * Throws an IllegalArgumentException if the provided value is null. */ public static boolean convertObjectToBoolean(Object value) throws IllegalArgumentException { if (value != null) { if (value instanceof Boolean) { return ((Boolean) value).booleanValue(); } else { return Boolean.valueOf(value.toString()).booleanValue(); } } else { throw new IllegalArgumentException("Property value was null so it couldn't be converted to a boolean."); } } // int typed public static void setPropertyAsInt(PropertyContainer container, String key, int value) { if (container != null) { container.setProperty(key, new Integer(value)); } else { throw new IllegalArgumentException("Provided PropertyContainer was null."); } } public static void setPropertyDefaultAsInt(PropertyContainer container, String key, int default_value) { if (container != null) { container.setPropertyDefault(key, new Integer(default_value)); } else { throw new IllegalArgumentException("Provided PropertyContainer was null."); } } public static int getPropertyAsInt(PropertyContainer container, String key) { if (container != null) { Object value = container.getProperty(key); return convertObjectToInt(value); } else { throw new IllegalArgumentException("Provided PropertyContainer was null."); } } public static int getPropertyAsInt(PropertyContainer container, String key, int backup_value) { if (container != null) { Object value = container.getProperty(key, new Integer(backup_value)); return convertObjectToInt(value); } else { throw new IllegalArgumentException("Provided PropertyContainer was null."); } } public static int getPropertyDefaultAsInt(PropertyContainer container, String key) { if (container != null) { Object value = container.getPropertyDefault(key); return convertObjectToInt(value); } else { throw new IllegalArgumentException("Provided PropertyContainer was null."); } } public static boolean propertyEqualsAsInt(PropertyContainer container, String key, int test_value) { if (container != null) { try { int value = getPropertyAsInt(container, key); return value == test_value; } catch (NullPointerException npe) { return false; } } else { throw new IllegalArgumentException("Provided PropertyContainer was null."); } } public static int convertObjectToInt(Object value) { if (value != null) { if (value instanceof Integer) { return ((Integer) value).intValue(); } else { return Integer.valueOf(value.toString()).intValue(); } } else { throw new NullPointerException("Property value was null so it couldn't be converted to an int."); } } // InnerClasses private static class PropertyContainerXMLParser extends XMLProcessor { // Instance Fields private List containers; private PropertyContainer container; // Constructors public PropertyContainerXMLParser() { super(); init(); } private void init() { containers = null; container = null; } // Accessors public List getPropertyContainerList() { return this.containers; } // Sax DocumentHandler Implementation public void startDocument () {} public void endDocument () {} public void startElement(String namespaceURI, String localName, String qName, Attributes atts) { if (ELEMENT_PROPERTY.equals(qName)) { try { String class_name = atts.getValue(ATTRIBUTE_CLASS); String property_name = atts.getValue(ATTRIBUTE_NAME); String property_value = atts.getValue(ATTRIBUTE_VALUE); Class[] parameterTypes = {(new String("")).getClass()}; Constructor constructor = Class.forName(class_name).getConstructor(parameterTypes); Object[] args = {property_value}; Object property = constructor.newInstance(args); if (container != null) { container.setProperty(property_name, property); } else { System.out.println("Warning: no PropertyContainer to add property to during PropertyContainerXMLParser parsing."); } } catch (Exception e) { e.printStackTrace(); } } else if (ELEMENT_PROPERTY_CONTAINER.equals(qName)) { try { String class_name = atts.getValue(ATTRIBUTE_CLASS); container = (PropertyContainer) Class.forName(class_name).newInstance(); // Instantiate a List if we don't have one by now. if (containers == null) { containers = new ArrayList(); } containers.add(container); } catch (Exception e) { e.printStackTrace(); } } else if (ELEMENT_PROPERTY_CONTAINERS.equals(qName)) { try { String class_name = atts.getValue(ATTRIBUTE_CLASS); containers = (List) Class.forName(class_name).newInstance(); } catch (Exception e) { e.printStackTrace(); } } super.startElement(namespaceURI, localName, qName, atts); } public void endElement(String namespaceURI, String localName, String qName) { super.endElement(namespaceURI, localName, qName); } public void characters(char ch[], int start, int length) throws SAXException { super.characters(ch, start, length); } } }
bsd-3-clause
livenson/libcdmi-java
src/test/java/eu/venusc/cdmi/ContainerOperationsTest.java
4191
package eu.venusc.cdmi; import static eu.venusc.cdmi.CDMIResponseStatus.REQUEST_CREATED; import static eu.venusc.cdmi.CDMIResponseStatus.REQUEST_DELETED; import static eu.venusc.cdmi.CDMIResponseStatus.REQUEST_NOT_FOUND; import java.io.IOException; import java.net.URISyntaxException; import java.util.HashSet; import java.util.Random; import java.util.Set; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.json.simple.parser.ParseException; import org.junit.After; import org.junit.Before; import org.junit.Test; public class ContainerOperationsTest extends CDMIConnectionWrapper { ContainerOperations cops; static String containerName; static String baseContainer; static Random random = new Random(); public ContainerOperationsTest(String name) throws Exception { super(name); cops = cdmiConnection.getContainerProxy(); } @Before public void setUp() throws IOException { baseContainer = "/"; if (baseContainer.charAt(baseContainer.length() - 1) != '/') baseContainer = baseContainer + "/"; containerName = "libcdmi-java" + random.nextInt(); } @After public void tearDown() throws IOException, ParseException, CDMIOperationException, URISyntaxException { String[] children = cops.getChildren(baseContainer); for (int i = 0; i < children.length; i++) { String url = baseContainer + children[i]; HttpResponse response = cops.delete(url); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode == REQUEST_NOT_FOUND || responseCode == REQUEST_DELETED) continue; else fail("Container " + url + " could not be cleaned up." + responseCode); } } @Test public void testCreate() throws ClientProtocolException, IOException, CDMIOperationException, URISyntaxException { HttpResponse response = cops.create(baseContainer + containerName, parameters); int responseCode = response.getStatusLine().getStatusCode(); assertEquals("Creating container failed:" + baseContainer + containerName + "/", REQUEST_CREATED, responseCode); } @Test public void testGetChildren() throws ClientProtocolException, IOException, CDMIOperationException, ParseException, URISyntaxException { Set<String> set = new HashSet<String>(); // create containers for (int i = 0; i < 3; i++) { HttpResponse response = cops.create(baseContainer + containerName + i, parameters); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode != REQUEST_CREATED) fail("Could not create the container: " + baseContainer + containerName + "/"); set.add(containerName + i + "/"); } String[] children = cops.getChildren(baseContainer); Set<String> childSet = new HashSet<String>(); for (int i = 0; i < children.length; i++) { childSet.add(children[i]); } assertEquals("Getting the container children failed: ", set, childSet); childSet.clear(); } @Test public void testDelete() throws ClientProtocolException, IOException, CDMIOperationException, URISyntaxException { // Create a container HttpResponse response = cops.create(baseContainer + containerName, parameters); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode != REQUEST_CREATED) fail("Could not create the container: " + baseContainer + containerName); // delete the container response = cops.delete(baseContainer + containerName); responseCode = response.getStatusLine().getStatusCode(); assertEquals("Container could not be deleted: " + baseContainer + containerName, REQUEST_DELETED, responseCode); } }
bsd-3-clause
exponentjs/exponent
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/interfaces/sensors/services/PedometerServiceInterface.java
213
package abi43_0_0.expo.modules.interfaces.sensors.services; import abi43_0_0.expo.modules.interfaces.sensors.SensorServiceInterface; public interface PedometerServiceInterface extends SensorServiceInterface { }
bsd-3-clause
jevetools/data.model
com.jevetools.data.model.api.impl/src/com/jevetools/data/model/api/inventory/impl/MetaTypeImpl.java
4059
/* * Copyright (c) 2013, jEVETools * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of the contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.jevetools.data.model.api.inventory.impl; import com.jevetools.data.model.api.impl.AbstractEntity; import com.jevetools.data.model.api.inventory.MetaType; /** * Copyright (c) 2013, jEVETools. * * All rights reserved. * * @version 0.0.1 * @since 0.0.1 */ public final class MetaTypeImpl extends AbstractEntity implements MetaType { /** * The metaGroupID. */ private final int mMetaGroupID; /** * The parentTypeID. */ private final int mParentTypeID; /** * The typeID. */ private final int mTypeID; /** * Copyright (c) 2013, jEVETools. * * All rights reserved. * * @version 0.0.1 * @since 0.0.1 */ public static final class Builder implements com.jevetools.data.model.api.Builder<MetaType> { /** * The metaGroupID. */ private int mMetaGroupID; /** * The parentTypeID. */ private int mParentTypeID; /** * The typeID. */ private int mTypeID; /** * @param aMetaGroupID the metaGroupID */ public void metaGroupID(final int aMetaGroupID) { mMetaGroupID = aMetaGroupID; } /** * @param aParentTypeID the parentTypeID */ public void parentTypeID(final int aParentTypeID) { mParentTypeID = aParentTypeID; } /** * @param aTypeID the typeID */ public void typeID(final int aTypeID) { mTypeID = aTypeID; } @Override public MetaType build() { return new MetaTypeImpl(this); } }; /** * @param aBuilder {@link Builder} */ MetaTypeImpl(final Builder aBuilder) { super(); mMetaGroupID = aBuilder.mMetaGroupID; mParentTypeID = aBuilder.mParentTypeID; mTypeID = aBuilder.mTypeID; } @Override public int getMetaGroupID() { return mMetaGroupID; } @Override public int getParentTypeID() { return mParentTypeID; } @Override public int getTypeID() { return mTypeID; } @Override public int hashCode() { return HASHCODE_PRIME * 1 + mTypeID; } @Override public boolean equals(final Object aOther) { if (this == aOther) { return true; } if (aOther == null) { return false; } if (getClass() != aOther.getClass()) { return false; } final MetaType other = (MetaType) aOther; if (mTypeID != other.getTypeID()) { return false; } return true; } }
bsd-3-clause
NCIP/cab2b
software/dependencies/commonpackage/HEAD_TAG_10_Jan_2007_RELEASE_BRANCH_FOR_V11/test/edu/wustl/common/querysuite/queryobject/impl/ExpressionTestCase.java
15554
/*L * Copyright Georgetown University, Washington University. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cab2b/LICENSE.txt for details. */ package edu.wustl.common.querysuite.queryobject.impl; /** * @author Mandar Shidhore * @version 1.0 * @created 19-Oct-2006 16.12.04 PM */ import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import edu.common.dynamicextensions.domaininterface.AttributeInterface; import edu.common.dynamicextensions.exception.DynamicExtensionsApplicationException; import edu.common.dynamicextensions.exception.DynamicExtensionsSystemException; import edu.wustl.common.querysuite.EntityManagerMock; import edu.wustl.common.querysuite.factory.QueryObjectFactory; import edu.wustl.common.querysuite.queryobject.ICondition; import edu.wustl.common.querysuite.queryobject.IConnector; import edu.wustl.common.querysuite.queryobject.IConstraints; import edu.wustl.common.querysuite.queryobject.IExpression; import edu.wustl.common.querysuite.queryobject.IRule; import edu.wustl.common.querysuite.queryobject.LogicalOperator; import edu.wustl.common.querysuite.queryobject.RelationalOperator; public class ExpressionTestCase extends TestCase { IExpression expr; IExpression expr2; IExpression bigExpr; IConnector<LogicalOperator> orCondB, orCondE; IConnector<LogicalOperator> andCond, unknownCond; IRule a; IRule b; IRule c; IRule d; IRule e; public ExpressionTestCase() { super(); } public ExpressionTestCase(String name) { super(name); } /** * @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { IConstraints constraints = QueryObjectFactory.createConstraints(); expr = constraints.addExpression(null); a = QueryObjectFactory.createRule(createCondition("activityStatus")); expr.addOperand(a); b = QueryObjectFactory.createRule(createCondition("lastName")); orCondB = QueryObjectFactory.createLogicalConnector(LogicalOperator.Or); expr.addOperand(orCondB, b); c = QueryObjectFactory.createRule(createCondition("middleName")); andCond = QueryObjectFactory.createLogicalConnector(LogicalOperator.And); expr.addOperand(andCond, c); expr2 = constraints.addExpression(null); d = QueryObjectFactory.createRule(createCondition("ethnicity")); expr2.addOperand(d); e = QueryObjectFactory.createRule(createCondition("firstName")); orCondE = QueryObjectFactory.createLogicalConnector(LogicalOperator.Or); expr2.addOperand(orCondE, e); unknownCond = QueryObjectFactory.createLogicalConnector(LogicalOperator.Unknown); } /** * To create dummy Condition on Participant from the given name parameters as [name = 'name'] * @param name the name of the attribute & value. * @return the List containing one ICondition object. * @throws DynamicExtensionsApplicationException * @throws DynamicExtensionsSystemException */ private List<ICondition> createCondition(String name) throws DynamicExtensionsSystemException, DynamicExtensionsApplicationException { EntityManagerMock entityManager = new EntityManagerMock(); List<ICondition> conditions = new ArrayList<ICondition>(); AttributeInterface attribute = entityManager.getAttribute( EntityManagerMock.PARTICIPANT_NAME, name); List<String> values = new ArrayList<String>(); values.add(name); ICondition condition = QueryObjectFactory.createCondition(attribute, RelationalOperator.Equals, values); conditions.add(condition); return conditions; } /** * @see junit.framework.TestCase#tearDown() */ @Override protected void tearDown() throws Exception { // TODO Auto-generated method stub super.tearDown(); } /* * Expression is (a or b) and c -- we try to remove operand b; * it should give us a and c as the final expression */ public void testremoveOperandCase1() { expr.addParantheses(0, 1); assertTrue(expr.removeOperand(b)); try { assertEquals(andCond, expr.getConnector(0, 1)); } catch (IllegalArgumentException e) { assertTrue(false); } } /* * Expression is a or (b and c) -- we try to remove operand b; * it should give us a or c as the final expression */ public void testremoveOperandCase2() { expr.addParantheses(1, 2); assertTrue(expr.removeOperand(b)); try { assertEquals(orCondB, expr.getConnector(0, 1)); } catch (IllegalArgumentException e) { assertTrue(false); } } /* * Expression is (a or b and c) -- we try to remove operand b; * it should give us a or c as the final expression */ public void testremoveOperandCase3() { expr.addParantheses(0, 2); assertTrue(expr.removeOperand(b)); try { assertEquals(orCondB, expr.getConnector(0, 1)); } catch (IllegalArgumentException e) { assertTrue(false); } } /* * Expression is (a or b) and c -- we try to remove operand a; * it should give us b and c as the final expression */ public void testremoveOperandCase4() { expr.addParantheses(0, 1); assertTrue(expr.removeOperand(a)); try { assertEquals(andCond, expr.getConnector(0, 1)); } catch (IllegalArgumentException e) { assertTrue(false); } } /* * Expression is (a or b) and c -- we try to remove operand c; * it should give us a or b as the final expression */ public void testremoveOperandCase5() { expr.addParantheses(0, 1); assertTrue(expr.removeOperand(c)); try { assertEquals(orCondB, expr.getConnector(0, 1)); } catch (IllegalArgumentException e) { assertTrue(false); } } /* * Expression is a or (b and c) -- we try to remove operand c; * it should give us a or b as the final expression */ public void testremoveOperandCase6() { expr.addParantheses(1, 2); assertTrue(expr.removeOperand(c)); try { assertEquals(orCondB, expr.getConnector(0, 1)); } catch (IllegalArgumentException e) { assertTrue(false); } } /* * Expression is a or (b and c) -- we try to remove operand a; * it should give us b and c as the final expression */ public void testremoveOperandCase7() { expr.addParantheses(1, 2); assertTrue(expr.removeOperand(a)); try { assertEquals(andCond, expr.getConnector(0, 1)); } catch (IllegalArgumentException e) { assertTrue(false); } } /* * Expression is (a or b and c) -- we try to remove operand a; * it should give us b and c as the final expression */ public void testremoveOperandCase8() { expr.addParantheses(0, 2); assertTrue(expr.removeOperand(a)); try { assertEquals(andCond, expr.getConnector(0, 1)); } catch (IllegalArgumentException e) { assertTrue(false); } } /* * Expression is (a or b and c) -- we try to remove operand c; * it should give us a or b as the final expression */ public void testremoveOperandCase9() { expr.addParantheses(0, 2); assertTrue(expr.removeOperand(c)); try { assertEquals(orCondB, expr.getConnector(0, 1)); } catch (IllegalArgumentException e) { assertTrue(false); } } /* * Expression is (d or e)-- we try to remove operand d; * it should give us e as the final expression with no logical connector & getConnector(0,1) should return connector with 'unknown' logical operator. */ public void testremoveOperandCase10() { expr2.addParantheses(0, 1); assertTrue(expr2.removeOperand(e)); try { IConnector<LogicalOperator> logicalConnector = expr2.getConnector(0, 1); assertEquals("Incorrect Logical connector returned from getConnector() method!!!", logicalConnector.getOperator(), unknownCond.getOperator()); } catch (IndexOutOfBoundsException e) { assertTrue("Unexpected IndexOutOfBoundsException for removed Logical Connector!!!", false); } try { expr2.getOperand(1); assertTrue("Expected IndexOutOfBoundsException for removed Operand!!!", false); } catch (IndexOutOfBoundsException e) { } } /* * Expression is (a or b and c) -- we try to remove operand b and c; * it should give us a as the final expression */ public void testremoveOperandCase11() { expr.addParantheses(0, 2); assertTrue(expr.removeOperand(b)); assertTrue(expr.removeOperand(c)); /*try { assertEquals(orCond, expr.getConnector(0,1)); } catch (IllegalArgumentException e) { assertTrue(false); }*/ } /* * Expression is (a or b and c) -- we try to remove operand a and c; * it should give us b as the final expression */ public void testremoveOperandCase12() { expr.addParantheses(0, 2); assertTrue(expr.removeOperand(a)); assertTrue(expr.removeOperand(c)); /*try { assertEquals(orCond, expr.getConnector(0,1)); } catch (IllegalArgumentException e) { assertTrue(false); }*/ } /* * Expression is (a or b and c) and we try to remove operand a and b; * it should give us c as the final expression */ public void testremoveOperandCase13() { expr.addParantheses(0, 2); assertTrue(expr.removeOperand(a)); assertTrue(expr.removeOperand(b)); /*try { assertEquals(orCond, expr.getConnector(0,1)); } catch (IllegalArgumentException e) { assertTrue(false); }*/ } /* * Expression is (a or b and c) -- we try to remove operand a and b and c */ public void testremoveOperandCase14() { expr.addParantheses(0, 2); assertTrue(expr.removeOperand(a)); assertTrue(expr.removeOperand(b)); assertTrue(expr.removeOperand(c)); /*try { assertEquals(orCond, expr.getConnector(0,1)); } catch (IllegalArgumentException e) { assertTrue(false); }*/ } /* * Expression is a or b and c -- we try to get the logical * connector between 0 and 1 i.e. between a and b */ public void testgetLogicalConnectorCase1() { try { assertEquals(orCondB, expr.getConnector(0, 1)); } catch (IllegalArgumentException e) { assertFalse(true); } } /* * Expression is a or b and c -- we try to get the logical * connector between 1 and 2 i.e. between a and b */ public void testgetLogicalConnectorCase2() { try { assertEquals(andCond, expr.getConnector(1, 2)); } catch (IllegalArgumentException e) { assertFalse(true); } } /* * Expression is a or b and c -- we try to get the logical * connector between 0 and 2 which is invalid */ public void testgetLogicalConnectorCase3() { try { expr.getConnector(0, 2); assertTrue(false); } catch (IllegalArgumentException e) { } } /** * To test the method addOperand(int, IConnector<LogicalOperator>, IExpressionOperand) * It should insert an operand with the connector in front of it. * for Expression: a or b and c * call to addOperation(1, and, d) will change Expression to : a and d or b and c * */ public void testAddOperand1() { expr.addOperand(1, andCond, d); try { assertEquals("Unable to insert an operand with the connector in front of it!!!", expr .getConnector(0, 1), andCond); assertEquals("Unable to insert an operand with the connector in front of it!!!", expr .getOperand(1), d); } catch (IllegalArgumentException e) { assertTrue( "Unexpected IllegalArgumentException, while adding Operand with the connector in front it!!!", false); } } /** * To test the method addOperand(int, IExpressionOperand, IConnector<LogicalOperator>) * It should insert an operand with the connector behind it. * for Expression: a or b and c * call to addOperation(1, d, and) will change Expression to : a or d and b and c * */ public void testAddOperand2() { expr.addOperand(1, d, andCond); try { assertEquals("Unable to insert an operand with the connector behind it!!!", expr .getConnector(1, 2), andCond); assertEquals("Unable to insert an operand with the connector behind it!!!", expr .getOperand(1), d); } catch (IllegalArgumentException e) { assertTrue( "Unexpected IllegalArgumentException, while adding Operand with the connector behind it!!!", false); } } /** * To test the method addOperand(IExpressionOperand) * Expression is a or b and c and d; we verify the connector between c and d * then remove c and check operand at position 2 which should be d */ public void testAddOperand3() { expr.addOperand(d); assertEquals(unknownCond, expr.getConnector(2, 3)); assertEquals(d, expr.getOperand(3)); assertTrue(expr.removeOperand(c)); assertEquals(b, expr.getOperand(1)); assertEquals(d, expr.getOperand(2)); } /** * To test the method addOperand(IConnector<LogicalOperator>, IExpressionOperand) * If Expression contains no Expressions, then next call to this method should throw IndexOutOfBoundsException. */ public void testAddOperand4() { IExpression expression = new Expression(); try { expression.addOperand(andCond, a); assertTrue( "Expected IndexOutOfBoundsException, while adding Operand with connector when Expression has no Operands !!!", false); } catch (IndexOutOfBoundsException e) { } } /** * To test the method setConnector(int leftOperandIndex, int rightOperandIndex, IConnector<LogicalOperator> logicalConnector) * We try to set an invalid logical connector between two remote operands; so method * should throw an IllegalArgumentException. */ public void testsetLogicalConnector1() { try { expr.setConnector(1, 3, andCond); assertTrue(false); } catch (IllegalArgumentException e) { } } /** * To test the method setConnector(int leftOperandIndex, int rightOperandIndex, IConnector<LogicalOperator> logicalConnector) * We try to set an valid logical connector between two adjacent operands; * so method should not throw any IllegalArgumentException. */ public void testsetLogicalConnector2() { try { expr.setConnector(1, 2, andCond); } catch (IllegalArgumentException e) { assertTrue(false); } } /** * To test the method addParantheses(int leftOperandIndex, int rightOperandIndex) * We add parantheses between remote operands and verify the nesting number of * each logical connector. */ public void testaddParantheses1() { expr.addParantheses(0, 2); assertEquals(1, ((Connector) expr.getConnector(0, 1)).getNestingNumber()); assertEquals(1, ((Connector) expr.getConnector(1, 2)).getNestingNumber()); assertNotSame(2, ((Connector) expr.getConnector(1, 2)).getNestingNumber()); } /** * To test the method addParantheses(int leftOperandIndex, int rightOperandIndex) * We add parantheses between remote operands and verify the nesting number of * each logical connector. */ public void testaddParantheses2() { expr.addParantheses(0, 1); assertEquals(1, ((Connector) expr.getConnector(0, 1)).getNestingNumber()); assertEquals(0, ((Connector) expr.getConnector(1, 2)).getNestingNumber()); assertNotSame(1, ((Connector) expr.getConnector(1, 2)).getNestingNumber()); } }
bsd-3-clause
juniorbl/jtoyracing
src/net/juniorbl/jtoyracing/entity/vehicle/Wheel.java
3864
package net.juniorbl.jtoyracing.entity.vehicle; import net.juniorbl.jtoyracing.enums.ResourcesPath; import net.juniorbl.jtoyracing.util.ModelUtil; import com.jme.math.Vector3f; import com.jme.scene.Node; import com.jmex.physics.DynamicPhysicsNode; import com.jmex.physics.Joint; import com.jmex.physics.PhysicsSpace; import com.jmex.physics.RotationalJointAxis; import com.jmex.physics.geometry.PhysicsSphere; import com.jmex.physics.material.Material; /** * Wheel of a vehicle. It reacts to some speed by calculating the interaction between its own body * and the floor (done by JMonkeyEngine). * * @version 1.0 Aug 23, 2007 * @author Carlos Luz Junior */ public class Wheel extends Node { private static final long serialVersionUID = 8702035354026675358L; private static final float TIRE_SCALE = 1.5f; private static final float WHEEL_SCALE = .4f; private static final float MASS = 4; private static final float TRACTION_ACCELERATION = 150; private static final float TRACTION_BREAK_REVERSE_ACCELERATION = 250; private static final float STEER_ACCELERATION = 30; private static final float MAX_STEER_ROTATION = 0.3f; private DynamicPhysicsNode wheel; private RotationalJointAxis tractionAxis; private RotationalJointAxis steerAxis; public Wheel(DynamicPhysicsNode wheelBase, Vector3f location) { createWheel(wheelBase, location); Joint tireBaseJoint = createBaseTireJoint(wheelBase.getSpace(), wheelBase); createSteerAxis(tireBaseJoint); createTractionAxis(tireBaseJoint); this.attachChild(wheel); } private void createWheel(DynamicPhysicsNode wheelBase, Vector3f location) { wheel = wheelBase.getSpace().createDynamicNode(); wheel.setLocalTranslation(wheelBase.getLocalTranslation().add(location)); PhysicsSphere tire = wheel.createSphere("tire"); tire.setLocalScale(TIRE_SCALE); wheel.generatePhysicsGeometry(); wheel.attachChild(ModelUtil.convertOBJToStatial(ResourcesPath.MODELS_PATH + "obj/whell.obj")); wheel.setMass(MASS); wheel.setMaterial(Material.RUBBER); wheel.setLocalScale(WHEEL_SCALE); } /** * Creates a traction axis. It responds the traction action in the wheel. */ private void createTractionAxis(Joint tireBaseJoint) { tractionAxis = tireBaseJoint.createRotationalAxis(); tractionAxis.setDirection(Vector3f.UNIT_X); tractionAxis.setRelativeToSecondObject(true); tractionAxis.setAvailableAcceleration(TRACTION_ACCELERATION); } /** * Creates a steer axis. It responds the steer action in the wheel. */ private void createSteerAxis(Joint tireBaseJoint) { steerAxis = tireBaseJoint.createRotationalAxis(); steerAxis.setDirection(Vector3f.UNIT_Y); steerAxis.setAvailableAcceleration(STEER_ACCELERATION); unsteer(); } /** * Creates a joint which connects the base and the tire. */ private Joint createBaseTireJoint(PhysicsSpace physicsSpace, DynamicPhysicsNode wheelBase) { Joint tireBaseJoint = physicsSpace.createJoint(); tireBaseJoint.attach(wheelBase, wheel); tireBaseJoint.setAnchor(wheel.getLocalTranslation().subtract(wheelBase.getLocalTranslation())); return tireBaseJoint; } public final void accelerate(float desiredVelocity) { boolean breakOrReverse = desiredVelocity < 0; if (breakOrReverse) { tractionAxis.setAvailableAcceleration(TRACTION_BREAK_REVERSE_ACCELERATION); } else { tractionAxis.setAvailableAcceleration(TRACTION_ACCELERATION); } tractionAxis.setDesiredVelocity(desiredVelocity); } public final void stop() { tractionAxis.setDesiredVelocity(0); } public final void steer(float desiredDirection) { steerAxis.setDesiredVelocity(desiredDirection); steerAxis.setPositionMaximum(MAX_STEER_ROTATION); steerAxis.setPositionMinimum(-MAX_STEER_ROTATION); } public final void unsteer() { steerAxis.setDesiredVelocity(0); steerAxis.setPositionMaximum(0); steerAxis.setPositionMinimum(0); } }
bsd-3-clause
AurionProject/Aurion
Product/Production/Services/PatientDiscoveryCore/src/test/java/gov/hhs/fha/nhinc/patientdiscovery/outbound/PassthroughOutboundPatientDiscoveryTest.java
9636
/* * Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the United States Government nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package gov.hhs.fha.nhinc.patientdiscovery.outbound; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType; import gov.hhs.fha.nhinc.common.nhinccommon.HomeCommunityType; import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetCommunitiesType; import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetCommunityType; import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetSystemType; import gov.hhs.fha.nhinc.connectmgr.UrlInfo; import gov.hhs.fha.nhinc.patientdiscovery.PatientDiscoveryAuditLogger; import gov.hhs.fha.nhinc.patientdiscovery.entity.OutboundPatientDiscoveryDelegate; import gov.hhs.fha.nhinc.patientdiscovery.entity.OutboundPatientDiscoveryOrchestratable; import gov.hhs.fha.nhinc.patientdiscovery.nhin.proxy.NhinPatientDiscoveryProxy; import ihe.iti.xcpd._2009.PatientLocationQueryRequestType; import ihe.iti.xcpd._2009.PatientLocationQueryResponseType; import ihe.iti.xcpd._2009.PatientLocationQueryResponseType.PatientLocationResponse; import ihe.iti.xcpd._2009.RespondingGatewayPatientLocationQueryRequestType; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.hl7.v3.II; import org.hl7.v3.PRPAIN201305UV02; import org.hl7.v3.PRPAIN201306UV02; import org.hl7.v3.RespondingGatewayPRPAIN201305UV02RequestType; import org.hl7.v3.RespondingGatewayPRPAIN201306UV02ResponseType; import org.junit.Test; /** * @author akong * */ public class PassthroughOutboundPatientDiscoveryTest { @Test public void invoke() { RespondingGatewayPRPAIN201305UV02RequestType request = new RespondingGatewayPRPAIN201305UV02RequestType(); request.setPRPAIN201305UV02(new PRPAIN201305UV02()); request.setNhinTargetCommunities(createNhinTargetCommunitiesType("1.1")); AssertionType assertion = new AssertionType(); PRPAIN201306UV02 expectedResponse = new PRPAIN201306UV02(); OutboundPatientDiscoveryOrchestratable outOrchestratable = new OutboundPatientDiscoveryOrchestratable(); outOrchestratable.setResponse(expectedResponse); OutboundPatientDiscoveryDelegate delegate = mock(OutboundPatientDiscoveryDelegate.class); PatientDiscoveryAuditLogger auditLogger = mock(PatientDiscoveryAuditLogger.class); when(delegate.process(any(OutboundPatientDiscoveryOrchestratable.class))).thenReturn(outOrchestratable); PassthroughOutboundPatientDiscovery passthroughPatientDiscovery = new PassthroughOutboundPatientDiscovery( delegate, auditLogger); RespondingGatewayPRPAIN201306UV02ResponseType actualMessage = passthroughPatientDiscovery .respondingGatewayPRPAIN201305UV02(request, assertion); assertSame(outOrchestratable.getResponse(), actualMessage.getCommunityResponse().get(0).getPRPAIN201306UV02()); verify(auditLogger, never()).auditEntity201305(any(RespondingGatewayPRPAIN201305UV02RequestType.class), any(AssertionType.class), any(String.class)); verify(auditLogger, never()).auditEntity201306(any(RespondingGatewayPRPAIN201306UV02ResponseType.class), any(AssertionType.class), any(String.class)); } @Test public void invokePLQ() throws Exception { final String gatewayHcid = "1.1"; final String gatewayUrl = "1.1.1.1:8080"; final String reqPatientIdExt = "12345"; final String reqPatientIdRoot = "4.4"; final String corrPatientIdExt = "5678"; final String corrPatientIdRoot = "2.2"; final String correspondingHcid = "2.2"; RespondingGatewayPatientLocationQueryRequestType request = new RespondingGatewayPatientLocationQueryRequestType(); request.setPatientLocationQueryRequest(new PatientLocationQueryRequestType()); request.setNhinTargetCommunities(createNhinTargetCommunitiesType(gatewayHcid)); AssertionType assertion = new AssertionType(); OutboundPatientDiscoveryDelegate delegate = mock(OutboundPatientDiscoveryDelegate.class); PatientDiscoveryAuditLogger auditLogger = mock(PatientDiscoveryAuditLogger.class); final NhinPatientDiscoveryProxy mockNhinPDProxy = mock(NhinPatientDiscoveryProxy.class); PassthroughOutboundPatientDiscovery passthroughPatientDiscovery = new PassthroughOutboundPatientDiscovery( delegate, auditLogger) { @Override protected NhinPatientDiscoveryProxy getNhinProxy() { return mockNhinPDProxy; } @Override protected List<UrlInfo> getEndpoints(NhinTargetCommunitiesType targetCommunities){ List<UrlInfo> urlInfoList = new ArrayList<UrlInfo>(); UrlInfo urlToQuery = new UrlInfo(); urlToQuery.setHcid(gatewayHcid); urlToQuery.setUrl(gatewayUrl); urlInfoList.add(urlToQuery); return urlInfoList; } @Override protected PatientLocationQueryResponseType sendPLQToNhin(PatientLocationQueryRequestType nhinRequest, AssertionType assertion, NhinTargetSystemType target) { PatientLocationQueryResponseType expectedResponse = createExpectedResponse(); return expectedResponse; } }; PatientLocationQueryResponseType actualResponse = passthroughPatientDiscovery.respondingGatewayPatientLocationQuery(request, assertion); assertNotNull(actualResponse); assertNotNull(actualResponse.getPatientLocationResponse()); assertNotNull(actualResponse.getPatientLocationResponse().get(0)); PatientLocationResponse location = actualResponse.getPatientLocationResponse().get(0); assertNotNull(location.getHomeCommunityId()); assertEquals(correspondingHcid, location.getHomeCommunityId()); assertNotNull(location.getRequestedPatientId()); assertEquals(reqPatientIdExt, location.getRequestedPatientId().getExtension()); assertEquals(reqPatientIdRoot, location.getRequestedPatientId().getRoot()); assertNotNull(location.getCorrespondingPatientId()); assertEquals(corrPatientIdExt, location.getCorrespondingPatientId().getExtension()); assertEquals(corrPatientIdRoot, location.getCorrespondingPatientId().getRoot()); } private NhinTargetCommunitiesType createNhinTargetCommunitiesType(String hcid) { NhinTargetCommunitiesType targetCommunities = new NhinTargetCommunitiesType(); NhinTargetCommunityType targetCommunity = new NhinTargetCommunityType(); HomeCommunityType homeCommunity = new HomeCommunityType(); homeCommunity.setHomeCommunityId(hcid); targetCommunity.setHomeCommunity(homeCommunity); targetCommunities.getNhinTargetCommunity().add(targetCommunity); return targetCommunities; } /** * Returns a PatientLocationQueryResponse message with one PatientLocationResponse. */ private PatientLocationQueryResponseType createExpectedResponse() { PatientLocationQueryResponseType response = new PatientLocationQueryResponseType(); PatientLocationResponse location = new PatientLocationResponse(); II requestedPatientId = new II(); requestedPatientId.setRoot("4.4"); requestedPatientId.setExtension("12345"); location.setRequestedPatientId(requestedPatientId); location.setHomeCommunityId("2.2"); II correspondingPatientId = new II(); correspondingPatientId.setRoot("2.2"); correspondingPatientId.setExtension("5678"); location.setCorrespondingPatientId(correspondingPatientId); response.getPatientLocationResponse().add(location); return response; } }
bsd-3-clause
paksv/vijava
src/com/vmware/vim25/ArrayOfNetIpRouteConfigSpecIpRouteSpec.java
2347
/*================================================================================ Copyright (c) 2013 Steve Jin. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of VMware, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================*/ package com.vmware.vim25; /** * @author Steve Jin (http://www.doublecloud.org) * @version 5.1 */ public class ArrayOfNetIpRouteConfigSpecIpRouteSpec { public NetIpRouteConfigSpecIpRouteSpec[] NetIpRouteConfigSpecIpRouteSpec; public NetIpRouteConfigSpecIpRouteSpec[] getNetIpRouteConfigSpecIpRouteSpec() { return this.NetIpRouteConfigSpecIpRouteSpec; } public NetIpRouteConfigSpecIpRouteSpec getNetIpRouteConfigSpecIpRouteSpec(int i) { return this.NetIpRouteConfigSpecIpRouteSpec[i]; } public void setNetIpRouteConfigSpecIpRouteSpec(NetIpRouteConfigSpecIpRouteSpec[] NetIpRouteConfigSpecIpRouteSpec) { this.NetIpRouteConfigSpecIpRouteSpec=NetIpRouteConfigSpecIpRouteSpec; } }
bsd-3-clause
pongad/api-client-staging
generated/java/proto-google-cloud-dlp-v2beta2/src/main/java/com/google/privacy/dlp/v2beta2/ListJobTriggersResponse.java
35112
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/privacy/dlp/v2beta2/dlp.proto package com.google.privacy.dlp.v2beta2; /** * <pre> * Response message for ListJobTriggers. * </pre> * * Protobuf type {@code google.privacy.dlp.v2beta2.ListJobTriggersResponse} */ public final class ListJobTriggersResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.privacy.dlp.v2beta2.ListJobTriggersResponse) ListJobTriggersResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListJobTriggersResponse.newBuilder() to construct. private ListJobTriggersResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListJobTriggersResponse() { jobTriggers_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ListJobTriggersResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { jobTriggers_ = new java.util.ArrayList<com.google.privacy.dlp.v2beta2.JobTrigger>(); mutable_bitField0_ |= 0x00000001; } jobTriggers_.add( input.readMessage(com.google.privacy.dlp.v2beta2.JobTrigger.parser(), extensionRegistry)); break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); nextPageToken_ = s; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { jobTriggers_ = java.util.Collections.unmodifiableList(jobTriggers_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.privacy.dlp.v2beta2.DlpProto.internal_static_google_privacy_dlp_v2beta2_ListJobTriggersResponse_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.privacy.dlp.v2beta2.DlpProto.internal_static_google_privacy_dlp_v2beta2_ListJobTriggersResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.privacy.dlp.v2beta2.ListJobTriggersResponse.class, com.google.privacy.dlp.v2beta2.ListJobTriggersResponse.Builder.class); } private int bitField0_; public static final int JOB_TRIGGERS_FIELD_NUMBER = 1; private java.util.List<com.google.privacy.dlp.v2beta2.JobTrigger> jobTriggers_; /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public java.util.List<com.google.privacy.dlp.v2beta2.JobTrigger> getJobTriggersList() { return jobTriggers_; } /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public java.util.List<? extends com.google.privacy.dlp.v2beta2.JobTriggerOrBuilder> getJobTriggersOrBuilderList() { return jobTriggers_; } /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public int getJobTriggersCount() { return jobTriggers_.size(); } /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public com.google.privacy.dlp.v2beta2.JobTrigger getJobTriggers(int index) { return jobTriggers_.get(index); } /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public com.google.privacy.dlp.v2beta2.JobTriggerOrBuilder getJobTriggersOrBuilder( int index) { return jobTriggers_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; private volatile java.lang.Object nextPageToken_; /** * <pre> * If the next page is available then the next page token to be used * in following ListJobTriggers request. * </pre> * * <code>string next_page_token = 2;</code> */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * <pre> * If the next page is available then the next page token to be used * in following ListJobTriggers request. * </pre> * * <code>string next_page_token = 2;</code> */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < jobTriggers_.size(); i++) { output.writeMessage(1, jobTriggers_.get(i)); } if (!getNextPageTokenBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < jobTriggers_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, jobTriggers_.get(i)); } if (!getNextPageTokenBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.privacy.dlp.v2beta2.ListJobTriggersResponse)) { return super.equals(obj); } com.google.privacy.dlp.v2beta2.ListJobTriggersResponse other = (com.google.privacy.dlp.v2beta2.ListJobTriggersResponse) obj; boolean result = true; result = result && getJobTriggersList() .equals(other.getJobTriggersList()); result = result && getNextPageToken() .equals(other.getNextPageToken()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getJobTriggersCount() > 0) { hash = (37 * hash) + JOB_TRIGGERS_FIELD_NUMBER; hash = (53 * hash) + getJobTriggersList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.privacy.dlp.v2beta2.ListJobTriggersResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.privacy.dlp.v2beta2.ListJobTriggersResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.privacy.dlp.v2beta2.ListJobTriggersResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.privacy.dlp.v2beta2.ListJobTriggersResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.privacy.dlp.v2beta2.ListJobTriggersResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.privacy.dlp.v2beta2.ListJobTriggersResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.privacy.dlp.v2beta2.ListJobTriggersResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.privacy.dlp.v2beta2.ListJobTriggersResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.privacy.dlp.v2beta2.ListJobTriggersResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.privacy.dlp.v2beta2.ListJobTriggersResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.privacy.dlp.v2beta2.ListJobTriggersResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.privacy.dlp.v2beta2.ListJobTriggersResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.privacy.dlp.v2beta2.ListJobTriggersResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Response message for ListJobTriggers. * </pre> * * Protobuf type {@code google.privacy.dlp.v2beta2.ListJobTriggersResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.privacy.dlp.v2beta2.ListJobTriggersResponse) com.google.privacy.dlp.v2beta2.ListJobTriggersResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.privacy.dlp.v2beta2.DlpProto.internal_static_google_privacy_dlp_v2beta2_ListJobTriggersResponse_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.privacy.dlp.v2beta2.DlpProto.internal_static_google_privacy_dlp_v2beta2_ListJobTriggersResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.privacy.dlp.v2beta2.ListJobTriggersResponse.class, com.google.privacy.dlp.v2beta2.ListJobTriggersResponse.Builder.class); } // Construct using com.google.privacy.dlp.v2beta2.ListJobTriggersResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getJobTriggersFieldBuilder(); } } public Builder clear() { super.clear(); if (jobTriggersBuilder_ == null) { jobTriggers_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { jobTriggersBuilder_.clear(); } nextPageToken_ = ""; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.privacy.dlp.v2beta2.DlpProto.internal_static_google_privacy_dlp_v2beta2_ListJobTriggersResponse_descriptor; } public com.google.privacy.dlp.v2beta2.ListJobTriggersResponse getDefaultInstanceForType() { return com.google.privacy.dlp.v2beta2.ListJobTriggersResponse.getDefaultInstance(); } public com.google.privacy.dlp.v2beta2.ListJobTriggersResponse build() { com.google.privacy.dlp.v2beta2.ListJobTriggersResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public com.google.privacy.dlp.v2beta2.ListJobTriggersResponse buildPartial() { com.google.privacy.dlp.v2beta2.ListJobTriggersResponse result = new com.google.privacy.dlp.v2beta2.ListJobTriggersResponse(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (jobTriggersBuilder_ == null) { if (((bitField0_ & 0x00000001) == 0x00000001)) { jobTriggers_ = java.util.Collections.unmodifiableList(jobTriggers_); bitField0_ = (bitField0_ & ~0x00000001); } result.jobTriggers_ = jobTriggers_; } else { result.jobTriggers_ = jobTriggersBuilder_.build(); } result.nextPageToken_ = nextPageToken_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.privacy.dlp.v2beta2.ListJobTriggersResponse) { return mergeFrom((com.google.privacy.dlp.v2beta2.ListJobTriggersResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.privacy.dlp.v2beta2.ListJobTriggersResponse other) { if (other == com.google.privacy.dlp.v2beta2.ListJobTriggersResponse.getDefaultInstance()) return this; if (jobTriggersBuilder_ == null) { if (!other.jobTriggers_.isEmpty()) { if (jobTriggers_.isEmpty()) { jobTriggers_ = other.jobTriggers_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureJobTriggersIsMutable(); jobTriggers_.addAll(other.jobTriggers_); } onChanged(); } } else { if (!other.jobTriggers_.isEmpty()) { if (jobTriggersBuilder_.isEmpty()) { jobTriggersBuilder_.dispose(); jobTriggersBuilder_ = null; jobTriggers_ = other.jobTriggers_; bitField0_ = (bitField0_ & ~0x00000001); jobTriggersBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getJobTriggersFieldBuilder() : null; } else { jobTriggersBuilder_.addAllMessages(other.jobTriggers_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.privacy.dlp.v2beta2.ListJobTriggersResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.privacy.dlp.v2beta2.ListJobTriggersResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.util.List<com.google.privacy.dlp.v2beta2.JobTrigger> jobTriggers_ = java.util.Collections.emptyList(); private void ensureJobTriggersIsMutable() { if (!((bitField0_ & 0x00000001) == 0x00000001)) { jobTriggers_ = new java.util.ArrayList<com.google.privacy.dlp.v2beta2.JobTrigger>(jobTriggers_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.privacy.dlp.v2beta2.JobTrigger, com.google.privacy.dlp.v2beta2.JobTrigger.Builder, com.google.privacy.dlp.v2beta2.JobTriggerOrBuilder> jobTriggersBuilder_; /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public java.util.List<com.google.privacy.dlp.v2beta2.JobTrigger> getJobTriggersList() { if (jobTriggersBuilder_ == null) { return java.util.Collections.unmodifiableList(jobTriggers_); } else { return jobTriggersBuilder_.getMessageList(); } } /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public int getJobTriggersCount() { if (jobTriggersBuilder_ == null) { return jobTriggers_.size(); } else { return jobTriggersBuilder_.getCount(); } } /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public com.google.privacy.dlp.v2beta2.JobTrigger getJobTriggers(int index) { if (jobTriggersBuilder_ == null) { return jobTriggers_.get(index); } else { return jobTriggersBuilder_.getMessage(index); } } /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public Builder setJobTriggers( int index, com.google.privacy.dlp.v2beta2.JobTrigger value) { if (jobTriggersBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureJobTriggersIsMutable(); jobTriggers_.set(index, value); onChanged(); } else { jobTriggersBuilder_.setMessage(index, value); } return this; } /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public Builder setJobTriggers( int index, com.google.privacy.dlp.v2beta2.JobTrigger.Builder builderForValue) { if (jobTriggersBuilder_ == null) { ensureJobTriggersIsMutable(); jobTriggers_.set(index, builderForValue.build()); onChanged(); } else { jobTriggersBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public Builder addJobTriggers(com.google.privacy.dlp.v2beta2.JobTrigger value) { if (jobTriggersBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureJobTriggersIsMutable(); jobTriggers_.add(value); onChanged(); } else { jobTriggersBuilder_.addMessage(value); } return this; } /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public Builder addJobTriggers( int index, com.google.privacy.dlp.v2beta2.JobTrigger value) { if (jobTriggersBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureJobTriggersIsMutable(); jobTriggers_.add(index, value); onChanged(); } else { jobTriggersBuilder_.addMessage(index, value); } return this; } /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public Builder addJobTriggers( com.google.privacy.dlp.v2beta2.JobTrigger.Builder builderForValue) { if (jobTriggersBuilder_ == null) { ensureJobTriggersIsMutable(); jobTriggers_.add(builderForValue.build()); onChanged(); } else { jobTriggersBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public Builder addJobTriggers( int index, com.google.privacy.dlp.v2beta2.JobTrigger.Builder builderForValue) { if (jobTriggersBuilder_ == null) { ensureJobTriggersIsMutable(); jobTriggers_.add(index, builderForValue.build()); onChanged(); } else { jobTriggersBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public Builder addAllJobTriggers( java.lang.Iterable<? extends com.google.privacy.dlp.v2beta2.JobTrigger> values) { if (jobTriggersBuilder_ == null) { ensureJobTriggersIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, jobTriggers_); onChanged(); } else { jobTriggersBuilder_.addAllMessages(values); } return this; } /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public Builder clearJobTriggers() { if (jobTriggersBuilder_ == null) { jobTriggers_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { jobTriggersBuilder_.clear(); } return this; } /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public Builder removeJobTriggers(int index) { if (jobTriggersBuilder_ == null) { ensureJobTriggersIsMutable(); jobTriggers_.remove(index); onChanged(); } else { jobTriggersBuilder_.remove(index); } return this; } /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public com.google.privacy.dlp.v2beta2.JobTrigger.Builder getJobTriggersBuilder( int index) { return getJobTriggersFieldBuilder().getBuilder(index); } /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public com.google.privacy.dlp.v2beta2.JobTriggerOrBuilder getJobTriggersOrBuilder( int index) { if (jobTriggersBuilder_ == null) { return jobTriggers_.get(index); } else { return jobTriggersBuilder_.getMessageOrBuilder(index); } } /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public java.util.List<? extends com.google.privacy.dlp.v2beta2.JobTriggerOrBuilder> getJobTriggersOrBuilderList() { if (jobTriggersBuilder_ != null) { return jobTriggersBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(jobTriggers_); } } /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public com.google.privacy.dlp.v2beta2.JobTrigger.Builder addJobTriggersBuilder() { return getJobTriggersFieldBuilder().addBuilder( com.google.privacy.dlp.v2beta2.JobTrigger.getDefaultInstance()); } /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public com.google.privacy.dlp.v2beta2.JobTrigger.Builder addJobTriggersBuilder( int index) { return getJobTriggersFieldBuilder().addBuilder( index, com.google.privacy.dlp.v2beta2.JobTrigger.getDefaultInstance()); } /** * <pre> * List of triggeredJobs, up to page_size in ListJobTriggersRequest. * </pre> * * <code>repeated .google.privacy.dlp.v2beta2.JobTrigger job_triggers = 1;</code> */ public java.util.List<com.google.privacy.dlp.v2beta2.JobTrigger.Builder> getJobTriggersBuilderList() { return getJobTriggersFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.privacy.dlp.v2beta2.JobTrigger, com.google.privacy.dlp.v2beta2.JobTrigger.Builder, com.google.privacy.dlp.v2beta2.JobTriggerOrBuilder> getJobTriggersFieldBuilder() { if (jobTriggersBuilder_ == null) { jobTriggersBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.privacy.dlp.v2beta2.JobTrigger, com.google.privacy.dlp.v2beta2.JobTrigger.Builder, com.google.privacy.dlp.v2beta2.JobTriggerOrBuilder>( jobTriggers_, ((bitField0_ & 0x00000001) == 0x00000001), getParentForChildren(), isClean()); jobTriggers_ = null; } return jobTriggersBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * <pre> * If the next page is available then the next page token to be used * in following ListJobTriggers request. * </pre> * * <code>string next_page_token = 2;</code> */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * If the next page is available then the next page token to be used * in following ListJobTriggers request. * </pre> * * <code>string next_page_token = 2;</code> */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * If the next page is available then the next page token to be used * in following ListJobTriggers request. * </pre> * * <code>string next_page_token = 2;</code> */ public Builder setNextPageToken( java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; onChanged(); return this; } /** * <pre> * If the next page is available then the next page token to be used * in following ListJobTriggers request. * </pre> * * <code>string next_page_token = 2;</code> */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); onChanged(); return this; } /** * <pre> * If the next page is available then the next page token to be used * in following ListJobTriggers request. * </pre> * * <code>string next_page_token = 2;</code> */ public Builder setNextPageTokenBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.privacy.dlp.v2beta2.ListJobTriggersResponse) } // @@protoc_insertion_point(class_scope:google.privacy.dlp.v2beta2.ListJobTriggersResponse) private static final com.google.privacy.dlp.v2beta2.ListJobTriggersResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.privacy.dlp.v2beta2.ListJobTriggersResponse(); } public static com.google.privacy.dlp.v2beta2.ListJobTriggersResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListJobTriggersResponse> PARSER = new com.google.protobuf.AbstractParser<ListJobTriggersResponse>() { public ListJobTriggersResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ListJobTriggersResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ListJobTriggersResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListJobTriggersResponse> getParserForType() { return PARSER; } public com.google.privacy.dlp.v2beta2.ListJobTriggersResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
bsd-3-clause
ox-it/gaboto
src/main/java/net/sf/gaboto/node/annotation/SimpleURIProperty.java
2749
/** * Copyright 2009 University of Oxford * * Written by Arno Mittelbach for the Erewhon Project * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package net.sf.gaboto.node.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import net.sf.gaboto.node.GabotoEntity; /** * Used to annotate methods in {@link GabotoEntity}s that deal with simple URI properties. * * <p> * Simple URI properties are properties that consist of exactly 1 RDF triple and * where the object contains the URI of another {@link GabotoEntity}. * </p> * * <p> * An example of this could be the occupiedBy relationship from the Gaboto vocabulary: * <pre> * oxpdata:someBuilding oxp:occupiedBy oxpdata:someCollege . * </pre> * </p> * * @author Arno Mittelbach * @version 0.1 * @see GabotoEntity * @see BagURIProperty * */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface SimpleURIProperty { /** * Returns the URI of the corresponding property. * @return The URI of the corresponding property. */ public String value(); }
bsd-3-clause
cyrilmhansen/ExtJWNL
extjwnl/src/main/java/net/sf/extjwnl/dictionary/morph/LookupIndexWordOperation.java
791
package net.sf.extjwnl.dictionary.morph; import net.sf.extjwnl.JWNLException; import net.sf.extjwnl.data.POS; import net.sf.extjwnl.dictionary.Dictionary; import java.util.Map; /** * Looks up index words. * * @author John Didion <jdidion@didion.net> * @author <a rel="author" href="http://autayeu.com/">Aliaksandr Autayeu</a> */ public class LookupIndexWordOperation extends AbstractOperation { public LookupIndexWordOperation(Dictionary dictionary, Map params) { super(dictionary); } public boolean execute(POS pos, String lemma, BaseFormSet baseForms) throws JWNLException { if (dictionary.getIndexWord(pos, lemma) != null) { baseForms.add(lemma); return true; } return false; } }
bsd-3-clause