answer
stringlengths
17
10.2M
package net.zero918nobita.Xemime; import org.junit.Test; import java.util.HashMap; import static org.junit.Assert.assertThat; import static org.hamcrest.CoreMatchers.is; public class FrameTest { @Test public void test() throws Exception { Main.defValue(new X_Symbol("variable"), new X_String("global")); Main.loadLocalFrame(new HashMap<>()); Main.defValue(new X_Symbol("variable"), new X_String("local")); assertThat(Main.frame.numberOfLayers(), is(1)); assertThat(Main.getValueOfSymbol(new X_Symbol("variable")), is(new X_String("local"))); Main.unloadLocalFrame(); assertThat(Main.getValueOfSymbol(new X_Symbol("variable")), is(new X_String("global"))); } }
package sizebay.catalog.client; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import sizebay.catalog.client.http.ApiException; import sizebay.catalog.client.model.*; import sizebay.catalog.client.model.Modeling.Gender; import sizebay.catalog.client.model.ModelingSizeMeasures.SizeName; import java.util.Arrays; import static org.junit.Assert.*; import static sizebay.catalog.client.model.Product.Wearability.*; public class ExempleTest { final CatalogAPI api = new CatalogAPI( "testTenant", "secretTestTenant" ); @Before public void cleanUp(){ api.deleteCategories(); api.deleteBrands(); api.deleteModelings(); api.deleteProducts(); } @Test public void ensureThatCanCreateCategories(){ final Category category = new Category(); category.setName("Category Test"); final long id = api.insertCategory(category); final Category category1 = api.getCategory(id); assertEquals( category.getName(), category1.getName() ); assertEquals( id, category1.getId().longValue() ); api.deleteCategories(); try { assertNull( api.getCategory(id) ); fail( "Category wasn't removed" ); } catch (ApiException cause) {} } @Test //@Ignore public void ensureThatCreatesAProduct() { // criando uma marca final long brandId = createABrand(); assertNotEquals( -1, brandId ); System.out.println( "Just created a brand: " + brandId ); // criando uma modelagem (tabela de medidas) final long modelingId = createModeling( brandId ); System.out.println( "Just created a modeling: " + modelingId ); // criando um produto final Product product = new Product(); product.setModelingId( modelingId ); product.setName( "Produto" ); product.setWearability( REGULAR ); product.setCategoryId( 6l ); product.setAvailableSizes( Arrays.asList( SizeName.XXXL ) ); product.setImages( Arrays.asList( "http://teste.com/p.png" ) ); product.setPermalink("http://teste.com/p"); final long productId = api.insertProduct( product ); System.out.println( "Just created product " + productId ); } private long createABrand() { final Brand brand = new Brand(); brand.setName( "Minha Marca" ); return api.insertBrand( brand ); } private long createModeling( final long brandId ) { final ModelingSizeMeasures measures = new ModelingSizeMeasures(); measures.setSizeName( SizeName.XXXL ); measures.setHip( range( 50, 60 ) ); measures.setWaist( range( 70, 80 ) ); measures.setChest( range( 55, 75 ) ); final Modeling modeling = new Modeling(); modeling.setName( "Tabela de Medida A" ); modeling.setBrandId( brandId ); modeling.setGender( Gender.M ); modeling.setSizeMeasures( Arrays.asList( measures ) ); return api.insertModeling( modeling ); } private ModelingMeasureRange range( long initialValue, long finalValue ) { final ModelingMeasureRange range = new ModelingMeasureRange(); range.setInitialValue( initialValue ); range.setFinalValue( finalValue ); return range; } }
package org.spine3.protobuf; import com.google.common.collect.ImmutableSet; import org.junit.Test; import org.spine3.base.Command; import org.spine3.base.CommandContext; import org.spine3.protobuf.error.UnknownTypeException; import org.spine3.type.ClassName; import org.spine3.type.TypeName; import static org.junit.Assert.*; import static org.spine3.test.Tests.hasPrivateUtilityConstructor; /** * @author Alexander Litus */ @SuppressWarnings("InstanceMethodNamingConvention") public class TypeToClassMapShould { @Test public void have_private_constructor() { assertTrue(hasPrivateUtilityConstructor(TypeToClassMap.class)); } @Test public void return_known_proto_message_types() { final ImmutableSet<TypeName> types = TypeToClassMap.knownTypes(); assertFalse(types.isEmpty()); } @Test public void return_java_class_name_by_proto_type_name() { final TypeName typeName = TypeName.of(Command.getDescriptor()); final ClassName className = TypeToClassMap.get(typeName); assertEquals(ClassName.of(Command.class), className); } @Test public void return_java_inner_class_name_by_proto_type_name() { final TypeName typeName = TypeName.of(CommandContext.Schedule.getDescriptor()); final ClassName className = TypeToClassMap.get(typeName); assertEquals(ClassName.of(CommandContext.Schedule.class), className); } @Test public void return_proto_type_name_by_java_class_name() { final ClassName className = ClassName.of(Command.class); final TypeName typeName = TypeToClassMap.get(className); assertEquals(TypeName.of(Command.getDescriptor()), typeName); } @Test(expected = IllegalStateException.class) public void throw_exception_if_no_proto_type_name_by_java_class_name() { TypeToClassMap.get(ClassName.of(Exception.class)); } @Test(expected = UnknownTypeException.class) public void throw_exception_if_no_java_class_name_by_proto_type_name() { TypeToClassMap.get(TypeName.of("unexpected.type")); } }
package org.jimmutable.cloud.storage.s3; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.commons.io.input.CloseShieldInputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jimmutable.cloud.ApplicationId; import org.jimmutable.cloud.cache.CacheKey; import org.jimmutable.cloud.storage.GenericStorageKey; import org.jimmutable.cloud.storage.ObjectIdStorageKey; import org.jimmutable.cloud.storage.StandardImmutableObjectCache; import org.jimmutable.cloud.storage.Storage; import org.jimmutable.cloud.storage.StorageKey; import org.jimmutable.cloud.storage.StorageKeyExtension; import org.jimmutable.cloud.storage.StorageKeyName; import org.jimmutable.cloud.storage.StorageMetadata; import org.jimmutable.core.objects.StandardImmutableObject; import org.jimmutable.core.objects.StandardObject; import org.jimmutable.core.objects.common.Kind; import org.jimmutable.core.objects.common.ObjectId; import org.jimmutable.core.utils.IOUtils; //import org.jimmutable.core.utils.IOUtils; import org.jimmutable.core.utils.Validator; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.AmazonS3Exception; import com.amazonaws.services.s3.model.CreateBucketRequest; import com.amazonaws.services.s3.model.DeleteObjectRequest; import com.amazonaws.services.s3.model.GetObjectRequest; import com.amazonaws.services.s3.model.ListObjectsRequest; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectSummary; import com.amazonaws.services.s3.transfer.Download; import com.amazonaws.services.s3.transfer.Transfer.TransferState; import com.amazonaws.services.s3.transfer.TransferManager; import com.amazonaws.services.s3.transfer.TransferManagerBuilder; import com.amazonaws.services.s3.transfer.Upload; public class StorageS3 extends Storage { static private final Logger LOGGER = LogManager.getLogger(StorageS3.class); static private final String BUCKET_NAME_PREFIX = "jimmutable-app-"; static private final long TRANSFER_MANAGER_POLLING_INTERVAL_MS = 500L; final private String bucket_name; final private AmazonS3Client client; final private TransferManager transfer_manager; // Since this will be init'd in CEE.startup, we can't rely on the singleton for // access to the ApplicationId public StorageS3( final AmazonS3ClientFactory client_factory, final ApplicationId application_id, final boolean is_read_only ) { super(is_read_only); bucket_name = BUCKET_NAME_PREFIX + application_id; Validator.notNull(client_factory); client = client_factory.create(); transfer_manager = TransferManagerBuilder.standard().withS3Client(client).build(); } public StorageS3( final AmazonS3ClientFactory client_factory, final ApplicationId application_id, StandardImmutableObjectCache cache, final boolean is_read_only ) { super(is_read_only, cache); bucket_name = BUCKET_NAME_PREFIX + application_id; Validator.notNull(client_factory); client = client_factory.create(); transfer_manager = TransferManagerBuilder.standard().withS3Client(client).build(); } public void upsertBucketIfNeeded() { if ( !client.doesBucketExist(bucket_name) ) { LOGGER.info("creating bucket: " + bucket_name); CreateBucketRequest request = new CreateBucketRequest(bucket_name, RegionSpecificAmazonS3ClientFactory.DEFAULT_REGION); client.createBucket(request); } else { LOGGER.info("using storage bucket: " + bucket_name); } } public String getSimpleBucketName() { return bucket_name; } @Override public boolean exists( final StorageKey key, final boolean default_value ) { try { return client.doesObjectExist(bucket_name, key.toString()); } catch ( Exception e ) { LOGGER.catching(e); return default_value; } } // TODO Use hint_content_likely_to_be_compressible to auto-gzip contents. Must // be able to detect dynamically on read. @Override public boolean upsert( StorageKey key, byte[] bytes, boolean hint_content_likely_to_be_compressible ) { Validator.max(bytes.length, MAX_TRANSFER_BYTES_IN_BYTES); if ( isReadOnly() ) return false; try { InputStream bin = new ByteArrayInputStream(bytes); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(bytes.length); client.putObject(bucket_name, key.toString(), bin, metadata); if ( isCacheEnabled() ) { removeFromCache(key.getSimpleKind(), new ObjectId(key.getSimpleName().getSimpleValue())); } return true; } catch ( Exception e ) { LOGGER.catching(e); return false; } } // TODO Use hint_content_likely_to_be_compressible to auto-gzip contents. Must // be able to detect dynamically on read. @Override public boolean upsertStreaming( final StorageKey key, final InputStream source, final boolean hint_content_likely_to_be_compressible ) { Validator.notNull(key, source); if ( isReadOnly() ) return false; if ( isCacheEnabled() ) { removeFromCache(key.getSimpleKind(), new ObjectId(key.getSimpleName().getSimpleValue())); } final String log_prefix = "[upsert(" + key + ")] "; File temp = null; try { temp = File.createTempFile("storage_s3_", null); System.out.println("Temp file On Default Location: " + temp.getAbsolutePath()); LOGGER.debug(log_prefix + "Writing source to temp file"); try ( OutputStream fout = new BufferedOutputStream(new FileOutputStream(temp)) ) { IOUtils.transferAllBytes(source, fout); } final String s3_key = key.toString(); Upload upload = null; try { upload = transfer_manager.upload(bucket_name, s3_key, temp); LOGGER.info(log_prefix + "Upload: " + upload.getDescription()); while ( !upload.isDone() ) { LOGGER.debug(log_prefix + "Progress: " + upload.getProgress().getPercentTransferred()); try { Thread.sleep(TRANSFER_MANAGER_POLLING_INTERVAL_MS); } catch ( Exception e ) { } // give progress updates every .5 sec } LOGGER.debug(log_prefix + "Progress: " + upload.getProgress().getPercentTransferred()); // give the 100 // percent // before // exiting boolean result = TransferState.Completed == upload.getState(); // if ( result && isCacheEnabled() ) // removeFromCache(key.getSimpleKind(), new ObjectId(key.getSimpleName().getSimpleValue())); deleteTempFile(temp); return result; } catch ( Exception e ) { LOGGER.catching(e); upload.abort(); } } catch ( Exception e ) { LOGGER.catching(e); } deleteTempFile(temp); return false; } /** * Similar to getCurrentVerionStreaming, except there is a maximum byte range. * * @param key * @param default_value * @return */ @Override public byte[] getCurrentVersion( final StorageKey key, byte[] default_value ) { byte[] object = getComplexCurrentVersionFromCache(key, null); if ( object != null ) { return object; } Validator.notNull(key, "StorageKey"); S3Object s3_obj = null; try { s3_obj = client.getObject(new GetObjectRequest(bucket_name, key.toString()).withRange(0, MAX_TRANSFER_BYTES_IN_BYTES)); byte[] obj = org.apache.commons.io.IOUtils.toByteArray(s3_obj.getObjectContent()); if ( isCacheEnabled() ) { try { if ( key.getSimpleExtension().equals(StorageKeyExtension.XML) || key.getSimpleExtension().equals(StorageKeyExtension.JSON) ) { StandardObject standard_obj = StandardObject.deserialize(new String(obj)); if ( standard_obj instanceof StandardImmutableObject ) { addToStandardImmutableObjectCache(key.getSimpleKind(), new ObjectId(key.getSimpleName().getSimpleValue()), (StandardImmutableObject) standard_obj); } } } catch ( Exception e ) { LogManager.getRootLogger().error("Failure to make into a StandardImmutableObject " + key.toString() + ". This object is not in the cache.", e); } } return obj; } catch ( Exception e ) { LOGGER.error(String.format("Failed to retrieve %s from S3!", key.toString()), e); } finally { if ( s3_obj != null ) { try { s3_obj.close(); } catch ( IOException e ) { LOGGER.error(String.format("Failed to close S3Object when reading %s!", key.toString()), e); } } } return default_value; } /** * Note: calling getObject always returns a stream anyways * * @param key * @param default_value * @return */ @Override public boolean getCurrentVersionStreaming( final StorageKey key, final OutputStream sink ) { long start = System.currentTimeMillis(); Validator.notNull(key, "StorageKey"); byte[] object = getComplexCurrentVersionFromCache(key, null); if ( object != null ) { try { IOUtils.transferAllBytes(new ByteArrayInputStream(object), sink); return true; } catch ( IOException e ) { // we do not return false here because we want to try to get it from storage. } } S3Object s3_obj = null; try { s3_obj = client.getObject(new GetObjectRequest(bucket_name, key.toString())); org.apache.commons.io.IOUtils.copy(s3_obj.getObjectContent(), sink); LOGGER.debug(String.format("Took %d millis", System.currentTimeMillis() - start)); return true; } catch ( Exception e ) { LOGGER.error(String.format("Failed to retrieve %s from S3!", key.toString()), e); } finally { if ( s3_obj != null ) { try { s3_obj.close(); } catch ( IOException e ) { LOGGER.error(String.format("Failed to close S3Object when reading %s!", key.toString()), e); } } } return false; } /** * old getCurrentVersionStreaming method. This method takes longer and may not * be needed for now. We may need to * * @param key * @param sink * @return */ @Override public boolean getThreadedCurrentVersionStreaming( final StorageKey key, final OutputStream sink ) { long start = System.currentTimeMillis(); Validator.notNull(key, sink); final String log_prefix = "[getCurrentVersion(" + key + ")] "; File temp = null; try { final String s3_key = key.toString(); temp = File.createTempFile("storage_s3_", null); Download download = null; try { download = transfer_manager.download(bucket_name, s3_key, temp); LOGGER.debug(log_prefix + "Download: " + download.getDescription()); while ( !download.isDone() ) { LOGGER.debug(log_prefix + "Progress: " + download.getProgress().getPercentTransferred()); try { Thread.sleep(TRANSFER_MANAGER_POLLING_INTERVAL_MS); } catch ( Exception e ) { } // give progress updates every .5 sec } /* * give the 100 percent before exiting */ LOGGER.info(log_prefix + "Progress: " + download.getProgress().getPercentTransferred()); } catch ( Exception e ) { deleteTempFile(temp); LOGGER.catching(e); download.abort(); return false; } LOGGER.debug(log_prefix + "Writing temp file to sink"); try ( InputStream fin = new BufferedInputStream(new FileInputStream(temp)) ) { IOUtils.transferAllBytes(fin, sink); } boolean completed = TransferState.Completed == download.getState(); LOGGER.debug(String.format("Took %d millis", System.currentTimeMillis() - start)); deleteTempFile(temp); return completed; } catch ( Exception e ) { LOGGER.catching(e); } deleteTempFile(temp); return false; } private void deleteTempFile( File temp ) { if(temp == null || !temp.exists()) { return; } try { if ( !temp.delete() ) { LOGGER.error("Unable to delete temp file. Ensure this isn't happening consistently"); } } catch ( Exception e ) { LOGGER.error("Exception thrown deleting temp file. Ensure this isn't happening consistently", e); } } @Override public boolean delete( final StorageKey key ) { if ( isReadOnly() ) return false; try { client.deleteObject(new DeleteObjectRequest(bucket_name, key.toString())); if ( isCacheEnabled() ) { removeFromCache(key); } return true; } catch ( Exception e ) { LOGGER.catching(e); return false; } } @Override public StorageMetadata getObjectMetadata( final StorageKey key, final StorageMetadata default_value ) { try { ObjectMetadata s3_metadata = client.getObjectMetadata(bucket_name, key.toString()); long last_modified = s3_metadata.getLastModified().getTime(); long size = s3_metadata.getContentLength(); String etag = s3_metadata.getETag(); return new StorageMetadata(last_modified, size, etag); } catch ( AmazonS3Exception e ) { // We get a 404 Not Found for any object that doesn't exist. // A separate doesObjectExist call would be an entire extra // network round trip... so just special case it. if ( 404 == e.getStatusCode() ) { return default_value; } throw e; } catch ( Exception e ) { LOGGER.catching(e); return default_value; } } /** * This class does the main listing operation for scan*. It runs in it's own * thread and throws each StorageKey it finds into another OperationRunnable * running in a common pool. * * @author Jeff Dezso */ private class Scanner extends Storage.Scanner { public Scanner( final Kind kind, final StorageKeyName prefix, final boolean only_object_ids ) { super(kind, prefix, only_object_ids); } @Override protected Result performOperation() throws Exception { String root = getSimpleKind().getSimpleValue(); if ( hasPrefix() ) { root += "/" + getOptionalPrefix(null); } ListObjectsRequest request = new ListObjectsRequest(bucket_name, root + "/", null, null, -1); while ( true ) { ObjectListing object_listing = client.listObjects(request); if ( null == object_listing ) return Result.ERROR; for ( S3ObjectSummary summary : object_listing.getObjectSummaries() ) { final String key = summary.getKey(); // The full S3 key, also the StorageKey final String full_key_name = key.substring(root.length() + 1); // The "filename" without the // backslash // This would be the folder of the Kind we are looking at if ( full_key_name.isEmpty() ) continue; String[] key_name_and_ext = full_key_name.split("\\."); String key_name = key_name_and_ext[0]; StorageKeyName name = null; try { name = new StorageKeyName(key_name); } catch ( Exception e ) { LOGGER.error(String.format("[StorageS3.performOperation] could not create StorageKeyName for key:%s root:%s bucket:%s request:%s", key, root, bucket_name, request), e); continue; } if ( name.isObjectId() ) { emit(new ObjectIdStorageKey(key)); } else { if ( !onlyObjectIds() ) { emit(new GenericStorageKey(key)); } } } if ( !object_listing.isTruncated() ) break; request.setMarker(object_listing.getNextMarker()); } return shouldStop() ? Result.STOPPED : Result.SUCCESS; } } @Override protected Storage.Scanner createScanner( Kind kind, StorageKeyName prefix, boolean only_object_ids ) { return new Scanner(kind, prefix, only_object_ids); } }
// jTDS JDBC Driver for Microsoft SQL Server and Sybase // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package net.sourceforge.jtds.jdbc; import java.sql.*; import java.math.BigDecimal; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * @version 1.0 */ public class ResultSetTest extends DatabaseTestCase { public ResultSetTest(String name) { super(name); } /** * Test BIT data type. */ public void testGetObject1() throws Exception { boolean data = true; Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #getObject1 (data BIT, minval BIT, maxval BIT)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #getObject1 (data, minval, maxval) VALUES (?, ?, ?)"); pstmt.setBoolean(1, data); pstmt.setBoolean(2, false); pstmt.setBoolean(3, true); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); Statement stmt2 = con.createStatement(); ResultSet rs = stmt2.executeQuery("SELECT data, minval, maxval FROM #getObject1"); assertTrue(rs.next()); assertTrue(rs.getBoolean(1)); assertTrue(rs.getByte(1) == 1); assertTrue(rs.getShort(1) == 1); assertTrue(rs.getInt(1) == 1); assertTrue(rs.getLong(1) == 1); assertTrue(rs.getFloat(1) == 1); assertTrue(rs.getDouble(1) == 1); assertTrue(rs.getBigDecimal(1).byteValue() == 1); assertEquals("1", rs.getString(1)); Object tmpData = rs.getObject(1); assertTrue(tmpData instanceof Boolean); assertEquals(true, ((Boolean) tmpData).booleanValue()); ResultSetMetaData resultSetMetaData = rs.getMetaData(); assertNotNull(resultSetMetaData); assertEquals(Types.BIT, resultSetMetaData.getColumnType(1)); assertFalse(rs.getBoolean(2)); assertTrue(rs.getBoolean(3)); assertFalse(rs.next()); stmt2.close(); rs.close(); } /** * Test TINYINT data type. */ public void testGetObject2() throws Exception { byte data = 1; Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #getObject2 (data TINYINT, minval TINYINT, maxval TINYINT)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #getObject2 (data, minval, maxval) VALUES (?, ?, ?)"); pstmt.setByte(1, data); pstmt.setByte(2, (byte)0); pstmt.setShort(3, (short)255); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); Statement stmt2 = con.createStatement(); ResultSet rs = stmt2.executeQuery("SELECT data, minval, maxval FROM #getObject2"); assertTrue(rs.next()); assertTrue(rs.getBoolean(1)); assertTrue(rs.getByte(1) == 1); assertTrue(rs.getShort(1) == 1); assertTrue(rs.getInt(1) == 1); assertTrue(rs.getLong(1) == 1); assertTrue(rs.getFloat(1) == 1); assertTrue(rs.getDouble(1) == 1); assertTrue(rs.getBigDecimal(1).byteValue() == 1); assertEquals("1", rs.getString(1)); Object tmpData = rs.getObject(1); assertTrue(tmpData instanceof Integer); assertEquals(data, ((Integer) tmpData).byteValue()); ResultSetMetaData resultSetMetaData = rs.getMetaData(); assertNotNull(resultSetMetaData); assertEquals(Types.TINYINT, resultSetMetaData.getColumnType(1)); assertEquals(rs.getByte(2), 0); assertEquals(rs.getShort(3), 255); assertFalse(rs.next()); stmt2.close(); rs.close(); } /** * Test SMALLINT data type. */ public void testGetObject3() throws Exception { short data = 1; Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #getObject3 (data SMALLINT, minval SMALLINT, maxval SMALLINT)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #getObject3 (data, minval, maxval) VALUES (?, ?, ?)"); pstmt.setShort(1, data); pstmt.setShort(2, Short.MIN_VALUE); pstmt.setShort(3, Short.MAX_VALUE); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); Statement stmt2 = con.createStatement(); ResultSet rs = stmt2.executeQuery("SELECT data, minval, maxval FROM #getObject3"); assertTrue(rs.next()); assertTrue(rs.getBoolean(1)); assertTrue(rs.getByte(1) == 1); assertTrue(rs.getShort(1) == 1); assertTrue(rs.getInt(1) == 1); assertTrue(rs.getLong(1) == 1); assertTrue(rs.getFloat(1) == 1); assertTrue(rs.getDouble(1) == 1); assertTrue(rs.getBigDecimal(1).shortValue() == 1); assertEquals("1", rs.getString(1)); Object tmpData = rs.getObject(1); assertTrue(tmpData instanceof Integer); assertEquals(data, ((Integer) tmpData).shortValue()); ResultSetMetaData resultSetMetaData = rs.getMetaData(); assertNotNull(resultSetMetaData); assertEquals(Types.SMALLINT, resultSetMetaData.getColumnType(1)); assertEquals(rs.getShort(2), Short.MIN_VALUE); assertEquals(rs.getShort(3), Short.MAX_VALUE); assertFalse(rs.next()); stmt2.close(); rs.close(); } /** * Test INT data type. */ public void testGetObject4() throws Exception { int data = 1; Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #getObject4 (data INT, minval INT, maxval INT)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #getObject4 (data, minval, maxval) VALUES (?, ?, ?)"); pstmt.setInt(1, data); pstmt.setInt(2, Integer.MIN_VALUE); pstmt.setInt(3, Integer.MAX_VALUE); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); Statement stmt2 = con.createStatement(); ResultSet rs = stmt2.executeQuery("SELECT data, minval, maxval FROM #getObject4"); assertTrue(rs.next()); assertTrue(rs.getBoolean(1)); assertTrue(rs.getByte(1) == 1); assertTrue(rs.getShort(1) == 1); assertTrue(rs.getInt(1) == 1); assertTrue(rs.getLong(1) == 1); assertTrue(rs.getFloat(1) == 1); assertTrue(rs.getDouble(1) == 1); assertTrue(rs.getBigDecimal(1).intValue() == 1); assertEquals("1", rs.getString(1)); Object tmpData = rs.getObject(1); assertTrue(tmpData instanceof Integer); assertEquals(data, ((Integer) tmpData).intValue()); ResultSetMetaData resultSetMetaData = rs.getMetaData(); assertNotNull(resultSetMetaData); assertEquals(Types.INTEGER, resultSetMetaData.getColumnType(1)); assertEquals(rs.getInt(2), Integer.MIN_VALUE); assertEquals(rs.getInt(3), Integer.MAX_VALUE); assertFalse(rs.next()); stmt2.close(); rs.close(); } /** * Test BIGINT data type. */ public void testGetObject5() throws Exception { long data = 1; Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #getObject5 (data DECIMAL(28, 0), minval DECIMAL(28, 0), maxval DECIMAL(28, 0))"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #getObject5 (data, minval, maxval) VALUES (?, ?, ?)"); pstmt.setLong(1, data); pstmt.setLong(2, Long.MIN_VALUE); pstmt.setLong(3, Long.MAX_VALUE); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); Statement stmt2 = con.createStatement(); ResultSet rs = stmt2.executeQuery("SELECT data, minval, maxval FROM #getObject5"); assertTrue(rs.next()); assertTrue(rs.getBoolean(1)); assertTrue(rs.getByte(1) == 1); assertTrue(rs.getShort(1) == 1); assertTrue(rs.getInt(1) == 1); assertTrue(rs.getLong(1) == 1); assertTrue(rs.getFloat(1) == 1); assertTrue(rs.getDouble(1) == 1); assertTrue(rs.getBigDecimal(1).longValue() == 1); assertEquals("1", rs.getString(1)); Object tmpData = rs.getObject(1); assertTrue(tmpData instanceof BigDecimal); assertEquals(data, ((BigDecimal) tmpData).longValue()); ResultSetMetaData resultSetMetaData = rs.getMetaData(); assertNotNull(resultSetMetaData); assertEquals(Types.DECIMAL, resultSetMetaData.getColumnType(1)); assertEquals(rs.getLong(2), Long.MIN_VALUE); assertEquals(rs.getLong(3), Long.MAX_VALUE); assertFalse(rs.next()); stmt2.close(); rs.close(); } /** * Test for bug [961594] ResultSet. */ public void testResultSetScroll1() throws Exception { int count = 125; Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #resultSetScroll1 (data INT)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #resultSetScroll1 (data) VALUES (?)"); for (int i = 1; i <= count; i++) { pstmt.setInt(1, i); assertEquals(1, pstmt.executeUpdate()); } pstmt.close(); Statement stmt2 = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt2.executeQuery("SELECT data FROM #resultSetScroll1"); assertTrue(rs.last()); assertEquals(count, rs.getRow()); stmt2.close(); rs.close(); } /** * Test for bug [945462] getResultSet() return null if you use scrollable/updatable. */ public void testResultSetScroll2() throws Exception { Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #resultSetScroll2 (data INT)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #resultSetScroll2 (data) VALUES (?)"); pstmt.setInt(1, 1); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); Statement stmt2 = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt2.executeQuery("SELECT data FROM #resultSetScroll2"); ResultSet rs = stmt2.getResultSet(); assertNotNull(rs); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertFalse(rs.next()); stmt2.close(); rs.close(); } /** * Test for bug [1028881] statement.execute() causes wrong ResultSet type. */ public void testResultSetScroll3() throws Exception { Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #resultSetScroll3 (data INT)"); stmt.execute("CREATE PROCEDURE #procResultSetScroll3 AS SELECT data FROM #resultSetScroll3"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #resultSetScroll3 (data) VALUES (?)"); pstmt.setInt(1, 1); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); // Test plain Statement Statement stmt2 = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); assertTrue("Was expecting a ResultSet", stmt2.execute("SELECT data FROM #resultSetScroll3")); ResultSet rs = stmt2.getResultSet(); assertEquals("ResultSet not scrollable", ResultSet.TYPE_SCROLL_INSENSITIVE, rs.getType()); rs.close(); stmt2.close(); // Test PreparedStatement pstmt = con.prepareStatement("SELECT data FROM #resultSetScroll3", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); assertTrue("Was expecting a ResultSet", pstmt.execute()); rs = pstmt.getResultSet(); assertEquals("ResultSet not scrollable", ResultSet.TYPE_SCROLL_INSENSITIVE, rs.getType()); rs.close(); pstmt.close(); // Test CallableStatement CallableStatement cstmt = con.prepareCall("{call #procResultSetScroll3}", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); assertTrue("Was expecting a ResultSet", cstmt.execute()); rs = cstmt.getResultSet(); assertEquals("ResultSet not scrollable", ResultSet.TYPE_SCROLL_INSENSITIVE, rs.getType()); rs.close(); cstmt.close(); } /** * Test for bug [1008208] 0.9-rc1 updateNull doesn't work. */ public void testResultSetUpdate1() throws Exception { Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #resultSetUpdate1 (id INT PRIMARY KEY, dsi SMALLINT NULL, di INT NULL)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #resultSetUpdate1 (id, dsi, di) VALUES (?, ?, ?)"); pstmt.setInt(1, 1); pstmt.setShort(2, (short) 1); pstmt.setInt(3, 1); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); stmt.executeQuery("SELECT id, dsi, di FROM #resultSetUpdate1"); ResultSet rs = stmt.getResultSet(); assertNotNull(rs); assertTrue(rs.next()); rs.updateNull("dsi"); rs.updateNull("di"); rs.updateRow(); rs.moveToInsertRow(); rs.updateInt(1, 2); rs.updateNull("dsi"); rs.updateNull("di"); rs.insertRow(); stmt.close(); rs.close(); stmt = con.createStatement(); stmt.executeQuery("SELECT id, dsi, di FROM #resultSetUpdate1 ORDER BY id"); rs = stmt.getResultSet(); assertNotNull(rs); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); rs.getShort(2); assertTrue(rs.wasNull()); rs.getInt(3); assertTrue(rs.wasNull()); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); rs.getShort(2); assertTrue(rs.wasNull()); rs.getInt(3); assertTrue(rs.wasNull()); assertFalse(rs.next()); stmt.close(); rs.close(); } /** * Test for bug [1009233] ResultSet getColumnName, getColumnLabel return wrong values */ public void testResultSetColumnName1() throws Exception { Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #resultSetCN1 (data INT)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #resultSetCN1 (data) VALUES (?)"); pstmt.setInt(1, 1); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); Statement stmt2 = con.createStatement(); stmt2.executeQuery("SELECT data as test FROM #resultSetCN1"); ResultSet rs = stmt2.getResultSet(); assertNotNull(rs); assertTrue(rs.next()); assertEquals(1, rs.getInt("test")); assertFalse(rs.next()); stmt2.close(); rs.close(); } /** * Test for fixed bugs in ResultSetMetaData: * <ol> * <li>isNullable() always returns columnNoNulls. * <li>isSigned returns true in error for TINYINT columns. * <li>Type names for numeric / decimal have (prec,scale) appended in error. * <li>Type names for auto increment columns do not have "identity" appended. * <li>table names are empty when not using cursors, bug [1833720]</li> * </ol> * NB: This test assumes getColumnName has been fixed to work as per the suggestion * in bug report [1009233]. * * @throws Exception */ public void testResultSetMetaData() throws Exception { // Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #TRSMD (id INT IDENTITY NOT NULL, byte TINYINT NOT NULL, num DECIMAL(28,10) NULL)"); ResultSetMetaData rsmd = stmt.executeQuery("SELECT id as idx, byte, num FROM #TRSMD").getMetaData(); assertNotNull(rsmd); // Check id assertEquals("idx", rsmd.getColumnName(1)); // no longer returns base name assertEquals("idx", rsmd.getColumnLabel(1)); assertTrue(rsmd.isAutoIncrement(1)); assertTrue(rsmd.isSigned(1)); assertEquals(ResultSetMetaData.columnNoNulls, rsmd.isNullable(1)); assertEquals("int identity", rsmd.getColumnTypeName(1)); assertEquals(Types.INTEGER, rsmd.getColumnType(1)); // Check byte assertFalse(rsmd.isAutoIncrement(2)); assertFalse(rsmd.isSigned(2)); assertEquals(ResultSetMetaData.columnNoNulls, rsmd.isNullable(2)); assertEquals("tinyint", rsmd.getColumnTypeName(2)); assertEquals(Types.TINYINT, rsmd.getColumnType(2)); // Check num assertFalse(rsmd.isAutoIncrement(3)); assertTrue(rsmd.isSigned(3)); assertEquals(ResultSetMetaData.columnNullable, rsmd.isNullable(3)); assertEquals("decimal", rsmd.getColumnTypeName(3)); assertEquals(Types.DECIMAL, rsmd.getColumnType(3)); assertEquals("#TRSMD", rsmd.getTableName(1)); stmt.close(); } /** * Test for bug [1022445] Cursor downgrade warning not raised. */ public void testCursorWarning() throws Exception { Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #TESTCW (id INT PRIMARY KEY, DATA VARCHAR(255))"); stmt.execute("CREATE PROC #SPTESTCW @P0 INT OUTPUT AS SELECT * FROM #TESTCW"); stmt.close(); CallableStatement cstmt = con.prepareCall("{call #SPTESTCW(?)}", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); cstmt.registerOutParameter(1, Types.INTEGER); ResultSet rs = cstmt.executeQuery(); // This should generate a ResultSet type/concurrency downgraded error. assertNotNull(rs.getWarnings()); cstmt.close(); } /** * Test that the cursor fallback logic correctly discriminates between * "real" sql errors and cursor open failures. * <p/> * This illustrates the logic added to fix: * <ol> * <li>[1323363] Deadlock Exception not reported (SQL Server)</li> * <li>[1283472] Unable to cancel statement with cursor resultset</li> * </ol> */ public void testCursorFallback() throws Exception { Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // This test should fail on the cursor open but fall back to normal // execution returning two result sets stmt.execute("CREATE PROC #testcursor as SELECT 'data' select 'data2'"); stmt.execute("exec #testcursor"); assertNotNull(stmt.getWarnings()); ResultSet rs = stmt.getResultSet(); assertNotNull(rs); // First result set OK assertTrue(stmt.getMoreResults()); rs = stmt.getResultSet(); assertNotNull(rs); // Second result set OK // This test should fail on the cursor open (because of the for browse) // but fall back to normal execution returning a single result set rs = stmt.executeQuery("SELECT description FROM master..sysmessages FOR BROWSE"); assertNotNull(rs); assertNotNull(rs.getWarnings()); rs.close(); // Enable logging to see that this test should just fail without // attempting to fall back on normal execution. // DriverManager.setLogStream(System.out); try { stmt.executeQuery("select bad from syntax"); fail("Expected SQLException"); } catch (SQLException e) { assertEquals("S0002", e.getSQLState()); } // DriverManager.setLogStream(null); stmt.close(); } /** * Test for bug [1246270] Closing a statement after canceling it throws an * exception. */ public void testCancelResultSet() throws Exception { Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #TEST (id int primary key, data varchar(255))"); for (int i = 1; i < 1000; i++) { stmt.executeUpdate("INSERT INTO #TEST VALUES (" + i + ", 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')"); } ResultSet rs = stmt.executeQuery("SELECT * FROM #TEST"); assertNotNull(rs); assertTrue(rs.next()); stmt.cancel(); stmt.close(); } /** * Test whether retrieval by name returns the first occurence (that's what * the spec requires). */ public void testGetByName() throws Exception { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT 1 myCol, 2 myCol, 3 myCol"); assertTrue(rs.next()); assertEquals(1, rs.getInt("myCol")); assertFalse(rs.next()); stmt.close(); } /** * Test if COL_INFO packets are processed correctly for * <code>ResultSet</code>s with over 255 columns. */ public void testMoreThan255Columns() throws Exception { Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); // create the table int cols = 260; StringBuffer create = new StringBuffer("create table #manycolumns ("); for (int i=0; i<cols; ++i) { create.append("col" + i + " char(10), ") ; } create.append(")"); stmt.executeUpdate(create.toString()); String query = "select * from #manycolumns"; ResultSet rs = stmt.executeQuery(query); rs.close(); stmt.close(); } /** * Test that <code>insertRow()</code> works with no values set. */ public void testEmptyInsertRow() throws Exception { int rows = 10; Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); stmt.executeUpdate( "create table #emptyInsertRow (id int identity, val int default 10)"); ResultSet rs = stmt.executeQuery("select * from #emptyInsertRow"); for (int i=0; i<rows; i++) { rs.moveToInsertRow(); rs.insertRow(); } rs.close(); rs = stmt.executeQuery("select count(*) from #emptyInsertRow"); assertTrue(rs.next()); assertEquals(rows, rs.getInt(1)); rs.close(); rs = stmt.executeQuery("select * from #emptyInsertRow order by id"); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals(10, rs.getInt(2)); rs.close(); stmt.close(); } /** * Test that inserted rows are visible in a scroll sensitive * <code>ResultSet</code> and that they show up at the end. */ public void testInsertRowVisible() throws Exception { int rows = 10; Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.executeUpdate( "create table #insertRowNotVisible (val int primary key)"); ResultSet rs = stmt.executeQuery("select * from #insertRowNotVisible"); for (int i = 1; i <= rows; i++) { rs.moveToInsertRow(); rs.updateInt(1, i); rs.insertRow(); rs.moveToCurrentRow(); rs.last(); assertEquals(i, rs.getRow()); } rs.close(); stmt.close(); } /** * Test that updated rows are marked as deleted and the new values inserted * at the end of the <code>ResultSet</code> if the primary key is updated. */ public void testUpdateRowDuplicatesRow() throws Exception { Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.executeUpdate( "create table #updateRowDuplicatesRow (val int primary key)"); stmt.executeUpdate( "insert into #updateRowDuplicatesRow (val) values (1)"); stmt.executeUpdate( "insert into #updateRowDuplicatesRow (val) values (2)"); stmt.executeUpdate( "insert into #updateRowDuplicatesRow (val) values (3)"); ResultSet rs = stmt.executeQuery( "select val from #updateRowDuplicatesRow order by val"); for (int i = 0; i < 3; i++) { assertTrue(rs.next()); assertFalse(rs.rowUpdated()); assertFalse(rs.rowInserted()); assertFalse(rs.rowDeleted()); rs.updateInt(1, rs.getInt(1) + 10); rs.updateRow(); assertFalse(rs.rowUpdated()); assertFalse(rs.rowInserted()); assertTrue(rs.rowDeleted()); } for (int i = 11; i <= 13; i++) { assertTrue(rs.next()); assertFalse(rs.rowUpdated()); assertFalse(rs.rowInserted()); assertFalse(rs.rowDeleted()); assertEquals(i, rs.getInt(1)); } rs.close(); stmt.close(); } /** * Test that updated rows are modified in place if the primary key is not * updated. */ public void testUpdateRowUpdatesRow() throws Exception { Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.executeUpdate( "create table #updateRowUpdatesRow (id int primary key, val int)"); stmt.executeUpdate( "insert into #updateRowUpdatesRow (id, val) values (1, 1)"); stmt.executeUpdate( "insert into #updateRowUpdatesRow (id, val) values (2, 2)"); stmt.executeUpdate( "insert into #updateRowUpdatesRow (id, val) values (3, 3)"); ResultSet rs = stmt.executeQuery( "select id, val from #updateRowUpdatesRow order by id"); for (int i = 0; i < 3; i++) { assertTrue(rs.next()); assertFalse(rs.rowUpdated()); assertFalse(rs.rowInserted()); assertFalse(rs.rowDeleted()); rs.updateInt(2, rs.getInt(2) + 10); rs.updateRow(); assertFalse(rs.rowUpdated()); assertFalse(rs.rowInserted()); assertFalse(rs.rowDeleted()); assertEquals(rs.getInt(1) + 10, rs.getInt(2)); } assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test that deleted rows are not removed but rather marked as deleted. */ public void testDeleteRowMarksDeleted() throws Exception { Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.executeUpdate( "create table #deleteRowMarksDeleted (val int primary key)"); stmt.executeUpdate( "insert into #deleteRowMarksDeleted (val) values (1)"); stmt.executeUpdate( "insert into #deleteRowMarksDeleted (val) values (2)"); stmt.executeUpdate( "insert into #deleteRowMarksDeleted (val) values (3)"); ResultSet rs = stmt.executeQuery( "select val from #deleteRowMarksDeleted order by val"); for (int i = 0; i < 3; i++) { assertTrue(rs.next()); assertFalse(rs.rowUpdated()); assertFalse(rs.rowInserted()); assertFalse(rs.rowDeleted()); rs.deleteRow(); assertFalse(rs.rowUpdated()); assertFalse(rs.rowInserted()); assertTrue(rs.rowDeleted()); } assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test for bug [1170777] resultSet.updateRow() fails if no row has been * changed. */ public void testUpdateRowNoChanges() throws Exception { Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.executeUpdate( "create table #deleteRowMarksDeleted (val int primary key)"); stmt.executeUpdate( "insert into #deleteRowMarksDeleted (val) values (1)"); ResultSet rs = stmt.executeQuery( "select val from #deleteRowMarksDeleted order by val"); assertTrue(rs.next()); // This should not crash; it should be a no-op rs.updateRow(); rs.refreshRow(); assertEquals(1, rs.getInt(1)); assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test the behavior of <code>sp_cursorfetch</code> with fetch sizes * greater than 1. * <p> * <b>Assertions tested:</b> * <ul> * <li>The <i>current row</i> is always the first row returned by the * last fetch, regardless of what fetch type was used. * <li>Row number parameter is ignored by fetch types other than absolute * and relative. * <li>Refresh fetch type simply reruns the previous request (it ignores * both row number and number of rows) and will not affect the * <i>current row</i>. * <li>Fetch next returns the packet of rows right after the last row * returned by the last fetch (regardless of what type of fetch that * was). * <li>Fetch previous returns the packet of rows right before the first * row returned by the last fetch (regardless of what type of fetch * that was). * <li>If a fetch previous tries to read before the start of the * <code>ResultSet</code> the requested number of rows is returned, * starting with row 1 and the error code returned is non-zero (2). * </ul> */ public void testCursorFetch() throws Exception { int rows = 10; Statement stmt = con.createStatement(); stmt.executeUpdate( "create table #testCursorFetch (id int primary key, val int)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement( "insert into #testCursorFetch (id, val) values (?, ?)"); for (int i = 1; i <= rows; i++) { pstmt.setInt(1, i); pstmt.setInt(2, i); pstmt.executeUpdate(); } pstmt.close(); // Open cursor CallableStatement cstmt = con.prepareCall( "{?=call sp_cursoropen(?, ?, ?, ?, ?)}"); // Return value (OUT) cstmt.registerOutParameter(1, Types.INTEGER); // Cursor handle (OUT) cstmt.registerOutParameter(2, Types.INTEGER); // Statement (IN) cstmt.setString(3, "select * from #testCursorFetch order by id"); // Scroll options (INOUT) cstmt.setInt(4, 1); // Keyset driven cstmt.registerOutParameter(4, Types.INTEGER); // Concurrency options (INOUT) cstmt.setInt(5, 2); // Scroll locks cstmt.registerOutParameter(5, Types.INTEGER); // Row count (OUT) cstmt.registerOutParameter(6, Types.INTEGER); ResultSet rs = cstmt.executeQuery(); assertEquals(2, rs.getMetaData().getColumnCount()); assertFalse(rs.next()); assertEquals(0, cstmt.getInt(1)); int cursor = cstmt.getInt(2); assertEquals(1, cstmt.getInt(4)); assertEquals(2, cstmt.getInt(5)); assertEquals(rows, cstmt.getInt(6)); cstmt.close(); // Play around with fetch cstmt = con.prepareCall("{?=call sp_cursorfetch(?, ?, ?, ?)}"); // Return value (OUT) cstmt.registerOutParameter(1, Types.INTEGER); // Cursor handle (IN) cstmt.setInt(2, cursor); // Fetch type (IN) cstmt.setInt(3, 2); // Next row // Row number (INOUT) cstmt.setInt(4, 1); // Only matters for absolute and relative fetching // Number of rows (INOUT) cstmt.setInt(5, 2); // Read 2 rows // Fetch rows 1-2 (current row is 1) rs = cstmt.executeQuery(); assertTrue(rs.next()); assertTrue(rs.next()); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Fetch rows 3-4 (current row is 3) rs = cstmt.executeQuery(); assertTrue(rs.next()); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Refresh rows 3-4 (current row is 3) cstmt.setInt(3, 0x80); // Refresh cstmt.setInt(4, 2); // Try to refresh only 2nd row (will be ignored) cstmt.setInt(5, 1); // Try to refresh only 1 row (will be ignored) rs = cstmt.executeQuery(); assertTrue(rs.next()); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Fetch rows 5-6 (current row is 5) cstmt.setInt(3, 2); // Next cstmt.setInt(4, 1); // Row number 1 cstmt.setInt(5, 2); // Get 2 rows rs = cstmt.executeQuery(); assertTrue(rs.next()); assertTrue(rs.next()); assertEquals(6, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Fetch previous rows (3-4) (current row is 3) cstmt.setInt(3, 4); // Previous rs = cstmt.executeQuery(); assertTrue(rs.next()); assertEquals(3, rs.getInt(1)); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Refresh rows 3-4 (current row is 3) cstmt.setInt(3, 0x80); // Refresh rs = cstmt.executeQuery(); assertTrue(rs.next()); assertEquals(3, rs.getInt(1)); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Fetch previous rows (1-2) (current row is 1) cstmt.setInt(3, 4); // Previous rs = cstmt.executeQuery(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Fetch next rows (3-4) (current row is 3) cstmt.setInt(3, 2); // Next rs = cstmt.executeQuery(); assertTrue(rs.next()); assertEquals(3, rs.getInt(1)); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Fetch first rows (1-2) (current row is 1) cstmt.setInt(3, 1); // First rs = cstmt.executeQuery(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Fetch last rows (9-10) (current row is 9) cstmt.setInt(3, 8); // Last rs = cstmt.executeQuery(); assertTrue(rs.next()); assertEquals(9, rs.getInt(1)); assertTrue(rs.next()); assertEquals(10, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Fetch next rows; should not fail (current position is after last) cstmt.setInt(3, 2); // Next rs = cstmt.executeQuery(); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Fetch absolute starting with 6 (6-7) (current row is 6) cstmt.setInt(3, 0x10); // Absolute cstmt.setInt(4, 6); rs = cstmt.executeQuery(); assertTrue(rs.next()); assertEquals(6, rs.getInt(1)); assertTrue(rs.next()); assertEquals(7, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Fetch relative -4 (2-3) (current row is 2) cstmt.setInt(3, 0x20); // Relative cstmt.setInt(4, -4); rs = cstmt.executeQuery(); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertTrue(rs.next()); assertEquals(3, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Fetch previous 2 rows; should fail (current row is 1) cstmt.setInt(3, 4); // Previous rs = cstmt.executeQuery(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertFalse(rs.next()); rs.close(); // Returns 2 on error assertEquals(2, cstmt.getInt(1)); // Fetch next rows (3-4) (current row is 3) cstmt.setInt(3, 2); // Next rs = cstmt.executeQuery(); assertTrue(rs.next()); assertEquals(3, rs.getInt(1)); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); cstmt.close(); // Close cursor cstmt = con.prepareCall("{?=call sp_cursorclose(?)}"); // Return value (OUT) cstmt.registerOutParameter(1, Types.INTEGER); // Cursor handle (IN) cstmt.setInt(2, cursor); assertFalse(cstmt.execute()); assertEquals(0, cstmt.getInt(1)); cstmt.close(); } /** * Test that <code>absolute(-1)</code> works the same as <code>last()</code>. */ public void testAbsoluteMinusOne() throws Exception { Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); stmt.executeUpdate( "create table #absoluteMinusOne (val int primary key)"); stmt.executeUpdate( "insert into #absoluteMinusOne (val) values (1)"); stmt.executeUpdate( "insert into #absoluteMinusOne (val) values (2)"); stmt.executeUpdate( "insert into #absoluteMinusOne (val) values (3)"); ResultSet rs = stmt.executeQuery( "select val from #absoluteMinusOne order by val"); rs.absolute(-1); assertTrue(rs.isLast()); assertEquals(3, rs.getInt(1)); assertFalse(rs.next()); rs.last(); assertTrue(rs.isLast()); assertEquals(3, rs.getInt(1)); assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test that calling <code>absolute()</code> with very large positive * values positions the cursor after the last row and with very large * negative values positions the cursor before the first row. */ public void testAbsoluteLargeValue() throws SQLException { Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); stmt.executeUpdate( "create table #absoluteLargeValue (val int primary key)"); stmt.executeUpdate( "insert into #absoluteLargeValue (val) values (1)"); stmt.executeUpdate( "insert into #absoluteLargeValue (val) values (2)"); stmt.executeUpdate( "insert into #absoluteLargeValue (val) values (3)"); ResultSet rs = stmt.executeQuery( "select val from #absoluteLargeValue order by val"); assertFalse(rs.absolute(10)); assertEquals(0, rs.getRow()); assertTrue(rs.isAfterLast()); assertFalse(rs.next()); assertEquals(0, rs.getRow()); assertTrue(rs.isAfterLast()); assertFalse(rs.absolute(-10)); assertEquals(0, rs.getRow()); assertTrue(rs.isBeforeFirst()); assertFalse(rs.previous()); assertEquals(0, rs.getRow()); assertTrue(rs.isBeforeFirst()); rs.close(); stmt.close(); } /** * Test that calling <code>absolute()</code> with very large positive * values positions the cursor after the last row and with very large * negative values positions the cursor before the first row. */ public void testRelativeLargeValue() throws SQLException { Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); stmt.executeUpdate( "create table #relativeLargeValue (val int primary key)"); stmt.executeUpdate( "insert into #relativeLargeValue (val) values (1)"); stmt.executeUpdate( "insert into #relativeLargeValue (val) values (2)"); stmt.executeUpdate( "insert into #relativeLargeValue (val) values (3)"); ResultSet rs = stmt.executeQuery( "select val from #relativeLargeValue order by val"); assertFalse(rs.relative(10)); assertEquals(0, rs.getRow()); assertTrue(rs.isAfterLast()); assertFalse(rs.next()); assertEquals(0, rs.getRow()); assertTrue(rs.isAfterLast()); assertFalse(rs.relative(-10)); assertEquals(0, rs.getRow()); assertTrue(rs.isBeforeFirst()); assertFalse(rs.previous()); assertEquals(0, rs.getRow()); assertTrue(rs.isBeforeFirst()); rs.close(); stmt.close(); } /** * Test that <code>read()</code> works ok on the stream returned by * <code>ResultSet.getUnicodeStream()</code> (i.e. it doesn't always fill * the buffer, regardless of whether there's available data or not). */ public void testUnicodeStream() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #unicodeStream (val varchar(255))"); stmt.executeUpdate("insert into #unicodeStream (val) values ('test')"); ResultSet rs = stmt.executeQuery("select val from #unicodeStream"); if (rs.next()) { byte[] buf = new byte[8000]; InputStream is = rs.getUnicodeStream(1); int length = is.read(buf); assertEquals(4 * 2, length); } rs.close(); stmt.close(); } /** * Check whether <code>Statement.setMaxRows()</code> works okay, bug * [1812686]. */ public void testMaxRows() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #statementMaxRows (val int)"); stmt.close(); // insert 1000 rows PreparedStatement pstmt = con.prepareStatement("insert into #statementMaxRows values (?)"); for (int i = 0; i < 1000; i++) { pstmt.setInt(1, i); assertEquals(1, pstmt.executeUpdate()); } pstmt.close(); stmt = con.createStatement(); // set maxRows to 100 stmt.setMaxRows(100); // select all rows (should only return 100 rows) ResultSet rs = stmt.executeQuery("select * from #statementMaxRows"); int rows = 0; while (rs.next()) { rows++; } assertEquals(100, rows); rs.close(); stmt.close(); } /** * Test that <code>Statement.setMaxRows()</code> works on cursor * <code>ResultSet</code>s. */ public void testCursorMaxRows() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #cursorMaxRows (val int)"); stmt.close(); // Insert 10 rows PreparedStatement pstmt = con.prepareStatement( "insert into #cursorMaxRows (val) values (?)"); for (int i = 0; i < 10; i++) { pstmt.setInt(1, i); assertEquals(1, pstmt.executeUpdate()); } pstmt.close(); // Create a cursor ResultSet stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // Set maxRows to 5 stmt.setMaxRows(5); // Select all (should only return 5 rows) ResultSet rs = stmt.executeQuery("select * from #cursorMaxRows"); rs.last(); assertEquals(5, rs.getRow()); rs.beforeFirst(); int cnt = 0; while (rs.next()) { cnt++; } assertEquals(5, cnt); rs.close(); stmt.close(); } /** * Test for bug [1075977] <code>setObject()</code> causes SQLException. * <p> * Conversion of <code>float</code> values to <code>String</code> adds * grouping to the value, which cannot then be parsed. */ public void testSetObjectScale() throws Exception { Statement stmt = con.createStatement(); stmt.execute("create table #testsetobj (i int)"); PreparedStatement pstmt = con.prepareStatement("insert into #testsetobj values(?)"); // next line causes sqlexception pstmt.setObject(1, new Float(1234.5667), Types.INTEGER, 0); assertEquals(1, pstmt.executeUpdate()); ResultSet rs = stmt.executeQuery("select * from #testsetobj"); assertTrue(rs.next()); assertEquals("1234", rs.getString(1)); } /** * Test that <code>ResultSet.previous()</code> works correctly on cursor * <code>ResultSet</code>s. */ public void testCursorPrevious() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #cursorPrevious (val int)"); stmt.close(); // Insert 10 rows PreparedStatement pstmt = con.prepareStatement( "insert into #cursorPrevious (val) values (?)"); for (int i = 0; i < 10; i++) { pstmt.setInt(1, i); assertEquals(1, pstmt.executeUpdate()); } pstmt.close(); // Create a cursor ResultSet stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // Set fetch size to 2 stmt.setFetchSize(2); // Select all ResultSet rs = stmt.executeQuery("select * from #cursorPrevious"); rs.last(); int i = 10; do { assertEquals(i, rs.getRow()); assertEquals(--i, rs.getInt(1)); } while (rs.previous()); assertTrue(rs.isBeforeFirst()); assertEquals(0, i); rs.close(); stmt.close(); } /** * Test the behavior of the ResultSet/Statement/Connection when the JVM * runs out of memory (hopefully) in the middle of a packet. * <p/> * Previously jTDS was not able to close a ResultSet/Statement/Connection * after an OutOfMemoryError because the input stream pointer usually * remained inside a packet and further attempts to dump the rest of the * response failed because of "protocol confusions". */ public void testOutOfMemory() throws SQLException { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #testOutOfMemory (val binary(8000))"); // Insert a 8KB value byte[] val = new byte[8000]; PreparedStatement pstmt = con.prepareStatement( "insert into #testOutOfMemory (val) values (?)"); pstmt.setBytes(1, val); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); // Create a list and keep adding rows to it until we run out of memory // Most probably this will happen in the middle of a row packet, when // jTDS tries to allocate the array, after reading the data length ArrayList results = new ArrayList(); ResultSet rs = null; try { while (true) { rs = stmt.executeQuery("select val from #testOutOfMemory"); assertTrue(rs.next()); results.add(rs.getBytes(1)); assertFalse(rs.next()); rs.close(); rs = null; } } catch (OutOfMemoryError err) { // Do not remove this. Although not really used, it will free // memory, avoiding another OutOfMemoryError results = null; if (rs != null) { // This used to fail, because the parser got confused rs.close(); } } // Make sure the Statement still works rs = stmt.executeQuery("select 1"); assertTrue(rs.next()); assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test for bug [1182066] regression bug resultset: relative() not working * as expected. */ public void testRelative() throws Exception { final int ROW_COUNT = 99; Statement stmt = con.createStatement(); stmt.executeUpdate("create table #test2 (i int primary key, v varchar(100))"); for (int i = 1; i <= ROW_COUNT; i++) { stmt.executeUpdate("insert into #test2 (i, v) values (" + i + ", 'This is a test')"); } stmt.close(); String sql = "select * from #test2"; PreparedStatement pstmt = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); pstmt.setFetchSize(10); ResultSet rs = pstmt.executeQuery(); int resCnt = 0; if (rs.next()) { do { assertEquals(++resCnt, rs.getInt(1)); } while (rs.relative(1)); } assertEquals(ROW_COUNT, resCnt); if (rs.previous()) { do { assertEquals(resCnt--, rs.getInt(1)); } while (rs.relative(-1)); } pstmt.close(); assertEquals(0, resCnt); } /** * Test that after updateRow() the cursor is positioned correctly. */ public void testUpdateRowPosition() throws Exception { final int ROW_COUNT = 99; final int TEST_ROW = 33; Statement stmt = con.createStatement(); stmt.executeUpdate("create table #testPos (i int primary key, v varchar(100))"); for (int i = 1; i <= ROW_COUNT; i++) { stmt.executeUpdate("insert into #testPos (i, v) values (" + i + ", 'This is a test')"); } stmt.close(); String sql = "select * from #testPos order by i"; PreparedStatement pstmt = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); pstmt.setFetchSize(10); ResultSet rs = pstmt.executeQuery(); for (int i = 1; i <= TEST_ROW; i++) { assertTrue(rs.next()); assertEquals(i, rs.getInt(1)); } // We're on TEST_ROW now assertEquals(TEST_ROW, rs.getRow()); rs.updateString(2, "This is another test"); rs.updateRow(); assertEquals(TEST_ROW, rs.getRow()); assertEquals(TEST_ROW, rs.getInt(1)); rs.refreshRow(); assertEquals(TEST_ROW, rs.getRow()); assertEquals(TEST_ROW, rs.getInt(1)); for (int i = TEST_ROW + 1; i <= ROW_COUNT; i++) { assertTrue(rs.next()); assertEquals(i, rs.getInt(1)); } pstmt.close(); } /** * Test for bug [1197603] Cursor downgrade error in CachedResultSet -- * updateable result sets were incorrectly downgraded to read only forward * only ones when client side cursors were used. */ public void testUpdateableClientCursor() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #testUpdateableClientCursor " + "(i int primary key, v varchar(100))"); stmt.executeUpdate("insert into #testUpdateableClientCursor " + "(i, v) values (1, 'This is a test')"); stmt.close(); // Use a statement that the server won't be able to create a cursor on String sql = "select * from #testUpdateableClientCursor where i = ?"; PreparedStatement pstmt = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); pstmt.setInt(1, 1); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertNull(pstmt.getWarnings()); rs.updateString(2, "This is another test"); rs.updateRow(); rs.close(); pstmt.close(); stmt = con.createStatement(); rs = stmt.executeQuery( "select * from #testUpdateableClientCursor"); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals("This is another test", rs.getString(2)); assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test bug with Sybase where readonly scrollable result set based on a * SELECT DISTINCT returns duplicate rows. */ public void testDistinctBug() throws Exception { Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); stmt.execute( "CREATE TABLE #testdistinct (id int primary key, c varchar(255))"); stmt.addBatch("INSERT INTO #testdistinct VALUES(1, 'AAAA')"); stmt.addBatch("INSERT INTO #testdistinct VALUES(2, 'AAAA')"); stmt.addBatch("INSERT INTO #testdistinct VALUES(3, 'BBBB')"); stmt.addBatch("INSERT INTO #testdistinct VALUES(4, 'BBBB')"); stmt.addBatch("INSERT INTO #testdistinct VALUES(5, 'CCCC')"); int counts[] = stmt.executeBatch(); assertEquals(5, counts.length); ResultSet rs = stmt.executeQuery( "SELECT DISTINCT c FROM #testdistinct"); assertNotNull(rs); int rowCount = 0; while (rs.next()) { rowCount++; } assertEquals(3, rowCount); stmt.close(); } /** * Test pessimistic concurrency for SQL Server (for Sybase optimistic * concurrency will always be used). */ public void testPessimisticConcurrency() throws Exception { dropTable("pessimisticConcurrency"); Connection con2 = getConnection(); Statement stmt = null; ResultSet rs = null; try { // Create statement using pessimistic locking. stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE + 1); stmt.execute("CREATE TABLE pessimisticConcurrency (id int primary key, data varchar(255))"); for (int i = 0; i < 4; i++) { stmt.executeUpdate("INSERT INTO pessimisticConcurrency VALUES("+i+", 'Table A line "+i+"')"); } // Fetch one row at a time, making sure we know exactly which row is locked stmt.setFetchSize(1); // Open cursor rs = stmt.executeQuery("SELECT id, data FROM pessimisticConcurrency ORDER BY id"); assertNull(rs.getWarnings()); assertEquals(ResultSet.TYPE_SCROLL_SENSITIVE, rs.getType()); assertEquals(ResultSet.CONCUR_UPDATABLE + 1, rs.getConcurrency()); // If not a MSCursorResultSet, give up as no locking will happen if (rs.getClass().getName().indexOf("MSCursorResultSet") == -1) { rs.close(); stmt.close(); return; } // Scroll to and lock row 3 for (int i = 0; i < 3; ++i) { rs.next(); } // Create a second statement final Statement stmt2 = con2.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE + 1); // No better idea to store exceptions final ArrayList container = new ArrayList(); // Launch a thread that will cancel the second statement if it hangs. new Thread() { public void run() { try { sleep(1000); stmt2.cancel(); } catch (Exception ex) { container.add(ex); } } }.start(); // Open second cursor ResultSet rs2 = stmt2.executeQuery("SELECT id, data FROM pessimisticConcurrency WHERE id = 2"); assertNull(rs2.getWarnings()); assertEquals(ResultSet.TYPE_SCROLL_SENSITIVE, rs2.getType()); assertEquals(ResultSet.CONCUR_UPDATABLE + 1, rs2.getConcurrency()); try { System.out.println(rs2.next()); } catch (SQLException ex) { ex.printStackTrace(); System.out.println(ex.getNextException()); if ("HY010".equals(ex.getSQLState())) { stmt2.getMoreResults(); } if (!"HY008".equals(ex.getSQLState()) && !"HY010".equals(ex.getSQLState())) { fail("Expecting cancel exception."); } } rs.close(); stmt.close(); rs2.close(); stmt2.close(); // Check for exceptions thrown in the cancel thread if (container.size() != 0) { throw (SQLException) container.get(0); } } finally { dropTable("pessimisticConcurrency"); if (con2 != null) { con2.close(); } } } /** * Test if dynamic cursors (<code>ResultSet.TYPE_SCROLL_SENSITIVE+1</code>) * see others' updates. SQL Server only. */ public void testDynamicCursors() throws Exception { final int ROWS = 4; dropTable("dynamicCursors"); Connection con2 = getConnection(); try { Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE + 1, ResultSet.CONCUR_READ_ONLY); stmt.execute("CREATE TABLE dynamicCursors (id int primary key, data varchar(255))"); for (int i = 0; i < ROWS; i++) { stmt.executeUpdate("INSERT INTO dynamicCursors VALUES(" + i + ", 'Table A line " + i + "')"); } // Open cursor ResultSet rs = stmt.executeQuery("SELECT id, data FROM dynamicCursors"); // If not a MSCursorResultSet, give up as it will not see inserts if (rs.getClass().getName().indexOf("MSCursorResultSet") == -1) { rs.close(); stmt.close(); return; } // Insert new row from other connection Statement stmt2 = con2.createStatement(); assertEquals(1, stmt2.executeUpdate( "INSERT INTO dynamicCursors VALUES(" + ROWS + ", 'Table A line " + ROWS + "')")); stmt2.close(); // Count rows and make sure the newly inserted row is visible int cnt; for (cnt = 0; rs.next(); cnt++); assertEquals(ROWS + 1, cnt); rs.close(); stmt.close(); } finally { dropTable("dynamicCursors"); if (con2 != null) { con2.close(); } } } /** * Test for bug [1232733] setFetchSize(0) causes exception. */ public void testZeroFetchSize() throws Exception { Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); stmt.setFetchSize(0); ResultSet rs = stmt.executeQuery("SELECT 1 UNION SELECT 2"); assertTrue(rs.next()); rs.setFetchSize(0); assertTrue(rs.next()); assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test for bug [1329765] Pseudo column ROWSTAT is back with SQL 2005 * (September CTP). */ public void testRowstat() throws Exception { PreparedStatement stmt = con.prepareStatement("SELECT 'STRING' str", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery(); assertEquals(1, rs.getMetaData().getColumnCount()); assertTrue(rs.next()); assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test for bug [2051585], TDS Protocol error when 2 ResultSets on the * same connection are being iterated at the same time. */ public void testConcurrentResultSets() throws Exception { con.setAutoCommit(false); final int rows = 100; final int threads = 100; // prepare test data Statement stmt = con.createStatement(); stmt.execute("create table #conrs (id int,data varchar(20))"); for (int r=0; r < rows; r++) { assertEquals(1, stmt.executeUpdate("insert into #conrs values(" + r + ",'test" + r + "')")); } stmt.close(); final Thread[] workers = new Thread[threads]; final List errors = new ArrayList(); for (int i=0; i < threads; i++) { workers[i] = new Thread("thread " + i) { public void run() { int i=0; try { Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select * from #conrs order by id asc"); for ( ; i < rows; i++) { assertTrue("premature end of result, only " + i + "of " + rows + " rows present", rs.next()); assertEquals("resultset contains wrong row:", i, rs.getInt(1)); assertEquals("resultset contains wrong column value:", "test" + i, rs.getString(2)); // random delays should ensure that threads are not executed one after another if (Math.random() < 0.01) { Thread.sleep(1); } } rs.close(); st.close(); } catch (Throwable t) { synchronized (errors) { errors.add(new Exception(getName() + " at row " + i + ": " + t.getMessage())); } } } }; } // start all threads for (int i=0; i < threads; i++) { workers[i].start(); } // wait for the threads to finish for (int i=0; i < threads; i++) { workers[i].join(); } assertEquals("[]", array2String(errors.toArray())); con.setAutoCommit(true); } private static String array2String(Object[] a) { if (a == null) return "null"; int iMax = a.length - 1; if (iMax == -1) return "[]"; StringBuffer b = new StringBuffer(); b.append('['); for (int i = 0; ; i++) { b.append(String.valueOf(a[i])); if (i == iMax) return b.append(']').toString(); b.append(", "); } } /** * Test for bug [1855125], numeric overflow not reported by jTDS. */ public void testNumericOverflow() throws SQLException { Statement st = con.createStatement(); st.execute("create table #test(data numeric(30,10))"); assertEquals(1, st.executeUpdate("insert into #test values (10000000000000000000.0000)")); ResultSet rs = st.executeQuery("select * from #test"); assertTrue(rs.next()); try { byte b = rs.getByte(1); assertTrue("expected numeric overflow error, got " + b, false); } catch (SQLException e) { assertEquals(e.getSQLState(), "22003"); } try { short s = rs.getShort(1); assertTrue("expected numeric overflow error, got " + s, false); } catch (SQLException e) { assertEquals(e.getSQLState(), "22003"); } try { int i = rs.getInt(1); assertTrue("expected numeric overflow error, got " + i, false); } catch (SQLException e) { assertEquals(e.getSQLState(), "22003"); } try { long l = rs.getLong(1); assertTrue("expected numeric overflow error, got " + l, false); } catch (SQLException e) { assertEquals(e.getSQLState(), "22003"); } rs.close(); st.close(); } /** * Test for bug [2860742], getByte() causes overflow error for negative * values. */ public void testNegativeOverflow() throws SQLException { Statement st = con.createStatement(); st.execute("create table #testNegativeOverflow(data int)"); int [] values = new int [] { -1, -128, -129, 127, 128}; boolean[] overflow = new boolean[] {false, false, true, false, true}; for (int i = 0; i < values.length; i++) { assertEquals(1, st.executeUpdate("insert into #testNegativeOverflow values (" + values[i] + ")")); } ResultSet rs = st.executeQuery("select * from #testNegativeOverflow"); for (int i = 0; i < values.length; i++) { assertTrue(rs.next()); try { byte b = rs.getByte(1); assertFalse("expected numeric overflow error for value " + values[i] + ", got " + b, overflow[i]); } catch (SQLException e) { assertTrue("unexpected numeric overflow for value " + values[i], overflow[i]); } } rs.close(); st.close(); } /** * Test for bug #548, Select statement very slow with date parameter. */ public void testDatePerformance() throws SQLException { Statement st = con.createStatement(); st.execute("create table #test(data datetime)"); st.close(); PreparedStatement ps = con.prepareStatement("insert into #test values(?)"); final int iterations = 10000; final String dateString = "2009-09-03"; // test date value Date date = Date.valueOf(dateString); System.gc(); long start = System.currentTimeMillis(); // insert test data using prepared statement for (int i = 0; i < iterations; i ++) { ps.setDate(1, date); ps.executeUpdate(); } long prep = System.currentTimeMillis() - start; System.out.println("prepared: " + prep + " ms"); ps.close(); // delete test data st = con.createStatement(); assertEquals(iterations, st.executeUpdate("delete from #test")); st.close(); st = con.createStatement(); System.gc(); start = System.currentTimeMillis(); // insert test data using prepared statement for (int i = 0; i < iterations; i ++) { st.executeUpdate("insert into #test values(" + dateString + ")"); } long unprep = System.currentTimeMillis() - start; System.out.println("inlined : " + unprep + " ms"); st.close(); // prepared statement should be faster // ("faster" means prep taking not longer than 110% of unprep; // the 10% are there, because in my tests prep and unprep are almost // identical and jitter leads to the test case sometimes failing and // sometimes not. The "10%" are not really solving the issue, but // if the interpretation could be "prep should not be unexpectedly slower", // those 10% are good enough.) assertEquals( unprep, prep, unprep < prep ? unprep / 10 : unprep ); } public static void main(String[] args) { junit.textui.TestRunner.run(ResultSetTest.class); } }
package org.jetel.component; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.data.DataRecord; import org.jetel.data.Defaults; import org.jetel.data.formatter.SpreadsheetFormatter; import org.jetel.data.formatter.provider.SpreadsheetFormatterProvider; import org.jetel.data.lookup.LookupTable; import org.jetel.data.parser.XLSMapping; import org.jetel.enums.PartitionFileTagType; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.ConfigurationProblem; import org.jetel.exception.ConfigurationStatus; import org.jetel.exception.XMLConfigurationException; import org.jetel.graph.InputPort; import org.jetel.graph.Node; import org.jetel.graph.Result; import org.jetel.graph.TransformationGraph; import org.jetel.metadata.DataFieldFormatType; import org.jetel.metadata.DataFieldMetadata; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.MultiFileWriter; import org.jetel.util.SpreadsheetUtils.SpreadsheetAttitude; import org.jetel.util.SpreadsheetUtils.SpreadsheetExistingSheetsActions; import org.jetel.util.SpreadsheetUtils.SpreadsheetFormat; import org.jetel.util.SpreadsheetUtils.SpreadsheetWriteMode; import org.jetel.util.bytes.SystemOutByteChannel; import org.jetel.util.bytes.WritableByteChannelIterator; import org.jetel.util.file.FileUtils; import org.jetel.util.property.ComponentXMLAttributes; import org.jetel.util.property.RefResFlag; import org.jetel.util.string.StringUtils; import org.w3c.dom.Element; public class SpreadsheetWriter extends Node { public static final String COMPONENT_TYPE = "SPREADSHEET_WRITER"; public static final String XML_FILE_URL_ATTRIBUTE = "fileURL"; public static final String XML_TEMPLATE_FILE_URL_ATTRIBUTE = "templateFileURL"; public static final String XML_FORMATTER_TYPE_ATTRIBUTE = "formatterType"; public static final String XML_WRITE_MODE_ATTRIBUTE = "writeMode"; public static final String XML_MK_DIRS_ATTRIBUTE = "makeDirs"; public static final String XML_MAPPING_ATTRIBUTE = "mapping"; public static final String XML_MAPPING_URL_ATTRIBUTE = "mappingURL"; public static final String XML_SHEET_ATTRIBUTE = "sheet"; public static final String XML_EXISTING_SHEETS_ACTIONS_ATTRIBUTE = "existingSheetsActions"; public static final String XML_RECORD_SKIP_ATTRIBUTE = "skipRecords"; public static final String XML_RECORD_COUNT_ATTRIBUTE = "numRecords"; public static final String XML_RECORDS_PER_FILE = "numFileRecords"; public static final String XML_PARTITIONKEY_ATTRIBUTE = "partitionKey"; public static final String XML_PARTITION_ATTRIBUTE = "partition"; public static final String XML_PARTITION_OUTFIELDS_ATTRIBUTE = "partitionOutFields"; public static final String XML_PARTITION_FILETAG_ATTRIBUTE = "partitionFileTag"; public static final String XML_PARTITION_UNASSIGNED_FILE_NAME_ATTRIBUTE = "partitionUnassignedFileName"; private static Log LOGGER = LogFactory.getLog(SpreadsheetWriter.class); private static final int READ_FROM_PORT = 0; private static final int OUTPUT_PORT = 0; private static final HashSet<Character> supportedTypes; static { supportedTypes = new HashSet<Character>(9); supportedTypes.add(DataFieldMetadata.DATE_FIELD); supportedTypes.add(DataFieldMetadata.DATETIME_FIELD); supportedTypes.add(DataFieldMetadata.BYTE_FIELD); supportedTypes.add(DataFieldMetadata.STRING_FIELD); supportedTypes.add(DataFieldMetadata.DECIMAL_FIELD); supportedTypes.add(DataFieldMetadata.INTEGER_FIELD); supportedTypes.add(DataFieldMetadata.LONG_FIELD); supportedTypes.add(DataFieldMetadata.NUMERIC_FIELD); supportedTypes.add(DataFieldMetadata.BOOLEAN_FIELD); } public static Node fromXML(TransformationGraph graph, Element nodeXML) throws XMLConfigurationException { ComponentXMLAttributes xattribs = new ComponentXMLAttributes(nodeXML, graph); SpreadsheetWriter spreadsheetWriter; try { spreadsheetWriter = new SpreadsheetWriter(xattribs.getString(XML_ID_ATTRIBUTE)); spreadsheetWriter.setFileURL(xattribs.getStringEx(XML_FILE_URL_ATTRIBUTE, RefResFlag.SPEC_CHARACTERS_OFF)); if (xattribs.exists(XML_MK_DIRS_ATTRIBUTE)) { spreadsheetWriter.setMkDirs(xattribs.getBoolean(XML_MK_DIRS_ATTRIBUTE)); } if (xattribs.exists(XML_FORMATTER_TYPE_ATTRIBUTE)) { spreadsheetWriter.setFormatterType(SpreadsheetFormat.valueOfIgnoreCase(xattribs.getString(XML_FORMATTER_TYPE_ATTRIBUTE))); } if (xattribs.exists(XML_WRITE_MODE_ATTRIBUTE)) { spreadsheetWriter.setWriteMode(SpreadsheetWriteMode.valueOfIgnoreCase(xattribs.getString(XML_WRITE_MODE_ATTRIBUTE))); } String mappingURL = xattribs.getStringEx(XML_MAPPING_URL_ATTRIBUTE, null, RefResFlag.SPEC_CHARACTERS_OFF); if (xattribs.exists(XML_TEMPLATE_FILE_URL_ATTRIBUTE)) { spreadsheetWriter.setTemplateFileURL(xattribs.getString(XML_TEMPLATE_FILE_URL_ATTRIBUTE)); } String mapping = xattribs.getString(XML_MAPPING_ATTRIBUTE, null); if (mappingURL != null) { spreadsheetWriter.setMappingURL(mappingURL); } else if (mapping != null) { spreadsheetWriter.setMapping(mapping); } if (xattribs.exists(XML_SHEET_ATTRIBUTE)) { spreadsheetWriter.setSheet(xattribs.getString(XML_SHEET_ATTRIBUTE)); } if (xattribs.exists(XML_EXISTING_SHEETS_ACTIONS_ATTRIBUTE)) { spreadsheetWriter.setExistingSheetsActions(SpreadsheetExistingSheetsActions.valueOfIgnoreCase(xattribs.getString(XML_EXISTING_SHEETS_ACTIONS_ATTRIBUTE))); } if (xattribs.exists(XML_RECORD_SKIP_ATTRIBUTE)) { spreadsheetWriter.setRecordSkip(xattribs.getInteger(XML_RECORD_SKIP_ATTRIBUTE)); } if (xattribs.exists(XML_RECORD_COUNT_ATTRIBUTE)) { spreadsheetWriter.setRecordCount(xattribs.getInteger(XML_RECORD_COUNT_ATTRIBUTE)); } if (xattribs.exists(XML_RECORDS_PER_FILE)) { spreadsheetWriter.setRecordsPerFile(xattribs.getInteger(XML_RECORDS_PER_FILE)); } if (xattribs.exists(XML_PARTITIONKEY_ATTRIBUTE)) { spreadsheetWriter.setPartitionKey(xattribs.getString(XML_PARTITIONKEY_ATTRIBUTE)); } if (xattribs.exists(XML_PARTITION_ATTRIBUTE)) { spreadsheetWriter.setPartition(xattribs.getString(XML_PARTITION_ATTRIBUTE)); } if (xattribs.exists(XML_PARTITION_FILETAG_ATTRIBUTE)) { spreadsheetWriter.setPartitionFileTagType(xattribs.getString(XML_PARTITION_FILETAG_ATTRIBUTE)); } if (xattribs.exists(XML_PARTITION_OUTFIELDS_ATTRIBUTE)) { spreadsheetWriter.setPartitionOutFields(xattribs.getString(XML_PARTITION_OUTFIELDS_ATTRIBUTE)); } if (xattribs.exists(XML_PARTITION_UNASSIGNED_FILE_NAME_ATTRIBUTE)) { spreadsheetWriter.setPartitionUnassignedFileName(xattribs.getString(XML_PARTITION_UNASSIGNED_FILE_NAME_ATTRIBUTE)); } return spreadsheetWriter; } catch (Exception ex) { throw new XMLConfigurationException(COMPONENT_TYPE + ":" + xattribs.getString(XML_ID_ATTRIBUTE, " unknown ID ") + ":" + ex.getMessage(), ex); } } private String fileURL; private String templateFileURL; private boolean mkDirs; private SpreadsheetWriteMode writeMode = SpreadsheetWriteMode.OVERWRITE_SHEET_IN_MEMORY; private SpreadsheetFormat formatterType = SpreadsheetFormat.AUTO; private String mapping; private String mappingURL; private String sheet; private SpreadsheetExistingSheetsActions existingSheetsActions = SpreadsheetExistingSheetsActions.DO_NOTHING; private int recordSkip; private int recordCount; private int recordsPerFile; private String partitionKey; private String partition; private PartitionFileTagType partitionFileTagType = PartitionFileTagType.NUMBER_FILE_TAG; private String partitionOutFields; private String partitionUnassignedFileName; private LookupTable lookupTable = null; private SpreadsheetFormatterProvider formatterProvider; private MultiFileWriter writer; public SpreadsheetWriter(String id) { super(id); } @Override public String getType() { return COMPONENT_TYPE; } public void setWriteMode(SpreadsheetWriteMode writeMode) { this.writeMode = writeMode; } public void setFormatterType(SpreadsheetFormat formatterType) { this.formatterType = formatterType; } public void setFileURL(String fileURL) { this.fileURL = fileURL; } public void setTemplateFileURL(String templateFileURL) { this.templateFileURL = templateFileURL; } public void setMappingURL(String mappingURL) { this.mappingURL = mappingURL; } public void setMapping(String mapping) { this.mapping = mapping; } public void setSheet(String sheet) { this.sheet = sheet; } public void setExistingSheetsActions(SpreadsheetExistingSheetsActions existingSheetsActions) { this.existingSheetsActions = existingSheetsActions; } public void setMkDirs(boolean mkDirs) { this.mkDirs = mkDirs; } public void setRecordSkip(int recordSkip) { this.recordSkip = recordSkip; } public void setRecordCount(int recordCount) { this.recordCount = recordCount; } public void setRecordsPerFile(int recordsPerFile) { this.recordsPerFile = recordsPerFile; } public void setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; } public void setPartition(String partition) { this.partition = partition; } public void setPartitionFileTagType(String partitionFileTagType) { this.partitionFileTagType = PartitionFileTagType.valueOfIgnoreCase(partitionFileTagType); } public void setPartitionOutFields(String partitionOutFields) { this.partitionOutFields = partitionOutFields; } public void setPartitionUnassignedFileName(String partitionUnassignedFileName) { this.partitionUnassignedFileName = partitionUnassignedFileName; } @Override public ConfigurationStatus checkConfig(ConfigurationStatus status) { super.checkConfig(status); if (!checkInputPorts(status, 1, 1) || !checkOutputPorts(status, 0, 1)) { return status; } Map<String, Character> fieldsOfUnsupportedType = checkInputDataFieldsTypes(getInputPort(0).getMetadata()); if (!fieldsOfUnsupportedType.isEmpty()) { StringBuilder errorMessage = new StringBuilder("Input port metadata contain the following unsupported types: "); for (String fieldName : fieldsOfUnsupportedType.keySet()) { errorMessage.append("\n" + fieldName + " - " + DataFieldMetadata.type2Str(fieldsOfUnsupportedType.get(fieldName))); } status.add(new ConfigurationProblem(errorMessage.toString(), ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL)); } try { FileUtils.canWrite(getGraph() != null ? getGraph().getRuntimeContext().getContextURL() : null, fileURL, mkDirs); XLSMapping mapping = prepareMapping(); if (mapping != null) { if (mapping.getOrientation() != XLSMapping.HEADER_ON_TOP && writeMode.isStreamed()) { status.add(new ConfigurationProblem("Horizontal orientation is not supported with streaming!", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL)); } mapping.checkConfig(status); } } catch (ComponentNotReadyException e) { ConfigurationProblem problem = new ConfigurationProblem(e.getMessage(), ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL); if (!StringUtils.isEmpty(e.getAttributeName())) { problem.setAttributeName(e.getAttributeName()); } status.add(problem); } if (writeMode.isStreamed()) { if (templateFileURL != null) { // requires implementing workbook/sheet/row copying status.add(new ConfigurationProblem("Write using template is not supported with streaming mode!", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL)); } } if (templateFileURL!=null && fileURL!=null) { if (resolveFormat(formatterType, fileURL)!=resolveTemplateFormat(formatterType, templateFileURL)) { status.add(new ConfigurationProblem("Formats of template and an output file must match!", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL)); } } return status; } private Map<String, Character> checkInputDataFieldsTypes(DataRecordMetadata metadata) { HashMap<String, Character> result = new HashMap<String, Character>(); char fieldType; for (DataFieldMetadata field : metadata.getFields()) { fieldType = field.getType(); if (!supportedTypes.contains(fieldType)) { result.put(field.getName(), fieldType); } } return result; } @Override public void init() throws ComponentNotReadyException { if (isInitialized()) { return; } super.init(); formatterProvider = new SpreadsheetFormatterProvider(); formatterProvider.setAttitude(writeMode.isStreamed() ? SpreadsheetAttitude.STREAM : SpreadsheetAttitude.IN_MEMORY); formatterProvider.setFormatterType(resolveFormat(formatterType, fileURL)); formatterProvider.setMapping(prepareMapping()); formatterProvider.setSheet(sheet); formatterProvider.setAppend(writeMode.isAppend()); formatterProvider.setInsert(writeMode.isInsert()); formatterProvider.setCreateFile(writeMode.isCreatingNewFile()); formatterProvider.setRemoveSheets(existingSheetsActions.isRemovingAllSheets()); formatterProvider.setRemoveRows(existingSheetsActions.isRemovingAllRows()); if (templateFileURL!=null) { formatterProvider.setTemplateFile(getGraph().getRuntimeContext().getContextURL(), templateFileURL); } prepareWriter(); } public static SpreadsheetFormat resolveFormat(SpreadsheetFormat format, String fileURL) { if ((format == SpreadsheetFormat.AUTO && fileURL.matches(SpreadsheetFormatter.XLSX_FILE_PATTERN)) || format == SpreadsheetFormat.XLSX) { return SpreadsheetFormat.XLSX; } else { return SpreadsheetFormat.XLS; } } public static SpreadsheetFormat resolveTemplateFormat(SpreadsheetFormat format, String templateFileURL) { if ((format == SpreadsheetFormat.AUTO && templateFileURL.matches(SpreadsheetFormatter.XLTX_FILE_PATTERN)) || format == SpreadsheetFormat.XLSX) { return SpreadsheetFormat.XLSX; } else { return SpreadsheetFormat.XLS; } } private XLSMapping prepareMapping() throws ComponentNotReadyException { DataRecordMetadata metadata = getInputPort(READ_FROM_PORT).getMetadata(); XLSMapping parsedMapping = null; if (mappingURL != null) { TransformationGraph graph = getGraph(); try { InputStream stream = FileUtils.getInputStream(graph.getRuntimeContext().getContextURL(), mappingURL); parsedMapping = XLSMapping.parse(stream, metadata); } catch (IOException e) { LOGGER.error("cannot instantiate node from XML", e); throw new ComponentNotReadyException(e.getMessage(), e); } } else if (mapping != null) { parsedMapping = XLSMapping.parse(mapping, metadata); } return parsedMapping; } private void prepareWriter() throws ComponentNotReadyException { if (fileURL != null) { writer = new MultiFileWriter(formatterProvider, getGraph().getRuntimeContext().getContextURL(), fileURL); } else { WritableByteChannelIterator channelIterator = new WritableByteChannelIterator(new SystemOutByteChannel()); writer = new MultiFileWriter(formatterProvider, channelIterator); } writer.setLogger(LOGGER); writer.setDictionary(getGraph().getDictionary()); writer.setOutputPort(getOutputPort(OUTPUT_PORT)); writer.setMkDir(mkDirs); writer.setAppendData(true);//in order to allow input stream opening writer.setUseChannel(false); writer.setSkip(recordSkip); writer.setNumRecords(recordCount); writer.setRecordsPerFile(recordsPerFile); if (partition != null) { lookupTable = getGraph().getLookupTable(partition); if (lookupTable == null) { throw new ComponentNotReadyException("Lookup table \"" + partition + "\" not found."); } } else { lookupTable = null; } if (partitionKey != null) { writer.setLookupTable(lookupTable); writer.setPartitionKeyNames(partitionKey.split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX)); writer.setPartitionFileTag(partitionFileTagType); writer.setPartitionUnassignedFileName(partitionUnassignedFileName); if (partitionOutFields != null) { writer.setPartitionOutFields(partitionOutFields.split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX)); } } } @Override public void preExecute() throws ComponentNotReadyException { super.preExecute(); if (firstRun()) { // a phase-dependent part of initialization writer.init(getInputPort(READ_FROM_PORT).getMetadata()); } else { writer.reset(); } } @Override public Result execute() throws Exception { InputPort inPort = getInputPort(READ_FROM_PORT); DataRecord record = new DataRecord(inPort.getMetadata()); record.init(); while (record != null && runIt) { record = inPort.readRecord(record); if (record != null) { writer.write(record); } } writer.finish(); return runIt ? Result.FINISHED_OK : Result.ABORTED; } @Override public void postExecute() throws ComponentNotReadyException { super.postExecute(); try { writer.close(); } catch (IOException e) { throw new ComponentNotReadyException(COMPONENT_TYPE + ": " + e.getMessage(), e); } } @Override public synchronized void free() { super.free(); if (writer != null) { try { writer.close(); } catch (Throwable t) { LOGGER.warn("Resource releasing failed for '" + getId() + "'. " + t.getMessage(), t); } } } }
// jTDS JDBC Driver for Microsoft SQL Server and Sybase // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package net.sourceforge.jtds.jdbc; import java.math.BigDecimal; import java.sql.*; import java.util.Arrays; import java.util.Calendar; import java.util.TimeZone; import java.util.GregorianCalendar; import net.sourceforge.jtds.util.Logger; import junit.framework.ComparisonFailure; import junit.framework.TestSuite; /** * test getting timestamps from the database. * * @author Alin Sinpalean * @version $Id: TimestampTest.java,v 1.32.2.5 2009-08-20 19:44:04 ickzon Exp $ */ public class TimestampTest extends DatabaseTestCase { public TimestampTest(String name) { super(name); } /** * <p> Test for the error wrongly reported in bug #706. </p> */ public void testBug706() throws Exception { Statement sta = con.createStatement(); sta.executeUpdate( "create table #Bug706 (I int primary key, A datetime)" ); PreparedStatement ins = con.prepareStatement( "insert into #Bug706 values(?,?)" ); PreparedStatement sel = con.prepareStatement( "select A from #Bug706 where I = ?" ); long now = System.currentTimeMillis(); // test 10000 millisecond values from now for( int i = 0; i < 10000; i ++ ) { Timestamp ref = new Timestamp( now + i ); ins.setInt( 1, i ); ins.setTimestamp( 2, ref ); ins.executeUpdate(); sel.setInt( 1, i ); ResultSet res = sel.executeQuery(); assertTrue( res.next() ); assertEquals( roundDateTime( ref ), res.getTimestamp( 1 ) ); res.close(); } ins.close(); sel.close(); sta.close(); } /** * Regression test for bug #699, conversion from String value of Timestamp to * Date fails. */ public void testBug699() throws Exception { String ts = "2012-10-26 18:45:01.123"; Statement sta = con.createStatement(); sta.executeUpdate( "create table #Bug699 (A varchar(50))" ); PreparedStatement pst = con.prepareStatement( "insert into #Bug699 values(?)" ); pst.setString( 1, ts ); pst.executeUpdate(); ResultSet res = sta.executeQuery( "select * from #Bug699" ); assertTrue( res.next() ); assertEquals( Date.valueOf( ts.split( " " )[0] ), res.getDate( 1 ) ); assertFalse( res.next() ); sta.close(); } /** * <p> Regression test for bug #682, calling a procedure with a parameter of * type date, time or datetime fails with an error. </p> * */ public void testBug682() throws SQLException { dropProcedure( "sp_bug682" ); Statement st = con.createStatement(); st.executeUpdate( "create procedure sp_bug682 @A datetime as select 1" ); try { st.execute( "{call sp_bug682({ts '2000-01-01 20:59:00.123'})}" ); } finally { st.close(); } } /** * Test for bug #638, preparedStatement.setTimestamp sets seconds to 0. */ public void testBug638() throws Exception { Timestamp ts = Timestamp.valueOf( "2012-10-26 18:45:01.123" ); Statement sta = con.createStatement(); sta.executeUpdate( "create table #Bug638 (A datetime)" ); PreparedStatement pst = con.prepareStatement( "insert into #Bug638 values(?)" ); pst.setTimestamp( 1, ts ); pst.executeUpdate(); ResultSet res = sta.executeQuery( "select * from #Bug638" ); assertTrue( res.next() ); assertEquals( ts, res.getTimestamp( 1 ) ); assertFalse( res.next() ); sta.close(); } public static void main(String args[]) { boolean loggerActive = args.length > 0; Logger.setActive(loggerActive); if (args.length > 0) { junit.framework.TestSuite s = new TestSuite(); for (int i = 0; i < args.length; i++) { s.addTest(new TimestampTest(args[i])); } junit.textui.TestRunner.run(s); } else { junit.textui.TestRunner.run(TimestampTest.class); } // new TimestampTest("test").testOutputParams(); } /** * <p> Regression test for bug #632, valid DATE values range from 0001-01-01 * to 9999-12-31. </p> */ public void testDateRange() throws Exception { Statement stmt = con.createStatement(); boolean dateSupported = false; try { stmt.executeUpdate( "create table #Bug632 ( A date, X int primary key )" ); dateSupported = true; } catch( SQLException e ) { // date type not supported, skip test } if( dateSupported ) { int id = 0; PreparedStatement ins = con.prepareStatement( "insert into #Bug632 values ( ?, ? )" ); PreparedStatement sel = con.prepareStatement( "select A from #Bug632 where X = ?" ); // ensure that invalid year-0 dates are rejected by the driver try { ins.setDate( 1, Date.valueOf( "0000-12-31" ) ); ins.setInt( 2, ++ id ); ins.executeUpdate(); fail(); } catch( SQLException e ) { try { assertEquals( e.getSQLState(), "22007" ); } catch( ComparisonFailure f ) { e.printStackTrace(); throw f; } } // ensure that all valid date values come through for( String date : new String[] { "0001-01-01", "1111-11-11", "8888-08-08", "9999-12-31" } ) { // insert values ins.setDate( 1, Date.valueOf( date ) ); ins.setInt( 2, ++ id ); assertEquals( 1, ins.executeUpdate() ); // read back value sel.setInt( 1, id ); ResultSet res = sel.executeQuery(); assertTrue( res.next() ); assertEquals( Date.valueOf( date ), res.getDate( 1 ) ); res.close(); } } stmt.close(); } public void testBigint0000() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0000 " + " (i decimal(28,10) not null, " + " s char(10) not null) "); final int rowsToAdd = 20; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { String sql = "insert into #t0000 values (" + i + ", 'row" + i + "')"; count += stmt.executeUpdate(sql); } stmt.close(); assertEquals(count, rowsToAdd); PreparedStatement pstmt = con.prepareStatement("select i from #t0000 where i = ?"); pstmt.setLong(1, 7); ResultSet rs = pstmt.executeQuery(); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertEquals(rs.getLong(1), 7); assertTrue("Expected no result set", !rs.next()); pstmt.setLong(1, 8); rs = pstmt.executeQuery(); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertEquals(rs.getLong(1), 8); assertTrue("Expected no result set", !rs.next()); pstmt.close(); } public void testTimestamps0001() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0001 " + " (t1 datetime not null, " + " t2 datetime null, " + " t3 smalldatetime not null, " + " t4 smalldatetime null)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement( "insert into #t0001 values (?, '1998-03-09 15:35:06.4', " + " ?, '1998-03-09 15:35:00')"); Timestamp t0 = Timestamp.valueOf("1998-03-09 15:35:06.4"); Timestamp t1 = Timestamp.valueOf("1998-03-09 15:35:00"); pstmt.setTimestamp(1, t0); pstmt.setTimestamp(2, t1); int count = pstmt.executeUpdate(); assertTrue(count == 1); pstmt.close(); pstmt = con.prepareStatement("select t1, t2, t3, t4 from #t0001"); ResultSet rs = pstmt.executeQuery(); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertEquals(t0, rs.getTimestamp(1)); assertEquals(t0, rs.getTimestamp(2)); assertEquals(t1, rs.getTimestamp(3)); assertEquals(t1, rs.getTimestamp(4)); pstmt.close(); } public void testTimestamps0004() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0004 " + " (mytime datetime not null, " + " mytime2 datetime null, " + " mytime3 datetime null )"); stmt.close(); PreparedStatement pstmt = con.prepareStatement( "insert into #t0004 values ('1964-02-14 10:00:00.0', ?, ?)"); Timestamp t0 = Timestamp.valueOf("1964-02-14 10:00:00.0"); pstmt.setTimestamp(1, t0); pstmt.setTimestamp(2, t0); assertEquals(1, pstmt.executeUpdate()); pstmt.setNull(2, java.sql.Types.TIMESTAMP); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); pstmt = con.prepareStatement("select mytime, mytime2, mytime3 from #t0004"); ResultSet rs = pstmt.executeQuery(); assertNotNull(rs); Timestamp t1, t2, t3; assertTrue("Expected a result set", rs.next()); t1 = rs.getTimestamp(1); t2 = rs.getTimestamp(2); t3 = rs.getTimestamp(3); assertEquals(t0, t1); assertEquals(t0, t2); assertEquals(t0, t3); assertTrue("Expected a result set", rs.next()); t1 = rs.getTimestamp(1); t2 = rs.getTimestamp(2); t3 = rs.getTimestamp(3); assertEquals(t0, t1); assertEquals(t0, t2); assertEquals(null, t3); pstmt.close(); } public void checkEscape( String sql, String expected ) throws Exception { String tmp = con.nativeSQL( sql ); assertEquals( expected, tmp ); } public void testEscapes0006() throws Exception { checkEscape( "select * from tmp where d={d 1999-09-19}", "select * from tmp where d=convert(datetime,'19990919')" ); checkEscape( "select * from tmp where d={d '1999-09-19'}", "select * from tmp where d=convert(datetime,'19990919')" ); checkEscape( "select * from tmp where t={t 12:34:00}", "select * from tmp where t=convert(datetime,'12:34:00')" ); checkEscape( "select * from tmp where ts={ts 1998-12-15 12:34:00.1234}", "select * from tmp where ts=convert(datetime,'19981215 12:34:00.123')" ); checkEscape( "select * from tmp where ts={ts 1998-12-15 12:34:00}", "select * from tmp where ts=convert(datetime,'19981215 12:34:00.000')" ); checkEscape( "select * from tmp where ts={ts 1998-12-15 12:34:00.1}", "select * from tmp where ts=convert(datetime,'19981215 12:34:00.100')" ); checkEscape( "select * from tmp where ts={ts 1998-12-15 12:34:00}", "select * from tmp where ts=convert(datetime,'19981215 12:34:00.000')" ); checkEscape( "select * from tmp where d={d 1999-09-19}", "select * from tmp where d=convert(datetime,'19990919')" ); checkEscape( "select * from tmp where a like '\\%%'", "select * from tmp where a like '\\%%'" ); checkEscape( "select * from tmp where a like 'b%%' {escape 'b'}", "select * from tmp where a like 'b%%' escape 'b'" ); checkEscape( "select * from tmp where a like 'bbb' {escape 'b'}", "select * from tmp where a like 'bbb' escape 'b'" ); checkEscape( "select * from tmp where a='{fn user}'", "select * from tmp where a='{fn user}'" ); checkEscape( "select * from tmp where a={fn user()}", "select * from tmp where a=user_name()" ); } public void testEscapes0007() throws Exception { con.createStatement().execute( "exec dbo.spGetOrdersByItemID 7499, {d '2000-01-01'}, {d '2099-12-31'}" ); } public void testPreparedStatement0007() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0007 " + " (i integer not null, " + " s char(10) not null) "); final int rowsToAdd = 20; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { String sql = "insert into #t0007 values (" + i + ", 'row" + i + "')"; count += stmt.executeUpdate(sql); } stmt.close(); assertEquals(count, rowsToAdd); PreparedStatement pstmt = con.prepareStatement("select s from #t0007 where i = ?"); pstmt.setInt(1, 7); ResultSet rs = pstmt.executeQuery(); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertEquals(rs.getString(1).trim(), "row7"); // assertTrue("Expected no result set", !rs.next()); pstmt.setInt(1, 8); rs = pstmt.executeQuery(); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertEquals(rs.getString(1).trim(), "row8"); assertTrue("Expected no result set", !rs.next()); pstmt.close(); } public void testPreparedStatement0008() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0008 " + " (i integer not null, " + " s char(10) not null) "); PreparedStatement pstmt = con.prepareStatement( "insert into #t0008 values (?, ?)"); final int rowsToAdd = 8; final String theString = "abcdefghijklmnopqrstuvwxyz"; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } assertEquals(count, rowsToAdd); pstmt.close(); ResultSet rs = stmt.executeQuery("select s, i from #t0008"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertEquals(rs.getString(1).trim().length(), rs.getInt(2)); } assertTrue(count == rowsToAdd); stmt.close(); pstmt.close(); } public void testPreparedStatement0009() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0009 " + " (i integer not null, " + " s char(10) not null) "); con.setAutoCommit(false); PreparedStatement pstmt = con.prepareStatement( "insert into #t0009 values (?, ?)"); int rowsToAdd = 8; final String theString = "abcdefghijklmnopqrstuvwxyz"; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } pstmt.close(); assertEquals(count, rowsToAdd); con.rollback(); ResultSet rs = stmt.executeQuery("select s, i from #t0009"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertEquals(rs.getString(1).trim().length(), rs.getInt(2)); } assertEquals(count, 0); con.commit(); pstmt = con.prepareStatement("insert into #t0009 values (?, ?)"); rowsToAdd = 6; count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } assertEquals(count, rowsToAdd); con.commit(); pstmt.close(); rs = stmt.executeQuery("select s, i from #t0009"); count = 0; while (rs.next()) { count++; assertEquals(rs.getString(1).trim().length(), rs.getInt(2)); } assertEquals(count, rowsToAdd); con.commit(); stmt.close(); con.setAutoCommit(true); } public void testTransactions0010() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0010 " + " (i integer not null, " + " s char(10) not null) "); con.setAutoCommit(false); PreparedStatement pstmt = con.prepareStatement( "insert into #t0010 values (?, ?)"); int rowsToAdd = 8; final String theString = "abcdefghijklmnopqrstuvwxyz"; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } assertEquals(count, rowsToAdd); con.rollback(); ResultSet rs = stmt.executeQuery("select s, i from #t0010"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertEquals(rs.getString(1).trim().length(), rs.getInt(2)); } assertEquals(count, 0); rowsToAdd = 6; for (int j = 1; j <= 2; j++) { count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i + ((j - 1) * rowsToAdd)); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } assertEquals(count, rowsToAdd); con.commit(); } rs = stmt.executeQuery("select s, i from #t0010"); count = 0; while (rs.next()) { count++; int i = rs.getInt(2); if (i > rowsToAdd) { i -= rowsToAdd; } assertEquals(rs.getString(1).trim().length(), i); } assertEquals(count, (2 * rowsToAdd)); stmt.close(); pstmt.close(); con.setAutoCommit(true); } public void testEmptyResults0011() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0011 " + " (mytime datetime not null, " + " mytime2 datetime null )"); ResultSet rs = stmt.executeQuery("select mytime, mytime2 from #t0011"); assertNotNull(rs); assertTrue("Expected no result set", !rs.next()); rs = stmt.executeQuery("select mytime, mytime2 from #t0011"); assertTrue("Expected no result set", !rs.next()); stmt.close(); } public void testEmptyResults0012() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0012 " + " (mytime datetime not null, " + " mytime2 datetime null )"); stmt.close(); PreparedStatement pstmt = con.prepareStatement( "select mytime, mytime2 from #t0012"); ResultSet rs = pstmt.executeQuery(); assertNotNull(rs); assertTrue("Expected no result", !rs.next()); rs.close(); rs = pstmt.executeQuery(); assertTrue("Expected no result", !rs.next()); pstmt.close(); } public void testEmptyResults0013() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0013 " + " (mytime datetime not null, " + " mytime2 datetime null )"); ResultSet rs1 = stmt.executeQuery("select mytime, mytime2 from #t0013"); assertNotNull(rs1); assertTrue("Expected no result set", !rs1.next()); stmt.close(); PreparedStatement pstmt = con.prepareStatement( "select mytime, mytime2 from #t0013"); ResultSet rs2 = pstmt.executeQuery(); assertNotNull(rs2); assertTrue("Expected no result", !rs2.next()); pstmt.close(); } public void testForBrowse0014() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0014 (i integer not null)"); PreparedStatement pstmt = con.prepareStatement( "insert into #t0014 values (?)"); final int rowsToAdd = 100; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i); count += pstmt.executeUpdate(); } assertEquals(count, rowsToAdd); pstmt.close(); pstmt = con.prepareStatement("select i from #t0014 for browse"); ResultSet rs = pstmt.executeQuery(); assertNotNull(rs); count = 0; while (rs.next()) { rs.getInt("i"); count++; } assertEquals(count, rowsToAdd); pstmt.close(); rs = stmt.executeQuery("select * from #t0014"); assertNotNull(rs); count = 0; while (rs.next()) { rs.getInt("i"); count++; } assertEquals(count, rowsToAdd); rs = stmt.executeQuery("select * from #t0014"); assertNotNull(rs); count = 0; while (rs.next() && count < 5) { rs.getInt("i"); count++; } assertTrue(count == 5); rs = stmt.executeQuery("select * from #t0014"); assertNotNull(rs); count = 0; while (rs.next()) { rs.getInt("i"); count++; } assertEquals(count, rowsToAdd); stmt.close(); } public void testMultipleResults0015() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0015 " + " (i integer not null, " + " s char(10) not null) "); PreparedStatement pstmt = con.prepareStatement( "insert into #t0015 values (?, ?)"); int rowsToAdd = 8; final String theString = "abcdefghijklmnopqrstuvwxyz"; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } assertEquals(count, rowsToAdd); pstmt.close(); stmt.execute("select s from #t0015 select i from #t0015"); ResultSet rs = stmt.getResultSet(); assertNotNull(rs); count = 0; while (rs.next()) { count++; } assertEquals(count, rowsToAdd); assertTrue(stmt.getMoreResults()); rs = stmt.getResultSet(); assertNotNull(rs); count = 0; while (rs.next()) { count++; } assertEquals(count, rowsToAdd); rs = stmt.executeQuery("select i, s from #t0015"); count = 0; while (rs.next()) { count++; } assertEquals(count, rowsToAdd); stmt.close(); } public void testMissingParameter0016() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0016 " + " (i integer not null, " + " s char(10) not null) "); final int rowsToAdd = 20; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { String sql = "insert into #t0016 values (" + i + ", 'row" + i + "')"; count += stmt.executeUpdate(sql); } stmt.close(); assertEquals(count, rowsToAdd); PreparedStatement pstmt = con.prepareStatement( "select s from #t0016 where i=? and s=?"); // see what happens if neither is set try { pstmt.executeQuery(); assertTrue("Failed to throw exception", false); } catch (SQLException e) { assertTrue("07000".equals(e.getSQLState()) && (e.getMessage().indexOf('1') >= 0 || e.getMessage().indexOf('2') >= 0)); } pstmt.clearParameters(); try { pstmt.setInt(1, 7); pstmt.setString(2, "row7"); pstmt.clearParameters(); pstmt.executeQuery(); assertTrue("Failed to throw exception", false); } catch (SQLException e) { assertTrue("07000".equals(e.getSQLState()) && (e.getMessage().indexOf('1') >= 0 || e.getMessage().indexOf('2') >= 0)); } pstmt.clearParameters(); try { pstmt.setInt(1, 7); pstmt.executeQuery(); assertTrue("Failed to throw exception", false); } catch (SQLException e) { assertTrue("07000".equals(e.getSQLState()) && e.getMessage().indexOf('2') >= 0); } pstmt.clearParameters(); try { pstmt.setString(2, "row7"); pstmt.executeQuery(); assertTrue("Failed to throw exception", false); } catch (SQLException e) { assertTrue("07000".equals(e.getSQLState()) && e.getMessage().indexOf('1') >= 0); } pstmt.close(); } Object[][] getDatatypes() { return new Object[][] { /* { "binary(272)", "0x101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f", new byte[] { 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f } }, */ {"float(6)", "65.4321", new BigDecimal("65.4321")}, {"binary(5)", "0x1213141516", new byte[] { 0x12, 0x13, 0x14, 0x15, 0x16}}, {"varbinary(4)", "0x1718191A", new byte[] { 0x17, 0x18, 0x19, 0x1A}}, {"varchar(8)", "'12345678'", "12345678"}, {"datetime", "'19990815 21:29:59.01'", Timestamp.valueOf("1999-08-15 21:29:59.01")}, {"smalldatetime", "'19990215 20:45'", Timestamp.valueOf("1999-02-15 20:45:00")}, {"float(6)", "65.4321", new Float(65.4321)/* new BigDecimal("65.4321") */}, {"float(14)", "1.123456789", new Double(1.123456789) /*new BigDecimal("1.123456789") */}, {"real", "7654321.0", new Double(7654321.0)}, {"int", "4097", new Integer(4097)}, {"float(6)", "65.4321", new BigDecimal("65.4321")}, {"float(14)", "1.123456789", new BigDecimal("1.123456789")}, {"decimal(10,3)", "1234567.089", new BigDecimal("1234567.089")}, {"numeric(5,4)", "1.2345", new BigDecimal("1.2345")}, {"smallint", "4094", new Short((short) 4094)}, // {"tinyint", "127", new Byte((byte) 127)}, // {"tinyint", "-128", new Byte((byte) -128)}, {"tinyint", "127", new Byte((byte) 127)}, {"tinyint", "128", new Short((short) 128)}, {"money", "19.95", new BigDecimal("19.95")}, {"smallmoney", "9.97", new BigDecimal("9.97")}, {"bit", "1", Boolean.TRUE}, // { "text", "'abcedefg'", "abcdefg" }, /* { "char(1000)", "'123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890'", "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" }, */ // { "char(1000)", "'1234567890'", "1234567890" }, // { "image", "0x0a0a0b", new byte[] { 0x0a, 0x0a, 0x0b } }, }; } public void testOutputParams() throws Exception { Statement stmt = con.createStatement(); dropProcedure("jtds_outputTest"); Object[][] datatypes = getDatatypes(); for (int i = 0; i < datatypes.length; i++) { String valueToAssign; boolean bImage = datatypes[i][0].equals("image"); if (bImage) { valueToAssign = ""; } else { valueToAssign = " = " + datatypes[i][1]; } String sql = "create procedure jtds_outputTest " + "@a1 " + datatypes[i][0] + " = null out " + "as select @a1" + valueToAssign; stmt.executeUpdate(sql); for (int pass = 0; (pass < 2 && !bImage) || pass < 1; pass++) { CallableStatement cstmt = con.prepareCall("{call jtds_outputTest(?)}"); int jtype = getType(datatypes[i][2]); if (pass == 1) cstmt.setObject(1, null, jtype, 10); if (jtype == java.sql.Types.NUMERIC || jtype == java.sql.Types.DECIMAL) { cstmt.registerOutParameter(1, jtype, 10); if (pass == 0) { cstmt.setObject(1, datatypes[i][2], jtype, 10); } } else if (jtype == java.sql.Types.VARCHAR) { cstmt.registerOutParameter(1, jtype); if (pass == 0) { cstmt.setObject(1, datatypes[i][2]); } } else { cstmt.registerOutParameter(1, jtype); if (pass == 0) { cstmt.setObject(1, datatypes[i][2]); } } assertEquals(bImage, cstmt.execute()); while (cstmt.getMoreResults() || cstmt.getUpdateCount() != -1) ; if (jtype == java.sql.Types.VARBINARY) { assertTrue(compareBytes(cstmt.getBytes(1), (byte[]) datatypes[i][2]) == 0); } else if (datatypes[i][2] instanceof Number) { Number n = (Number) cstmt.getObject(1); if (n != null) { assertEquals("Failed on " + datatypes[i][0], n.doubleValue(), ((Number) datatypes[i][2]).doubleValue(), 0.001); } else { assertEquals("Failed on " + datatypes[i][0], n, datatypes[i][2]); } } else { assertEquals("Failed on " + datatypes[i][0], cstmt.getObject(1), datatypes[i][2]); } cstmt.close(); } // for (pass stmt.executeUpdate(" drop procedure jtds_outputTest"); } // for (int stmt.close(); } public void testStatements0020() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0020a ( " + " i1 int not null, " + " s1 char(10) not null " + ") " + ""); stmt.executeUpdate("create table #t0020b ( " + " i2a int not null, " + " i2b int not null, " + " s2 char(10) not null " + ") " + ""); stmt.executeUpdate("create table #t0020c ( " + " i3 int not null, " + " s3 char(10) not null " + ") " + ""); int nextB = 1; int nextC = 1; for (int i = 1; i < 50; i++) { stmt.executeUpdate("insert into #t0020a " + " values(" + i + ", " + " 'row" + i + "') " + ""); for (int j = nextB; (nextB % 5) != 0; j++, nextB++) { stmt.executeUpdate("insert into #t0020b " + " values(" + i + ", " + " " + j + ", " + " 'row" + i + "." + j + "' " + " )" + ""); for (int k = nextC; (nextC % 3) != 0; k++, nextC++) { stmt.executeUpdate("insert into #t0020c " + " values(" + j + ", " + " 'row" + i + "." + j + "." + k + "' " + " )" + ""); } } } Statement stmtA = con.createStatement(); PreparedStatement stmtB = con.prepareStatement( "select i2b, s2 from #t0020b where i2a=?"); PreparedStatement stmtC = con.prepareStatement( "select s3 from #t0020c where i3=?"); ResultSet rs1 = stmtA.executeQuery("select i1 from #t0020a"); assertNotNull(rs1); while (rs1.next()) { stmtB.setInt(1, rs1.getInt("i1")); ResultSet rs2 = stmtB.executeQuery(); assertNotNull(rs2); while (rs2.next()) { stmtC.setInt(1, rs2.getInt(1)); ResultSet rs3 = stmtC.executeQuery(); assertNotNull(rs3); rs3.next(); } } stmt.close(); stmtA.close(); stmtB.close(); stmtC.close(); } public void testBlob0021() throws Exception { byte smallarray[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; byte array1[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; String bigtext1 = "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + ""; Statement stmt = con.createStatement(); dropTable("#t0021"); stmt.executeUpdate( "create table #t0021 ( " + " mybinary binary(16) not null, " + " myimage image not null, " + " mynullimage image null, " + " mytext text not null, " + " mynulltext text null) "); // Insert a row without nulls via a Statement PreparedStatement insert = con.prepareStatement( "insert into #t0021( " + " mybinary, " + " myimage, " + " mynullimage, " + " mytext, " + " mynulltext " + ") " + "values(?, ?, ?, ?, ?) "); insert.setBytes(1, smallarray); insert.setBytes(2, array1); insert.setBytes(3, array1); insert.setString(4, bigtext1); insert.setString(5, bigtext1); int count = insert.executeUpdate(); assertEquals(count, 1); insert.close(); ResultSet rs = stmt.executeQuery("select * from #t0021"); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); byte[] a1 = rs.getBytes("myimage"); byte[] a2 = rs.getBytes("mynullimage"); String s1 = rs.getString("mytext"); String s2 = rs.getString("mynulltext"); assertEquals(0, compareBytes(a1, array1)); assertEquals(0, compareBytes(a2, array1)); assertEquals(bigtext1, s1); assertEquals(bigtext1, s2); stmt.close(); } public void testNestedStatements0022() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0022a " + " (i integer not null, " + " str char(254) not null) "); stmt.executeUpdate("create table #t0022b " + " (i integer not null, " + " t datetime not null) "); PreparedStatement pStmtA = con.prepareStatement( "insert into #t0022a values (?, ?)"); PreparedStatement pStmtB = con.prepareStatement( "insert into #t0022b values (?, getdate())"); final int rowsToAdd = 100; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pStmtA.setInt(1, i); StringBuilder tmp = new StringBuilder(255); while (tmp.length() < 240) { tmp.append("row ").append(i).append(". "); } pStmtA.setString(2, tmp.toString()); count += pStmtA.executeUpdate(); pStmtB.setInt(1, i); pStmtB.executeUpdate(); } pStmtA.close(); pStmtB.close(); assertEquals(count, rowsToAdd); Statement stmtA = con.createStatement(); Statement stmtB = con.createStatement(); count = 0; ResultSet rsA = stmtA.executeQuery("select * from #t0022a"); assertNotNull(rsA); while (rsA.next()) { count++; ResultSet rsB = stmtB.executeQuery( "select * from #t0022b where i=" + rsA.getInt("i")); assertNotNull(rsB); assertTrue("Expected a result set", rsB.next()); assertTrue("Expected no result set", !rsB.next()); } assertEquals(count, rowsToAdd); stmt.close(); stmtA.close(); stmtB.close(); } public void testPrimaryKeyFloat0023() throws Exception { Double d[] = { new Double(-1.0), new Double(1234.543), new Double(0.0), new Double(1), new Double(-2.0), new Double(0.14), new Double(0.79), new Double(1000000.12345), new Double(-1000000.12345), new Double(1000000), new Double(-1000000), new Double(1.7E+308), new Double(1.7E-307) // jikes 1.04 has a bug and can't handle 1.7E-308 }; Statement stmt = con.createStatement(); stmt.executeUpdate("" + "create table #t0023 " + " (pk float not null, " + " type char(30) not null, " + " b bit, " + " str char(30) not null, " + " t int identity, " + " primary key (pk, type)) "); PreparedStatement pstmt = con.prepareStatement( "insert into #t0023 (pk, type, b, str) values(?, 'prepared', 0, ?)"); for (int i = 0; i < d.length; i++) { pstmt.setDouble(1, d[i].doubleValue()); pstmt.setString(2, (d[i]).toString()); int preparedCount = pstmt.executeUpdate(); assertEquals(preparedCount, 1); int adhocCount = stmt.executeUpdate("" + "insert into #t0023 " + " (pk, type, b, str) " + " values(" + " " + d[i] + ", " + " 'adhoc', " + " 1, " + " '" + d[i] + "') "); assertEquals(adhocCount, 1); } int count = 0; ResultSet rs = stmt.executeQuery("select * from #t0023 where type='prepared' order by t"); assertNotNull(rs); while (rs.next()) { assertEquals(d[count].toString(), "" + rs.getDouble("pk")); count++; } assertEquals(count, d.length); count = 0; rs = stmt.executeQuery("select * from #t0023 where type='adhoc' order by t"); while (rs.next()) { assertEquals(d[count].toString(), "" + rs.getDouble("pk")); count++; } assertEquals(count, d.length); stmt.close(); pstmt.close(); } public void testPrimaryKeyReal0024() throws Exception { Float d[] = { new Float(-1.0), new Float(1234.543), new Float(0.0), new Float(1), new Float(-2.0), new Float(0.14), new Float(0.79), new Float(1000000.12345), new Float(-1000000.12345), new Float(1000000), new Float(-1000000), new Float(3.4E+38), new Float(3.4E-38) }; Statement stmt = con.createStatement(); stmt.executeUpdate("" + "create table #t0024 " + " (pk real not null, " + " type char(30) not null, " + " b bit, " + " str char(30) not null, " + " t int identity, " + " primary key (pk, type)) "); PreparedStatement pstmt = con.prepareStatement( "insert into #t0024 (pk, type, b, str) values(?, 'prepared', 0, ?)"); for (int i=0; i < d.length; i++) { pstmt.setFloat(1, d[i].floatValue()); pstmt.setString(2, (d[i]).toString()); int preparedCount = pstmt.executeUpdate(); assertTrue(preparedCount == 1); int adhocCount = stmt.executeUpdate("" + "insert into #t0024 " + " (pk, type, b, str) " + " values(" + " " + d[i] + ", " + " 'adhoc', " + " 1, " + " '" + d[i] + "') "); assertEquals(adhocCount, 1); } int count = 0; ResultSet rs = stmt.executeQuery("select * from #t0024 where type='prepared' order by t"); assertNotNull(rs); while (rs.next()) { String s1 = d[count].toString().trim(); String s2 = ("" + rs.getFloat("pk")).trim(); assertTrue(s1.equalsIgnoreCase(s2)); count++; } assertEquals(count, d.length); count = 0; rs = stmt.executeQuery("select * from #t0024 where type='adhoc' order by t"); while (rs.next()) { String s1 = d[count].toString().trim(); String s2 = ("" + rs.getFloat("pk")).trim(); assertTrue(s1.equalsIgnoreCase(s2)); count++; } assertEquals(count, d.length); stmt.close(); pstmt.close(); } public void testGetBoolean0025() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0025 " + " (i integer, " + " b bit, " + " s char(5), " + " f float) "); // @todo Check which CHAR/VARCHAR values should be true and which should be false. assertTrue(stmt.executeUpdate("insert into #t0025 values(0, 0, 'false', 0.0)") == 1); assertTrue(stmt.executeUpdate("insert into #t0025 values(0, 0, '0', 0.0)") == 1); assertTrue(stmt.executeUpdate("insert into #t0025 values(1, 1, 'true', 7.0)") == 1); assertTrue(stmt.executeUpdate("insert into #t0025 values(2, 1, '1', -5.0)") == 1); ResultSet rs = stmt.executeQuery("select * from #t0025 order by i"); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertTrue(!rs.getBoolean("i")); assertTrue(!rs.getBoolean("b")); assertTrue(!rs.getBoolean("s")); assertTrue(!rs.getBoolean("f")); assertTrue("Expected a result set", rs.next()); assertTrue(!rs.getBoolean("i")); assertTrue(!rs.getBoolean("b")); assertTrue(!rs.getBoolean("s")); assertTrue(!rs.getBoolean("f")); assertTrue("Expected a result set", rs.next()); assertTrue(rs.getBoolean("i")); assertTrue(rs.getBoolean("b")); assertTrue(rs.getBoolean("s")); assertTrue(rs.getBoolean("f")); assertTrue("Expected a result set", rs.next()); assertTrue(rs.getBoolean("i")); assertTrue(rs.getBoolean("b")); assertTrue(rs.getBoolean("s")); assertTrue(rs.getBoolean("f")); assertTrue("Expected no result set", !rs.next()); stmt.close(); } /** * <b>SAfe</b> Tests whether cursor-based statements still work ok when * nested. Similar to <code>testNestedStatements0022</code>, which tests * the same with plain (non-cursor-based) statements (and unfortunately * fails). * * @throws Exception if an Exception occurs (very relevant, huh?) */ public void testNestedStatements0026() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0026a " + " (i integer not null, " + " str char(254) not null) "); stmt.executeUpdate("create table #t0026b " + " (i integer not null, " + " t datetime not null) "); stmt.close(); PreparedStatement pstmtA = con.prepareStatement( "insert into #t0026a values (?, ?)"); PreparedStatement pstmtB = con.prepareStatement( "insert into #t0026b values (?, getdate())"); final int rowsToAdd = 100; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmtA.setInt(1, i); StringBuilder tmp = new StringBuilder(255); while (tmp.length() < 240) { tmp.append("row ").append(i).append(". "); } pstmtA.setString(2, tmp.toString()); count += pstmtA.executeUpdate(); pstmtB.setInt(1, i); pstmtB.executeUpdate(); } assertEquals(count, rowsToAdd); pstmtA.close(); pstmtB.close(); Statement stmtA = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); Statement stmtB = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); count = 0; ResultSet rsA = stmtA.executeQuery("select * from #t0026a"); assertNotNull(rsA); while (rsA.next()) { count++; ResultSet rsB = stmtB.executeQuery( "select * from #t0026b where i=" + rsA.getInt("i")); assertNotNull(rsB); assertTrue("Expected a result set", rsB.next()); assertTrue("Expected no result set", !rsB.next()); rsB.close(); } assertEquals(count, rowsToAdd); stmtA.close(); stmtB.close(); } public void testErrors0036() throws Exception { Statement stmt = con.createStatement(); final int numberToTest = 5; for (int i = 0; i < numberToTest; i++) { String table = "#t0036_no_create_" + i; try { stmt.executeUpdate("drop table " + table); fail("Did not expect to reach here"); } catch (SQLException e) { assertEquals("42S02", e.getSQLState()); } } stmt.close(); } public void testTimestamps0037() throws Exception { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery( "select " + " convert(smalldatetime, '1999-01-02') a, " + " convert(smalldatetime, null) b, " + " convert(datetime, '1999-01-02') c, " + " convert(datetime, null) d "); assertNotNull(rs); assertTrue("Expected a result", rs.next()); assertNotNull(rs.getDate("a")); assertNull(rs.getDate("b")); assertNotNull(rs.getDate("c")); assertNull(rs.getDate("d")); assertNotNull(rs.getTime("a")); assertNull(rs.getTime("b")); assertNotNull(rs.getTime("c")); assertNull(rs.getTime("d")); assertNotNull(rs.getTimestamp("a")); assertNull(rs.getTimestamp("b")); assertNotNull(rs.getTimestamp("c")); assertNull(rs.getTimestamp("d")); assertTrue("Expected no more results", !rs.next()); stmt.close(); } public void testConnection0038() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0038 (" + " keyField char(255) not null, " + " descField varchar(255) not null) "); int count = stmt.executeUpdate("insert into #t0038 values ('value', 'test')"); assertEquals(count, 1); con.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); con.setAutoCommit(false); PreparedStatement ps = con.prepareStatement("update #t0038 set descField=descField where keyField=?"); ps.setString(1, "value"); ps.executeUpdate(); ps.close(); con.commit(); // conn.rollback(); ResultSet resultSet = stmt.executeQuery( "select descField from #t0038 where keyField='value'"); assertTrue(resultSet.next()); stmt.close(); } public void testConnection0039() throws Exception { for (int i = 0; i < 10; i++) { Connection conn = getConnection(); Statement statement = conn.createStatement(); ResultSet resultSet = statement.executeQuery("select 5"); assertNotNull(resultSet); resultSet.close(); statement.close(); conn.close(); } } public void testPreparedStatement0040() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0040 (" + " c255 char(255) not null, " + " v255 varchar(255) not null) "); PreparedStatement pstmt = con.prepareStatement("insert into #t0040 values (?, ?)"); String along = getLongString('a'); String blong = getLongString('b'); pstmt.setString(1, along); pstmt.setString(2, along); int count = pstmt.executeUpdate(); assertEquals(count, 1); pstmt.close(); count = stmt.executeUpdate("" + "insert into #t0040 values ( " + "'" + blong + "', " + "'" + blong + "')"); assertEquals(count, 1); pstmt = con.prepareStatement("select c255, v255 from #t0040 order by c255"); ResultSet rs = pstmt.executeQuery(); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertEquals(rs.getString("c255"), along); assertEquals(rs.getString("v255"), along); assertTrue("Expected a result set", rs.next()); assertEquals(rs.getString("c255"), blong); assertEquals(rs.getString("v255"), blong); assertTrue("Expected no result set", !rs.next()); pstmt.close(); rs = stmt.executeQuery("select c255, v255 from #t0040 order by c255"); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertEquals(rs.getString("c255"), along); assertEquals(rs.getString("v255"), along); assertTrue("Expected a result set", rs.next()); assertEquals(rs.getString("c255"), blong); assertEquals(rs.getString("v255"), blong); assertTrue("Expected no result set", !rs.next()); stmt.close(); } public void testPreparedStatement0041() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0041 " + " (i integer not null, " + " s text not null) "); PreparedStatement pstmt = con.prepareStatement("insert into #t0041 values (?, ?)"); // TODO: Check values final int rowsToAdd = 400; final String theString = getLongString(400); int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } assertEquals(rowsToAdd, count); pstmt.close(); ResultSet rs = stmt.executeQuery("select s, i from #t0041"); assertNotNull(rs); count = 0; while (rs.next()) { rs.getString("s"); count++; } assertEquals(rowsToAdd, count); stmt.close(); } public void testPreparedStatement0042() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0042 (s char(5) null, i integer null, j integer not null)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("insert into #t0042 (s, i, j) values (?, ?, ?)"); pstmt.setString(1, "hello"); pstmt.setNull(2, java.sql.Types.INTEGER); pstmt.setInt(3, 1); int count = pstmt.executeUpdate(); assertEquals(count, 1); pstmt.setInt(2, 42); pstmt.setInt(3, 2); count = pstmt.executeUpdate(); assertEquals(count, 1); pstmt.close(); pstmt = con.prepareStatement("select i from #t0042 order by j"); ResultSet rs = pstmt.executeQuery(); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); rs.getInt(1); assertTrue(rs.wasNull()); assertTrue("Expected a result set", rs.next()); assertEquals(rs.getInt(1), 42); assertTrue(!rs.wasNull()); assertTrue("Expected no result set", !rs.next()); pstmt.close(); } public void testResultSet0043() throws Exception { Statement stmt = con.createStatement(); try { ResultSet rs = stmt.executeQuery("select 1"); assertNotNull(rs); rs.getInt(1); fail("Did not expect to reach here"); } catch (SQLException e) { assertEquals("24000", e.getSQLState()); } stmt.close(); } public void testResultSet0044() throws Exception { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select 1"); assertNotNull(rs); rs.close(); try { rs.next(); fail("Was expecting ResultSet.next() to throw an exception if the ResultSet was closed"); } catch (SQLException e) { assertEquals("HY010", e.getSQLState()); } stmt.close(); } public void testResultSet0045() throws Exception { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select 1"); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); rs.getInt(1); assertTrue("Expected no result set", !rs.next()); try { rs.getInt(1); fail("Did not expect to reach here"); } catch (java.sql.SQLException e) { assertEquals("24000", e.getSQLState()); } stmt.close(); } public void testMetaData0046() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0046 (" + " i integer identity, " + " a integer not null, " + " b integer null ) "); int count = stmt.executeUpdate("insert into #t0046 (a, b) values (-2, -3)"); assertEquals(count, 1); ResultSet rs = stmt.executeQuery("select i, a, b, 17 c from #t0046"); assertNotNull(rs); ResultSetMetaData md = rs.getMetaData(); assertNotNull(md); assertTrue(md.isAutoIncrement(1)); assertTrue(!md.isAutoIncrement(2)); assertTrue(!md.isAutoIncrement(3)); assertTrue(!md.isAutoIncrement(4)); assertTrue(md.isReadOnly(1)); assertTrue(!md.isReadOnly(2)); assertTrue(!md.isReadOnly(3)); // assertTrue(md.isReadOnly(4)); SQL 6.5 does not report this one correctly! assertEquals(md.isNullable(1),java.sql.ResultSetMetaData.columnNoNulls); assertEquals(md.isNullable(2),java.sql.ResultSetMetaData.columnNoNulls); assertEquals(md.isNullable(3),java.sql.ResultSetMetaData.columnNullable); // assert(md.isNullable(4) == java.sql.ResultSetMetaData.columnNoNulls); rs.close(); stmt.close(); } public void testTimestamps0047() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate( "create table #t0047 " + "( " + " t1 datetime not null, " + " t2 datetime null, " + " t3 smalldatetime not null, " + " t4 smalldatetime null " + ")"); String query = "insert into #t0047 (t1, t2, t3, t4) " + " values('2000-01-02 19:35:01.333', " + " '2000-01-02 19:35:01.333', " + " '2000-01-02 19:35:01.333', " + " '2000-01-02 19:35:01.333' " + ")"; int count = stmt.executeUpdate(query); assertEquals(count, 1); ResultSet rs = stmt.executeQuery("select t1, t2, t3, t4 from #t0047"); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); java.sql.Timestamp t1 = rs.getTimestamp("t1"); java.sql.Timestamp t2 = rs.getTimestamp("t2"); java.sql.Timestamp t3 = rs.getTimestamp("t3"); java.sql.Timestamp t4 = rs.getTimestamp("t4"); java.sql.Timestamp r1 = Timestamp.valueOf("2000-01-02 19:35:01.333"); java.sql.Timestamp r2 = Timestamp.valueOf("2000-01-02 19:35:00"); assertEquals(r1, t1); assertEquals(r1, t2); assertEquals(r2, t3); assertEquals(r2, t4); stmt.close(); } public void testTimestamps0048() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate( "create table #t0048 " + "( " + " t1 datetime not null, " + " t2 datetime null, " + " t3 smalldatetime not null, " + " t4 smalldatetime null " + ")"); java.sql.Timestamp r1; java.sql.Timestamp r2; r1 = Timestamp.valueOf("2000-01-02 19:35:01"); r2 = Timestamp.valueOf("2000-01-02 19:35:00"); java.sql.PreparedStatement pstmt = con.prepareStatement( "insert into #t0048 (t1, t2, t3, t4) values(?, ?, ?, ?)"); pstmt.setTimestamp(1, r1); pstmt.setTimestamp(2, r1); pstmt.setTimestamp(3, r1); pstmt.setTimestamp(4, r1); int count = pstmt.executeUpdate(); assertEquals(count, 1); pstmt.close(); ResultSet rs = stmt.executeQuery("select t1, t2, t3, t4 from #t0048"); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); java.sql.Timestamp t1 = rs.getTimestamp("t1"); java.sql.Timestamp t2 = rs.getTimestamp("t2"); java.sql.Timestamp t3 = rs.getTimestamp("t3"); java.sql.Timestamp t4 = rs.getTimestamp("t4"); assertEquals(r1, t1); assertEquals(r1, t2); assertEquals(r2, t3); assertEquals(r2, t4); stmt.close(); } public void testDecimalConversion0058() throws Exception { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select convert(DECIMAL(4,0), 0)"); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertEquals(rs.getInt(1), 0); assertTrue("Expected no result set", !rs.next()); rs = stmt.executeQuery("select convert(DECIMAL(4,0), 1)"); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertEquals(rs.getInt(1), 1); assertTrue("Expected no result set", !rs.next()); rs = stmt.executeQuery("select convert(DECIMAL(4,0), -1)"); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertEquals(rs.getInt(1), -1); assertTrue("Expected no result set", !rs.next()); stmt.close(); } /** * Test for bug [994916] datetime decoding in TdsData.java */ public void testDatetimeRounding1() throws Exception { // Per the SQL Server documentation // Send: 01/01/98 23:59:59.990 // Receive: 01/01/98 23:59:59.990 Calendar sendValue = Calendar.getInstance(); Calendar receiveValue = Calendar.getInstance(); sendValue.set(Calendar.MONTH, Calendar.JANUARY); sendValue.set(Calendar.DAY_OF_MONTH, 1); sendValue.set(Calendar.YEAR, 1998); sendValue.set(Calendar.HOUR_OF_DAY, 23); sendValue.set(Calendar.MINUTE, 59); sendValue.set(Calendar.SECOND, 59); sendValue.set(Calendar.MILLISECOND, 990); receiveValue.set(Calendar.MONTH, Calendar.JANUARY); receiveValue.set(Calendar.DAY_OF_MONTH, 1); receiveValue.set(Calendar.YEAR, 1998); receiveValue.set(Calendar.HOUR_OF_DAY, 23); receiveValue.set(Calendar.MINUTE, 59); receiveValue.set(Calendar.SECOND, 59); receiveValue.set(Calendar.MILLISECOND, 990); Statement stmt = con.createStatement(); stmt.execute("create table #dtr1 (data datetime)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("insert into #dtr1 (data) values (?)"); pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime())); assertEquals(pstmt.executeUpdate(), 1); pstmt.close(); pstmt = con.prepareStatement("select data from #dtr1"); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertEquals(receiveValue.getTime().getTime(), rs.getTimestamp(1).getTime()); assertTrue(!rs.next()); pstmt.close(); rs.close(); } /** * Test for bug [994916] datetime decoding in TdsData.java */ public void testDatetimeRounding2() throws Exception { // Per the SQL Server documentation // Send: 01/01/98 23:59:59.991 // Receive: 01/01/98 23:59:59.990 Calendar sendValue = Calendar.getInstance(); Calendar receiveValue = Calendar.getInstance(); sendValue.set(Calendar.MONTH, Calendar.JANUARY); sendValue.set(Calendar.DAY_OF_MONTH, 1); sendValue.set(Calendar.YEAR, 1998); sendValue.set(Calendar.HOUR_OF_DAY, 23); sendValue.set(Calendar.MINUTE, 59); sendValue.set(Calendar.SECOND, 59); sendValue.set(Calendar.MILLISECOND, 991); receiveValue.set(Calendar.MONTH, Calendar.JANUARY); receiveValue.set(Calendar.DAY_OF_MONTH, 1); receiveValue.set(Calendar.YEAR, 1998); receiveValue.set(Calendar.HOUR_OF_DAY, 23); receiveValue.set(Calendar.MINUTE, 59); receiveValue.set(Calendar.SECOND, 59); receiveValue.set(Calendar.MILLISECOND, 990); Statement stmt = con.createStatement(); stmt.execute("create table #dtr2 (data datetime)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("insert into #dtr2 (data) values (?)"); pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime())); assertEquals(pstmt.executeUpdate(), 1); pstmt.close(); pstmt = con.prepareStatement("select data from #dtr2"); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertEquals(receiveValue.getTime().getTime(), rs.getTimestamp(1).getTime()); assertTrue(!rs.next()); pstmt.close(); rs.close(); } /** * Test for bug [994916] datetime decoding in TdsData.java */ public void testDatetimeRounding3() throws Exception { // Per the SQL Server documentation // Send: 01/01/98 23:59:59.992 // Receive: 01/01/98 23:59:59.993 Calendar sendValue = Calendar.getInstance(); Calendar receiveValue = Calendar.getInstance(); sendValue.set(Calendar.MONTH, Calendar.JANUARY); sendValue.set(Calendar.DAY_OF_MONTH, 1); sendValue.set(Calendar.YEAR, 1998); sendValue.set(Calendar.HOUR_OF_DAY, 23); sendValue.set(Calendar.MINUTE, 59); sendValue.set(Calendar.SECOND, 59); sendValue.set(Calendar.MILLISECOND, 992); receiveValue.set(Calendar.MONTH, Calendar.JANUARY); receiveValue.set(Calendar.DAY_OF_MONTH, 1); receiveValue.set(Calendar.YEAR, 1998); receiveValue.set(Calendar.HOUR_OF_DAY, 23); receiveValue.set(Calendar.MINUTE, 59); receiveValue.set(Calendar.SECOND, 59); receiveValue.set(Calendar.MILLISECOND, 993); Statement stmt = con.createStatement(); stmt.execute("create table #dtr3 (data datetime)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("insert into #dtr3 (data) values (?)"); pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime())); assertEquals(pstmt.executeUpdate(), 1); pstmt.close(); pstmt = con.prepareStatement("select data from #dtr3"); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertEquals(receiveValue.getTime().getTime(), rs.getTimestamp(1).getTime()); assertTrue(!rs.next()); pstmt.close(); rs.close(); } /** * Test for bug [994916] datetime decoding in TdsData.java */ public void testDatetimeRounding4() throws Exception { // Per the SQL Server documentation // Send: 01/01/98 23:59:59.993 // Receive: 01/01/98 23:59:59.993 Calendar sendValue = Calendar.getInstance(); Calendar receiveValue = Calendar.getInstance(); sendValue.set(Calendar.MONTH, Calendar.JANUARY); sendValue.set(Calendar.DAY_OF_MONTH, 1); sendValue.set(Calendar.YEAR, 1998); sendValue.set(Calendar.HOUR_OF_DAY, 23); sendValue.set(Calendar.MINUTE, 59); sendValue.set(Calendar.SECOND, 59); sendValue.set(Calendar.MILLISECOND, 993); receiveValue.set(Calendar.MONTH, Calendar.JANUARY); receiveValue.set(Calendar.DAY_OF_MONTH, 1); receiveValue.set(Calendar.YEAR, 1998); receiveValue.set(Calendar.HOUR_OF_DAY, 23); receiveValue.set(Calendar.MINUTE, 59); receiveValue.set(Calendar.SECOND, 59); receiveValue.set(Calendar.MILLISECOND, 993); Statement stmt = con.createStatement(); stmt.execute("create table #dtr4 (data datetime)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("insert into #dtr4 (data) values (?)"); pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime())); assertEquals(pstmt.executeUpdate(), 1); pstmt.close(); pstmt = con.prepareStatement("select data from #dtr4"); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertEquals(receiveValue.getTime().getTime(), rs.getTimestamp(1).getTime()); assertTrue(!rs.next()); pstmt.close(); rs.close(); } /** * Test for bug [994916] datetime decoding in TdsData.java */ public void testDatetimeRounding5() throws Exception { // Per the SQL Server documentation // Send: 01/01/98 23:59:59.994 // Receive: 01/01/98 23:59:59.993 Calendar sendValue = Calendar.getInstance(); Calendar receiveValue = Calendar.getInstance(); sendValue.set(Calendar.MONTH, Calendar.JANUARY); sendValue.set(Calendar.DAY_OF_MONTH, 1); sendValue.set(Calendar.YEAR, 1998); sendValue.set(Calendar.HOUR_OF_DAY, 23); sendValue.set(Calendar.MINUTE, 59); sendValue.set(Calendar.SECOND, 59); sendValue.set(Calendar.MILLISECOND, 994); receiveValue.set(Calendar.MONTH, Calendar.JANUARY); receiveValue.set(Calendar.DAY_OF_MONTH, 1); receiveValue.set(Calendar.YEAR, 1998); receiveValue.set(Calendar.HOUR_OF_DAY, 23); receiveValue.set(Calendar.MINUTE, 59); receiveValue.set(Calendar.SECOND, 59); receiveValue.set(Calendar.MILLISECOND, 993); Statement stmt = con.createStatement(); stmt.execute("create table #dtr5 (data datetime)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("insert into #dtr5 (data) values (?)"); pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime())); assertEquals(pstmt.executeUpdate(), 1); pstmt.close(); pstmt = con.prepareStatement("select data from #dtr5"); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertEquals(receiveValue.getTime().getTime(), rs.getTimestamp(1).getTime()); assertTrue(!rs.next()); pstmt.close(); rs.close(); } /** * Test for bug [994916] datetime decoding in TdsData.java */ public void testDatetimeRounding6() throws Exception { // Per the SQL Server documentation // Send: 01/01/98 23:59:59.995 // Receive: 01/01/98 23:59:59.997 Calendar sendValue = Calendar.getInstance(); Calendar receiveValue = Calendar.getInstance(); sendValue.set(Calendar.MONTH, Calendar.JANUARY); sendValue.set(Calendar.DAY_OF_MONTH, 1); sendValue.set(Calendar.YEAR, 1998); sendValue.set(Calendar.HOUR_OF_DAY, 23); sendValue.set(Calendar.MINUTE, 59); sendValue.set(Calendar.SECOND, 59); sendValue.set(Calendar.MILLISECOND, 995); receiveValue.set(Calendar.MONTH, Calendar.JANUARY); receiveValue.set(Calendar.DAY_OF_MONTH, 1); receiveValue.set(Calendar.YEAR, 1998); receiveValue.set(Calendar.HOUR_OF_DAY, 23); receiveValue.set(Calendar.MINUTE, 59); receiveValue.set(Calendar.SECOND, 59); receiveValue.set(Calendar.MILLISECOND, 997); Statement stmt = con.createStatement(); stmt.execute("create table #dtr6 (data datetime)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("insert into #dtr6 (data) values (?)"); pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime())); assertEquals(pstmt.executeUpdate(), 1); pstmt.close(); pstmt = con.prepareStatement("select data from #dtr6"); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertEquals(receiveValue.getTime().getTime(), rs.getTimestamp(1).getTime()); assertTrue(!rs.next()); pstmt.close(); rs.close(); } /** * Test for bug [994916] datetime decoding in TdsData.java */ public void testDatetimeRounding7() throws Exception { // Per the SQL Server documentation // Send: 01/01/98 23:59:59.996 // Receive: 01/01/98 23:59:59.997 Calendar sendValue = Calendar.getInstance(); Calendar receiveValue = Calendar.getInstance(); sendValue.set(Calendar.MONTH, Calendar.JANUARY); sendValue.set(Calendar.DAY_OF_MONTH, 1); sendValue.set(Calendar.YEAR, 1998); sendValue.set(Calendar.HOUR_OF_DAY, 23); sendValue.set(Calendar.MINUTE, 59); sendValue.set(Calendar.SECOND, 59); sendValue.set(Calendar.MILLISECOND, 996); receiveValue.set(Calendar.MONTH, Calendar.JANUARY); receiveValue.set(Calendar.DAY_OF_MONTH, 1); receiveValue.set(Calendar.YEAR, 1998); receiveValue.set(Calendar.HOUR_OF_DAY, 23); receiveValue.set(Calendar.MINUTE, 59); receiveValue.set(Calendar.SECOND, 59); receiveValue.set(Calendar.MILLISECOND, 997); Statement stmt = con.createStatement(); stmt.execute("create table #dtr7 (data datetime)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("insert into #dtr7 (data) values (?)"); pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime())); assertEquals(pstmt.executeUpdate(), 1); pstmt.close(); pstmt = con.prepareStatement("select data from #dtr7"); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertEquals(receiveValue.getTime().getTime(), rs.getTimestamp(1).getTime()); assertTrue(!rs.next()); pstmt.close(); rs.close(); } /** * Test for bug [994916] datetime decoding in TdsData.java */ public void testDatetimeRounding8() throws Exception { // Per the SQL Server documentation // Send: 01/01/98 23:59:59.997 // Receive: 01/01/98 23:59:59.997 Calendar sendValue = Calendar.getInstance(); Calendar receiveValue = Calendar.getInstance(); sendValue.set(Calendar.MONTH, Calendar.JANUARY); sendValue.set(Calendar.DAY_OF_MONTH, 1); sendValue.set(Calendar.YEAR, 1998); sendValue.set(Calendar.HOUR_OF_DAY, 23); sendValue.set(Calendar.MINUTE, 59); sendValue.set(Calendar.SECOND, 59); sendValue.set(Calendar.MILLISECOND, 997); receiveValue.set(Calendar.MONTH, Calendar.JANUARY); receiveValue.set(Calendar.DAY_OF_MONTH, 1); receiveValue.set(Calendar.YEAR, 1998); receiveValue.set(Calendar.HOUR_OF_DAY, 23); receiveValue.set(Calendar.MINUTE, 59); receiveValue.set(Calendar.SECOND, 59); receiveValue.set(Calendar.MILLISECOND, 997); Statement stmt = con.createStatement(); stmt.execute("create table #dtr8 (data datetime)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("insert into #dtr8 (data) values (?)"); pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime())); assertEquals(pstmt.executeUpdate(), 1); pstmt.close(); pstmt = con.prepareStatement("select data from #dtr8"); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertEquals(receiveValue.getTime().getTime(), rs.getTimestamp(1).getTime()); assertTrue(!rs.next()); pstmt.close(); rs.close(); } /** * Test for bug [994916] datetime decoding in TdsData.java */ public void testDatetimeRounding9() throws Exception { // Per the SQL Server documentation // Send: 01/01/98 23:59:59.998 // Receive: 01/01/98 23:59:59.997 Calendar sendValue = Calendar.getInstance(); Calendar receiveValue = Calendar.getInstance(); sendValue.set(Calendar.MONTH, Calendar.JANUARY); sendValue.set(Calendar.DAY_OF_MONTH, 1); sendValue.set(Calendar.YEAR, 1998); sendValue.set(Calendar.HOUR_OF_DAY, 23); sendValue.set(Calendar.MINUTE, 59); sendValue.set(Calendar.SECOND, 59); sendValue.set(Calendar.MILLISECOND, 998); receiveValue.set(Calendar.MONTH, Calendar.JANUARY); receiveValue.set(Calendar.DAY_OF_MONTH, 1); receiveValue.set(Calendar.YEAR, 1998); receiveValue.set(Calendar.HOUR_OF_DAY, 23); receiveValue.set(Calendar.MINUTE, 59); receiveValue.set(Calendar.SECOND, 59); receiveValue.set(Calendar.MILLISECOND, 997); Statement stmt = con.createStatement(); stmt.execute("create table #dtr9 (data datetime)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("insert into #dtr9 (data) values (?)"); pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime())); assertEquals(pstmt.executeUpdate(), 1); pstmt.close(); pstmt = con.prepareStatement("select data from #dtr9"); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertEquals(receiveValue.getTime().getTime(), rs.getTimestamp(1).getTime()); assertTrue(!rs.next()); pstmt.close(); rs.close(); } /** * Test for bug [994916] datetime decoding in TdsData.java */ public void testDatetimeRounding10() throws Exception { // Per the SQL Server documentation // Send: 01/01/98 23:59:59.999 // Receive: 01/02/98 00:00:00.000 Calendar sendValue = Calendar.getInstance(); Calendar receiveValue = Calendar.getInstance(); sendValue.set(Calendar.MONTH, Calendar.JANUARY); sendValue.set(Calendar.DAY_OF_MONTH, 1); sendValue.set(Calendar.YEAR, 1998); sendValue.set(Calendar.HOUR_OF_DAY, 23); sendValue.set(Calendar.MINUTE, 59); sendValue.set(Calendar.SECOND, 59); sendValue.set(Calendar.MILLISECOND, 999); receiveValue.set(Calendar.MONTH, Calendar.JANUARY); receiveValue.set(Calendar.DAY_OF_MONTH, 2); receiveValue.set(Calendar.YEAR, 1998); receiveValue.set(Calendar.HOUR_OF_DAY, 0); receiveValue.set(Calendar.MINUTE, 0); receiveValue.set(Calendar.SECOND, 0); receiveValue.set(Calendar.MILLISECOND, 0); Statement stmt = con.createStatement(); stmt.execute("create table #dtr10 (data datetime)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("insert into #dtr10 (data) values (?)"); pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime())); assertEquals(pstmt.executeUpdate(), 1); pstmt.close(); pstmt = con.prepareStatement("select data from #dtr10"); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertEquals(receiveValue.getTime().getTime(), rs.getTimestamp(1).getTime()); assertTrue(!rs.next()); pstmt.close(); rs.close(); } /** * Test for bug [1036059] getTimestamp with Calendar applies tzone offset * wrong way. */ public void testTimestampTimeZone() throws SQLException { Statement stmt = con.createStatement(); stmt.executeUpdate("CREATE TABLE #testTimestampTimeZone (" + "ref INT NOT NULL, " + "tstamp DATETIME NOT NULL)"); stmt.close(); Calendar calNY = Calendar.getInstance (TimeZone.getTimeZone("America/New_York")); Timestamp tsStart = new Timestamp(System.currentTimeMillis()); PreparedStatement pstmt = con.prepareStatement( "INSERT INTO #testTimestampTimeZone (ref, tstamp) VALUES (?, ?)"); pstmt.setInt(1, 0); pstmt.setTimestamp(2, tsStart, calNY); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); pstmt = con.prepareStatement( "SELECT * FROM #testTimestampTimeZone WHERE ref = ?"); pstmt.setInt(1, 0); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); Timestamp ts = rs.getTimestamp("tstamp", calNY); // The difference should be less than 3 milliseconds (i.e. 1 or 2) assertTrue(Math.abs(tsStart.getTime()-ts.getTime()) < 3); rs.close(); pstmt.close(); } /** * Test for bug [1040475] Possible bug when converting to and from * datetime. * <p> * jTDS seems to accept dates outside the range accepted by SQL * Server (i.e. 1753-9999). */ public void testTimestampRange() throws SQLException { Statement stmt = con.createStatement(); stmt.executeUpdate( "CREATE TABLE #testTimestampRange (id INT, d DATETIME)"); PreparedStatement pstmt = con.prepareStatement( "INSERT INTO #testTimestampRange VALUES (?, ?)"); pstmt.setInt(1, 1); try { pstmt.setDate(2, Date.valueOf("0012-03-03")); // This should fail pstmt.executeUpdate(); fail("Expecting an exception to be thrown. Date out of range."); } catch (SQLException ex) { assertEquals("22003", ex.getSQLState()); } pstmt.close(); ResultSet rs = stmt.executeQuery("SELECT * FROM #testTimestampRange"); assertFalse("Row was inserted even though date was out of range.", rs.next()); rs.close(); stmt.close(); } /** * Test that <code>java.sql.Date</code> objects are inserted and retrieved * correctly (ie no time component). */ public void testWriteDate() throws SQLException { Statement stmt = con.createStatement(); stmt.executeUpdate( "CREATE TABLE #testWriteDate (d DATETIME)"); stmt.close(); long time = System.currentTimeMillis(); PreparedStatement pstmt = con.prepareStatement( "INSERT INTO #testWriteDate VALUES (?)"); pstmt.setDate(1, new Date(time)); pstmt.executeUpdate(); pstmt.close(); pstmt = con.prepareStatement("SELECT * FROM #testWriteDate WHERE d=?"); pstmt.setDate(1, new Date(time + 10)); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertTrue(time - rs.getDate(1).getTime() < 24 * 60 * 60 * 1000); Calendar c1 = new GregorianCalendar(), c2 = new GregorianCalendar(); c1.setTime(rs.getTimestamp(1)); c2.setTime(new Timestamp(time)); assertEquals(c2.get(Calendar.YEAR), c1.get(Calendar.YEAR)); assertEquals(c2.get(Calendar.MONTH), c1.get(Calendar.MONTH)); assertEquals(c2.get(Calendar.DAY_OF_MONTH), c1.get(Calendar.DAY_OF_MONTH)); assertEquals(0, c1.get(Calendar.HOUR)); assertEquals(0, c1.get(Calendar.MINUTE)); assertEquals(0, c1.get(Calendar.SECOND)); assertEquals(0, c1.get(Calendar.MILLISECOND)); rs.close(); pstmt.close(); stmt = con.createStatement(); rs = stmt.executeQuery("select datepart(hour, d), datepart(minute, d)," + " datepart(second, d), datepart(millisecond, d)" + " from #testWriteDate"); assertTrue(rs.next()); assertEquals(0, rs.getInt(1)); assertEquals(0, rs.getInt(2)); assertEquals(0, rs.getInt(3)); assertEquals(0, rs.getInt(4)); assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test for bug [1226210] {fn dayofweek()} depends on the language. */ public void testDayOfWeek() throws Exception { PreparedStatement pstmt = con.prepareStatement("SELECT {fn dayofweek({fn curdate()})}"); // Execute and retrieve the day of week with the default @@DATEFIRST ResultSet rs = pstmt.executeQuery(); assertNotNull(rs); assertTrue(rs.next()); int day = rs.getInt(1); // Set a new (very unlikely) value for @@DATEFIRST (Thursday) Statement stmt = con.createStatement(); assertEquals(0, stmt.executeUpdate("SET DATEFIRST 4")); stmt.close(); // Now re-execute and compare the two values rs = pstmt.executeQuery(); assertNotNull(rs); assertTrue(rs.next()); assertEquals(day, rs.getInt(1)); pstmt.close(); } public void testGetString() throws SQLException { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select getdate()"); assertTrue(rs.next()); String stringValue = rs.getString(1); String timestampValue = rs.getTimestamp(1).toString(); assertEquals(stringValue, timestampValue); rs.close(); stmt.close(); } /** * Test for bug [1234531] Dates before 01/01/1900 broken due to DateTime * value markers. */ public void test1899Date() throws Exception { // Per the SQL Server documentation // Send: 12/31/1899 23:59:59.990 // Receive: 12/31/1899 23:59:59.990 Calendar originalValue = Calendar.getInstance(); originalValue.set(Calendar.MONTH, Calendar.DECEMBER); originalValue.set(Calendar.DAY_OF_MONTH, 31); originalValue.set(Calendar.YEAR, 1899); originalValue.set(Calendar.HOUR_OF_DAY, 23); originalValue.set(Calendar.MINUTE, 59); originalValue.set(Calendar.SECOND, 59); originalValue.set(Calendar.MILLISECOND, 990); PreparedStatement pstmt = con.prepareStatement("select ?"); pstmt.setTimestamp(1, new Timestamp(originalValue.getTime().getTime())); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertEquals(originalValue.getTime().getTime(), rs.getTimestamp(1).getTime()); assertFalse(rs.next()); rs.close(); pstmt.close(); } /** * Test for bug [2508201], date field is changed by 3 milliseconds. * * Note: This test will be skipped for data types not supported by the server * the test is run against (e.g. only DATETIME will be tested on SQL server). */ public void testDateTimeDegeneration() throws Exception { Timestamp ts1 = Timestamp.valueOf( "1970-01-01 00:00:00.000" ); String[] types = new String[] { "datetime", "date", "time" }; for( int t = 0; t < types.length; t++ ) { String type = types[t]; // create table and insert initial value Statement stmt = con.createStatement(); boolean dateSupported = false; try { stmt.execute( "create table #t_" + type + " (id int,data " + type + ")" ); dateSupported = true; } catch( SQLException e ) { // date type not supported, skip test } if( dateSupported ) { stmt.execute( "insert into #t_" + type + " values (0,'" + ts1.toString() + "')" ); PreparedStatement ps1 = con.prepareStatement( "update #t_" + type + " set data=? where id=0" ); PreparedStatement ps2 = con.prepareStatement( "select data from #t_" + type ); // read previous value ResultSet rs = ps2.executeQuery(); rs.next(); Timestamp ts2 = rs.getTimestamp( 1 ); // compare current value to initial value assertEquals( type + " value degenerated: ", ts1.toString(), ts2.toString() ); rs.close(); // update DB with current value ps1.setTimestamp( 1, ts2 ); ps1.executeUpdate(); ps1.close(); ps2.close(); } stmt.close(); } } /** * Test conversion between DATETIME, DATE and TIME. */ public void testDateTimeConversion() throws Exception { Timestamp dati = Timestamp.valueOf( "1970-01-01 01:00:00.000" ); Date date = Date .valueOf( "1970-1-1" ); Time time = Time .valueOf( "1:0:0" ); Object[] ref = new Object[] { dati , date , time }; String[] types = new String[] { "datetime", "date", "time" }; for( int t = 0; t < types.length; t++ ) { String type = types[t]; // create table and insert initial value Statement stmt = con.createStatement(); boolean typeSupported = false; try { stmt.execute( "create table #t_" + type + " ( id int, data " + type + " )" ); typeSupported = true; } catch( SQLException e ) { // date type not supported, skip test } if( typeSupported ) { stmt.execute( "insert into #t_" + type + " values ( 0, '" + ref[t].toString() + "' )" ); ResultSet rs = stmt.executeQuery( "select data from #t_" + type ); // read previous value assertTrue( rs.next() ); // read back as DATETIME/DATE/TIME value to check conversion Object[] res = new Object[] { rs.getTimestamp( 1 ), rs.getDate ( 1 ), rs.getTime ( 1 ) }; // compare read value to initial value assertTrue( res[t].getClass().isAssignableFrom( ref[t].getClass() ) ); assertEquals( type + " value degenerated: ", Arrays.toString( ref ), Arrays.toString( res ) ); rs.close(); } stmt.close(); } } /** * Test for bug #541, data type mismatch when using date/time/timestamp JDBC * escapes. */ public void testDateEscaping() throws SQLException { String val = "1970-12-21"; Date ref = Date.valueOf( val ); Statement st = con.createStatement(); ResultSet rs = st.executeQuery( "SELECT {d '" + val + "'}" ); assertTrue ( rs.next() ); assertEquals( ref, rs.getDate( 1 ) ); assertEquals( 1, rs.getMetaData().getColumnCount() ); // assertEquals( Types.DATE, rs.getMetaData().getColumnType( 1 ) ); assertEquals( Types.TIMESTAMP, rs.getMetaData().getColumnType( 1 ) ); rs.close(); st.close(); } /** * Test for bug #541, data type mismatch when using date/time/timestamp JDBC * escapes. */ public void testTimeEscaping() throws SQLException { String val = "14:41:11"; Time ref = Time.valueOf( val ); Statement st = con.createStatement(); ResultSet rs = st.executeQuery( "SELECT {t '" + val + "'}" ); assertTrue ( rs.next() ); assertEquals( ref, rs.getTime( 1 ) ); assertEquals( 1, rs.getMetaData().getColumnCount() ); // assertEquals( Types.TIME, rs.getMetaData().getColumnType( 1 ) ); assertEquals( Types.TIMESTAMP, rs.getMetaData().getColumnType( 1 ) ); rs.close(); st.close(); } /** * Test for bug #541, data type mismatch when using date/time/timestamp JDBC * escapes. */ public void testTimestampEscaping() throws SQLException { String val = "1970-12-21 14:41:11.400"; Timestamp ref = Timestamp.valueOf( val ); Statement st = con.createStatement(); ResultSet rs = st.executeQuery( "SELECT {ts '" + val + "'}" ); assertTrue ( rs.next() ); assertEquals( ref, rs.getTimestamp( 1 ) ); assertEquals( 1, rs.getMetaData().getColumnCount() ); assertEquals( Types.TIMESTAMP, rs.getMetaData().getColumnType( 1 ) ); rs.close(); st.close(); } /** * Test for bug #541, data type mismatch when using date/time/timestamp JDBC * escapes. */ public void testPreparedTimestampEscaping() throws SQLException { String val = "1970-12-21 14:41:11.400"; Timestamp ref = Timestamp.valueOf( val ); PreparedStatement st = con.prepareStatement( "SELECT {ts ?}" ); st.setTimestamp( 1, ref ); ResultSet rs = st.executeQuery(); assertTrue ( rs.next() ); assertEquals( ref, rs.getTimestamp( 1 ) ); assertEquals( 1, rs.getMetaData().getColumnCount() ); assertEquals( Types.TIMESTAMP, rs.getMetaData().getColumnType( 1 ) ); rs.close(); st.close(); } /** * Test for bugs [2181003]/[2349058], an attempt to set a BC date * invalidates driver state/DateTime allows invalid dates through. */ public void testEra() throws SQLException { Statement st = con.createStatement(); st.execute("create table #testEra(data datetime)"); st.close(); String date = "2000-11-11"; Date original = Date.valueOf(date); PreparedStatement in = con.prepareStatement("insert into #testEra values(?)"); PreparedStatement out = con.prepareStatement("select * from #testEra"); ResultSet rs = null; // insert valid value in.setDate(1, Date.valueOf(date)); in.execute(); // check timestamp rs = out.executeQuery(); assertTrue(rs.next()); assertEquals(original,rs.getDate(1)); rs.close(); // attempt to set invalid BC date (January 1st, 300 BC) try { GregorianCalendar gc = new GregorianCalendar(); gc.set(Calendar.ERA, GregorianCalendar.BC); gc.set(Calendar.YEAR, 300); gc.set(Calendar.MONTH,Calendar.JANUARY); gc.set(Calendar.DAY_OF_MONTH, 1); in.setDate(1, new Date(gc.getTime().getTime())); assertTrue("invalid date should cause an exception", false); } catch( SQLException e ) { // expected error } // re-check timestamp rs = out.executeQuery(); assertTrue(rs.next()); assertEquals(original,rs.getDate(1)); rs.close(); in.close(); out.close(); } /** * <p> Round a {@link Timestamp} value to increments of 0,000, 0,003 or 0,007 * seconds, according to the MS SQL Server's DATETIME data type. </p> * * @param ts * original timestamp * * @return * the rounded value */ private Timestamp roundDateTime( Timestamp ts ) { long ret = ts.getTime(); int rem = (int) (ret % 10); ret = ret - rem; switch( rem ) { case 0: // fall through case 1: ret += 0; break; case 2: // fall through case 3: // fall through case 4: ret += 3; break; case 5: // fall through case 6: // fall through case 7: // fall through case 8: // fall through ret += 7; break; case 9: // fall through ret += 10; break; } return new Timestamp( ret ); } }
package net.sourceforge.jtds.test; import java.sql.*; import java.math.BigDecimal; import net.sourceforge.jtds.jdbc.EscapeProcessor; import net.sourceforge.jtds.util.Logger; import junit.framework.TestSuite; /** * test getting timestamps from the database. * */ public class TimestampTest extends DatabaseTestCase { public TimestampTest(String name) { super(name); } public static void main(String args[]) { boolean loggerActive = args.length > 0; Logger.setActive(loggerActive); if (args.length > 0) { junit.framework.TestSuite s = new TestSuite(); for (int i = 0; i < args.length; i++) { s.addTest(new TimestampTest(args[i])); } junit.textui.TestRunner.run(s); } else junit.textui.TestRunner.run(TimestampTest.class); // new TimestampTest("test").testOutputParams(); } public void testBigint0000() throws Exception { Connection cx = getConnection(); dropTable("#t0000"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0000 " + " (i decimal(28,10) not null, " + " s char(10) not null) "); final int rowsToAdd = 20; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { String sql = "insert into #t0000 values (" + i + ", 'row" + i + "')"; count += stmt.executeUpdate(sql); } assertTrue(count == rowsToAdd); PreparedStatement pStmt = cx.prepareStatement("select i from #t0000 where i = ?"); pStmt.setLong(1, 7); ResultSet rs = pStmt.executeQuery(); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertTrue(rs.getLong(1) == 7); assertTrue("Expected no result set", !rs.next()); pStmt.setLong(1, 8); rs = pStmt.executeQuery(); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertTrue(rs.getLong(1) == 8); assertTrue("Expected no result set", !rs.next()); } public void testTimestamps0001() throws Exception { Connection cx = getConnection(); dropTable("#t0001"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0001 " + " (t1 datetime not null, " + " t2 datetime null, " + " t3 smalldatetime not null, " + " t4 smalldatetime null)"); PreparedStatement pStmt = cx.prepareStatement( "insert into #t0001 values (?, '1998-03-09 15:35:06.4', " + " ?, '1998-03-09 15:35:00')"); Timestamp t0 = Timestamp.valueOf("1998-03-09 15:35:06.4"); Timestamp t1 = Timestamp.valueOf("1998-03-09 15:35:00"); pStmt.setTimestamp(1, t0); pStmt.setTimestamp(2, t1); int count = pStmt.executeUpdate(); assertTrue(count == 1); pStmt.close(); pStmt = cx.prepareStatement("select t1, t2, t3, t4 from #t0001"); ResultSet rs = pStmt.executeQuery(); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertEquals(t0, rs.getTimestamp(1)); assertEquals(t0, rs.getTimestamp(2)); assertEquals(t1, rs.getTimestamp(3)); assertEquals(t1, rs.getTimestamp(4)); } public void testTimestamps0004() throws Exception { Connection cx = getConnection(); dropTable("#t0004"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0004 " + " (mytime datetime not null, " + " mytime2 datetime null, " + " mytime3 datetime null )"); PreparedStatement pStmt = cx.prepareStatement( "insert into #t0004 values ('1964-02-14 10:00:00.0', ?, ?)"); Timestamp t0 = Timestamp.valueOf("1964-02-14 10:00:00.0"); pStmt.setTimestamp(1, t0); pStmt.setTimestamp(2, t0); int count = pStmt.executeUpdate(); pStmt.setNull(2, java.sql.Types.TIMESTAMP); count = pStmt.executeUpdate(); pStmt.close(); pStmt = cx.prepareStatement("select mytime, mytime2, mytime3 from #t0004"); ResultSet rs = pStmt.executeQuery(); assertNotNull(rs); Timestamp t1, t2, t3; assertTrue("Expected a result set", rs.next()); t1 = rs.getTimestamp(1); t2 = rs.getTimestamp(2); t3 = rs.getTimestamp(3); assertEquals(t0, t1); assertEquals(t0, t2); assertEquals(t0, t3); assertTrue("Expected a result set", rs.next()); t1 = rs.getTimestamp(1); t2 = rs.getTimestamp(2); t3 = rs.getTimestamp(3); assertEquals(t0, t1); assertEquals(t0, t2); assertEquals(null, t3); } public void testEscape(String sql, String expected) throws Exception { String tmp = EscapeProcessor.nativeSQL(sql); assertEquals(tmp, expected); } public void testEscapes0006() throws Exception { testEscape("select * from tmp where d={d 1999-09-19}", "select * from tmp where d='19990919'"); testEscape("select * from tmp where d={d '1999-09-19'}", "select * from tmp where d='19990919'"); testEscape("select * from tmp where t={t 12:34:00}", "select * from tmp where t='12:34:00'"); testEscape("select * from tmp where ts={ts 1998-12-15 12:34:00.1234}", "select * from tmp where ts='19981215 12:34:00.123'"); testEscape("select * from tmp where ts={ts 1998-12-15 12:34:00}", "select * from tmp where ts='19981215 12:34:00.000'"); testEscape("select * from tmp where ts={ts 1998-12-15 12:34:00.1}", "select * from tmp where ts='19981215 12:34:00.100'"); testEscape("select * from tmp where ts={ts 1998-12-15 12:34:00}", "select * from tmp where ts='19981215 12:34:00.000'"); testEscape("select * from tmp where d={d 1999-09-19}", "select * from tmp where d='19990919'"); testEscape("select * from tmp where a like '\\%%'", "select * from tmp where a like '\\%%'"); testEscape("select * from tmp where a like 'b%%' {escape 'b'}", "select * from tmp where a like 'b%%' escape 'b'"); testEscape("select * from tmp where a like 'bbb' {escape 'b'}", "select * from tmp where a like 'bbb' escape 'b'"); testEscape("select * from tmp where a='{fn user}'", "select * from tmp where a='{fn user}'"); testEscape("select * from tmp where a={fn user()}", "select * from tmp where a=user_name()"); } public void testPreparedStatement0007() throws Exception { Connection cx = getConnection(); dropTable("#t0007"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0007 " + " (i integer not null, " + " s char(10) not null) "); final int rowsToAdd = 20; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { String sql = "insert into #t0007 values (" + i + ", 'row" + i + "')"; count += stmt.executeUpdate(sql); } assertTrue(count == rowsToAdd); PreparedStatement pStmt = cx.prepareStatement("select s from #t0007 where i = ?"); pStmt.setInt(1, 7); ResultSet rs = pStmt.executeQuery(); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertEquals(rs.getString(1).trim(), "row7"); // assertTrue("Expected no result set", !rs.next()); pStmt.setInt(1, 8); rs = pStmt.executeQuery(); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertEquals(rs.getString(1).trim(), "row8"); assertTrue("Expected no result set", !rs.next()); } public void testPreparedStatement0008() throws Exception { Connection cx = getConnection(); dropTable("#t0008"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0008 " + " (i integer not null, " + " s char(10) not null) "); PreparedStatement pStmt = cx.prepareStatement( "insert into #t0008 values (?, ?)"); final int rowsToAdd = 8; final String theString = "abcdefghijklmnopqrstuvwxyz"; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pStmt.setInt(1, i); pStmt.setString(2, theString.substring(0, i)); count += pStmt.executeUpdate(); } assertTrue(count == rowsToAdd); pStmt.close(); ResultSet rs = stmt.executeQuery("select s, i from #t0008"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertTrue(rs.getString(1).trim().length() == rs.getInt(2)); } assertTrue(count == rowsToAdd); } public void testPreparedStatement0009() throws Exception { Connection cx = getConnection(); dropTable("#t0009"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0009 " + " (i integer not null, " + " s char(10) not null) "); cx.setAutoCommit(false); PreparedStatement pStmt = cx.prepareStatement( "insert into #t0009 values (?, ?)"); int rowsToAdd = 8; final String theString = "abcdefghijklmnopqrstuvwxyz"; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pStmt.setInt(1, i); pStmt.setString(2, theString.substring(0, i)); count += pStmt.executeUpdate(); } pStmt.close(); assertTrue(count == rowsToAdd); cx.rollback(); stmt = cx.createStatement(); ResultSet rs = stmt.executeQuery("select s, i from #t0009"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertTrue(rs.getString(1).trim().length() == rs.getInt(2)); } assertTrue(count == 0); cx.commit(); stmt.close(); pStmt = cx.prepareStatement("insert into #t0009 values (?, ?)"); rowsToAdd = 6; count = 0; for (int i = 1; i <= rowsToAdd; i++) { pStmt.setInt(1, i); pStmt.setString(2, theString.substring(0, i)); count += pStmt.executeUpdate(); } assertTrue(count == rowsToAdd); cx.commit(); pStmt.close(); stmt = cx.createStatement(); rs = stmt.executeQuery("select s, i from #t0009"); count = 0; while (rs.next()) { count++; assertTrue(rs.getString(1).trim().length() == rs.getInt(2)); } assertTrue(count == rowsToAdd); cx.commit(); stmt.close(); cx.setAutoCommit(true); } public void testTransactions0010() throws Exception { Connection cx = getConnection(); dropTable("#t0010"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0010 " + " (i integer not null, " + " s char(10) not null) "); cx.setAutoCommit(false); PreparedStatement pStmt = cx.prepareStatement( "insert into #t0010 values (?, ?)"); int rowsToAdd = 8; final String theString = "abcdefghijklmnopqrstuvwxyz"; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pStmt.setInt(1, i); pStmt.setString(2, theString.substring(0, i)); count += pStmt.executeUpdate(); } assertTrue(count == rowsToAdd); cx.rollback(); stmt = cx.createStatement(); ResultSet rs = stmt.executeQuery("select s, i from #t0010"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertTrue(rs.getString(1).trim().length() == rs.getInt(2)); } assertTrue(count == 0); cx.commit(); rowsToAdd = 6; for (int j = 1; j <= 2; j++) { count = 0; for (int i = 1; i <= rowsToAdd; i++) { pStmt.setInt(1, i + ((j-1) * rowsToAdd)); pStmt.setString(2, theString.substring(0, i)); count += pStmt.executeUpdate(); } assertTrue(count == rowsToAdd); cx.commit(); } rs = stmt.executeQuery("select s, i from #t0010"); count = 0; while (rs.next()) { count++; int i = rs.getInt(2); if (i > rowsToAdd) i -= rowsToAdd; assertTrue(rs.getString(1).trim().length() == i); } assertTrue(count == (2 * rowsToAdd)); cx.commit(); cx.setAutoCommit(true); } public void testEmptyResults0011() throws Exception { Connection cx = getConnection(); dropTable("#t0011"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0011 " + " (mytime datetime not null, " + " mytime2 datetime null )"); ResultSet rs = stmt.executeQuery("select mytime, mytime2 from #t0011"); assertNotNull(rs); assertTrue("Expected no result set", !rs.next()); stmt.close(); stmt = cx.createStatement(); rs = stmt.executeQuery("select mytime, mytime2 from #t0011"); assertTrue("Expected no result set", !rs.next()); stmt.close(); } public void testEmptyResults0012() throws Exception { Connection cx = getConnection(); dropTable("#t0012"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0012 " + " (mytime datetime not null, " + " mytime2 datetime null )"); // cx.close(); // cx = getConnection(); PreparedStatement pStmt = cx.prepareStatement( "select mytime, mytime2 from #t0012"); ResultSet rs = pStmt.executeQuery(); assertNotNull(rs); assertTrue("Expected no result set", !rs.next()); rs.close(); rs = pStmt.executeQuery(); assertTrue("Expected no result set", !rs.next()); pStmt.close(); } public void testEmptyResults0013() throws Exception { Connection cx = getConnection(); dropTable("#t0013"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0013 " + " (mytime datetime not null, " + " mytime2 datetime null )"); ResultSet rs1 = stmt.executeQuery("select mytime, mytime2 from #t0013"); assertNotNull(rs1); assertTrue("Expected no result set", !rs1.next()); PreparedStatement pStmt = cx.prepareStatement( "select mytime, mytime2 from #t0013"); ResultSet rs2 = pStmt.executeQuery(); assertNotNull(rs2); assertTrue("Expected no result set", !rs2.next()); } public void testForBrowse0014() throws Exception { Connection cx = getConnection(); dropTable("#t0014"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0014 (i integer not null)"); PreparedStatement pStmt = cx.prepareStatement( "insert into #t0014 values (?)"); final int rowsToAdd = 100; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pStmt.setInt(1, i); count += pStmt.executeUpdate(); } assertTrue(count == rowsToAdd); pStmt.close(); pStmt = cx.prepareStatement("select i from #t0014 for browse"); ResultSet rs = pStmt.executeQuery(); assertNotNull(rs); count = 0; while (rs.next()) { int n = rs.getInt("i"); count++; } assertTrue(count == rowsToAdd); pStmt.close(); rs = stmt.executeQuery("select * from #t0014"); assertNotNull(rs); count = 0; while (rs.next()) { int n = rs.getInt("i"); count++; } assertTrue(count == rowsToAdd); rs = stmt.executeQuery("select * from #t0014"); assertNotNull(rs); count = 0; while (rs.next() && count < 5) { int n = rs.getInt("i"); count++; } assertTrue(count == 5); rs = stmt.executeQuery("select * from #t0014"); assertNotNull(rs); count = 0; while (rs.next()) { int n = rs.getInt("i"); count++; } assertTrue(count == rowsToAdd); stmt.close(); } public void testMultipleResults0015() throws Exception { Connection cx = getConnection(); dropTable("#t0015"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0015 " + " (i integer not null, " + " s char(10) not null) "); PreparedStatement pStmt = cx.prepareStatement( "insert into #t0015 values (?, ?)"); int rowsToAdd = 8; final String theString = "abcdefghijklmnopqrstuvwxyz"; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pStmt.setInt(1, i); pStmt.setString(2, theString.substring(0, i)); count += pStmt.executeUpdate(); } assertTrue(count == rowsToAdd); pStmt.close(); stmt = cx.createStatement(); ResultSet rs = stmt.executeQuery("select s from #t0015 select i from #t0015"); assertNotNull(rs); count = 0; while (rs.next()) { count++; } assertTrue(count == rowsToAdd); assertTrue(stmt.getMoreResults()); rs = stmt.getResultSet(); assertNotNull(rs); count = 0; while (rs.next()) { count++; } assertTrue(count == rowsToAdd); rs = stmt.executeQuery("select i, s from #t0015"); count = 0; while (rs.next()) { count++; } assertTrue(count == rowsToAdd); cx.close(); } public void testMissingParameter0016() throws Exception { Connection cx = getConnection(); dropTable("#t0016"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0016 " + " (i integer not null, " + " s char(10) not null) "); stmt = cx.createStatement(); final int rowsToAdd = 20; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { String sql = "insert into #t0016 values (" + i + ", 'row" + i + "')"; count += stmt.executeUpdate(sql); } assertTrue(count == rowsToAdd); PreparedStatement pStmt = cx.prepareStatement( "select s from #t0016 where i=? and s=?"); // see what happens if neither is set try { ResultSet rs = pStmt.executeQuery(); assertTrue("Failed to throw exception", false); } catch (SQLException e) { assertTrue( (e.getMessage().equals("parameter #1 has not been set") || e.getMessage().equals("parameter #2 has not been set"))); } pStmt.clearParameters(); try { pStmt.setInt(1, 7); pStmt.setString(2, "row7"); pStmt.clearParameters(); ResultSet rs = pStmt.executeQuery(); assertTrue("Failed to throw exception", false); } catch (SQLException e) { assertTrue( (e.getMessage().equals("parameter #1 has not been set") || e.getMessage().equals("parameter #2 has not been set"))); } pStmt.clearParameters(); try { pStmt.setInt(1, 7); ResultSet rs = pStmt.executeQuery(); assertTrue("Failed to throw exception", false); } catch (SQLException e) { assertTrue(e.getMessage().equals("parameter #2 has not been set")); } pStmt.clearParameters(); try { pStmt.setString(2, "row7"); ResultSet rs = pStmt.executeQuery(); assertTrue("Failed to throw exception", false); } catch (SQLException e) { assertTrue(e.getMessage().equals("parameter #1 has not been set")); } } Object[][] getDatatypes() { return new Object[][] { /* { "binary(272)", "0x101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f" + "101112131415161718191a1b1c1d1e1f", new byte[] { 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f } }, */ { "float(6)", "65.4321", new BigDecimal("65.4321") }, { "binary(5)", "0x1213141516", new byte[] { 0x12, 0x13, 0x14, 0x15, 0x16 } }, { "varbinary(4)", "0x1718191A", new byte[] { 0x17, 0x18, 0x19, 0x1A } }, { "varchar(8)", "'12345678'", new String("12345678") }, { "datetime", "'19990815 21:29:59.01'", Timestamp.valueOf("1999-08-15 21:29:59.01") }, { "smalldatetime", "'19990215 20:45'", Timestamp.valueOf("1999-02-15 20:45:00") }, { "float(6)", "65.4321", new Float(65.4321)/* new BigDecimal("65.4321") */}, { "float(14)", "1.123456789", new Double(1.123456789) /*new BigDecimal("1.123456789") */}, { "real", "7654321.0", new Double(7654321.0) }, { "int", "4097", new Integer(4097) }, { "float(6)", "65.4321", new BigDecimal("65.4321") }, { "float(14)", "1.123456789", new BigDecimal("1.123456789") }, { "decimal(10,3)", "1234567.089", new BigDecimal("1234567.089") }, { "numeric(5,4)", "1.2345", new BigDecimal("1.2345") }, { "smallint", "4094", new Short((short)4094) }, // { "tinyint", "127", new Byte((byte)127) }, // { "tinyint", "-128", new Byte((byte)-128) }, { "smallint", "127", new Byte((byte)127) }, { "smallint", "-128", new Byte((byte)-128) }, { "money", "19.95", new BigDecimal("19.95") }, { "smallmoney", "9.97", new BigDecimal("9.97") }, { "bit", "1", Boolean.TRUE }, // { "text", "'abcedefg'", new String("abcdefg") }, /* { "char(1000)", "'123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890'", new String("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890") }, */ // { "char(1000)", "'1234567890'", new String("1234567890") }, { "image", "0x0a0a0b", new byte[] { 0x0a, 0x0a, 0x0b } }, }; } public void testOutputParams() throws Exception { Statement stmt = con.createStatement(); dropProcedure("#jtds_outputTest"); Object[][] datatypes = getDatatypes(); for (int i = 0; i < datatypes.length; i++) { String valueToAssign; boolean bImage = datatypes[i][0].equals("image"); if( bImage ) valueToAssign = ""; else valueToAssign = " = " + datatypes[i][1]; String sql = "create procedure #jtds_outputTest " + "@a1 " + datatypes[i][0] + " = null out " + "as select @a1" + valueToAssign; stmt.executeUpdate(sql); for( int pass=0; (pass<2 && !bImage) || pass<1; pass++ ) { CallableStatement cstmt = con.prepareCall("{call #jtds_outputTest(?)}"); int jtype = getType(datatypes[i][2]); if (pass == 1) cstmt.setObject(1,null,jtype,10); if (jtype == java.sql.Types.NUMERIC || jtype == java.sql.Types.DECIMAL) { cstmt.registerOutParameter(1, jtype, 10); if (pass == 0) cstmt.setObject(1,datatypes[i][2],jtype,10); } else if (jtype == java.sql.Types.VARCHAR) { cstmt.registerOutParameter(1, jtype, 255); if (pass == 0) cstmt.setObject(1,datatypes[i][2]); } else { cstmt.registerOutParameter(1, jtype); if (pass == 0) cstmt.setObject(1,datatypes[i][2]); } if( !bImage ) assertTrue(!cstmt.execute()); while(cstmt.getUpdateCount() != -1 && cstmt.getMoreResults()); if (jtype == java.sql.Types.VARBINARY) { assertTrue(compareBytes(cstmt.getBytes(1), (byte[])datatypes[i][2]) == 0); } else if (datatypes[i][2] instanceof Number) { Number n = (Number)cstmt.getObject(1); assertEquals("Failed on " + datatypes[i][0], ((Number)cstmt.getObject(1)).doubleValue(), ((Number)datatypes[i][2]).doubleValue(),0.001); } else { assertEquals("Failed on " + datatypes[i][0], cstmt.getObject(1), datatypes[i][2]); } } // for (pass stmt.executeUpdate(" drop procedure #jtds_outputTest"); } // for (int } public void testDatatypes0017() throws Exception { Connection cx = getConnection(); Statement stmt = cx.createStatement(); dropTable("#t0017"); /* remove ( ), convert , to _ myXXXX, mynullXXXX // Insert a row without nulls via a Statement // Insert a row with nulls via a Statement // Insert a row without nulls via a PreparedStatement // Insert a row with nulls via a PreparedStatement // Now verify that the database has the same data as we put in. */ } public void testStatements0020() throws Exception { Connection cx = getConnection(); dropTable("#t0020a"); dropTable("#t0020b"); dropTable("#t0020c"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0020a ( " + " i1 int not null, " + " s1 char(10) not null " + ") " + ""); stmt.executeUpdate("create table #t0020b ( " + " i2a int not null, " + " i2b int not null, " + " s2 char(10) not null " + ") " + ""); stmt.executeUpdate("create table #t0020c ( " + " i3 int not null, " + " s3 char(10) not null " + ") " + ""); int nextB = 1; int nextC = 1; for (int i = 1; i < 50; i++) { stmt.executeUpdate("insert into #t0020a " + " values(" + i + ", " + " 'row" + i + "') " + ""); for (int j = nextB; (nextB % 5) != 0; j++, nextB++) { stmt.executeUpdate("insert into #t0020b " + " values(" + i + ", " + " " + j + ", " + " 'row" + i + "." + j + "' " + " )" + ""); for (int k = nextC; (nextC % 3) != 0; k++, nextC++) { stmt.executeUpdate("insert into #t0020c " + " values(" + j + ", " + " 'row" + i + "." + j + "." + k + "' " + " )" + ""); } } } Statement stmtA = cx.createStatement(); PreparedStatement stmtB = cx.prepareStatement( "select i2b, s2 from #t0020b where i2a=?"); PreparedStatement stmtC = cx.prepareStatement( "select s3 from #t0020c where i3=?"); ResultSet rs1 = stmtA.executeQuery("select i1 from #t0020a"); assertNotNull(rs1); while (rs1.next()) { int i1 = rs1.getInt("i1"); stmtB.setInt(1, rs1.getInt("i1")); ResultSet rs2 = stmtB.executeQuery(); assertNotNull(rs2); while (rs2.next()) { stmtC.setInt(1, rs2.getInt(1)); ResultSet rs3 = stmtC.executeQuery(); assertNotNull(rs3); if (rs3.next()) { // nop } } } } public void testBlob0021() throws Exception { byte smallarray[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; byte array1[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; String bigtext1 = "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + ""; Connection cx = getConnection(); Statement stmt = cx.createStatement(); dropTable("#t0021"); stmt.executeUpdate( "create table #t0021 ( " + " mybinary binary(16) not null, " + " myimage image not null, " + " mynullimage image null, " + " mytext text not null, " + " mynulltext text null) "); // Insert a row without nulls via a Statement PreparedStatement insert = cx.prepareStatement( "insert into #t0021( " + " mybinary, " + " myimage, " + " mynullimage, " + " mytext, " + " mynulltext " + ") " + "values(?, ?, ?, ?, ?) "); insert.setBytes(1, smallarray); insert.setBytes(2, array1); insert.setBytes(3, array1); insert.setString(4, "abcd" /* bigtext1 */); insert.setString(5, "defg" /* bigtext1 */); int count = insert.executeUpdate(); assertTrue(count == 1); insert.close(); ResultSet rs = stmt.executeQuery("select * from #t0021"); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); byte[] a1 = rs.getBytes("myimage"); byte[] a2 = rs.getBytes("mynullimage"); assertTrue(compareBytes(a1, array1) == 0); assertTrue(compareBytes(a2, array1) == 0); cx.close(); } public void testNestedStatements0022() throws Exception { Connection cx = getConnection(); dropTable("#t0022a"); dropTable("#t0022b"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0022a " + " (i integer not null, " + " str char(254) not null) "); stmt.executeUpdate("create table #t0022b " + " (i integer not null, " + " t datetime not null) "); PreparedStatement pStmtA = cx.prepareStatement( "insert into #t0022a values (?, ?)"); PreparedStatement pStmtB = cx.prepareStatement( "insert into #t0022b values (?, getdate())"); final int rowsToAdd = 1000; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pStmtA.setInt(1, i); String tmp = ""; while (tmp.length() < 240) { tmp = tmp + "row " + i + ". "; } pStmtA.setString(2, tmp); count += pStmtA.executeUpdate(); pStmtB.setInt(1, i); pStmtB.executeUpdate(); } assertTrue(count == rowsToAdd); Statement stmtA = cx.createStatement(); Statement stmtB = cx.createStatement(); count = 0; ResultSet rsA = stmtA.executeQuery("select * from #t0022a"); assertNotNull(rsA); while (rsA.next()) { count++; ResultSet rsB = stmtB.executeQuery( "select * from #t0022b where i=" + rsA.getInt("i")); assertNotNull(rsB); assertTrue("Expected a result set", rsB.next()); assertTrue("Expected no result set", !rsB.next()); } assertTrue(count == rowsToAdd); stmtA.close(); stmtB.close(); } public void testPrimaryKeyFloat0023() throws Exception { Double d[] = { new Double(-1.0), new Double(1234.543), new Double(0.0), new Double(1), new Double(-2.0), new Double(0.14), new Double(0.79), new Double(1000000.12345), new Double(-1000000.12345), new Double(1000000), new Double(-1000000), new Double(1.7E+308), new Double(1.7E-307) // jikes 1.04 has a bug and can't handle 1.7E-308 }; Connection cx = getConnection(); dropTable("#t0023"); Statement stmt = cx.createStatement(); stmt.executeUpdate("" + "create table #t0023 " + " (pk float not null, " + " type char(30) not null, " + " b bit, " + " str char(30) not null, " + " t int identity(1,1), " + " primary key (pk, type)) "); PreparedStatement pStmt = cx.prepareStatement( "insert into #t0023 (pk, type, b, str) values(?, 'prepared', 0, ?)"); for (int i = 0; i < d.length; i++) { pStmt.setDouble(1, d[i].doubleValue()); pStmt.setString(2, (d[i]).toString()); int preparedCount = pStmt.executeUpdate(); assertTrue(preparedCount == 1); int adhocCount = stmt.executeUpdate("" + "insert into #t0023 " + " (pk, type, b, str) " + " values(" + " " + d[i] + ", " + " 'adhoc', " + " 1, " + " '" + d[i] + "') "); assertTrue(adhocCount == 1); } int count = 0; ResultSet rs = stmt.executeQuery("select * from #t0023 where type='prepared' order by t"); assertNotNull(rs); while (rs.next()) { assertEquals(d[count].toString(), "" + rs.getDouble("pk")); count++; } assertTrue(count == d.length); count = 0; rs = stmt.executeQuery("select * from #t0023 where type='adhoc' order by t"); while (rs.next()) { assertEquals(d[count].toString(), "" + rs.getDouble("pk")); count++; } assertTrue(count == d.length); } public void testPrimaryKeyReal0024() throws Exception { Float d[] = { new Float(-1.0), new Float(1234.543), new Float(0.0), new Float(1), new Float(-2.0), new Float(0.14), new Float(0.79), new Float(1000000.12345), new Float(-1000000.12345), new Float(1000000), new Float(-1000000), new Float(3.4E+38), new Float(3.4E-38) }; Connection cx = getConnection(); dropTable("#t0024"); Statement stmt = cx.createStatement(); stmt.executeUpdate("" + "create table #t0024 " + " (pk real not null, " + " type char(30) not null, " + " b bit, " + " str char(30) not null, " + " t int identity(1,1), " +" primary key (pk, type)) "); PreparedStatement pStmt = cx.prepareStatement( "insert into #t0024 (pk, type, b, str) values(?, 'prepared', 0, ?)"); for (int i=0; i < d.length; i++) { pStmt.setFloat(1, d[i].floatValue()); pStmt.setString(2, (d[i]).toString()); int preparedCount = pStmt.executeUpdate(); assertTrue(preparedCount == 1); int adhocCount = stmt.executeUpdate("" + "insert into #t0024 " + " (pk, type, b, str) " + " values(" + " " + d[i] + ", " + " 'adhoc', " + " 1, " + " '" + d[i] + "') "); assertTrue(adhocCount == 1); } int count = 0; ResultSet rs = stmt.executeQuery("select * from #t0024 where type='prepared' order by t"); assertNotNull(rs); while (rs.next()) { String s1 = d[count].toString().trim(); String s2 = ("" + rs.getFloat("pk")).trim(); assertTrue(s1.equalsIgnoreCase(s2)); count++; } assertTrue(count == d.length); count = 0; rs = stmt.executeQuery("select * from #t0024 where type='adhoc' order by t"); while (rs.next()) { String s1 = d[count].toString().trim(); String s2 = ("" + rs.getFloat("pk")).trim(); assertTrue(s1.equalsIgnoreCase(s2)); count++; } assertTrue(count == d.length); } public void testGetBoolean0025() throws Exception { Connection cx = getConnection(); dropTable("#t0025"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0025 " + " (i integer, " + " b bit, " + " s char(5), " + " f float) "); // @todo Check which CHAR/VARCHAR values should be true and which should be false. assertTrue(stmt.executeUpdate("insert into #t0025 values(0, 0, 'false', 0.0)") == 1); assertTrue(stmt.executeUpdate("insert into #t0025 values(0, 0, '0', 0.0)") == 1); assertTrue(stmt.executeUpdate("insert into #t0025 values(1, 1, 'true', 7.0)") == 1); assertTrue(stmt.executeUpdate("insert into #t0025 values(2, 1, '1', -5.0)") == 1); ResultSet rs = stmt.executeQuery("select * from #t0025 order by i"); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertTrue(!rs.getBoolean("i")); assertTrue(!rs.getBoolean("b")); assertTrue(!rs.getBoolean("s")); assertTrue(!rs.getBoolean("f")); assertTrue("Expected a result set", rs.next()); assertTrue(!rs.getBoolean("i")); assertTrue(!rs.getBoolean("b")); assertTrue(!rs.getBoolean("s")); assertTrue(!rs.getBoolean("f")); assertTrue("Expected a result set", rs.next()); assertTrue(rs.getBoolean("i")); assertTrue(rs.getBoolean("b")); assertTrue(rs.getBoolean("s")); assertTrue(rs.getBoolean("f")); assertTrue("Expected a result set", rs.next()); assertTrue(rs.getBoolean("i")); assertTrue(rs.getBoolean("b")); assertTrue(rs.getBoolean("s")); assertTrue(rs.getBoolean("f")); assertTrue("Expected no result set", !rs.next()); } /** * <b>SAfe</b> Tests whether cursor-based statements still work ok when * nested. Similar to <code>testNestedStatements0022</code>, which tests * the same with plain (non-cursor-based) statements (and unfortunately * fails). * * @throws Exception if an Exception occurs (very relevant, huh?) */ public void testNestedStatements0026() throws Exception { Connection cx = getConnection(); dropTable("#t0026a"); dropTable("#t0026b"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0026a " + " (i integer not null, " + " str char(254) not null) "); stmt.executeUpdate("create table #t0026b " + " (i integer not null, " + " t datetime not null) "); stmt.close(); PreparedStatement pStmtA = cx.prepareStatement( "insert into #t0026a values (?, ?)"); PreparedStatement pStmtB = cx.prepareStatement( "insert into #t0026b values (?, getdate())"); final int rowsToAdd = 1000; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pStmtA.setInt(1, i); String tmp = ""; while (tmp.length() < 240) { tmp = tmp + "row " + i + ". "; } pStmtA.setString(2, tmp); count += pStmtA.executeUpdate(); pStmtB.setInt(1, i); pStmtB.executeUpdate(); } assertTrue(count == rowsToAdd); pStmtA.close(); pStmtB.close(); Statement stmtA = cx.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); Statement stmtB = cx.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); count = 0; ResultSet rsA = stmtA.executeQuery("select * from #t0026a"); assertNotNull(rsA); while (rsA.next()) { count++; ResultSet rsB = stmtB.executeQuery( "select * from #t0026b where i=" + rsA.getInt("i")); assertNotNull(rsB); assertTrue("Expected a result set", rsB.next()); assertTrue("Expected no result set", !rsB.next()); } assertTrue(count == rowsToAdd); stmtA.close(); stmtB.close(); } public void testErrors0036() throws Exception { Connection cx = getConnection(); Statement stmt = cx.createStatement(); final int numberToTest = 5; for (int i = 0; i < numberToTest; i++) { String table = "#t0036_do_not_create_" + i; try { stmt.executeUpdate("drop table " + table); assertTrue("Did not expect to reach here", false); } catch (SQLException e) { assertTrue(e.getMessage().startsWith("Cannot drop the table '" + table+"', because it does")); } } } public void testTimestamps0037() throws Exception { Connection cx = getConnection(); Statement stmt = cx.createStatement(); ResultSet rs = stmt.executeQuery( "select " + " convert(smalldatetime, '1999-01-02') a, " + " convert(smalldatetime, null) b, " + " convert(datetime, '1999-01-02') c, " + " convert(datetime, null) d " + ""); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertTrue(rs.getDate("a") != null); assertTrue(rs.getDate("b") == null); assertTrue(rs.getDate("c") != null); assertTrue(rs.getDate("d") == null); assertTrue(rs.getTime("a") != null); assertTrue(rs.getTime("b") == null); assertTrue(rs.getTime("c") != null); assertTrue(rs.getTime("d") == null); assertTrue(rs.getTimestamp("a") != null); assertTrue(rs.getTimestamp("b") == null); assertTrue(rs.getTimestamp("c") != null); assertTrue(rs.getTimestamp("d") == null); assertTrue("Expected no result set", !rs.next()); } public void testConnection0038() throws Exception { Connection conn = getConnection(); dropTable("#t0038"); Statement stmt = conn.createStatement(); stmt.executeUpdate("create table #t0038 (" + " keyfield char(255) not null, " + " descField varchar(255) not null) "); int count = stmt.executeUpdate("insert into #t0038 values ('value', 'test')"); assertTrue(count == 1); conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); conn.setAutoCommit(false); PreparedStatement ps = conn.prepareStatement("update #t0038 set descField=descField where keyField=?"); ps.setString(1, "value"); ps.executeUpdate(); ps.close(); conn.commit(); // conn.rollback(); Statement statement = conn.createStatement(); ResultSet resultSet = statement.executeQuery( "select descField from #t0038 where keyField='value'"); assertTrue(resultSet.next()); statement.close(); conn.close(); } public void testConnection0039() throws Exception { for( int i = 0; i < 10; i++ ) { Connection conn = getConnection(); Statement statement = conn.createStatement(); ResultSet resultSet = statement.executeQuery("select 5"); assertNotNull(resultSet); resultSet.close(); statement.close(); conn.close(); } } public void testPreparedStatement0040() throws Exception { Connection cx = getConnection(); dropTable("#t0040"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0040 (" + " c255 char(255) not null, " + " v255 varchar(255) not null) "); PreparedStatement pStmt = cx.prepareStatement("insert into #t0040 values (?, ?)"); String along = getLongString('a'); String blong = getLongString('b'); pStmt.setString(1, along); pStmt.setString(2, along); int count = pStmt.executeUpdate(); assertTrue(count == 1); pStmt.close(); count = stmt.executeUpdate("" + "insert into #t0040 values ( " + "'" + blong + "', " + "'" + blong + "')"); assertTrue(count == 1); pStmt = cx.prepareStatement("select c255, v255 from #t0040 order by c255"); ResultSet rs = pStmt.executeQuery(); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertEquals(rs.getString("c255"), along); assertEquals(rs.getString("v255"), along); assertTrue("Expected a result set", rs.next()); assertEquals(rs.getString("c255"), blong); assertEquals(rs.getString("v255"), blong); assertTrue("Expected no result set", !rs.next()); pStmt.close(); rs = stmt.executeQuery("select c255, v255 from #t0040 order by c255"); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertEquals(rs.getString("c255"), along); assertEquals(rs.getString("v255"), along); assertTrue("Expected a result set", rs.next()); assertEquals(rs.getString("c255"), blong); assertEquals(rs.getString("v255"), blong); assertTrue("Expected no result set", !rs.next()); stmt.close(); cx.close(); } public void testPreparedStatement0041() throws Exception { Connection cx = getConnection(); dropTable("#t0041"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0041 " + " (i integer not null, " + " s text not null) "); PreparedStatement pStmt = cx.prepareStatement("insert into #t0041 values (?, ?)"); // TODO: Check values final int rowsToAdd = 400; final String theString = getLongString(400); int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pStmt.setInt(1, i); pStmt.setString(2, theString.substring(0, i)); count += pStmt.executeUpdate(); } assertTrue(count == rowsToAdd); pStmt.close(); ResultSet rs = stmt.executeQuery("select s, i from #t0041"); assertNotNull(rs); count = 0; while (rs.next()) { rs.getString("s"); count++; } assertTrue(count == rowsToAdd); cx.close(); } public void testPreparedStatement0042() throws Exception { Connection cx = getConnection(); dropTable("#t0042"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0042 (s char(5) null, i integer null, j integer not null)"); PreparedStatement pStmt = cx.prepareStatement("insert into #t0042 (s, i, j) values (?, ?, ?)"); pStmt.setString(1, "hello"); pStmt.setNull(2, java.sql.Types.INTEGER); pStmt.setInt(3, 1); int count = pStmt.executeUpdate(); assertTrue(count == 1); pStmt.setInt(2, 42); pStmt.setInt(3, 2); count = pStmt.executeUpdate(); assertTrue(count == 1); pStmt.close(); pStmt = cx.prepareStatement("select i from #t0042 order by j"); ResultSet rs = pStmt.executeQuery(); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); rs.getInt(1); assertTrue(rs.wasNull()); assertTrue("Expected a result set", rs.next()); assertTrue(rs.getInt(1) == 42); assertTrue(!rs.wasNull()); assertTrue("Expected no result set", !rs.next()); cx.close(); } public void testResultSet0043() throws Exception { Connection cx = getConnection(); Statement stmt = cx.createStatement(); try { ResultSet rs = stmt.executeQuery("select 1"); assertNotNull(rs); rs.getInt(1); assertTrue("Did not expect to reach here", false); } catch (SQLException e) { assertTrue(e.getMessage().startsWith("No current row in the ResultSet")); } } public void testResultSet0044() throws Exception { Connection cx = getConnection(); Statement stmt = cx.createStatement(); ResultSet rs = stmt.executeQuery("select 1"); assertNotNull(rs); rs.close(); try { assertTrue("Expected no result set", !rs.next()); } catch (SQLException e) { assertTrue(e.getMessage().startsWith("Invalid state")); } } public void testResultSet0045() throws Exception { try { Connection cx = getConnection(); Statement stmt = cx.createStatement(); ResultSet rs = stmt.executeQuery("select 1"); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); rs.getInt(1); assertTrue("Expected no result set", !rs.next()); rs.getInt(1); assertTrue("Did not expect to reach here", false); } catch (java.sql.SQLException e) { assertTrue(e.getMessage().startsWith("No more results in ResultSet")); } } public void testMetaData0046() throws Exception { Connection cx = getConnection(); dropTable("#t0046"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0046 (" + " i integer identity, " + " a integer not null, " + " b integer null ) "); int count = stmt.executeUpdate("insert into #t0046 (a, b) values (-2, -3)"); assertTrue(count == 1); ResultSet rs = stmt.executeQuery("select i, a, b, 17 c from #t0046"); assertNotNull(rs); ResultSetMetaData md = rs.getMetaData(); assertNotNull(md); assertTrue(md.isAutoIncrement(1)); assertTrue(!md.isAutoIncrement(2)); assertTrue(!md.isAutoIncrement(3)); assertTrue(!md.isAutoIncrement(4)); assertTrue(md.isReadOnly(1)); assertTrue(!md.isReadOnly(2)); assertTrue(!md.isReadOnly(3)); assertTrue(md.isReadOnly(4)); assertEquals(md.isNullable(1),java.sql.ResultSetMetaData.columnNoNulls); assertEquals(md.isNullable(2),java.sql.ResultSetMetaData.columnNoNulls); assertEquals(md.isNullable(3),java.sql.ResultSetMetaData.columnNullable); // assert(md.isNullable(4) == java.sql.ResultSetMetaData.columnNoNulls); rs.close(); } public void testTimestamps0047() throws Exception { Connection cx = getConnection(); dropTable("#t0047"); Statement stmt = cx.createStatement(); stmt.executeUpdate( "create table #t0047 " + "( " + " t1 datetime not null, " + " t2 datetime null, " + " t3 smalldatetime not null, " + " t4 smalldatetime null " + ")"); String query = "insert into #t0047 (t1, t2, t3, t4) " + " values('2000-01-02 19:35:01.333', " + " '2000-01-02 19:35:01.333', " + " '2000-01-02 19:35:01.333', " + " '2000-01-02 19:35:01.333' " + ")"; int count = stmt.executeUpdate(query); assertTrue(count == 1); ResultSet rs = stmt.executeQuery("select t1, t2, t3, t4 from #t0047"); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); java.sql.Timestamp t1 = rs.getTimestamp("t1"); java.sql.Timestamp t2 = rs.getTimestamp("t2"); java.sql.Timestamp t3 = rs.getTimestamp("t3"); java.sql.Timestamp t4 = rs.getTimestamp("t4"); java.sql.Timestamp r1 = Timestamp.valueOf("2000-01-02 19:35:01.333"); java.sql.Timestamp r2 = Timestamp.valueOf("2000-01-02 19:35:00"); assertEquals(r1, t1); assertEquals(r1, t2); assertEquals(r2, t3); assertEquals(r2, t4); } public void testTimestamps0048() throws Exception { Connection cx = getConnection(); dropTable("#t0048"); Statement stmt = cx.createStatement(); stmt.executeUpdate( "create table #t0048 " + "( " + " t1 datetime not null, " + " t2 datetime null, " + " t3 smalldatetime not null, " + " t4 smalldatetime null " + ")"); java.sql.Timestamp r1; java.sql.Timestamp r2; r1 = Timestamp.valueOf("2000-01-02 19:35:01"); r2 = Timestamp.valueOf("2000-01-02 19:35:00"); java.sql.PreparedStatement pstmt = cx.prepareStatement( "insert into #t0048 (t1, t2, t3, t4) values(?, ?, ?, ?)"); pstmt.setTimestamp(1, r1); pstmt.setTimestamp(2, r1); pstmt.setTimestamp(3, r1); pstmt.setTimestamp(4, r1); int count = pstmt.executeUpdate(); assertTrue(count == 1); pstmt.close(); ResultSet rs = stmt.executeQuery("select t1, t2, t3, t4 from #t0048"); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); java.sql.Timestamp t1 = rs.getTimestamp("t1"); java.sql.Timestamp t2 = rs.getTimestamp("t2"); java.sql.Timestamp t3 = rs.getTimestamp("t3"); java.sql.Timestamp t4 = rs.getTimestamp("t4"); assertEquals(r1, t1); assertEquals(r1, t2); assertEquals(r2, t3); assertEquals(r2, t4); } public void testDecimalConversion0058() throws Exception { Connection cx = getConnection(); Statement stmt = cx.createStatement(); ResultSet rs = stmt.executeQuery("select convert(DECIMAL(4,0), 0)"); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertTrue(rs.getInt(1) == 0); assertTrue("Expected no result set", !rs.next()); rs = stmt.executeQuery("select convert(DECIMAL(4,0), 1)"); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertTrue(rs.getInt(1) == 1); assertTrue("Expected no result set", !rs.next()); rs = stmt.executeQuery("select convert(DECIMAL(4,0), -1)"); assertNotNull(rs); assertTrue("Expected a result set", rs.next()); assertTrue(rs.getInt(1) == -1); assertTrue("Expected no result set", !rs.next()); } }
package bdv.ui.settings; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import javax.swing.border.MatteBorder; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import bdv.ui.UIUtils; /** * Main panel for preferences dialogs. * <p> * On the right, one of several {@link SettingsPage}s is shown. On the left, a * {@code JTree} is used to select between pages. On the top, a breadcrumbs * trail shows the tree path of the current {@link SettingsPage}. On the bottom, * "Cancel", "Apply", and "OK" buttons are shown. * </p> * * @author Tobias Pietzsch */ public class SettingsPanel extends JPanel { private static final long serialVersionUID = 1L; private final DefaultMutableTreeNode root; private final DefaultTreeModel model; private final FullWidthSelectionJTree tree; private final JScrollPane treeScrollPane; private final JSplitPane splitPane; private final JPanel pages; private final JPanel breadcrumbs; private final ModificationListener modificationListener; private final ArrayList< Runnable > runOnOk; private final ArrayList< Runnable > runOnCancel; private final JButton apply; public void addPage( final SettingsPage page ) { final String path = page.getTreePath(); final String[] parts = path.split( ">" ); DefaultMutableTreeNode current = root; for ( final String part : parts ) { final String text = part.trim(); DefaultMutableTreeNode next = null; for ( int i = 0; i < current.getChildCount(); ++i ) { final DefaultMutableTreeNode child = ( DefaultMutableTreeNode ) current.getChildAt( i ); final SettingsNodeData data = ( SettingsNodeData ) child.getUserObject(); if ( text.equals( data.name ) ) { next = child; break; } } if ( next == null ) { final SettingsNodeData data = new SettingsNodeData( text, null ); next = new DefaultMutableTreeNode( data ); model.insertNodeInto( next, current, current.getChildCount() ); } current = next; } page.modificationListeners().add( modificationListener ); final SettingsNodeData data = ( SettingsNodeData ) current.getUserObject(); data.page = page; tree.expandPath( new TreePath( root ) ); if ( pages.getComponents().length == 0 ) tree.getSelectionModel().setSelectionPath( new TreePath( model.getPathToRoot( current ) ) ); pages.add( data.page.getTreePath(), data.page.getJPanel() ); pages.revalidate(); pages.repaint(); } /** * Removes the settings page with the specified path. Does nothing if there * is no settings page for the path. * * @param path * the path of the settings page to remove. Example: * {@code "Analyze > Tables"} */ public void removePage( final String path ) { final String[] parts = path.split( ">" ); DefaultMutableTreeNode current = root; for ( final String part : parts ) { final String text = part.trim(); DefaultMutableTreeNode next = null; for ( int i = 0; i < current.getChildCount(); ++i ) { final DefaultMutableTreeNode child = ( DefaultMutableTreeNode ) current.getChildAt( i ); final SettingsNodeData data = ( SettingsNodeData ) child.getUserObject(); if ( text.equals( data.name ) ) { next = child; break; } } current = next; } if ( null == current ) return; // Path not found in the tree. model.removeNodeFromParent( current ); for ( final SettingsPage page : getPages() ) { if ( page.getTreePath().equals( path ) ) pages.remove( page.getJPanel() ); } pages.revalidate(); pages.repaint(); } public SettingsPanel() { root = new DefaultMutableTreeNode( new SettingsNodeData( "root", null ) ); model = new DefaultTreeModel( root ); tree = new FullWidthSelectionJTree( model ); breadcrumbs = new JPanel(); breadcrumbs.setLayout( new BoxLayout( breadcrumbs, BoxLayout.LINE_AXIS ) ); breadcrumbs.setBorder( new EmptyBorder( 5, 5, 5, 0 ) ); setBreadCrumbs( root ); final CardLayout cardLayout = new CardLayout(); pages = new JPanel( cardLayout ); tree.setEditable( false ); tree.setSelectionRow( 0 ); tree.setRootVisible( false ); tree.setShowsRootHandles( true ); tree.setExpandsSelectedPaths( true ); tree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION ); final DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer(); renderer.setIcon( null ); renderer.setLeafIcon( null ); renderer.setOpenIcon( null ); renderer.setClosedIcon( null ); final Color bg = renderer.getBackgroundSelectionColor(); tree.setBackgroundSelectionColor( bg ); tree.setCellRenderer( renderer ); tree.getSelectionModel().addTreeSelectionListener( new TreeSelectionListener() { @Override public void valueChanged( final TreeSelectionEvent e ) { final DefaultMutableTreeNode selectedNode = ( DefaultMutableTreeNode ) tree.getLastSelectedPathComponent(); if ( selectedNode != null ) { setBreadCrumbs( selectedNode ); final SettingsNodeData data = ( SettingsNodeData ) selectedNode.getUserObject(); if ( data.page != null ) cardLayout.show( pages, data.page.getTreePath() ); } } } ); final JButton cancel = new JButton("Cancel"); apply = new JButton("Apply"); final JButton ok = new JButton("OK"); final JPanel buttons = new JPanel(); buttons.setLayout( new BoxLayout( buttons, BoxLayout.LINE_AXIS ) ); buttons.add( Box.createHorizontalGlue() ); buttons.add( cancel ); buttons.add( apply ); buttons.add( ok ); final JPanel content = new JPanel( new BorderLayout() ); content.add( breadcrumbs, BorderLayout.NORTH ); content.add( pages, BorderLayout.CENTER ); content.setBorder( new EmptyBorder( 10, 0, 10, 10 ) ); treeScrollPane = new JScrollPane( tree ); treeScrollPane.setPreferredSize( new Dimension( 200, 500 ) ); treeScrollPane.setMinimumSize( new Dimension( 150, 200 ) ); treeScrollPane.setBorder( new MatteBorder( 0, 0, 0, 1, UIManager.getColor( "Separator.foreground" ) ) ); renderer.setBackgroundNonSelectionColor( treeScrollPane.getBackground() ); splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, treeScrollPane, content ); splitPane.setResizeWeight( 0 ); splitPane.setContinuousLayout( true ); splitPane.setDividerSize( 10 ); splitPane.setDividerLocation( treeScrollPane.getPreferredSize().width ); splitPane.setBorder( new MatteBorder( 0, 0, 1, 0, UIManager.getColor( "Separator.foreground" ) ) ); this.setLayout( new BorderLayout() ); this.add( splitPane, BorderLayout.CENTER ); buttons.setBorder( new EmptyBorder( 10, 0, 5, 10 ) ); this.add( buttons, BorderLayout.SOUTH ); runOnCancel = new ArrayList<>(); runOnOk = new ArrayList<>(); cancel.addActionListener( e -> cancel() ); apply.setEnabled( false ); modificationListener = () -> apply.setEnabled( true ); apply.addActionListener( e -> { getPages().forEach( SettingsPage::apply ); apply.setEnabled( false ); } ); ok.addActionListener( e -> { getPages().forEach( SettingsPage::apply ); runOnOk.forEach( Runnable::run ); apply.setEnabled( false ); } ); } @Override public void updateUI() { super.updateUI(); if ( treeScrollPane != null ) { final Color c = UIManager.getColor( "Separator.foreground" ); treeScrollPane.setBorder( new MatteBorder( 0, 0, 0, 1, c ) ); splitPane.setBorder( new MatteBorder( 0, 0, 1, 0, c ) ); } if ( model != null ) { SwingUtilities.invokeLater( model::reload ); } } public void cancel() { getPages().forEach( SettingsPage::cancel ); runOnCancel.forEach( Runnable::run ); apply.setEnabled( false ); } public synchronized void onOk( final Runnable runnable ) { runOnOk.add( runnable ); } public synchronized void onCancel( final Runnable runnable ) { runOnCancel.add( runnable ); } private ArrayList< SettingsPage > getPages() { final ArrayList< SettingsPage > list = new ArrayList<>(); getPages( root, list ); return list; } private void getPages( final DefaultMutableTreeNode node, final ArrayList< SettingsPage > pages ) { final SettingsNodeData data = ( SettingsNodeData ) node.getUserObject(); if ( data.page != null ) pages.add( data.page ); for ( int i = 0; i < node.getChildCount(); ++i ) getPages( ( DefaultMutableTreeNode ) node.getChildAt( i ), pages ); } private void setBreadCrumbs( final DefaultMutableTreeNode selectedNode ) { breadcrumbs.removeAll(); DefaultMutableTreeNode current = selectedNode; while ( current != root ) { final SettingsNodeData data = ( SettingsNodeData ) current.getUserObject(); JLabel label = semiboldLabel( data.name ); final TreePath tpath = new TreePath( model.getPathToRoot( current ) ); label.addMouseListener( new MouseAdapter() { @Override public void mouseClicked( final MouseEvent e ) { tree.getSelectionModel().setSelectionPath( tpath ); } } ); breadcrumbs.add( label, 0 ); final DefaultMutableTreeNode parent = ( DefaultMutableTreeNode ) current.getParent(); if ( parent != root ) { label = semiboldLabel( " \u25b8 " ); breadcrumbs.add( label, 0 ); } current = parent; } if ( breadcrumbs.getComponentCount() == 0 ) breadcrumbs.add( semiboldLabel( " " ) ); breadcrumbs.revalidate(); breadcrumbs.repaint(); } private JLabel semiboldLabel( final String text ) { return new JLabel( text ) { @Override public void updateUI() { super.updateUI(); setFont( UIUtils.getFont( "semibold.font" ) ); } }; } static class SettingsNodeData { private final String name; private SettingsPage page; SettingsNodeData( final String name, final SettingsPage page ) { this.name = name; this.page = page; } @Override public String toString() { return name; } } static class FullWidthSelectionJTree extends JTree { private static final long serialVersionUID = 1L; private Color backgroundSelectionColor; FullWidthSelectionJTree( final TreeModel newModel ) { super( newModel ); backgroundSelectionColor = new DefaultTreeCellRenderer().getBackgroundSelectionColor(); setOpaque( false ); } void setBackgroundSelectionColor( final Color backgroundSelectionColor ) { this.backgroundSelectionColor = backgroundSelectionColor; } @Override public void paintComponent( final Graphics g ) { final int[] rows = getSelectionRows(); if ( rows != null ) { g.setColor( backgroundSelectionColor ); for ( final int i : rows ) { final Rectangle r = getRowBounds( i ); g.fillRect( 0, r.y, getWidth(), r.height ); } } super.paintComponent( g ); } } }
package cn.liutils.util.mc; import java.util.ArrayList; import java.util.List; import net.minecraft.block.Block; import net.minecraft.command.IEntitySelector; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.World; import cn.liutils.util.helper.BlockPos; import cn.liutils.util.helper.Motion3D; import cn.liutils.util.mc.EntitySelectors.SelectorList; /** * Utils about block/entity lookup and interaction. * @author WeAthFolD */ public class WorldUtils { public static AxisAlignedBB getBoundingBox(Vec3 vec1, Vec3 vec2) { double minX = 0.0, minY = 0.0, minZ = 0.0, maxX = 0.0, maxY = 0.0, maxZ = 0.0; if(vec1.xCoord < vec2.xCoord) { minX = vec1.xCoord; maxX = vec2.xCoord; } else { minX = vec2.xCoord; maxX = vec1.xCoord; } if(vec1.yCoord < vec2.yCoord) { minY = vec1.yCoord; maxY = vec2.yCoord; } else { minY = vec2.yCoord; maxY = vec1.yCoord; } if(vec1.zCoord < vec2.zCoord) { minZ = vec1.zCoord; maxZ = vec2.zCoord; } else { minZ = vec2.zCoord; maxZ = vec1.zCoord; } return AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); } /** * Return a minimum AABB that can hold the points given. */ public static AxisAlignedBB ofPoints(Vec3 ...points) { if(points.length == 0) { throw new RuntimeException("Invalid call: too few vectors"); } AxisAlignedBB ret = AxisAlignedBB.getBoundingBox( points[0].xCoord, points[0].yCoord, points[0].zCoord, points[0].xCoord, points[0].yCoord, points[0].zCoord); for(int i = 1; i < points.length; ++i) { if(ret.minX > points[i].xCoord) ret.minX = points[i].xCoord; if(ret.maxX < points[i].xCoord) ret.maxX = points[i].xCoord; if(ret.minY > points[i].yCoord) ret.minY = points[i].yCoord; if(ret.maxY < points[i].yCoord) ret.maxY = points[i].yCoord; if(ret.minZ > points[i].zCoord) ret.minZ = points[i].zCoord; if(ret.maxZ < points[i].zCoord) ret.maxZ = points[i].zCoord; } return ret; } public static List<BlockPos> getBlocksWithin(Entity entity, double range, int max, IBlockFilter ...filters) { return getBlocksWithin(entity.worldObj, entity.posX, entity.posY, entity.posZ, range, max, filters); } public static List<BlockPos> getBlocksWithin(TileEntity te, double range, int max, IBlockFilter ...filters) { return getBlocksWithin(te.getWorldObj(), te.xCoord + 0.5, te.yCoord + 0.5, te.zCoord + 0.5, range, max, filters); } public static List<BlockPos> getBlocksWithin( World world, final double x, final double y, final double z, double range, int max, IBlockFilter ...filter) { IBlockFilter [] fs = new IBlockFilter[filter.length + 1]; for(int i = 0; i < filter.length; ++i) fs[i] = filter[i]; final double rangeSq = range * range; fs[filter.length] = new IBlockFilter() { @Override public boolean accepts(World world, int xx, int yy, int zz, Block block) { double dx = xx - x, dy = yy - y, dz = zz - z; return dx * dx + dy * dy + dz * dz <= rangeSq; } }; int minX = MathHelper.floor_double(x - range), minY = MathHelper.floor_double(y - range), minZ = MathHelper.floor_double(z - range), maxX = MathHelper.ceiling_double_int(x + range), maxY = MathHelper.ceiling_double_int(y + range), maxZ = MathHelper.ceiling_double_int(z + range); return getBlocksWithin(world, minX, minY, minZ, maxX, maxY, maxZ, max, fs); } public static List<BlockPos> getBlocksWithin( World world, int minX, int minY, int minZ, int maxX, int maxY, int maxZ, int max, IBlockFilter ...filter) { List<BlockPos> ret = new ArrayList(); for(int x = minX; x <= maxX; ++x) { for(int y = minY; y <= maxY; ++y) { for(int z = minZ; z <= maxZ; ++z) { boolean match = true; for(IBlockFilter f : filter) { if(!f.accepts(world, x, y, z, world.getBlock(x, y, z))) { match = false; break; } } if(match) { ret.add(new BlockPos(world, x, y, z)); if(ret.size() == max) return ret; } } } } return ret; } public static List<Entity> getEntities(TileEntity te, double range, IEntitySelector filter) { return getEntities(te.getWorldObj(), te.xCoord + 0.5, te.yCoord + 0.5, te.zCoord + 0.5, range, filter); } public static List<Entity> getEntities(Entity ent, double range, IEntitySelector filter) { return getEntities(ent.worldObj, ent.posX, ent.posY, ent.posZ, range, filter); } public static List<Entity> getEntities(World world, double x, double y, double z, double range, IEntitySelector filter) { AxisAlignedBB box = AxisAlignedBB.getBoundingBox( x - range, y - range, z - range, x + range, y + range, z + range); SelectorList list = new SelectorList(filter, new EntitySelectors.RestrictRange(x, y, z, range)); return getEntities(world, box, list); } public static List<Entity> getEntities(World world, AxisAlignedBB box, IEntitySelector filter) { return world.getEntitiesWithinAABBExcludingEntity(null, box, filter); } /** * Get the tile entity at the given position and check if it is the specified type. * Return the tile entity if is of the type, null otherwise. */ public static <T extends TileEntity> T getTileEntity(World world, int x, int y, int z, Class<T> type) { TileEntity te = world.getTileEntity(x, y, z); return type.isInstance(te) ? (T) te : null; } }
package vg.civcraft.mc.citadel.events; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; import vg.civcraft.mc.citadel.reinforcement.PlayerReinforcement; /** * Event that is called when an acid block action is performed * */ public class AcidBlockEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private final PlayerReinforcement acidBlock; private final PlayerReinforcement destroyedBlock; /** * Creates a new AcidBlockEvent instance * @param player The player performing the acid action * @param acidBlock The acid block instance * @param destroyedBlock The destroyed block instance */ public AcidBlockEvent(final Player player, final PlayerReinforcement acidBlock, PlayerReinforcement destroyedBlock) { super(player); this.acidBlock = acidBlock; this.destroyedBlock = destroyedBlock; } /** * Gets the PlayerReinforcement on the acid block. * @return Returns the PlayerReinforcement. */ public PlayerReinforcement getAcidBlockReinforcement() { return acidBlock; } /** * Gets the PlayerReinforcement on the block above the Acid Block. * @return Returns the PlayerReinforcement for the block above the Acid Block. */ public PlayerReinforcement getDestroyedBlockReinforcement() { return destroyedBlock; } private boolean isCancelled = false; @Override public boolean isCancelled() { return isCancelled; } @Override public void setCancelled(boolean value) { isCancelled = value; } @Override public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } }
package com.anyconsole.db; import org.springframework.stereotype.Component; @Component public class MongoPlugin implements Plugin { @Override public Parser parse(String statement) { // TODO Auto-generated method stub return null; } @Override public String execute(Parser parser) { // TODO Auto-generated method stub return null; } }
package com.aol.cyclops.control; import java.util.Objects; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Stream; import org.jooq.lambda.Seq; import org.jooq.lambda.tuple.Tuple; import org.jooq.lambda.tuple.Tuple2; import org.reactivestreams.Publisher; import com.aol.cyclops.Monoid; import com.aol.cyclops.Reducer; import com.aol.cyclops.control.Matchable.CheckValue1; import com.aol.cyclops.data.collections.extensions.CollectionX; import com.aol.cyclops.data.collections.extensions.standard.ListX; import com.aol.cyclops.types.Combiner; import com.aol.cyclops.types.ConvertableFunctor; import com.aol.cyclops.types.Filterable; import com.aol.cyclops.types.MonadicValue; import com.aol.cyclops.types.To; import com.aol.cyclops.types.Value; import com.aol.cyclops.types.Zippable; import com.aol.cyclops.types.applicative.ApplicativeFunctor; import com.aol.cyclops.types.stream.reactive.ValueSubscriber; import com.aol.cyclops.util.function.Curry; import com.aol.cyclops.util.function.QuadFunction; import com.aol.cyclops.util.function.TriFunction; import lombok.AccessLevel; import lombok.AllArgsConstructor; /** * Totally lazy more powerful general Option(al) type. Maybe is lazy like a Java * 8 Stream that represents 0 or 1 values rather than eager like a Java 8 * Optional. map / peek/ filter and flatMap build the execution chaing, but are * not executed until the value inside the Maybe is required. * * The Maybe interface has two implementations Some which holds a value and None which represents no value * * <pre> * {@code * * //eagerly load data * Optional.of(10) * .map(this::load); * * //lazily tee up loading of data until needed * Maybe.of(10) * .map(this::load); * . * * } * </pre> * * Maybe is tail recursive * * <pre> * {@code * @Test public void odd() { System.out.println(even(Maybe.just(200000)).get()); } public Maybe<String> odd(Maybe<Integer> n) { return n.flatMap(x -> even(Maybe.just(x - 1))); } public Maybe<String> even(Maybe<Integer> n) { return n.flatMap(x -> { return x <= 0 ? Maybe.just("done") : odd(Maybe.just(x - 1)); }); } * * } * </pre> * * Maybe is a functor (map) monad (flatMap) and an applicative (ap) * * Maybe has pattern matching built in (visit, matches, patternMatch) * * Maybe is convertable to all cyclops-react data types. * * * @author johnmcclean * * @param <T> Data type of element stored in Maybe */ public interface Maybe<T> extends To<Maybe<T>>, MonadicValue<T>, Zippable<T>, Supplier<T>, ConvertableFunctor<T>, Filterable<T>, ApplicativeFunctor<T>, Matchable.ValueAndOptionalMatcher<T> { @SuppressWarnings("rawtypes") final static Maybe EMPTY = new Nothing<>(); /** * @return Get the empty Maybe (single instance) */ @SuppressWarnings("unchecked") static <T> Maybe<T> none() { return EMPTY; } /* (non-Javadoc) * @see com.aol.cyclops.types.MonadicValue#flatMapIterable(java.util.function.Function) */ @Override default <R> Maybe<R> flatMapIterable(final Function<? super T, ? extends Iterable<? extends R>> mapper) { return (Maybe<R>) MonadicValue.super.flatMapIterable(mapper); } /* (non-Javadoc) * @see com.aol.cyclops.types.MonadicValue#flatMapPublisher(java.util.function.Function) */ @Override default <R> Maybe<R> flatMapPublisher(final Function<? super T, ? extends Publisher<? extends R>> mapper) { final MonadicValue<R> m = MonadicValue.super.flatMapPublisher(mapper); return (Maybe<R>) m; } /** * Construct a Maybe that contains a single value extracted from the supplied reactive-streams Publisher * <pre> * {@code * ReactiveSeq<Integer> stream = ReactiveSeq.of(1,2,3); Maybe<Integer> maybe = Maybe.fromPublisher(stream); //Maybe[1] * * } * </pre> * * @param pub Publisher to extract value from * @return Maybe populated with first value from Publisher (Maybe.empty if Publisher empty) */ public static <T> Maybe<T> fromPublisher(final Publisher<T> pub) { final ValueSubscriber<T> sub = ValueSubscriber.subscriber(); pub.subscribe(sub); return sub.toMaybe(); } /** * Construct a Maybe that contains a single value extracted from the supplied Iterable * <pre> * {@code * ReactiveSeq<Integer> stream = ReactiveSeq.of(1,2,3); Maybe<Integer> maybe = Maybe.fromIterable(stream); //Maybe[1] * * } * </pre> * @param iterable Iterable to extract value from * @return Maybe populated with first value from Iterable (Maybe.empty if Publisher empty) */ static <T> Maybe<T> fromIterable(final Iterable<T> iterable) { return Maybe.fromEval(Eval.fromIterable(iterable)); } /** * Construct an equivalent Maybe from the Supplied Optional * <pre> * {@code * Maybe<Integer> some = Maybe.fromOptional(Optional.of(10)); * //Maybe[10], Some[10] * * Maybe<Integer> none = Maybe.fromOptional(Optional.empty()); * //Maybe.empty, None[] * } * </pre> * * @param opt Optional to construct Maybe from * @return Maybe created from Optional */ static <T> Maybe<T> fromOptional(final Optional<T> opt) { if (opt.isPresent()) return Maybe.of(opt.get()); return none(); } @Deprecated static <T> Maybe<T> fromEvalOf(final Eval<T> eval) { return new Just<T>( eval); } /** * Construct a Maybe from the supplied Eval * * <pre> * {@code * Maybe<Integer> maybe = Maybe.fromEval(Eval.now(10)); * //Maybe[10] * * } * </pre> * * @param eval Eval to construct Maybe from * @return Maybe created from Eval */ static <T> Maybe<T> fromEval(final Eval<T> eval) { return new Just<T>( eval); } static <T> Maybe<T> fromEvalNullable(final Eval<T> eval) { return new Lazy<T>( eval.map(u->Maybe.ofNullable(u))); } static <T> Maybe<T> fromEvalOptional(final Eval<Optional<T>> value){ return new Lazy<T>(value.map(in->Maybe.<T>fromOptional(in))); } /** * Construct an Maybe which contains the provided (non-null) value. * Alias for @see {@link Maybe#of(Object)} * * <pre> * {@code * * Maybe<Integer> some = Maybe.just(10); * some.map(i->i*2); * } * </pre> * * @param value Value to wrap inside a Maybe * @return Maybe containing the supplied value */ static <T> Maybe<T> just(final T value) { return of(value); } /** * Construct an Maybe which contains the provided (non-null) value * Equivalent to @see {@link Maybe#just(Object)} * <pre> * {@code * * Maybe<Integer> some = Maybe.of(10); * some.map(i->i*2); * } * </pre> * * @param value Value to wrap inside a Maybe * @return Maybe containing the supplied value */ static <T> Maybe<T> of(final T value) { Objects.requireNonNull(value); return new Just<T>( Eval.later(() -> value)); } /** * <pre> * {@code * Maybe<Integer> maybe = Maybe.ofNullable(null); * //None * * Maybe<Integer> maybe = Maybe.ofNullable(10); * //Maybe[10], Some[10] * * } * </pre> * * * @param value * @return */ static <T> Maybe<T> ofNullable(final T value) { if (value != null) return of(value); return none(); } /** * Narrow covariant type parameter * * @param broad Maybe with covariant type parameter * @return Narrowed Maybe */ static <T> Maybe<T> narrow(final Maybe<? extends T> broad) { return (Maybe<T>) broad; } /** * Sequence operation, take a Collection of Maybes and turn it into a Maybe with a Collection * Only successes are retained. By constrast with {@link Maybe#sequence(CollectionX)} Maybe#empty/ None types are * tolerated and ignored. * * <pre> * {@code * Maybe<Integer> just = Maybe.of(10); Maybe<Integer> none = Maybe.none(); * * Maybe<ListX<Integer>> maybes = Maybe.sequenceJust(ListX.of(just, none, Maybe.of(1))); //Maybe.of(ListX.of(10, 1)); * } * </pre> * * @param maybes Maybes to Sequence * @return Maybe with a List of values */ public static <T> Maybe<ListX<T>> sequenceJust(final CollectionX<Maybe<T>> maybes) { final Maybe<ListX<T>> unwrapped = AnyM.sequence(maybes.map(o -> AnyM.fromMaybe(o))) .unwrap(); return unwrapped; } /** * Sequence operation, take a Collection of Maybes and turn it into a Maybe with a Collection * By constrast with {@link Maybe#sequenceJust(CollectionX)} if any Maybe types are None / empty * the return type will be an empty Maybe / None * * <pre> * {@code * * Maybe<Integer> just = Maybe.of(10); Maybe<Integer> none = Maybe.none(); * * Maybe<ListX<Integer>> maybes = Maybe.sequence(ListX.of(just, none, Maybe.of(1))); //Maybe.none(); * * } * </pre> * * * @param maybes Maybes to Sequence * @return Maybe with a List of values */ public static <T> Maybe<ListX<T>> sequence(final CollectionX<Maybe<T>> maybes) { return sequence(maybes.stream()).map(s -> s.toListX()); } /** * Sequence operation, take a Stream of Maybes and turn it into a Maybe with a Stream * By constrast with {@link Maybe#sequenceJust(CollectionX)} Maybe#empty/ None types are * result in the returned Maybe being Maybe.empty / None * * * <pre> * {@code * * Maybe<Integer> just = Maybe.of(10); Maybe<Integer> none = Maybe.none(); * Maybe<ReactiveSeq<Integer>> maybes = Maybe.sequence(Stream.of(just, none, Maybe.of(1))); //Maybe.none(); * * } * </pre> * * * @param maybes Maybes to Sequence * @return Maybe with a Stream of values */ public static <T> Maybe<ReactiveSeq<T>> sequence(final Stream<Maybe<T>> maybes) { return AnyM.sequence(maybes.map(f -> AnyM.fromMaybe(f)), () -> AnyM.fromMaybe(Maybe.just(Stream.<T> empty()))) .map(s -> ReactiveSeq.fromStream(s)) .unwrap(); } /** * Accummulating operation using the supplied Reducer (@see com.aol.cyclops.Reducers). A typical use case is to accumulate into a Persistent Collection type. * Accumulates the present results, ignores empty Maybes. * * <pre> * {@code * Maybe<Integer> just = Maybe.of(10); Maybe<Integer> none = Maybe.none(); * Maybe<PSetX<Integer>> maybes = Maybe.accumulateJust(ListX.of(just, none, Maybe.of(1)), Reducers.toPSetX()); //Maybe.of(PSetX.of(10, 1))); * * } * </pre> * * @param maybes Maybes to accumulate * @param reducer Reducer to accumulate values with * @return Maybe with reduced value */ public static <T, R> Maybe<R> accumulateJust(final CollectionX<Maybe<T>> maybes, final Reducer<R> reducer) { return sequenceJust(maybes).map(s -> s.mapReduce(reducer)); } /** * Accumulate the results only from those Maybes which have a value present, using the supplied mapping function to * convert the data from each Maybe before reducing them using the supplied Monoid (a combining BiFunction/BinaryOperator and identity element that takes two * input values of the same type and returns the combined result) {@see com.aol.cyclops.Monoids }.. * * <pre> * {@code * Maybe<Integer> just = Maybe.of(10); Maybe<Integer> none = Maybe.none(); * Maybe<String> maybes = Maybe.accumulateJust(ListX.of(just, none, Maybe.of(1)), i -> "" + i, Semigroups.stringConcat); //Maybe.of("101") * * } * </pre> * * @param maybes Maybes to accumulate * @param mapper Mapping function to be applied to the result of each Maybe * @param reducer Monoid to combine values from each Maybe * @return Maybe with reduced value */ public static <T, R> Maybe<R> accumulateJust(final CollectionX<Maybe<T>> maybes, final Function<? super T, R> mapper, final Monoid<R> reducer) { return sequenceJust(maybes).map(s -> s.map(mapper) .reduce(reducer)); } /** * Accumulate the results only from those Maybes which have a value present, using the supplied Monoid (a combining BiFunction/BinaryOperator and identity element that takes two * input values of the same type and returns the combined result) {@see com.aol.cyclops.Monoids }. * * <pre> * {@code * * Maybe<Integer> maybes = Maybe.accumulateJust(Monoids.intSum,ListX.of(just, none, Maybe.of(1))); //Maybe.of(11) * * } * </pre> * * * * @param maybes Maybes to accumulate * @param reducer Monoid to combine values from each Maybe * @return Maybe with reduced value */ public static <T> Maybe<T> accumulateJust(final Monoid<T> reducer,final CollectionX<Maybe<T>> maybes) { return sequenceJust(maybes).map(s -> s.reduce(reducer)); } /* (non-Javadoc) * @see com.aol.cyclops.types.MonadicValue#forEach4(java.util.function.Function, java.util.function.BiFunction, com.aol.cyclops.util.function.TriFunction, com.aol.cyclops.util.function.QuadFunction) */ @Override default <T2, R1, R2, R3, R> Maybe<R> forEach4(Function<? super T, ? extends MonadicValue<R1>> value1, BiFunction<? super T, ? super R1, ? extends MonadicValue<R2>> value2, TriFunction<? super T, ? super R1, ? super R2, ? extends MonadicValue<R3>> value3, QuadFunction<? super T, ? super R1, ? super R2, ? super R3, ? extends R> yieldingFunction) { return (Maybe<R>)MonadicValue.super.forEach4(value1, value2, value3, yieldingFunction); } /* (non-Javadoc) * @see com.aol.cyclops.types.MonadicValue#forEach4(java.util.function.Function, java.util.function.BiFunction, com.aol.cyclops.util.function.TriFunction, com.aol.cyclops.util.function.QuadFunction, com.aol.cyclops.util.function.QuadFunction) */ @Override default <T2, R1, R2, R3, R> Maybe<R> forEach4(Function<? super T, ? extends MonadicValue<R1>> value1, BiFunction<? super T, ? super R1, ? extends MonadicValue<R2>> value2, TriFunction<? super T, ? super R1, ? super R2, ? extends MonadicValue<R3>> value3, QuadFunction<? super T, ? super R1, ? super R2, ? super R3, Boolean> filterFunction, QuadFunction<? super T, ? super R1, ? super R2, ? super R3, ? extends R> yieldingFunction) { return (Maybe<R>)MonadicValue.super.forEach4(value1, value2, value3, filterFunction, yieldingFunction); } /* (non-Javadoc) * @see com.aol.cyclops.types.MonadicValue#forEach3(java.util.function.Function, java.util.function.BiFunction, com.aol.cyclops.util.function.TriFunction) */ @Override default <T2, R1, R2, R> Maybe<R> forEach3(Function<? super T, ? extends MonadicValue<R1>> value1, BiFunction<? super T, ? super R1, ? extends MonadicValue<R2>> value2, TriFunction<? super T, ? super R1, ? super R2, ? extends R> yieldingFunction) { return (Maybe<R>)MonadicValue.super.forEach3(value1, value2, yieldingFunction); } /* (non-Javadoc) * @see com.aol.cyclops.types.MonadicValue#forEach3(java.util.function.Function, java.util.function.BiFunction, com.aol.cyclops.util.function.TriFunction, com.aol.cyclops.util.function.TriFunction) */ @Override default <T2, R1, R2, R> Maybe<R> forEach3(Function<? super T, ? extends MonadicValue<R1>> value1, BiFunction<? super T, ? super R1, ? extends MonadicValue<R2>> value2, TriFunction<? super T, ? super R1, ? super R2, Boolean> filterFunction, TriFunction<? super T, ? super R1, ? super R2, ? extends R> yieldingFunction) { return (Maybe<R>)MonadicValue.super.forEach3(value1, value2, filterFunction, yieldingFunction); } /* (non-Javadoc) * @see com.aol.cyclops.types.MonadicValue#forEach2(java.util.function.Function, java.util.function.BiFunction) */ @Override default <R1, R> Maybe<R> forEach2(Function<? super T, ? extends MonadicValue<R1>> value1, BiFunction<? super T, ? super R1, ? extends R> yieldingFunction) { return (Maybe<R>)MonadicValue.super.forEach2(value1, yieldingFunction); } /* (non-Javadoc) * @see com.aol.cyclops.types.MonadicValue#forEach2(java.util.function.Function, java.util.function.BiFunction, java.util.function.BiFunction) */ @Override default <R1, R> Maybe<R> forEach2(Function<? super T, ? extends MonadicValue<R1>> value1, BiFunction<? super T, ? super R1, Boolean> filterFunction, BiFunction<? super T, ? super R1, ? extends R> yieldingFunction) { return (Maybe<R>)MonadicValue.super.forEach2(value1, filterFunction, yieldingFunction); } /* * Apply a function across to values at once. If this Maybe is none, or the * supplied value represents none Maybe.none is returned. Otherwise a Maybe * with the function applied with this value and the supplied value is * returned * * (non-Javadoc) * * @see * com.aol.cyclops.types.applicative.ApplicativeFunctor#combine(com.aol. * cyclops.types.Value, java.util.function.BiFunction) */ @Override default <T2, R> Maybe<R> combine(final Value<? extends T2> app, final BiFunction<? super T, ? super T2, ? extends R> fn) { return map(v -> Tuple.tuple(v, Curry.curry2(fn) .apply(v))).flatMap(tuple -> app.visit(i -> Maybe.just(tuple.v2.apply(i)), () -> Maybe.none())); } /* * Equivalent to combine, but accepts an Iterable and takes the first value * only from that iterable. (non-Javadoc) * * @see com.aol.cyclops.types.Zippable#zip(java.lang.Iterable, * java.util.function.BiFunction) */ @Override default <T2, R> Maybe<R> zip(final Iterable<? extends T2> app, final BiFunction<? super T, ? super T2, ? extends R> fn) { return map(v -> Tuple.tuple(v, Curry.curry2(fn) .apply(v))).flatMap(tuple -> Maybe.fromIterable(app) .visit(i -> Maybe.just(tuple.v2.apply(i)), () -> Maybe.none())); } /* * Equivalent to combine, but accepts a Publisher and takes the first value * only from that publisher. (non-Javadoc) * * @see com.aol.cyclops.types.Zippable#zip(java.util.function.BiFunction, * org.reactivestreams.Publisher) */ @Override default <T2, R> Maybe<R> zip(final BiFunction<? super T, ? super T2, ? extends R> fn, final Publisher<? extends T2> app) { return map(v -> Tuple.tuple(v, Curry.curry2(fn) .apply(v))).flatMap(tuple -> Maybe.fromPublisher(app) .visit(i -> Maybe.just(tuple.v2.apply(i)), () -> Maybe.none())); } /* (non-Javadoc) * @see com.aol.cyclops.types.Applicative#combine(java.util.function.BinaryOperator, com.aol.cyclops.types.Applicative) */ @Override default Maybe<T> combine(BinaryOperator<Combiner<T>> combiner, Combiner<T> app) { return (Maybe<T>)ApplicativeFunctor.super.combine(combiner, app); } /* * (non-Javadoc) * * @see com.aol.cyclops.types.Zippable#zip(org.jooq.lambda.Seq, * java.util.function.BiFunction) */ @Override default <U, R> Maybe<R> zip(final Seq<? extends U> other, final BiFunction<? super T, ? super U, ? extends R> zipper) { return (Maybe<R>) MonadicValue.super.zip(other, zipper); } /* * (non-Javadoc) * * @see com.aol.cyclops.types.Zippable#zip(java.util.stream.Stream, * java.util.function.BiFunction) */ @Override default <U, R> Maybe<R> zip(final Stream<? extends U> other, final BiFunction<? super T, ? super U, ? extends R> zipper) { return (Maybe<R>) MonadicValue.super.zip(other, zipper); } /* * (non-Javadoc) * * @see com.aol.cyclops.types.Zippable#zip(java.util.stream.Stream) */ @Override default <U> Maybe<Tuple2<T, U>> zip(final Stream<? extends U> other) { return (Maybe) MonadicValue.super.zip(other); } /* * (non-Javadoc) * * @see com.aol.cyclops.types.Zippable#zip(org.jooq.lambda.Seq) */ @Override default <U> Maybe<Tuple2<T, U>> zip(final Seq<? extends U> other) { return (Maybe) MonadicValue.super.zip(other); } /* * (non-Javadoc) * * @see com.aol.cyclops.types.Zippable#zip(java.lang.Iterable) */ @Override default <U> Maybe<Tuple2<T, U>> zip(final Iterable<? extends U> other) { return (Maybe) MonadicValue.super.zip(other); } /* (non-Javadoc) * @see com.aol.cyclops.types.MonadicValue#unit(java.lang.Object) */ @Override default <T> Maybe<T> unit(final T unit) { return Maybe.of(unit); } /* * (non-Javadoc) * * @see * com.aol.cyclops.types.MonadicValue#coflatMap(java.util.function.Function) */ @Override default <R> Maybe<R> coflatMap(final Function<? super MonadicValue<T>, R> mapper) { return (Maybe<R>) MonadicValue.super.coflatMap(mapper); } /* * cojoin (non-Javadoc) * * @see com.aol.cyclops.types.MonadicValue#nest() */ @Override default Maybe<MonadicValue<T>> nest() { return (Maybe<MonadicValue<T>>) MonadicValue.super.nest(); } /* * (non-Javadoc) * * @see com.aol.cyclops.types.MonadicValue2#combine(com.aol.cyclops.Monoid, * com.aol.cyclops.types.MonadicValue2) */ @Override default Maybe<T> combineEager(final Monoid<T> monoid, final MonadicValue<? extends T> v2) { return (Maybe<T>) MonadicValue.super.combineEager(monoid, v2); } /* * (non-Javadoc) * * @see com.aol.cyclops.value.Value#toMaybe() */ @Override default Maybe<T> toMaybe() { return this; } /* (non-Javadoc) * @see com.aol.cyclops.types.Convertable#isPresent() */ @Override boolean isPresent(); Maybe<T> recover(Supplier<T> value); Maybe<T> recover(T value); Maybe<T> recoverWith(Supplier<? extends Maybe<T>> fn); /* (non-Javadoc) * @see com.aol.cyclops.types.MonadicValue#map(java.util.function.Function) */ @Override <R> Maybe<R> map(Function<? super T, ? extends R> mapper); /* (non-Javadoc) * @see com.aol.cyclops.types.MonadicValue#flatMap(java.util.function.Function) */ @Override <R> Maybe<R> flatMap(Function<? super T, ? extends MonadicValue<? extends R>> mapper); /* (non-Javadoc) * @see com.aol.cyclops.types.Convertable#visit(java.util.function.Function, java.util.function.Supplier) */ @Override <R> R visit(Function<? super T, ? extends R> some, Supplier<? extends R> none); /* * (non-Javadoc) * * @see com.aol.cyclops.lambda.monads.Filterable#filter(java.util.function. * Predicate) */ @Override Maybe<T> filter(Predicate<? super T> fn); /* * (non-Javadoc) * * @see com.aol.cyclops.lambda.monads.Filterable#ofType(java.lang.Class) */ @Override default <U> Maybe<U> ofType(final Class<? extends U> type) { return (Maybe<U>) MonadicValue.super.ofType(type); } /* * (non-Javadoc) * * @see * com.aol.cyclops.lambda.monads.Filterable#filterNot(java.util.function. * Predicate) */ @Override default Maybe<T> filterNot(final Predicate<? super T> fn) { return (Maybe<T>) MonadicValue.super.filterNot(fn); } /* * (non-Javadoc) * * @see com.aol.cyclops.lambda.monads.Filterable#notNull() */ @Override default Maybe<T> notNull() { return (Maybe<T>) MonadicValue.super.notNull(); } /* * (non-Javadoc) * * @see com.aol.cyclops.lambda.monads.Functor#cast(java.lang.Class) */ @Override default <U> Maybe<U> cast(final Class<? extends U> type) { return (Maybe<U>) ApplicativeFunctor.super.cast(type); } /* * (non-Javadoc) * * @see * com.aol.cyclops.lambda.monads.Functor#peek(java.util.function.Consumer) */ @Override default Maybe<T> peek(final Consumer<? super T> c) { return (Maybe<T>) ApplicativeFunctor.super.peek(c); } /* * (non-Javadoc) * * @see com.aol.cyclops.lambda.monads.Functor#trampoline(java.util.function. * Function) */ @Override default <R> Maybe<R> trampoline(final Function<? super T, ? extends Trampoline<? extends R>> mapper) { return (Maybe<R>) ApplicativeFunctor.super.trampoline(mapper); } /* (non-Javadoc) * @see com.aol.cyclops.types.Functor#patternMatch(java.util.function.Function, java.util.function.Supplier) */ @Override default <R> Maybe<R> patternMatch(final Function<CheckValue1<T, R>, CheckValue1<T, R>> case1, final Supplier<? extends R> otherwise) { return (Maybe<R>) ApplicativeFunctor.super.patternMatch(case1, otherwise); } @AllArgsConstructor(access = AccessLevel.PRIVATE) public static final class Just<T> implements Maybe<T> { private final Eval<T> lazy; @Override public <R> Maybe<R> map(final Function<? super T, ? extends R> mapper) { return new Just<>( lazy.map(t -> mapper.apply(t))); } @Override public <R> Maybe<R> flatMap(final Function<? super T, ? extends MonadicValue<? extends R>> mapper) { Eval<? extends Maybe<? extends R>> ret = lazy.map(mapper.andThen(v->v.toMaybe())); final Eval<Maybe<R>> e3 = (Eval<Maybe<R>>)ret; return new Lazy<>( e3); } @Override public Maybe<T> filter(final Predicate<? super T> test) { if (test.test(lazy.get())) return this; return EMPTY; } @Override public <R> R visit(final Function<? super T, ? extends R> some, final Supplier<? extends R> none) { return map(some).get(); } @Override public Maybe<T> recover(final T value) { return this; } @Override public Maybe<T> recover(final Supplier<T> value) { return this; } @Override public String toString() { return mkString(); } @Override public T get() { return lazy.get(); } @Override public boolean isPresent() { return true; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return Objects.hashCode(lazy.get()); } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object obj) { if (obj instanceof Just) return Objects.equals(lazy.get(), ((Just) obj).get()); else if (obj instanceof Lazy) { return Objects.equals(get(), ((Lazy) obj).get()); } return false; } @Override public T orElse(final T value) { return lazy.get(); } @Override public T orElseGet(final Supplier<? extends T> value) { return lazy.get(); } @Override public <R> Just<R> flatMapIterable(final Function<? super T, ? extends Iterable<? extends R>> mapper) { final Maybe<R> maybe = Maybe.super.flatMapIterable(mapper); return (Just<R>) Maybe.just(maybe.get()); } @Override public <R> Just<R> flatMapPublisher(final Function<? super T, ? extends Publisher<? extends R>> mapper) { final Maybe<R> m = Maybe.super.flatMapPublisher(mapper); return (Just<R>) Maybe.just(m.get()); } /* (non-Javadoc) * @see com.aol.cyclops.control.Maybe#recoverWith(java.util.function.Supplier) */ @Override public Maybe<T> recoverWith(Supplier<? extends Maybe<T>> fn) { return this; } } @AllArgsConstructor(access = AccessLevel.PRIVATE) static final class Lazy<T> implements Maybe<T> { private final Eval<Maybe<T>> lazy; @Override public <R> Maybe<R> map(final Function<? super T, ? extends R> mapper) { return flatMap(t -> Maybe.just(mapper.apply(t))); } private static <T> Lazy<T> lazy(Eval<Maybe<T>> lazy) { return new Lazy<>( lazy); } public Maybe<T> resolve() { return lazy.get() .visit(Maybe::just,Maybe::none); } @Override public <R> Maybe<R> flatMap(final Function<? super T, ? extends MonadicValue<? extends R>> mapper) { return lazy(Eval.later( () -> resolve().flatMap(mapper))); } @Override public Maybe<T> filter(final Predicate<? super T> test) { return flatMap(t -> test.test(t) ? this : Maybe.none()); } @Override public <R> R visit(final Function<? super T, ? extends R> some, final Supplier<? extends R> none) { final Maybe<R> mapped = map(some); if (isPresent()) { return mapped.get(); } return none.get(); } @Override public Maybe<T> recover(final T value) { return new Lazy<T>( lazy.map(m -> m.recover(value))); } @Override public Maybe<T> recover(final Supplier<T> value) { return new Lazy<T>( lazy.map(m -> m.recover(value))); } @Override public Maybe<T> recoverWith(Supplier<? extends Maybe<T>> fn) { return new Lazy<T>( lazy.map(m -> m.recoverWith(fn))); } @Override public String toString() { Maybe<T> maybe = lazy.get(); while (maybe instanceof Lazy) { maybe = ((Lazy<T>) maybe).lazy.get(); } return maybe.mkString(); } @Override public T get() { Maybe<T> maybe = lazy.get(); while (maybe instanceof Lazy) { maybe = ((Lazy<T>) maybe).lazy.get(); } return maybe.get(); } @Override public boolean isPresent() { Maybe<T> maybe = lazy.get(); while (maybe instanceof Lazy) { maybe = ((Lazy<T>) maybe).lazy.get(); } return maybe.isPresent(); } @Override public T orElse(final T value) { Maybe<T> maybe = lazy.get(); while (maybe instanceof Lazy) { maybe = ((Lazy<T>) maybe).lazy.get(); } return maybe.orElse(value); } @Override public T orElseGet(final Supplier<? extends T> value) { Maybe<T> maybe = lazy.get(); while (maybe instanceof Lazy) { maybe = ((Lazy<T>) maybe).lazy.get(); } return maybe.orElseGet(value); } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { Maybe<T> maybe = lazy.get(); while (maybe instanceof Lazy) { maybe = ((Lazy<T>) maybe).lazy.get(); } return Objects.hashCode(maybe.get()); } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object obj) { if (obj instanceof Just) return Objects.equals(get(), ((Just) obj).get()); else if (obj instanceof Nothing) { return !isPresent(); } else if (obj instanceof Lazy) { if (isPresent()) return Objects.equals(get(), ((Lazy) obj).get()); else { return !((Lazy) obj).isPresent(); } } return false; } @Override public <R> Lazy<R> flatMapIterable(final Function<? super T, ? extends Iterable<? extends R>> mapper) { final Maybe<R> m = Maybe.super.flatMapIterable(mapper); return new Lazy( Eval.later(() -> m.get())); } @Override public <R> Lazy<R> flatMapPublisher(final Function<? super T, ? extends Publisher<? extends R>> mapper) { final Maybe<R> m = (Lazy<R>) Maybe.super.flatMapPublisher(mapper); return new Lazy( Eval.later(() -> m.get())); } } public static class Nothing<T> implements Maybe<T> { @Override public <R> Maybe<R> map(final Function<? super T, ? extends R> mapper) { return EMPTY; } @Override public <R> Maybe<R> flatMap(final Function<? super T, ? extends MonadicValue<? extends R>> mapper) { return EMPTY; } @Override public Maybe<T> filter(final Predicate<? super T> test) { return EMPTY; } @Override public T get() { return Optional.<T> ofNullable(null) .get(); } @Override public Maybe<T> recover(final T value) { return Maybe.of(value); } @Override public Maybe<T> recover(final Supplier<T> value) { return new Just<>( Eval.later(value)); } @Override public Maybe<T> recoverWith(Supplier<? extends Maybe<T>> fn) { return new Just<>(Eval.narrow(Eval.later(fn))).flatMap(m->m); } @Override public <R> R visit(final Function<? super T, ? extends R> some, final Supplier<? extends R> none) { return none.get(); } @Override public Optional<T> toOptional() { return Optional.ofNullable(null); } @Override public String toString() { return mkString(); } @Override public boolean isPresent() { return false; } @Override public boolean equals(final Object obj) { if (obj instanceof Nothing) return true; if (obj instanceof Lazy) { return !((Lazy) obj).isPresent(); } return false; } @Override public T orElse(final T value) { return value; } @Override public T orElseGet(final Supplier<? extends T> value) { return value.get(); } @Override public <R> Nothing<R> flatMapIterable(final Function<? super T, ? extends Iterable<? extends R>> mapper) { return (Nothing<R>) EMPTY; } @Override public <R> Nothing<R> flatMapPublisher(final Function<? super T, ? extends Publisher<? extends R>> mapper) { return (Nothing<R>) EMPTY; } } }
package com.api.access; import org.json.simple.JSONObject; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; public class HttpConnection { public String method; HttpURLConnection urlConnection = null; public HttpConnection() { this.setMethod("POST"); } public HttpConnection setMethod(String method) { this.method = method; return this; } public HashMap<String,String> response(String urlString, String params, String token, String headerName) { InputStream inStream = null; URL url = null; try { url = new URL(urlString.toString()); if (this.method.equals("POST")) { urlConnection = post(url, params, token, headerName); } else { urlConnection = get(url, token, headerName); } //this.printHeaders(urlConnection); inStream = urlConnection.getInputStream(); BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream)); String temp, response = ""; while ((temp = bReader.readLine()) != null) { response += temp; } System.out.println(response); return Json.jsonToMap(response); } catch (Exception e) { System.out.println(e); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException ignored) { } } if (urlConnection != null) { urlConnection.disconnect(); } } return new HashMap<String, String>(); } public String header(String urlString, String params, String headerName) { InputStream inStream = null; URL url = null; try { url = new URL(urlString.toString()); if (this.method.equals("POST")) { urlConnection = post(url, params, null, null); } else { urlConnection = get(url, null, null); } return urlConnection.getHeaderField(headerName); } catch (Exception e) { System.out.println(e); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException ignored) { } } if (urlConnection != null) { urlConnection.disconnect(); } } return null; } private HttpURLConnection get(URL url, String token, String headerName) throws Exception { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.setRequestProperty(headerName, token); urlConnection.connect(); return urlConnection; } private HttpURLConnection post(URL url, String params, String token, String headerName) throws Exception { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setRequestProperty("Content-Type", "application/json"); if (token != null && headerName != null) { urlConnection.setRequestProperty(headerName, token); } if (params != null) { //set the content length of the body urlConnection.setRequestProperty("Content-length", params.getBytes().length + ""); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); //send the json as body of the request OutputStream outputStream = urlConnection.getOutputStream(); outputStream.write(params.getBytes("UTF-8")); outputStream.close(); } urlConnection.connect(); return urlConnection; } private void printHeaders(HttpURLConnection urlConnection) { Map<String, List<String>> map = urlConnection.getHeaderFields(); System.out.println("Printing Response Header...\n"); for (Map.Entry<String, List<String>> entry : map.entrySet()) { System.out.println("Key : " + entry.getKey() + " ,Value : " + entry.getValue()); } } }
package com.areen.jlib.gui; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import javax.swing.plaf.basic.BasicArrowButton; /** * * @author dejan */ public class MenuButton extends JButton implements ChangeListener, ActionListener, PopupMenuListener, PropertyChangeListener { private JButton mainButton, dropDownButton; private JPopupMenu dropDownMenu; /** * Default Constructor that creates a blank button with a down facing arrow. */ public MenuButton() { this(""); } // MenuButton() method /** * Default Constructor that creates a blank button with the specified action and a down facing arrow. * @param argAction */ public MenuButton(final javax.swing.Action argAction) { this(new JButton(argAction), SwingConstants.SOUTH); } // MenuButton() method /** * Creates a button with the specified label and a down facing arrow. * @param argLabel String */ public MenuButton(final String argLabel) { this(new JButton(argLabel), SwingConstants.SOUTH); } // MenuButton() method /** * Creates a button with the specified text * and a arrow in the specified direction. * @param text String * @param orientation int */ public MenuButton(final String text, final int orientation) { this(new JButton(text), orientation); } // MenuButton() method /** * Passes in the button to use in the left hand side, with the specified * orientation for the arrow on the right hand side. * @param argMainButton * @param orientation int */ public MenuButton(final JButton argMainButton, final int orientation) { super(); this.mainButton = argMainButton; this.mainButton.setIcon(mainButton.getIcon()); this.dropDownButton = new BasicArrowButton(orientation); dropDownButton.addActionListener(this); AbstractAction action = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { MenuButton.this.actionPerformed(e); } // actionPerformed() method }; dropDownButton.setAction(action); this.setBorderPainted(false); this.dropDownButton.setBorderPainted(false); this.mainButton.setBorderPainted(false); this.setPreferredSize(new Dimension(40, 30)); this.setMaximumSize(new Dimension(46, 30)); this.setMinimumSize(new Dimension(40, 30)); this.setLayout(new BorderLayout()); this.setMargin(new Insets(-3, -3, -3, -3)); this.add(mainButton, BorderLayout.CENTER); this.add(dropDownButton, BorderLayout.EAST); this.mainButton.addPropertyChangeListener("enabled", this); } // MenuButton() method @Override public void setIcon(final Icon defaultIcon) { super.setIcon(defaultIcon); this.mainButton.setIcon(defaultIcon); } // setIcon() method @Override public void setToolTipText(final String text) { this.mainButton.setToolTipText(text); this.dropDownButton.setToolTipText(text); } // setToolTipText() method /** * Sets the popup menu to show when the arrow is clicked. * @param menu JPopupMenu */ public void setMenu(final JPopupMenu menu) { this.dropDownMenu = menu; } // setMenu() method /** * gets the drop down menu * @return JPopupMenu */ public JPopupMenu getMenu() { return dropDownMenu; } // getMenu() method /** * returns the main (left hand side) button. * @return JButton */ public JButton getMainButton() { return mainButton; } // getMainButton() method /** * gets the drop down button (with the arrow) * @return JButton */ public JButton getDropDownButton() { return dropDownButton; } // getDropDownButton() method @Override public void propertyChange(final PropertyChangeEvent evt) { dropDownButton.setEnabled(mainButton.isEnabled()); } // propertyChange() method @Override public void stateChanged(final ChangeEvent e) { if (e.getSource() == mainButton.getModel()) { if (dropDownMenu.isVisible() && !mainButton.getModel().isRollover()) { mainButton.getModel().setRollover(true); return; } dropDownButton.getModel().setRollover(mainButton.getModel().isRollover()); dropDownButton.setSelected(mainButton.getModel().isArmed() && mainButton.getModel().isPressed()); } else { if (dropDownMenu.isVisible() && !dropDownButton.getModel().isSelected()) { dropDownButton.getModel().setSelected(true); return; } mainButton.getModel().setRollover(dropDownButton.getModel().isRollover()); } // else } // stateChanged() method /** * action listener for the arrow button- shows / hides the popup menu. * @param e ActionEvent */ @Override public void actionPerformed(final ActionEvent e) { if (this.dropDownMenu == null) { return; } Point p = this.getLocationOnScreen(); dropDownMenu.setLocation((int) p.getX(), (int) p.getY() + this.getHeight()); dropDownMenu.show(mainButton, 0, mainButton.getHeight()); } // actionPerformed() method @Override public void popupMenuCanceled(final PopupMenuEvent e) { dropDownMenu.setVisible(false); } // popupMenuCanceled() method @Override public void popupMenuWillBecomeVisible(final PopupMenuEvent e) { mainButton.getModel().setRollover(true); dropDownButton.getModel().setSelected(true); } // popupMenuWillBecomeVisible() method @Override public void popupMenuWillBecomeInvisible(final PopupMenuEvent e) { //popupVisible = false; mainButton.getModel().setRollover(false); dropDownButton.getModel().setSelected(false); ((JPopupMenu) e.getSource()).removePopupMenuListener(this); // act as good programmer :) } // popupMenuWillBecomeInvisible() method /** * adds a action listener to this button (actually to the left hand side * button, and any left over surrounding space. the arrow button will not * be affected. * @param al ActionListener */ @Override public void addActionListener(final ActionListener al) { this.mainButton.addActionListener(al); //this.addActionListener(al); } // addActionListener() method public static void test() { JFrame frame = new JFrame("Simple Split Button Test"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.getContentPane().setLayout(new BorderLayout()); JPanel p = new JPanel(); p.setLayout(new BorderLayout()); JToolBar toolBar = new JToolBar("tb"); JButton sbButton = new JButton("sb"); sbButton.setBackground(Color.BLACK); sbButton.setContentAreaFilled(false); MenuButton sb = new MenuButton(sbButton, SwingConstants.SOUTH); toolBar.add(new JButton("test button")); toolBar.add(sb); p.add(new JLabel("DropDownButton test"), BorderLayout.CENTER); JPopupMenu testMenu = new JPopupMenu("test menu"); testMenu.add(addMI("menuItem1")); testMenu.add(addMI("menuItem2")); sb.setMenu(testMenu); frame.getContentPane().add(toolBar, BorderLayout.NORTH); frame.getContentPane().add(p, BorderLayout.CENTER); frame.setSize(200, 100); frame.show(); } // test() method private static JMenuItem addMI(final String text) { JMenuItem mi = new JMenuItem(text); mi.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { System.out.println(e.getActionCommand()); } // actionPerformed() method }); return mi; } // addMI() method /** * * @param args */ public static void main(final String[] args) { test(); } // main() method } // MenuButton class
package com.balancedpayments; import com.balancedpayments.core.Resource; import com.balancedpayments.core.ResourceCollection; import com.balancedpayments.core.ResourceField; import com.balancedpayments.errors.HTTPError; import java.util.Date; import java.util.Map; public class CardHold extends Resource { public static final String resource_href = "/card_holds"; // fields @ResourceField(mutable=true) public Integer amount; @ResourceField(mutable=true) public String description; // attributes @ResourceField() public Date created_at; @ResourceField() public String currency; @ResourceField() public Date expires_at; @ResourceField() public String failure_reason; @ResourceField() public String failure_reason_code; @ResourceField() public String status; @ResourceField() public String transaction_number; @ResourceField() public String voided_at; @ResourceField(field="card_holds.card") public Card card; @ResourceField(field="card_holds.debit") public Debit debit; @ResourceField(field="card_holds.debits") public Debit.Collection debits; @ResourceField(field="card_holds.events") public Event.Collection events; @ResourceField(field="card_holds.order") public Order order; public static class Collection extends ResourceCollection<CardHold> { public Collection(String uri) { super(CardHold.class, uri); } }; public CardHold() { super(); } public CardHold(String uri) throws HTTPError { super(uri); } public Debit capture(Map<String, Object> payload) throws HTTPError { debit = debits.create(payload); return debit; } public Debit capture() throws HTTPError { debit = debits.create(); return debit; } }
package com.brettonw.bag;
package com.bugsnag.android; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; class DateUtils { private static DateFormat iso8601; static { TimeZone tz = TimeZone.getTimeZone("UTC"); iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US); iso8601.setTimeZone(tz); } static String toISO8601(Date date) { return iso8601.format(date); } }
package com.clackathon.vuzii; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @author Euan */ public class Relation { public double relativity(Image a, Image b){ List<Double> percentages = new ArrayList<>(); percentages.add(getTagRelation(a.getUserTags(), b.getUserTags())); percentages.add(getUploaderRelation(a.getUploader(), b.getUploader())); // percentages.add(getCreationTimeRelation(a.getCreationTime(), b.getCreationTime())); percentages.add(getLocationRelation(a.getLocation(), b.getLocation())); percentages.add(getCommentsRelation(a.getComments(), b.getComments())); /* tags 0.4 uploader 0.8 creationTime 0.9 location 0.6 comments check for hash-tags/similar words 0.8 location of likes (javascript to check) */ return calculateAverage(percentages); } private double getCommentsRelation(List<String> commentsA, List<String> commentsB) { List<String> intersection = new ArrayList<>(commentsA); intersection.retainAll(commentsB); return ((double) intersection.size())/Math.max(commentsA.size(),commentsB.size()); } private double getLocationRelation(Location a, Location b) { double longDistance = a.getLongitude() - b.getLongitude(); double latDistance = Math.abs(a.getLatitude() - b.getLatitude()); return 1.0 / Math.sqrt(Math.sqrt(longDistance * longDistance + latDistance * latDistance)); } /*private Double getCreationTimeRelation(Date creationTime, Date creationTime1) { return } */ private double getUploaderRelation(User uploaderA, User uploaderB) { return uploaderA.getName().equals(uploaderB.getName()) ? 1 : 0; } private double getTagRelation(List<String> a, List<String> b) { List<String> intersection = new ArrayList<>(a); intersection.retainAll(b); return ((double) intersection.size())/Math.max(a.size(),b.size()); } private static double calculateAverage(List<Double> values) { double sum = 0; if(!values.isEmpty()) { for (double value : values) { sum += value; } return sum / values.size(); } return sum; } }
package com.clutch.dates; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.util.Assert; public class StringToTime extends Date { private static final long serialVersionUID = 7889493424407815134L; private static final Log log = LogFactory.getLog(StringToTime.class); // default SimpleDateFormat string is the standard MySQL date format private static final String defaultSimpleDateFormat = "yyyy-MM-dd HH:mm:ss.SSS"; // An expression of time (hour)(:(minute))?((:(second))(.(millisecond))?)?( *(am?|pm?))?(RFC 822 time zone|general time zone)? private static final String timeExpr = "(\\d{1,2})(:(\\d{1,2}))?(:(\\d{1,2})(\\.(\\d{1,3}))?)?( *(am?|pm?))?( *\\-\\d{4}|[a-z]{3}|[a-z ]+)?"; /** Patterns and formats recognized by the algorithm; first match wins, so insert most specific patterns first. */ private static final PatternAndFormat[] known = { // TODO: ISO 8601 and derivatives // just the year new PatternAndFormat( Pattern.compile("\\d{4}"), new Format(FormatType.YEAR) ), // decrement, e.g., -1 day new PatternAndFormat( Pattern.compile("\\-( *\\d{1,} +[^ ]+){1,}", Pattern.CASE_INSENSITIVE), new Format(FormatType.DECREMENT) ), // increment, e.g., +1 day new PatternAndFormat( Pattern.compile("\\+?( *\\d{1,} +[^ ]+){1,}", Pattern.CASE_INSENSITIVE), new Format(FormatType.INCREMENT) ), // e.g., October 26 and Oct 26 new PatternAndFormat( Pattern.compile("([a-z]+) +(\\d{1,2})", Pattern.CASE_INSENSITIVE), new Format(FormatType.MONTH_AND_DATE) ), // e.g., 26 October 1981, or 26 Oct 1981, or 26 Oct 81 new PatternAndFormat( Pattern.compile("\\d{1,2} +[a-z]+ +(\\d{2}|\\d{4})", Pattern.CASE_INSENSITIVE), new Format("d MMM y") ), // now or today new PatternAndFormat( Pattern.compile("(midnight|now|today|(this +)?(morning|afternoon|evening)|tonight|noon( +tomorrow)?|tomorrow|tomorrow +(morning|afternoon|evening|night|noon)?|yesterday|yesterday +(morning|afternoon|evening|night)?)", Pattern.CASE_INSENSITIVE), new Format(FormatType.WORD) ), // time, 24-hour and 12-hour new PatternAndFormat( Pattern.compile(timeExpr, Pattern.CASE_INSENSITIVE), new Format(FormatType.TIME) ), // e.g., October 26, 1981 or Oct 26, 1981 new PatternAndFormat( Pattern.compile("[a-z]+ +\\d{1,2} *, *(\\d{2}|\\d{4})", Pattern.CASE_INSENSITIVE), new Format("MMM d, y") ), // e.g., 10/26/1981 or 10/26/81 new PatternAndFormat( Pattern.compile("\\d{1,2}/\\d{1,2}/\\d{2,4}"), new Format("M/d/y") ), // e.g., 10-26-1981 or 10-26-81 new PatternAndFormat( Pattern.compile("\\d{1,2}\\-\\d{1,2}\\-\\d{2,4}"), new Format("M-d-y") ), // e.g., 10/26 or 10-26 new PatternAndFormat( Pattern.compile("(\\d{1,2})(/|\\-)(\\d{1,2})"), new Format(FormatType.MONTH_AND_DATE_WITH_SLASHES) ), // e.g., 1981/10/26 new PatternAndFormat( Pattern.compile("\\d{4}/\\d{1,2}/\\d{1,2}"), new Format("y/M/d") ), // e.g., 1981-10-26 new PatternAndFormat( Pattern.compile("\\d{4}\\-\\d{1,2}\\-\\d{1,2}"), new Format("y-M-d") ), // e.g., October or Oct new PatternAndFormat( Pattern.compile("(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)", Pattern.CASE_INSENSITIVE), new Format(FormatType.MONTH) ), // e.g., Tuesday or Tue new PatternAndFormat( Pattern.compile("(Sun(day)?|Mon(day)?|Tue(sday)?|Wed(nesday)?|Thu(rsday)?|Fri(day)?|Sat(urday)?)", Pattern.CASE_INSENSITIVE), new Format(FormatType.DAY_OF_WEEK) ), // next, e.g., next Tuesday new PatternAndFormat( Pattern.compile("next +(.*)", Pattern.CASE_INSENSITIVE), new Format(FormatType.NEXT) ), // last, e.g., last Tuesday new PatternAndFormat( Pattern.compile("last +(.*)", Pattern.CASE_INSENSITIVE), new Format(FormatType.LAST) ), // compound statement new PatternAndFormat( Pattern.compile("(.*) +(((\\+|\\-){1}.*)|"+timeExpr+")$", Pattern.CASE_INSENSITIVE), new Format(FormatType.COMPOUND) ) }; /** Date/Time string parsed */ private Object dateTimeString; /** The format to use in {@link #toString()) */ private String simpleDateFormat; /** The {@link java.util.Date} interpreted from {@link #dateTimeString}, or {@link java.lang.Boolean} <code>false</code> */ private Object date; public StringToTime() { super(); this.date = new Date(this.getTime()); } public StringToTime(Date date) { super(date.getTime()); this.date = new Date(this.getTime()); } public StringToTime(Object dateTimeString) { this(dateTimeString, new Date(), defaultSimpleDateFormat); } public StringToTime(Object dateTimeString, String simpleDateFormat) { this(dateTimeString, new Date(), simpleDateFormat); } public StringToTime(Object dateTimeString, Date now) { this(dateTimeString, now, defaultSimpleDateFormat); } public StringToTime(Object dateTimeString, Long now) { this(dateTimeString, new Date(now), defaultSimpleDateFormat); } public StringToTime(Object dateTimeString, Integer now) { this(dateTimeString, new Date(new Long(now)), defaultSimpleDateFormat); } public StringToTime(Object dateTimeString, Date now, String simpleDateFormat) { super(0); Assert.notNull(dateTimeString); Assert.notNull(now); Assert.notNull(simpleDateFormat); this.dateTimeString = dateTimeString; this.simpleDateFormat = simpleDateFormat; date = StringToTime.date(dateTimeString, now); if (!Boolean.FALSE.equals(date)) setTime(((Date) date).getTime()); else throw new StringToTimeException(dateTimeString); } /** * @return {@link java.util.Date#getTime()} */ public long getTime() { return super.getTime(); } /** * @return Calendar set to timestamp {@link java.util.Date#getTime()} */ public Calendar getCal() { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(super.getTime()); return cal; } /** * @param simpleDateFormat * @see {@link SimpleDateFormat} * @return Date formatted according to <code>simpleDateFormat</code> */ public String format(String simpleDateFormat) { return new SimpleDateFormat(simpleDateFormat).format(this); } /** * @return If {@link #simpleDateFormat} provided in constructor, then attempts to format <code>date</code> * accordingly; otherwise, returns the <code>String</code> value of {@link java.util.Date#getTime()}. */ public String toString() { if (simpleDateFormat != null) return new SimpleDateFormat(simpleDateFormat).format(this); else return new SimpleDateFormat("yyyy/dd/MM").format(this); //String.valueOf(super.getTime()); } /** * A single parameter version of {@link #time(String, Date)}, passing a new instance of {@link java.util.Date} as the * second parameter. * @param dateTimeString * @return A {@link java.lang.Long} timestamp representative of <code>dateTimeString</code>, or {@link java.lang.Boolean} <code>false</code>. * @see #time(String, Date) */ public static Object time(Object dateTimeString) { return time(dateTimeString, new Date()); } /** * Parse <code>dateTimeString</code> and produce a timestamp. * @param dateTimeString * @param now * @return <ul> * <li>If equal to &quot;now&quot;, return the number of milliseconds since January 1, 1970 or the value of <code>now</code>.</li> * <li>If an incremental or decremental statement, e.g., +1 hour or -1 week, or a composite thereof, e.g., +1 hour 1 minute 1 second, * returns a date equal to the increment/decrement plus the value of <code>now</code>. * </ul> */ public static Object time(Object dateTimeString, Date now) { try { if (dateTimeString == null) return Boolean.FALSE; else { String trimmed = String.valueOf(dateTimeString).trim(); for(PatternAndFormat paf : known) { Matcher m = paf.matches(trimmed); if (m.matches()) { Long time = paf.parse(trimmed, now, m); //System.out.println(String.format("[%s] triggered format [%s]: %s", dateTimeString, paf.f, new Date(time))); if (log.isDebugEnabled()) log.debug(String.format("[%s] triggered format [%s]: %s", dateTimeString, paf.f, new Date(time))); return time; } } // no match if (log.isDebugEnabled()) log.debug(String.format("Unrecognized date/time string [%s]", dateTimeString)); return Boolean.FALSE; } } catch (Exception e) { // thrown by various features of the parser if (!Boolean.parseBoolean(System.getProperty(StringToTime.class+".EXCEPTION_ON_PARSE_FAILURE", "false"))) { if (log.isDebugEnabled()) log.debug(String.format("Failed to parse [%s] into a java.util.Date instance", dateTimeString)); return Boolean.FALSE; } else throw new StringToTimeException(dateTimeString, e); } } private static ParserResult getParserResult(String trimmedDateTimeString, Date now) throws ParseException { for(PatternAndFormat paf : known) { Matcher m = paf.matches(trimmedDateTimeString); if (m.matches()) { log.debug(String.format("Date/time string [%s] triggered format [%s]", trimmedDateTimeString, paf.f)); return new ParserResult(paf.parse(trimmedDateTimeString, now, m), paf.f.type); } } return null; } public static Object date(Object dateTimeString) { return date(dateTimeString, new Date()); } public static Object date(Object dateTimeString, Date now) { Object time = time(dateTimeString, now); return (Boolean.FALSE.equals(time)) ? Boolean.FALSE : new Date((Long) time); } public static Object cal(Object dateTimeString) { return cal(dateTimeString, new Date()); } public static Object cal(Object dateTimeString, Date now) { Object date = date(dateTimeString, now); if (Boolean.FALSE.equals(date)) return Boolean.FALSE; else { Calendar cal = Calendar.getInstance(); cal.setTime((Date) date); return cal; } } private static class PatternAndFormat { public Pattern p; public Format f; public PatternAndFormat(Pattern p, Format f) { this.p = p; this.f = f; } public Matcher matches(String dateTimeString) { return p.matcher(dateTimeString); } public Long parse(String dateTimeString, Date now, Matcher m) throws ParseException { return f.parse(dateTimeString, now, m).getTime(); } } private static class ParserResult { public FormatType type; public Long timestamp; public ParserResult(Long timestamp, FormatType type) { this.timestamp = timestamp; this.type = type; } } private static class Format { private static Pattern unit = Pattern.compile("(\\d{1,}) +(s(ec(ond)?)?|mo(n(th)?)?|(hour|hr?)|d(ay)?|(w(eek)?|wk)|m(in(ute)?)?|(y(ear)?|yr))s?"); private static Pattern removeExtraSpaces = Pattern.compile(" +"); private static Map<String, Integer> translateDayOfWeek = new HashMap<String, Integer>(); static { translateDayOfWeek.put("sunday", 1); translateDayOfWeek.put("sun", 1); translateDayOfWeek.put("monday", 2); translateDayOfWeek.put("mon", 2); translateDayOfWeek.put("tuesday", 3); translateDayOfWeek.put("tue", 3); translateDayOfWeek.put("wednesday", 4); translateDayOfWeek.put("wed", 4); translateDayOfWeek.put("thursday", 5); translateDayOfWeek.put("thu", 5); translateDayOfWeek.put("friday", 6); translateDayOfWeek.put("fri", 6); translateDayOfWeek.put("saturday", 7); translateDayOfWeek.put("sat", 7); } private String sdf; private FormatType type; public Format(FormatType type) { this.type = type; } public Format(String sdf) { this.sdf = sdf; } public String toString() { if (sdf != null) return sdf; else return type.toString(); } public Date parse(String dateTimeString, Date now, Matcher m) throws ParseException { if (sdf != null) return new SimpleDateFormat(sdf).parse(dateTimeString); else { dateTimeString = removeExtraSpaces.matcher(dateTimeString).replaceAll(" ").toLowerCase(); try { Calendar cal = Calendar.getInstance(); cal.setTime(now); // word expressions, e.g., "now" and "today" and "tonight" if (type == FormatType.WORD) { if ("now".equals(dateTimeString)) return (now != null ? now : new Date()); else if ("today".equals(dateTimeString)) { cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return new Date(cal.getTimeInMillis()); } else if ("morning".equals(dateTimeString) || "this morning".equals(dateTimeString)) { // by default, this morning begins at 07:00:00.000 int thisMorningBeginsAt = Integer.parseInt(System.getProperty(StringToTime.class+".THIS_MORNING_BEGINS_AT", "7")); cal.set(Calendar.HOUR_OF_DAY, thisMorningBeginsAt); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return new Date(cal.getTimeInMillis()); } else if ("noon".equals(dateTimeString)) { // noon is 12:00:00.000 cal.set(Calendar.HOUR_OF_DAY, 12); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return new Date(cal.getTimeInMillis()); } else if ("afternoon".equals(dateTimeString) || "this afternoon".equals(dateTimeString)) { // by default, this afternoon begins at 13:00:00.000 int thisAfternoonBeginsAt = Integer.parseInt(System.getProperty(StringToTime.class+".THIS_AFTERNOON_BEGINS_AT", "13")); cal.set(Calendar.HOUR_OF_DAY, thisAfternoonBeginsAt); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return new Date(cal.getTimeInMillis()); } else if ("evening".equals(dateTimeString) || "this evening".equals(dateTimeString)) { // by default, this evening begins at 17:00:00.000 int thisEveningBeginsAt = Integer.parseInt(System.getProperty(StringToTime.class+".THIS_EVENING_BEGINS_AT", "17")); cal.set(Calendar.HOUR_OF_DAY, thisEveningBeginsAt); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return new Date(cal.getTimeInMillis()); } else if ("tonight".equals(dateTimeString)) { // by default, tonight begins at 20:00:00.000 int tonightBeginsAt = Integer.parseInt(System.getProperty(StringToTime.class+".TONIGHT_BEGINS_AT", "20")); cal.set(Calendar.HOUR_OF_DAY, tonightBeginsAt); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return new Date(cal.getTimeInMillis()); } else if ("midnight".equals(dateTimeString)) { return new StringToTime("00:00:00 +24 hours", now); } else if ("tomorrow".equals(dateTimeString)) { return new StringToTime("now +24 hours", now); } else if ("tomorrow morning".equals(dateTimeString)) { return new StringToTime("morning +24 hours", now); } else if ("tomorrow noon".equals(dateTimeString) || "noon tomorrow".equals(dateTimeString)) { return new StringToTime("noon +24 hours", now); } else if ("tomorrow afternoon".equals(dateTimeString)) { return new StringToTime("afternoon +24 hours", now); } else if ("tomorrow evening".equals(dateTimeString)) { return new StringToTime("evening +24 hours", now); } else if ("tomorrow night".equals(dateTimeString)) { return new StringToTime("tonight +24 hours", now); } else if ("yesterday".equals(dateTimeString)) { return new StringToTime("now -24 hours", now); } else if ("yesterday morning".equals(dateTimeString)) { return new StringToTime("morning -24 hours", now); } else if ("yesterday noon".equals(dateTimeString) || "noon yesterday".equals(dateTimeString)) { return new StringToTime("noon -24 hours", now); } else if ("yesterday afternoon".equals(dateTimeString)) { return new StringToTime("afternoon -24 hours", now); } else if ("yesterday evening".equals(dateTimeString)) { return new StringToTime("evening -24 hours", now); } else if ("yesterday night".equals(dateTimeString)) { return new StringToTime("tonight -24 hours", now); } else throw new ParseException(String.format("Unrecognized date word: %s", dateTimeString), 0); } // time expressions, 24-hour and 12-hour else if (type == FormatType.TIME) { // An expression of time (hour)(:(minute))?((:(second))(.(millisecond))?)?( *(am?|pm?))?(RFC 822 time zone|general time zone)? String hour = m.group(1); String min = m.group(3); String sec = m.group(5); String ms = m.group(7); String amOrPm = m.group(8); if (hour != null) { if (amOrPm != null) cal.set(Calendar.HOUR, new Integer(hour)); else cal.set(Calendar.HOUR_OF_DAY, new Integer(hour)); } else cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, (min != null ? new Integer(min) : 0)); cal.set(Calendar.SECOND, (sec != null ? new Integer(sec) : 0)); cal.set(Calendar.MILLISECOND, (ms != null ? new Integer(ms) : 0)); if (amOrPm != null) cal.set(Calendar.AM_PM, (amOrPm.equals("a") || amOrPm.equals("am") ? Calendar.AM : Calendar.PM)); return new Date(cal.getTimeInMillis()); } // increments else if (type == FormatType.INCREMENT || type == FormatType.DECREMENT) { Matcher units = unit.matcher(dateTimeString); while (units.find()) { Integer val = new Integer(units.group(1)) * (type == FormatType.DECREMENT ? -1 : 1); String u = units.group(2); // second if ("s".equals(u) || "sec".equals(u) || "second".equals(u)) cal.set(Calendar.SECOND, cal.get(Calendar.SECOND)+val); // minute else if ("m".equals(u) || "min".equals(u) || "minute".equals(u)) cal.set(Calendar.MINUTE, cal.get(Calendar.MINUTE)+val); // hour else if ("h".equals(u) || "hr".equals(u) || "hour".equals(u)) cal.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY)+val); // day else if ("d".equals(u) || "day".equals(u)) cal.set(Calendar.DATE, cal.get(Calendar.DATE)+val); // week else if ("w".equals(u) || "wk".equals(u) || "week".equals(u)) cal.set(Calendar.WEEK_OF_YEAR, cal.get(Calendar.WEEK_OF_YEAR)+val); // month else if ("mo".equals(u) || "mon".equals(u) || "month".equals(u)) cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)+val); // year else if ("y".equals(u) || "yr".equals(u) || "year".equals(u)) cal.set(Calendar.YEAR, cal.get(Calendar.YEAR)+val); else throw new IllegalArgumentException(String.format("Unrecognized %s unit: [%s]", type, u)); } return new Date(cal.getTimeInMillis()); } // compound expressions else if (type == FormatType.COMPOUND) { Object date = StringToTime.date(m.group(1), now); if (!Boolean.FALSE.equals(date)) return (Date) StringToTime.date(m.group(2), (Date) date); else throw new IllegalArgumentException(String.format("Couldn't parse %s, so couldn't compound with %s", m.group(1), m.group(2))); } // month of the year else if (type == FormatType.MONTH) { Calendar ref = Calendar.getInstance(); ref.setTime(new SimpleDateFormat("MMM d, y").parse(String.format("%s 1, 1970", m.group(1)))); if (cal.get(Calendar.MONTH) >= ref.get(Calendar.MONTH)) cal.set(Calendar.YEAR, cal.get(Calendar.YEAR)); cal.set(Calendar.MONTH, ref.get(Calendar.MONTH)); return new Date(cal.getTimeInMillis()); } // day of week else if (type == FormatType.DAY_OF_WEEK) { Integer ref = translateDayOfWeek.get(dateTimeString); if (cal.get(Calendar.DAY_OF_WEEK) >= ref) cal.set(Calendar.WEEK_OF_YEAR, cal.get(Calendar.WEEK_OF_YEAR)+1); cal.set(Calendar.DAY_OF_WEEK, ref); return new Date(cal.getTimeInMillis()); } // month and day with slashes else if (type == FormatType.MONTH_AND_DATE_WITH_SLASHES) { Calendar ref = Calendar.getInstance(); ref.setTime(new SimpleDateFormat("M/d/y").parse(String.format("%s/%s/1970", m.group(1), m.group(3)))); if (cal.get(Calendar.MONTH) >= ref.get(Calendar.MONTH)) cal.set(Calendar.YEAR, cal.get(Calendar.YEAR)); cal.set(Calendar.MONTH, ref.get(Calendar.MONTH)); cal.set(Calendar.DATE, ref.get(Calendar.DATE)); return new Date(cal.getTimeInMillis()); } // month and day long-hand else if (type == FormatType.MONTH_AND_DATE) { Calendar ref = Calendar.getInstance(); ref.setTime(new SimpleDateFormat("MMM d, y").parse(String.format("%s %s, 1970", m.group(1), m.group(2)))); if (cal.get(Calendar.MONTH) >= ref.get(Calendar.MONTH)) cal.set(Calendar.YEAR, cal.get(Calendar.YEAR)); cal.set(Calendar.MONTH, ref.get(Calendar.MONTH)); cal.set(Calendar.DATE, ref.get(Calendar.DATE)); return new Date(cal.getTimeInMillis()); } // next X else if (type == FormatType.NEXT) { // Format types MONTH and DAY_OF_WEEK both return future dates, so no additional processing is needed String expr = m.group(1); ParserResult parsed = StringToTime.getParserResult(expr, now); if (parsed != null && ( FormatType.MONTH.equals(parsed.type) || FormatType.DAY_OF_WEEK.equals(parsed.type) || FormatType.MONTH_AND_DATE.equals(parsed.type)) ) return new Date(parsed.timestamp); else { if ("week".equals(expr)) cal.set(Calendar.WEEK_OF_YEAR, cal.get(Calendar.WEEK_OF_YEAR)+1); else if ("month".equals(expr)) cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)+1); else if ("year".equals(expr)) cal.set(Calendar.YEAR, cal.get(Calendar.YEAR)+1); else throw new IllegalArgumentException(String.format("Invalid expression of time: %s", dateTimeString)); return new Date(cal.getTimeInMillis()); } } // last X else if (type == FormatType.LAST) { String expr = m.group(1); ParserResult parsed = StringToTime.getParserResult(expr, now); if (parsed != null && (FormatType.MONTH.equals(parsed.type) || FormatType.MONTH_AND_DATE.equals(parsed.type))) { return new StringToTime("-1 year", new Date(parsed.timestamp)); } else if (parsed != null && FormatType.DAY_OF_WEEK.equals(parsed.type)) { return new StringToTime("-1 week", new Date(parsed.timestamp)); } else { if ("week".equals(expr)) cal.set(Calendar.WEEK_OF_YEAR, cal.get(Calendar.WEEK_OF_YEAR)-1); else if ("month".equals(expr)) cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)-1); else if ("year".equals(expr)) cal.set(Calendar.YEAR, cal.get(Calendar.YEAR)-1); else throw new IllegalArgumentException(String.format("Invalid expression of time: %s", dateTimeString)); return new Date(cal.getTimeInMillis()); } } // year else if (type == FormatType.YEAR) { cal.set(Calendar.YEAR, new Integer(m.group(0))); return new Date(cal.getTimeInMillis()); } // unimplemented format type else throw new IllegalStateException(String.format("Unimplemented FormatType: %s", type)); } catch (ParseException e) { throw e; } catch (IllegalStateException e) { throw e; } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { throw new RuntimeException(String.format("Unknown failure in string-to-time conversion: %s", e.getMessage()), e); } } } } private enum FormatType { COMPOUND, MONTH_AND_DATE_WITH_SLASHES, MONTH_AND_DATE, MONTH, DAY_OF_WEEK, NEXT, LAST, INCREMENT, DECREMENT, WORD, TIME, YEAR } }
package com.fishercoder.solutions; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * 15. 3Sum * Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? * Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ] */ public class _15 { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> result = new ArrayList<>(); if (nums == null || nums.length == 0) { return result; } Arrays.sort(nums); for (int i = 0; i < nums.length; i++) { if (i >= 1 && nums[i] == nums[i - 1]) { continue; } int left = i + 1; int right = nums.length - 1; while (left < right) { int sum = nums[i] + nums[left] + nums[right]; if (sum == 0) { result.add(Arrays.asList(nums[i], nums[left], nums[right])); /**be sure to skip duplicates*/ while (left + 1 < right && nums[left] == nums[left + 1]) { left++; } while (right - 1 > left && nums[right] == nums[right - 1]) { right } left++; right } else if (sum > 0) { right } else { left++; } } } return result; } }
package com.fishercoder.solutions; /** * 33. Search in Rotated Sorted Array * * Suppose a sorted array is rotated at some pivot unknown to you beforehand. * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). * You are given a target value to search. If found in the array return its index, otherwise return -1. * You may assume no duplicate exists in the array. */ public class _33 { public static class Solution1 { public int search(int[] nums, int target) { if (nums == null || nums.length == 0) { return -1; } int minIdx = findMinIdx(nums); if (target == nums[minIdx]) { return minIdx; } int m = nums.length; int start = (target <= nums[m - 1]) ? minIdx : 0; int end = (target > nums[m - 1]) ? minIdx : m - 1; while (start <= end) { int mid = start + (end - start) / 2; if (nums[mid] == target) { return mid; } else if (target > nums[mid]) { start = mid + 1; } else { end = mid - 1; } } return -1; } private int findMinIdx(int[] nums) { int start = 0; int end = nums.length - 1; while (start < end) { int mid = start + (end - start) / 2; if (nums[mid] > nums[end]) { start = mid + 1; } else { end = mid; } } return start; } } public static class Solution2 { public int search(int[] nums, int target) { if (nums == null || nums.length == 0) { return -1; } int lo = 0; int hi = nums.length - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (nums[mid] == target) return mid; if (nums[lo] <= nums[mid]) { if (target >= nums[lo] && target < nums[mid]) { hi = mid - 1; } else { lo = mid + 1; } } else { if (target > nums[mid] && target <= nums[hi]) { lo = mid + 1; } else { hi = mid - 1; } } } return nums[lo] == target ? lo : -1; } } }
package com.fishercoder.solutions; /** * 79. Word Search * Given a 2D board and a word, find if the word exists in the grid. * The word can be constructed from letters of sequentially adjacent cell, * where "adjacent" cells are those horizontally or vertically neighboring. * The same letter cell may not be used more than once. For example, Given board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] word = "ABCCED", -> returns true, word = "SEE", -> returns true, word = "ABCB", -> returns false. */ public class _79 { public static class Solution1 { //I made it this time, completely by myself! Cheers! This let me completely understand backtracking! public boolean exist(char[][] board, String word) { int m = board.length; int n = board[0].length; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { boolean[][] visited = new boolean[m][n]; if (dfs(board, visited, i, j, word, 0)) { return true; } } } return false; } final int[] dirs = new int[]{0, 1, 0, -1, 0}; boolean dfs(char[][] board, boolean[][] visited, int row, int col, String word, int index) { if (index >= word.length() || word.charAt(index) != board[row][col]) { return false; } else if (index == word.length() - 1 && word.charAt(index) == board[row][col]) { visited[row][col] = true; return true; } visited[row][col] = true;//set it to true for this case boolean result = false; for (int i = 0; i < 4; i++) { int nextRow = row + dirs[i]; int nextCol = col + dirs[i + 1]; if (nextRow < 0 || nextRow >= board.length || nextCol < 0 || nextCol >= board[0].length || visited[nextRow][nextCol]) { continue; } result = dfs(board, visited, nextRow, nextCol, word, index + 1); if (result) { return result; } else { visited[nextRow][nextCol] = false;//set it back to false if this road doesn't work to allow it for other paths, this is backtracking!!! } } return result; } } public static class Solution2 { boolean[][] visited; public boolean exist(char[][] board, String word) { int m = board.length; int n = board[0].length; visited = new boolean[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (word.charAt(0) == board[i][j] && search(board, word, i, j, 0)) { return true; } } } return false; } boolean search(char[][] board, String word, int i, int j, int pos) { if (pos == word.length()) { return true; } if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || word.charAt(pos) != board[i][j] || visited[i][j]) { return false; } visited[i][j] = true; if (search(board, word, i + 1, j, pos + 1) || search(board, word, i - 1, j, pos + 1) || search(board, word, i, j + 1, pos + 1) || search(board, word, i, j - 1, pos + 1)) { return true; } visited[i][j] = false; return false; } } public static void main(String... strings) { _79 test = new _79(); // char[][] board = new char[][]{ // {'A','B','C','E'}, // {'S','F','C','S'}, // {'A','D','E','E'}, // String word = "ABCCED"; // String word = "SEE"; // String word = "ABCD"; // char[][] board = new char[][]{ // String word = "aaa"; char[][] board = new char[][]{ {'A', 'B', 'C', 'E'}, {'S', 'F', 'E', 'S'}, {'A', 'D', 'E', 'E'}, }; String word = "ABCEFSADEESE"; Solution1 solution1 = new Solution1(); System.out.println(solution1.exist(board, word)); } }
package com.fishercoder.solutions; import com.fishercoder.common.classes.TreeNode; /** * 98. Validate Binary Search Tree * * Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: 2 / \ 1 3 Binary tree [2,1,3], return true. Example 2: 1 / \ 2 3 Binary tree [1,2,3], return false. */ public class _98 { public static class Solution1 { public boolean isValidBST(TreeNode root) { return valid(root, null, null); } boolean valid(TreeNode root, Integer min, Integer max) { if (root == null) { return true; } if ((min != null && root.val <= min) || (max != null && root.val >= max)) { return false; } return valid(root.left, min, root.val) && valid(root.right, root.val, max); } } }
package com.loopperfect.buckaroo; import com.loopperfect.buckaroo.cli.CLICommand; import com.loopperfect.buckaroo.cli.CLIParsers; import com.loopperfect.buckaroo.views.ProgressView; import com.loopperfect.buckaroo.views.SummaryView; import com.loopperfect.buckaroo.virtualterminal.Color; import com.loopperfect.buckaroo.virtualterminal.TerminalBuffer; import com.loopperfect.buckaroo.virtualterminal.components.Component; import com.loopperfect.buckaroo.virtualterminal.components.StackLayout; import com.loopperfect.buckaroo.virtualterminal.components.Text; import io.reactivex.Observable; import io.reactivex.Scheduler; import io.reactivex.observables.ConnectableObservable; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.Schedulers; import org.fusesource.jansi.AnsiConsole; import org.jparsec.Parser; import org.jparsec.error.ParserException; import java.nio.charset.Charset; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.time.Instant; import java.util.Arrays; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static com.loopperfect.buckaroo.EvenMoreFiles.writeFile; public final class Main { private Main() {} public static void main(final String[] args) { if (args.length == 0) { System.out.println("Buck, Buck Buckaroo! \uD83E\uDD20"); System.out.println("https://buckaroo.readthedocs.io/"); return; } // We need to change the default behaviour of Schedulers.io() // so that it has a bounded thread-pool. // Take at least 2 threads to prevent dead-locks. final int threads = 10; ExecutorService IOExecutor = Executors.newFixedThreadPool(threads); final Scheduler IOScheduler = Schedulers.from(IOExecutor); RxJavaPlugins.setIoSchedulerHandler(scheduler -> { scheduler.shutdown(); return IOScheduler; }); final FileSystem fs = FileSystems.getDefault(); final String rawCommand = String.join(" ", args); // Send the command to the logging server, if present //LoggingTasks.log(fs, rawCommand).subscribe(); // Ignore any results // Parse the command final Parser<CLICommand> commandParser = CLIParsers.commandParser; try { final CLICommand command = commandParser.parse(rawCommand); final ExecutorService executorService = Executors.newCachedThreadPool(); final Scheduler scheduler = Schedulers.from(executorService); final Context ctx = Context.of(fs, scheduler); final Observable<Event> task = command.routine().apply(ctx); final ConnectableObservable<Either<Throwable, Event>> events$ = task .observeOn(scheduler) .subscribeOn(scheduler) .map(e->{ final Either<Throwable, Event> r = Either.right(e); return r; }) .onErrorReturn(Either::left) .publish(); final Observable<Component> current$ = events$ .flatMap(x->{ if(x.left().isPresent()) return Observable.error(x.left().get()); return Observable.just(x.right().get()); }) .compose(ProgressView::progressView) .subscribeOn(Schedulers.computation()) .sample(100, TimeUnit.MILLISECONDS) .distinctUntilChanged(); final Observable<Component> summary$ = events$ .flatMap(x -> { if(x.left().isPresent()) return Observable.error(x.left().get()); return Observable.just(x.right().get()); }) .compose(SummaryView::summaryView) .subscribeOn(Schedulers.computation()) .lastElement().toObservable(); AnsiConsole.systemInstall(); TerminalBuffer buffer = new TerminalBuffer(); //TODO: make sure that summary$ emits after current$ Observable .merge(current$, summary$ ) .map(c -> c.render(60)) .doOnNext(buffer::flip) .doOnError(error -> { buffer.flip( StackLayout.of( Text.of("buckaroo failed: "+ error.toString(), Color.RED), Text.of("writing stacktrace to buckaroo-stacktrace.log", Color.YELLOW) ).render(60)); writeFile( fs.getPath("").resolve("buckaroo-stacktrace.log"), Arrays.stream(error.getStackTrace()) .map(s->s.toString()) .reduce(Instant.now().toString()+":", (a, b) -> a+"\n"+b), Charset.defaultCharset(), true); }).doAfterTerminate(()->{ executorService.shutdown(); IOExecutor.shutdown(); IOScheduler.shutdown(); scheduler.shutdown(); }).subscribe(x -> {}, e -> {}, () -> { System.out.println("success!!"); }); events$.connect(); } catch (final ParserException e) { System.out.println("Uh oh!"); System.out.println(e.getMessage()); } catch (Throwable e){} } }
package com.mongodb; import com.github.fakemongo.FongoException; import com.github.fakemongo.impl.ExpressionParser; import com.github.fakemongo.impl.Filter; import com.github.fakemongo.impl.Tuple2; import com.github.fakemongo.impl.UpdateEngine; import com.github.fakemongo.impl.Util; import com.github.fakemongo.impl.geo.GeoUtil; import com.github.fakemongo.impl.geo.LatLong; import com.github.fakemongo.impl.index.GeoIndex; import com.github.fakemongo.impl.index.IndexAbstract; import com.github.fakemongo.impl.index.IndexFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.bson.BSON; import org.bson.types.Binary; import org.bson.types.ObjectId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * fongo override of com.mongodb.DBCollection you shouldn't need to use this class directly * * @author jon */ public class FongoDBCollection extends DBCollection { private final static Logger LOG = LoggerFactory.getLogger(FongoDBCollection.class); public static final String ID_KEY = "_id"; private static final String ID_NAME_INDEX = "_id_"; private final FongoDB fongoDb; private final ExpressionParser expressionParser; private final UpdateEngine updateEngine; private final boolean nonIdCollection; private final ExpressionParser.ObjectComparator objectComparator; // Fields/Index private final List<IndexAbstract> indexes = new ArrayList<IndexAbstract>(); private final IndexAbstract _idIndex; public FongoDBCollection(FongoDB db, String name) { super(db, name); this.fongoDb = db; this.nonIdCollection = name.startsWith("system"); this.expressionParser = new ExpressionParser(); this.updateEngine = new UpdateEngine(); this.objectComparator = expressionParser.buildObjectComparator(true); this._idIndex = IndexFactory.create("_id", new BasicDBObject("_id", 1), true); this.indexes.add(_idIndex); if (!this.nonIdCollection) { this.createIndex(new BasicDBObject("_id", 1), new BasicDBObject("name", ID_NAME_INDEX)); } } private CommandResult insertResult(int updateCount) { CommandResult result = fongoDb.okResult(); result.put("n", updateCount); return result; } private CommandResult updateResult(int updateCount, boolean updatedExisting) { CommandResult result = fongoDb.okResult(); result.put("n", updateCount); result.put("updatedExisting", updatedExisting); return result; } @Override public synchronized WriteResult insert(DBObject[] arr, WriteConcern concern, DBEncoder encoder) throws MongoException { return insert(Arrays.asList(arr), concern, encoder); } @Override public synchronized WriteResult insert(List<DBObject> toInsert, WriteConcern concern, DBEncoder encoder) { for (DBObject obj : toInsert) { DBObject cloned = filterLists(Util.cloneIdFirst(obj)); if (LOG.isDebugEnabled()) { LOG.debug("insert: " + cloned); } ObjectId id = putIdIfNotPresent(cloned); // Save the id field in the caller. if (!(obj instanceof LazyDBObject) && obj.get(ID_KEY) == null) { obj.put(ID_KEY, Util.clone(id)); } putSizeCheck(cloned, concern); } return new WriteResult(insertResult(toInsert.size()), concern); } boolean enforceDuplicates(WriteConcern concern) { WriteConcern writeConcern = concern == null ? getWriteConcern() : concern; return writeConcern._w instanceof Number && ((Number) writeConcern._w).intValue() > 0; } public ObjectId putIdIfNotPresent(DBObject obj) { Object object = obj.get(ID_KEY); if (object == null) { ObjectId id = new ObjectId(); id.notNew(); obj.put(ID_KEY, Util.clone(id)); return id; } else if (object instanceof ObjectId) { ObjectId id = (ObjectId) object; id.notNew(); return id; } return null; } public void putSizeCheck(DBObject obj, WriteConcern concern) { if (_idIndex.size() > 100000) { throw new FongoException("Whoa, hold up there. Fongo's designed for lightweight testing. 100,000 items per collection max"); } addToIndexes(obj, null, concern); } public DBObject filterLists(DBObject dbo) { if (dbo == null) { return null; } dbo = Util.clone(dbo); for (Map.Entry<String, Object> entry : Util.entrySet(dbo)) { Object replacementValue = replaceListAndMap(entry.getValue()); dbo.put(entry.getKey(), replacementValue); } return dbo; } public Object replaceListAndMap(Object value) { Object replacementValue = BSON.applyEncodingHooks(value); if (replacementValue instanceof DBObject) { replacementValue = filterLists((DBObject) replacementValue); } else if (replacementValue instanceof List) { BasicDBList list = new BasicDBList(); for (Object listItem : (List) replacementValue) { list.add(replaceListAndMap(listItem)); } replacementValue = list; } else if (replacementValue instanceof Object[]) { BasicDBList list = new BasicDBList(); for (Object listItem : (Object[]) replacementValue) { list.add(replaceListAndMap(listItem)); } replacementValue = list; } else if (replacementValue instanceof Map) { BasicDBObject newDbo = new BasicDBObject(); //noinspection unchecked for (Map.Entry<String, Object> entry : (Set<Map.Entry<String, Object>>) ((Map) replacementValue).entrySet()) { newDbo.put(entry.getKey(), replaceListAndMap(entry.getValue())); } replacementValue = newDbo; } else if (replacementValue instanceof Binary) { replacementValue = ((Binary) replacementValue).getData(); } return replacementValue; } protected void fInsert(DBObject obj, WriteConcern concern) { putIdIfNotPresent(obj); putSizeCheck(obj, concern); } @Override public synchronized WriteResult update(DBObject q, DBObject o, boolean upsert, boolean multi, WriteConcern concern, DBEncoder encoder) throws MongoException { q = filterLists(q); o = filterLists(o); if (LOG.isDebugEnabled()) { LOG.debug("update(" + q + ", " + o + ", " + upsert + ", " + multi + ")"); } if (o.containsField(ID_KEY) && q.containsField(ID_KEY) && objectComparator.compare(o.get(ID_KEY), q.get(ID_KEY)) != 0) { LOG.warn("can not change _id of a document query={}, document={}", q, o); throw new MongoException.DuplicateKey(fongoDb.notOkErrorResult(0, "can not change _id of a document " + ID_KEY)); } int updatedDocuments = 0; boolean idOnlyUpdate = q.containsField(ID_KEY) && q.keySet().size() == 1; boolean updatedExisting = false; if (idOnlyUpdate && isNotUpdateCommand(o)) { if (!o.containsField(ID_KEY)) { o.put(ID_KEY, Util.clone(q.get(ID_KEY))); } else { o.put(ID_KEY, Util.clone(o.get(ID_KEY))); } @SuppressWarnings("unchecked") Iterator<DBObject> oldObjects = _idIndex.retrieveObjects(q).iterator(); addToIndexes(Util.clone(o), oldObjects.hasNext() ? oldObjects.next() : null, concern); updatedDocuments++; } else { Filter filter = expressionParser.buildFilter(q); for (DBObject obj : filterByIndexes(q)) { if (filter.apply(obj)) { DBObject newObject = Util.clone(obj); updateEngine.doUpdate(newObject, o, q); // Check for uniqueness (throw MongoException if error) addToIndexes(newObject, obj, concern); updatedDocuments++; updatedExisting = true; if (!multi) { break; } } } if (updatedDocuments == 0 && upsert) { BasicDBObject newObject = createUpsertObject(q); fInsert(updateEngine.doUpdate(newObject, o, q), concern); } } return new WriteResult(updateResult(updatedDocuments, updatedExisting), concern); } private List idsIn(DBObject query) { Object idValue = query.get(ID_KEY); if (idValue == null || query.keySet().size() > 1) { return Collections.emptyList(); } else if (idValue instanceof DBObject) { DBObject idDbObject = (DBObject) idValue; Collection inList = (Collection) idDbObject.get(QueryOperators.IN); // I think sorting the inputed keys is a rough // approximation of how mongo creates the bounds for walking // the index. It has the desired affect of returning results // in _id index order, but feels pretty hacky. if (inList != null) { Object[] inListArray = inList.toArray(new Object[inList.size()]); // ids could be DBObjects, so we need a comparator that can handle that Arrays.sort(inListArray, objectComparator); return Arrays.asList(inListArray); } if (!isNotUpdateCommand(idValue)) { return Collections.emptyList(); } } return Collections.singletonList(Util.clone(idValue)); } protected BasicDBObject createUpsertObject(DBObject q) { BasicDBObject newObject = new BasicDBObject(); List idsIn = idsIn(q); if (!idsIn.isEmpty()) { newObject.put(ID_KEY, Util.clone(idsIn.get(0))); } else { BasicDBObject filteredQuery = new BasicDBObject(); for (String key : q.keySet()) { Object value = q.get(key); if (isNotUpdateCommand(value)) { filteredQuery.put(key, value); } } updateEngine.mergeEmbeddedValueFromQuery(newObject, filteredQuery); } return newObject; } public boolean isNotUpdateCommand(Object value) { boolean okValue = true; if (value instanceof DBObject) { for (String innerKey : ((DBObject) value).keySet()) { if (innerKey.startsWith("$")) { okValue = false; } } } return okValue; } @Override protected void doapply(DBObject o) { } @Override public synchronized WriteResult remove(DBObject o, WriteConcern concern, DBEncoder encoder) throws MongoException { o = filterLists(o); if (LOG.isDebugEnabled()) { LOG.debug("remove: " + o); } int updatedDocuments = 0; Collection<DBObject> objectsByIndex = filterByIndexes(o); Filter filter = expressionParser.buildFilter(o); List<DBObject> ids = new ArrayList<DBObject>(); // Double pass, objectsByIndex can be not "objects" for (DBObject object : objectsByIndex) { if (filter.apply(object)) { ids.add(object); } } // Real remove. for (DBObject object : ids) { LOG.debug("remove object : {}", object); removeFromIndexes(object); updatedDocuments++; } return new WriteResult(updateResult(updatedDocuments, false), concern); } @Override public synchronized void createIndex(DBObject keys, DBObject options, DBEncoder encoder) throws MongoException { DBCollection indexColl = fongoDb.getCollection("system.indexes"); BasicDBObject rec = new BasicDBObject(); rec.append("v", 1); rec.append("key", keys); rec.append("ns", this.getDB().getName() + "." + this.getName()); if (options != null && options.containsField("name")) { rec.append("name", options.get("name")); } else { StringBuilder sb = new StringBuilder(); boolean firstLoop = true; for (String keyName : keys.keySet()) { if (!firstLoop) { sb.append("_"); } sb.append(keyName).append("_").append(keys.get(keyName)); firstLoop = false; } rec.append("name", sb.toString()); } // Ensure index doesn't exist. if (indexColl.findOne(rec) != null) { return; } // Unique index must not be in previous find. boolean unique = options != null && options.get("unique") != null && (Boolean.TRUE.equals(options.get("unique")) || "1".equals(options.get("unique")) || Integer.valueOf(1).equals(options.get("unique"))); if (unique) { rec.append("unique", unique); } rec.putAll(options); try { IndexAbstract index = IndexFactory.create((String) rec.get("name"), keys, unique); @SuppressWarnings("unchecked") List<List<Object>> notUnique = index.addAll(_idIndex.values()); if (!notUnique.isEmpty()) { // Duplicate key. if (enforceDuplicates(getWriteConcern())) { fongoDb.errorResult(11000, "E11000 duplicate key error index: " + getFullName() + ".$" + rec.get("name") + " dup key: { : " + notUnique + " }").throwOnError(); } return; } indexes.add(index); } catch (MongoException me) { fongoDb.errorResult(me.getCode(), me.getMessage()).throwOnError(); } // Add index if all fine. indexColl.insert(rec); } @Override public DBObject findOne(DBObject query, DBObject fields, DBObject orderBy, ReadPreference readPref) { QueryOpBuilder queryOpBuilder = new QueryOpBuilder().addQuery(query).addOrderBy(orderBy); Iterator<DBObject> resultIterator = __find(queryOpBuilder.get(), fields, 0, 1, -1, 0, readPref, null); return resultIterator.hasNext() ? resultIterator.next() : null; } /** * note: encoder, decoder, readPref, options are ignored */ @Override Iterator<DBObject> __find(DBObject ref, DBObject fields, int numToSkip, int batchSize, int limit, int options, ReadPreference readPref, DBDecoder decoder, DBEncoder encoder) { return __find(ref, fields, numToSkip, batchSize, limit, options, readPref, decoder); } /** * note: decoder, readPref, options are ignored */ @Override synchronized Iterator<DBObject> __find(final DBObject pRef, DBObject fields, int numToSkip, int batchSize, int limit, int options, ReadPreference readPref, DBDecoder decoder) throws MongoException { DBObject ref = filterLists(pRef); long maxScan = Long.MAX_VALUE; // ref = filterLists(ref); if (LOG.isDebugEnabled()) { LOG.debug("find({}, {}).skip({}).limit({})", ref, fields, numToSkip, limit); LOG.debug("the db {} looks like {}", this.getDB().getName(), _idIndex.size()); } DBObject orderby = null; if (ref.containsField("$orderby")) { orderby = (DBObject) ref.get("$orderby"); } if (ref.containsField("$maxScan")) { maxScan = ((Number) ref.get("$maxScan")).longValue(); } if (ref.containsField("$query")) { ref = (DBObject) ref.get("$query"); } Filter filter = expressionParser.buildFilter(ref); int foundCount = 0; int upperLimit = Integer.MAX_VALUE; if (limit > 0) { upperLimit = limit; } Collection<DBObject> objectsFromIndex = filterByIndexes(ref); List<DBObject> results = new ArrayList<DBObject>(); List objects = idsIn(ref); if (!objects.isEmpty()) { if (!(ref.get(ID_KEY) instanceof DBObject)) { // Special case : find({id:<val}) doesn't handle skip... // But : find({_id:{$in:[1,2,3]}).skip(3) will return empty list. numToSkip = 0; } if (orderby == null) { orderby = new BasicDBObject(ID_KEY, 1); } else { // Special case : if order by is wrong (field doesn't exist), the sort must be directed by _id. objectsFromIndex = sortObjects(new BasicDBObject(ID_KEY, 1), objectsFromIndex); } } int seen = 0; Iterable<DBObject> objectsToSearch = sortObjects(orderby, objectsFromIndex); for (Iterator<DBObject> iter = objectsToSearch.iterator(); iter.hasNext() && foundCount <= upperLimit && maxScan DBObject dbo = iter.next(); if (filter.apply(dbo)) { if (seen++ >= numToSkip) { foundCount++; DBObject clonedDbo = Util.clone(dbo); if (nonIdCollection) { clonedDbo.removeField(ID_KEY); } for (String key : clonedDbo.keySet()) { Object value = clonedDbo.get(key); if (value instanceof DBRef && ((DBRef) value).getDB() == null) { clonedDbo.put(key, new DBRef(this.getDB(), ((DBRef) value).getRef(), ((DBRef) value).getId())); } } results.add(clonedDbo); } } } if (fields != null && !fields.keySet().isEmpty()) { LOG.debug("applying projections {}", fields); results = applyProjections(results, fields); } LOG.debug("found results {}", results); return results.iterator(); } /** * Return "objects.values()" if no index found. * * @return objects from "_id" if no index found, elsewhere the restricted values from an index. */ private Collection<DBObject> filterByIndexes(DBObject ref) { Collection<DBObject> dbObjectIterable = null; if (ref != null) { IndexAbstract matchingIndex = searchIndex(ref); if (matchingIndex != null) { //noinspection unchecked dbObjectIterable = matchingIndex.retrieveObjects(ref); if (LOG.isDebugEnabled()) { LOG.debug("restrict with index {}, from {} to {} elements", matchingIndex.getName(), _idIndex.size(), dbObjectIterable == null ? 0 : dbObjectIterable.size()); } } } if (dbObjectIterable == null) { //noinspection unchecked dbObjectIterable = _idIndex.values(); } return dbObjectIterable; } private List<DBObject> applyProjections(List<DBObject> results, DBObject projection) { final List<DBObject> ret = new ArrayList<DBObject>(results.size()); for (DBObject result : results) { DBObject projectionMacthedResult = applyProjections(result, projection); if (null != projectionMacthedResult) { ret.add(projectionMacthedResult); } } return ret; } private static void addValuesAtPath(BasicDBObject ret, DBObject dbo, List<String> path, int startIndex) { String subKey = path.get(startIndex); Object value = dbo.get(subKey); if (path.size() > startIndex + 1) { if (value instanceof DBObject && !(value instanceof List)) { BasicDBObject nb = (BasicDBObject) ret.get(subKey); if (nb == null) { nb = new BasicDBObject(); } ret.append(subKey, nb); addValuesAtPath(nb, (DBObject) value, path, startIndex + 1); } else if (value instanceof List) { BasicDBList list = new BasicDBList(); ret.append(subKey, list); for (Object v : (List) value) { if (v instanceof DBObject) { BasicDBObject nb = new BasicDBObject(); list.add(nb); addValuesAtPath(nb, (DBObject) v, path, startIndex + 1); } } } } else if (value != null) { ret.append(subKey, value); } } public static DBObject applyProjections(DBObject result, DBObject projectionObject) { if (projectionObject == null) { return Util.cloneIdFirst(result); } int inclusionCount = 0; int exclusionCount = 0; List<String> projectionFields = new ArrayList<String>(); boolean wasIdExcluded = false; List<Tuple2<List<String>, Boolean>> projections = new ArrayList<Tuple2<List<String>, Boolean>>(); for (String projectionKey : projectionObject.keySet()) { final Object projectionValue = projectionObject.get(projectionKey); boolean included = false; boolean project = false; if (projectionValue instanceof Number) { included = ((Number) projectionValue).intValue() > 0; } else if (projectionValue instanceof Boolean) { included = (Boolean) projectionValue; } else if (projectionValue instanceof DBObject) { project = true; projectionFields.add(projectionKey); } else if (!projectionValue.toString().equals("text")){ final String msg = "Projection `" + projectionKey + "' has a value that Fongo doesn't know how to handle: " + projectionValue + " (" + (projectionValue == null ? " " : projectionValue.getClass() + ")"); throw new IllegalArgumentException(msg); } List<String> projectionPath = Util.split(projectionKey); if (!ID_KEY.equals(projectionKey)) { if (included) { inclusionCount++; } else if (!project) { exclusionCount++; } } else { wasIdExcluded = !included; } if (projectionPath.size() > 0) { projections.add(new Tuple2<List<String>, Boolean>(projectionPath, included)); } } if (inclusionCount > 0 && exclusionCount > 0) { throw new IllegalArgumentException( "You cannot combine inclusion and exclusion semantics in a single projection with the exception of the _id field: " + projectionObject); } BasicDBObject ret; if (exclusionCount > 0) { ret = (BasicDBObject) Util.clone(result); } else { ret = new BasicDBObject(); if (!wasIdExcluded) { ret.append(ID_KEY, Util.clone(result.get(ID_KEY))); } else if (inclusionCount == 0) { ret = (BasicDBObject) Util.clone(result); ret.removeField(ID_KEY); } } for (Tuple2<List<String>, Boolean> projection : projections) { if (projection._1.size() == 1 && !projection._2) { ret.removeField(projection._1.get(0)); } else { addValuesAtPath(ret, result, projection._1, 0); } } if (!projectionFields.isEmpty()) { for (String projectionKey : projectionObject.keySet()) { if (!projectionFields.contains(projectionKey)) { continue; } final Object projectionValue = projectionObject.get(projectionKey); final boolean isElemMatch = ((BasicDBObject) projectionObject.get(projectionKey)).containsField(QueryOperators.ELEM_MATCH); if (isElemMatch) { ret.removeField(projectionKey); List searchIn = ((BasicDBList) result.get(projectionKey)); DBObject searchFor = (BasicDBObject) ((BasicDBObject) projectionObject.get(projectionKey)).get(QueryOperators.ELEM_MATCH); String searchKey = (String) searchFor.keySet().toArray()[0]; int pos = -1; for (int i = 0; i < searchIn.size(); i++) { boolean matches; DBObject fieldToSearch = (BasicDBObject) searchIn.get(i); if (fieldToSearch.containsField(searchKey)) { if (searchFor.get(searchKey) instanceof ObjectId && fieldToSearch.get(searchKey) instanceof String) { ObjectId m1 = new ObjectId(searchFor.get(searchKey).toString()); ObjectId m2 = new ObjectId(String.valueOf(fieldToSearch.get(searchKey))); matches = m1.equals(m2); } else if (searchFor.get(searchKey) instanceof String && fieldToSearch.get(searchKey) instanceof ObjectId) { ObjectId m1 = new ObjectId(String.valueOf(searchFor.get(searchKey))); ObjectId m2 = new ObjectId(fieldToSearch.get(searchKey).toString()); matches = m1.equals(m2); } else { matches = fieldToSearch.get(searchKey).equals(searchFor.get(searchKey)); } if (matches) { pos = i; break; } } } if (pos != -1) { BasicDBList append = new BasicDBList(); append.add(searchIn.get(pos)); ret.append(projectionKey, append); LOG.debug("$elemMatch projection of field \"{}\", gave result: {} ({})", projectionKey, ret, ret.getClass()); } } else { final String msg = "Projection `" + projectionKey + "' has a value that Fongo doesn't know how to handle: " + projectionValue + " (" + (projectionValue == null ? " " : projectionValue.getClass() + ")"); throw new IllegalArgumentException(msg); } } } return ret; } public Collection<DBObject> sortObjects(final DBObject orderby, final Collection<DBObject> objects) { Collection<DBObject> objectsToSearch = objects; if (orderby != null) { final Set<String> orderbyKeySet = orderby.keySet(); if (!orderbyKeySet.isEmpty()) { DBObject[] objectsToSort = objects.toArray(new DBObject[objects.size()]); Arrays.sort(objectsToSort, new Comparator<DBObject>() { @Override public int compare(DBObject o1, DBObject o2) { for (String sortKey : orderbyKeySet) { final List<String> path = Util.split(sortKey); int sortDirection = (Integer) orderby.get(sortKey); List<Object> o1list = expressionParser.getEmbeddedValues(path, o1); List<Object> o2list = expressionParser.getEmbeddedValues(path, o2); int compareValue = expressionParser.compareLists(o1list, o2list) * sortDirection; if (compareValue != 0) { return compareValue; } } return 0; } }); objectsToSearch = Arrays.asList(objectsToSort); } } if (LOG.isDebugEnabled()) { LOG.debug("sorted objectsToSearch " + objectsToSearch); } return objectsToSearch; } @Override public synchronized long getCount(DBObject query, DBObject fields, long limit, long skip) { query = filterLists(query); Filter filter = query == null ? ExpressionParser.AllFilter : expressionParser.buildFilter(query); long count = 0; long upperLimit = Long.MAX_VALUE; if (limit > 0) { upperLimit = limit; } int seen = 0; for (Iterator<DBObject> iter = filterByIndexes(query).iterator(); iter.hasNext() && count <= upperLimit;) { DBObject value = iter.next(); if (filter.apply(value)) { if (seen++ >= skip) { count++; } } } return count; } @Override public synchronized long getCount(DBObject query, DBObject fields, ReadPreference readPrefs) { //as we're in memory we don't need to worry about readPrefs return getCount(query, fields, 0, 0); } @Override public synchronized DBObject findAndModify(DBObject query, DBObject fields, DBObject sort, boolean remove, DBObject update, boolean returnNew, boolean upsert) { LOG.debug("findAndModify({}, {}, {}, {}, {}, {}, {}", query, fields, sort, remove, update, returnNew, upsert); query = filterLists(query); update = filterLists(update); Filter filter = expressionParser.buildFilter(query); Iterable<DBObject> objectsToSearch = sortObjects(sort, filterByIndexes(query)); DBObject beforeObject = null; DBObject afterObject = null; for (DBObject dbo : objectsToSearch) { if (filter.apply(dbo)) { beforeObject = dbo; if (!remove) { afterObject = Util.clone(beforeObject); updateEngine.doUpdate(afterObject, update, query); addToIndexes(afterObject, beforeObject, getWriteConcern()); break; } else { remove(dbo); return dbo; } } } if (beforeObject != null && !returnNew) { return applyProjections(beforeObject, fields); } if (beforeObject == null && upsert && !remove) { beforeObject = new BasicDBObject(); afterObject = createUpsertObject(query); fInsert(updateEngine.doUpdate(afterObject, update, query), getWriteConcern()); } if (returnNew) { return applyProjections(afterObject, fields); } else { return applyProjections(beforeObject, fields); } } @Override public synchronized List distinct(String key, DBObject query) { query = filterLists(query); Set<Object> results = new LinkedHashSet<Object>(); Filter filter = expressionParser.buildFilter(query); for (Iterator<DBObject> iter = filterByIndexes(query).iterator(); iter.hasNext();) { DBObject value = iter.next(); if (filter.apply(value)) { List<Object> keyValues = expressionParser.getEmbeddedValues(key, value); for (Object keyValue : keyValues) { if (keyValue instanceof List) { results.addAll((List) keyValue); } else { results.add(keyValue); } } } } //noinspection unchecked return new ArrayList(results); } protected synchronized void _dropIndexes(String name) throws MongoException { DBCollection indexColl = fongoDb.getCollection("system.indexes"); indexColl.remove(new BasicDBObject("name", name)); ListIterator<IndexAbstract> iterator = indexes.listIterator(); while (iterator.hasNext()) { IndexAbstract index = iterator.next(); if (index.getName().equals(name)) { iterator.remove(); break; } } } protected synchronized void _dropIndexes() { List<DBObject> indexes = fongoDb.getCollection("system.indexes").find().toArray(); // Two step for no concurrent modification exception for (DBObject index : indexes) { if (!ID_NAME_INDEX.equals(index.get("name").toString())) { dropIndexes(index.get("name").toString()); } } } @Override public void drop() { _idIndex.clear(); _dropIndexes(); // _idIndex must stay. fongoDb.removeCollection(this); } /** * Search the most restrictive index for query. * * @param query query for restriction * @return the most restrictive index, or null. */ private synchronized IndexAbstract searchIndex(DBObject query) { IndexAbstract result = null; int foundCommon = -1; Set<String> queryFields = query.keySet(); for (IndexAbstract index : indexes) { if (index.canHandle(queryFields)) { // The most restrictive first. if (index.getFields().size() > foundCommon || (result != null && !result.isUnique() && index.isUnique())) { result = index; foundCommon = index.getFields().size(); } } } LOG.debug("searchIndex() found index {} for fields {}", result, queryFields); return result; } /** * Search the geo index. * * @return the geo index, or null. */ private synchronized IndexAbstract searchGeoIndex(boolean unique) { IndexAbstract result = null; for (IndexAbstract index : indexes) { if (index.isGeoIndex()) { if (result != null && unique) { this.fongoDb.notOkErrorResult(-5, "more than one 2d index, not sure which to run geoNear on").throwOnError(); } result = index; if (!unique) { break; } } } LOG.debug("searchGeoIndex() found index {}", result); return result; } /** * Search the text index fields. * * @return the text index, or null. */ private synchronized Set<String> searchTextIndexFields(boolean unique) { IndexAbstract result = null; Set<String> indexFields = new TreeSet<String>(); for (IndexAbstract index : indexes) { DBObject keys = index.getKeys(); for (String field : (Set<String>) index.getFields()) { if (keys.get(field).equals("text")) { if (result != null && unique) { this.fongoDb.notOkErrorResult(-5, "more than one text index, not sure which to run text search on").throwOnError(); } result = index; indexFields.add(field); if (!unique) { break; } } } } LOG.debug("searchTextIndex() found index {}", result); return indexFields; } /** * Add entry to index. If necessary, remove oldObject from index. * * @param object new object to insert. * @param oldObject null if insert, old object if update. */ private synchronized void addToIndexes(DBObject object, DBObject oldObject, WriteConcern concern) { // Ensure "insert/update" create collection into "fongoDB" this.fongoDb.addCollection(this); Set<String> queryFields = object.keySet(); // First, try to see if index can add the new value. for (IndexAbstract index : indexes) { @SuppressWarnings("unchecked") List<List<Object>> error = index.checkAddOrUpdate(object, oldObject); if (!error.isEmpty()) { // TODO formatting : E11000 duplicate key error index: test.zip.$city_1_state_1_pop_1 dup key: { : "BARRE", : "MA", : 4546.0 } if (enforceDuplicates(concern)) { fongoDb.errorResult(11001, "E11000 duplicate key error index: " + this.getFullName() + "." + index.getName() + " dup key : {" + error + " }").throwOnError(); } return; // silently ignore. } } DBObject idFirst = Util.cloneIdFirst(object); Set<String> oldQueryFields = oldObject == null ? Collections.<String>emptySet() : oldObject.keySet(); for (IndexAbstract index : indexes) { if (index.canHandle(queryFields)) { index.addOrUpdate(idFirst, oldObject); } else if (index.canHandle(oldQueryFields)) // In case of update and removing a field, we must remove from the index. { index.remove(oldObject); } } } /** * Remove an object from indexes. * * @param object object to remove. */ private synchronized void removeFromIndexes(DBObject object) { Set<String> queryFields = object.keySet(); for (IndexAbstract index : indexes) { if (index.canHandle(queryFields)) { index.remove(object); } } } public synchronized Collection<IndexAbstract> getIndexes() { return Collections.unmodifiableList(indexes); } public synchronized List<DBObject> geoNear(DBObject near, DBObject query, Number limit, Number maxDistance, boolean spherical) { IndexAbstract matchingIndex = searchGeoIndex(true); if (matchingIndex == null) { fongoDb.notOkErrorResult(-5, "no geo indices for geoNear").throwOnError(); } //noinspection ConstantConditions LOG.info("geoNear() near:{}, query:{}, limit:{}, maxDistance:{}, spherical:{}, use index:{}", near, query, limit, maxDistance, spherical, matchingIndex.getName()); List<LatLong> latLongs = GeoUtil.latLon(Collections.<String>emptyList(), near); return ((GeoIndex) matchingIndex).geoNear(query == null ? new BasicDBObject() : query, latLongs, limit == null ? 100 : limit.intValue(), spherical); } //NOTE: Languages support will not be implamented in Fongo yet "english" will be always returned as search language public synchronized DBObject text(String search, Integer limit, DBObject project) { Set<String> textIndexFields = searchTextIndexFields(true); limit = (null != limit) ? limit : ((limit > 100) ? 100 : limit); if (LOG.isDebugEnabled()) { LOG.debug("Will try to emulate text search on collection \"" + this.getFullName() + "\""); LOG.debug("search: \"{}\"; limit {}", search, limit); LOG.debug("the db {} looks like {}", this.getDB().getName(), _idIndex.size()); } if (textIndexFields.isEmpty()) { return null; } //Words Lists List<String> allWords = new ArrayList(); List<String> fullPhrases = new ArrayList(); List<String> negatedWords = new ArrayList(); List<String> wordsToSearch = new ArrayList(); //Debug Strings StringBuilder queryDebugString = new StringBuilder(); StringBuilder querySearchWords = new StringBuilder(); StringBuilder queryNegatedWords = new StringBuilder(); StringBuilder querySearchPhrases = new StringBuilder(); //Analyse Search String //All Words Matcher matcherSW = Pattern.compile("([[^\\p{Space}\\\\\\\"-]&&\\p{Alnum}&&[^\\p{Space}\\\\\\\"]]+)").matcher(search); while (matcherSW.find()) { String matchPhrase = matcherSW.group(1); allWords.add(matchPhrase); } //Full Phrases Matcher matcherFP = Pattern.compile("\"\\s*(.*?)\\s*\"").matcher(search); while (matcherFP.find()) { String matchPhrase = matcherFP.group(1); fullPhrases.add(matchPhrase); querySearchPhrases.append(matchPhrase).append("|"); } //Negated words Matcher matcherNW = Pattern.compile("-(.\\S*)\\s*").matcher(search); while (matcherNW.find()) { String matchPhrase = matcherNW.group(1); negatedWords.add(matchPhrase); queryNegatedWords.append(matchPhrase).append("|"); } //Words To Search for (String word : allWords) { if (!negatedWords.contains(word) && !wordsToSearch.contains(word)) { wordsToSearch.add(word); querySearchWords.append(word).append("|"); } } //Create responce object DBObject resp = new BasicDBObject("queryDebugString", new StringBuilder() .append(querySearchWords).append("|") .append(queryNegatedWords).append("|") .append(querySearchPhrases).append("|") .toString()); resp.put("language", "english"); //Prepare Search Queries Iterator textKeyIterator; // Find Negations textKeyIterator = textIndexFields.iterator(); int negatedWordsCount = negatedWords.size(); BasicDBObject findNegatedQuery; BasicDBList ors = new BasicDBList(); while (textKeyIterator.hasNext()) { String key = (String) textKeyIterator.next(); for (int i = 0; i < negatedWordsCount; i++) { ors.add(new BasicDBObject(key, java.util.regex.Pattern.compile(negatedWords.get(i)))); } } findNegatedQuery = new BasicDBObject("$or", ors); DBCursor negationSearchResult = find(findNegatedQuery); List<DBObject> negatedSearchResults = new ArrayList<DBObject>(); while (negationSearchResult.hasNext()) { negatedSearchResults.add(negationSearchResult.next()); } //Find Phrases int phrasesCount = fullPhrases.size(); textKeyIterator = textIndexFields.iterator(); BasicDBObject findPhrasesQuery; ors = new BasicDBList(); while (textKeyIterator.hasNext()) { String key = (String) textKeyIterator.next(); for (int i = 0; i < phrasesCount; i++) { ors.add(new BasicDBObject(key, java.util.regex.Pattern.compile(fullPhrases.get(i)))); } } findPhrasesQuery = new BasicDBObject("$or", ors); DBCursor fullPhrasesSearchResult = find(findPhrasesQuery); List<DBObject> phrasesSearchResult = new ArrayList<DBObject>(); while (fullPhrasesSearchResult.hasNext()) { phrasesSearchResult.add(fullPhrasesSearchResult.next()); } //Build Query // "results" : [ ], // "stats" : { // "nscanned" : 0, // "nscannedObjects" : 0, // "n" : 0, // "nfound" : 0, // "timeMicros" : 115 // "ok" : 1 //Find eatch match and apply weight and put in responce object //return throw new UnsupportedOperationException( "Not supported yet."); } }
package digitalseraphim.tcgc.core.logic; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Random; public class Card { private final static HashMap<String,Card> manaCards = new HashMap<>(); private final static HashMap<String,Card> allCards = new HashMap<>(); static{ // E F A W O N new Card(Mana.EARTH.name(), Type.MANA, 1,0,0,0,0,0); new Card(Mana.FIRE.name(), Type.MANA, 0,1,0,0,0,0); new Card(Mana.AIR.name(), Type.MANA, 0,0,1,0,0,0); new Card(Mana.WATER.name(), Type.MANA, 0,0,0,1,0,0); new Card(Mana.ORDER.name(), Type.MANA, 0,0,0,0,1,0); new Card(Mana.ENTROPY.name(),Type.MANA, 0,0,0,0,0,1); new Card("Volcano", Type.MANA, 1,1,0,0,0,0); new Card("Flying Island", Type.MANA, 1,0,1,0,0,0); new Card("Island", Type.MANA, 1,0,0,1,0,0); new Card("Fire Vortex", Type.MANA, 0,1,1,0,0,0); new Card("Newborn Island", Type.MANA, 0,1,0,1,0,0); new Card("Cloud", Type.MANA, 0,0,1,1,0,0); } private final String name; private final Type type; //for mana cards this is how much mana is provided by the card private final int earthCost; private final int fireCost; private final int airCost; private final int waterCost; private final int orderCost; private final int entropyCost; public Card(String name, Type t, int earthCost, int fireCost, int airCost, int waterCost, int orderCost, int entropyCost) { this.name = name; this.type = t; this.earthCost = earthCost; this.fireCost = fireCost; this.airCost = airCost; this.waterCost = waterCost; this.orderCost = orderCost; this.entropyCost = entropyCost; switch(type){ case CARD_MODIFIER: break; case MANA: manaCards.put(name, this); break; case SELF_MODIFIER: break; case SPELL: break; case SUMMON: break; default: break; } allCards.put(name, this); } public String getName() { return name; } public static Map<String, Card> getAllCards() { return Collections.unmodifiableMap(allCards); } public static Card getRandomCard(Random r){ return allCards.values().toArray(new Card[0])[r.nextInt(allCards.size())]; } public static Map<String, Card> getManaCards() { return Collections.unmodifiableMap(manaCards); } public static Card getRandomManaCard(Random r){ return manaCards.values().toArray(new Card[0])[r.nextInt(manaCards.size())]; } public Type getType() { return type; } public int getEarthCost() { return earthCost; } public int getFireCost() { return fireCost; } public int getAirCost() { return airCost; } public int getWaterCost() { return waterCost; } public int getOrderCost() { return orderCost; } public int getEntropyCost() { return entropyCost; } public Card fromName(String n){ return allCards.get(n); } public static enum Type { MANA, SPELL, SELF_MODIFIER, CARD_MODIFIER, SUMMON } //yes, planning for future Thaumcraft integration public static enum Mana { EARTH, FIRE, AIR, WATER, ORDER, ENTROPY } }
package com.pump.window; import java.awt.Component; import java.awt.Point; import java.awt.Window; import java.awt.event.MouseEvent; import javax.swing.SwingUtilities; import javax.swing.event.MouseInputAdapter; import com.pump.util.JVM; public class WindowDragger extends MouseInputAdapter { Point mouseLoc; boolean dragging; boolean active; @Override public void mousePressed(MouseEvent e) { mouseLoc = e.getLocationOnScreen(); dragging = true; } @Override public void mouseReleased(MouseEvent e) { dragging = false; mouseLoc = null; } @Override public void mouseDragged(MouseEvent e) { if (mouseLoc == null || dragging == false) { return; } synchronized (mouseLoc) { Point p = e.getLocationOnScreen(); if (JVM.isMac) p.y = Math.max(0, p.y); if (active) { Component src = (Component) e.getSource(); Window w = e.getSource() instanceof Window ? (Window) src : SwingUtilities.getWindowAncestor(src); WindowDragger.translateWindow(p.x - mouseLoc.x, p.y - mouseLoc.y, w); } mouseLoc.setLocation(p); } } public WindowDragger() { } public WindowDragger(Component c) { this(new Component[] { c }); } public WindowDragger(Component[] c) { for (int a = 0; a < c.length; a++) { c[a].addMouseListener(this); c[a].addMouseMotionListener(this); } } /** * Translates a window, after possibly adjusting dx and dy for OS-based * restraints. */ protected static void translateWindow(int dx, int dy, Window window) { Point p = window.getLocation(); p.x += dx; p.y += dy; if (JVM.isMac) p.y = Math.max(0, p.y); window.setLocation(p); } public void setActive(boolean b) { active = b; } public boolean isActive() { return active; } }
package com.wanakanajava; import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; public class WanaKanaJava { static final String TAG = "WanaKanaJava"; //static final int LOWERCASE_START = 0x61; //static final int LOWERCASE_END = 0x7A; static final int UPPERCASE_START = 0x41; static final int UPPERCASE_END = 0x5A; static final int HIRAGANA_START = 0x3041; static final int HIRAGANA_END = 0x3096; static final int KATAKANA_START = 0x30A1; static final int KATAKANA_END = 0x30FA; HashMap<String, Boolean> mOptions = new HashMap<String, Boolean>(); static final String OPTION_USE_OBSOLETE_KANA = "useObsoleteKana"; static final String OPTION_IME_MODE = "IMEMode"; HashMap<String, String> mRtoJ = new HashMap<String, String>(); HashMap<String, String> mJtoR = new HashMap<String, String>(); EditText gInputWindow; private interface Command { public boolean run(String str); } public WanaKanaJava(EditText et, Boolean useObsoleteKana) { gInputWindow = et; mOptions.put(OPTION_USE_OBSOLETE_KANA, useObsoleteKana); mOptions.put(OPTION_IME_MODE, false); prepareRtoJ(); prepareJtoR(); } TextWatcher tw = new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {} @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {} @Override public void afterTextChanged(Editable romaji) { unbind(); // Convert the text String sKana = toKana(romaji.toString()); gInputWindow.setText(sKana); gInputWindow.setSelection(gInputWindow.getText().length()); bind(); } }; // Bind a listener to the EditText so we know to start converting text entered into it public void bind() { gInputWindow.addTextChangedListener(tw); } // Stop listening to text input on the EditText public void unbind() { gInputWindow.removeTextChangedListener(tw); } // Pass every character of a string through a function and return TRUE if every character passes the function's check private boolean _allTrue(String checkStr, Command func) { for (int _i = 0; _i < checkStr.length(); _i++) { if (!func.run(String.valueOf(checkStr.charAt(_i)))) { return false; } } return true; } // Check if a character is within a Unicode range private boolean _isCharInRange(char chr, int start, int end) { int code = (int) chr; return (start <= code && code <= end); } private boolean _isCharVowel(char chr, boolean includeY) { Pattern regexp = includeY ? Pattern.compile("[aeiouy]") : Pattern.compile("[aeiou]"); Matcher matcher = regexp.matcher(String.valueOf(chr)); return matcher.find(); } private boolean _isCharConsonant(char chr, boolean excludeY) { Pattern regexp = excludeY ? Pattern.compile("[bcdfghjklmnpqrstvwxz]") : Pattern.compile("[bcdfghjklmnpqrstvwxyz]"); Matcher matcher = regexp.matcher(String.valueOf(chr)); return matcher.find(); } private boolean _isCharKatakana(char chr) { return _isCharInRange(chr, KATAKANA_START, KATAKANA_END); } private boolean _isCharHiragana(char chr) { return _isCharInRange(chr, HIRAGANA_START, HIRAGANA_END); } private boolean _isCharKana(char chr) { return _isCharHiragana(chr) || _isCharKatakana(chr); } private String _katakanaToHiragana(String kata) { int code; String hira = ""; for (int _i = 0; _i < kata.length(); _i++) { char kataChar = kata.charAt(_i); if (_isCharKatakana(kataChar)) { code = (int) kataChar; code += HIRAGANA_START - KATAKANA_START; hira += String.valueOf(Character.toChars(code)); } else { hira += kataChar; } } return hira; } private String _hiraganaToKatakana(String hira) { int code; String kata = ""; for (int _i = 0; _i < hira.length(); _i++) { char hiraChar = hira.charAt(_i); if (_isCharHiragana(hiraChar)) { code = (int) hiraChar; code += KATAKANA_START - HIRAGANA_START; kata += String.valueOf(Character.toChars(code)); } else { kata += hiraChar; } } return kata; } public String _hiraganaToRomaji(String hira) { if(isRomaji(hira)) { return hira; } String chunk = ""; int chunkSize; int cursor = 0; int len = hira.length(); int maxChunk = 2; boolean nextCharIsDoubleConsonant = false; String roma = ""; String romaChar = null; while (cursor < len) { chunkSize = Math.min(maxChunk, len - cursor); while (chunkSize > 0) { chunk = hira.substring(cursor, (cursor+chunkSize)); if (isKatakana(chunk)) { chunk = _katakanaToHiragana(chunk); } if (String.valueOf(chunk.charAt(0)).equals("") && chunkSize == 1 && cursor < (len - 1)) { nextCharIsDoubleConsonant = true; romaChar = ""; break; } romaChar = mJtoR.get(chunk); if ((romaChar != null) && nextCharIsDoubleConsonant) { romaChar += romaChar.charAt(0); nextCharIsDoubleConsonant = false; } if (romaChar != null) { break; } chunkSize } if (romaChar == null) { romaChar = chunk; } roma += romaChar; cursor += chunkSize > 0 ? chunkSize : 1; } return roma; } private String _romajiToHiragana(String roma) { return _romajiToKana(roma, true); } private String _romajiToKana(String roma, Boolean ignoreCase) { String chunk = ""; String chunkLC = ""; int chunkSize; int position = 0; int len = roma.length(); int maxChunk = 3; String kana = ""; String kanaChar = ""; if (ignoreCase == null) { ignoreCase = false; } while (position < len) { chunkSize = Math.min(maxChunk, len - position); while (chunkSize > 0) { chunk = roma.substring(position, (position+chunkSize)); chunkLC = chunk.toLowerCase(); if ((chunkLC.equals("lts") || chunkLC.equals("xts")) && (len - position) >= 4) { chunkSize++; // The second parameter in substring() is an end point, not a length! chunk = roma.substring(position, (position+chunkSize)); chunkLC = chunk.toLowerCase(); } if (String.valueOf(chunkLC.charAt(0)).equals("n")) { // If the user types "nto", automatically convert "n" to "" first if (chunk.length() > 2 && _isCharConsonant(chunkLC.charAt(1), false) && _isCharVowel(chunkLC.charAt(2), false)) { chunkSize = 1; // I removed the "n"->"" mapping because the IME wouldn't let me type "na" for "" without returning "", // so the chunk needs to be manually set to a value that will map to "" chunk = "nn"; chunkLC = chunk.toLowerCase(); } } // Prepare to return a small- because we're looking at double-consonants. if (chunk.length() > 1 && !String.valueOf(chunkLC.charAt(0)).equals("n") && _isCharConsonant(chunkLC.charAt(0), false) && chunk.charAt(0) == chunk.charAt(1)) { chunkSize = 1; // Return a small katakana when typing in uppercase if(_isCharInRange(chunk.charAt(0), UPPERCASE_START, UPPERCASE_END)) { chunkLC = chunk = ""; } else { chunkLC = chunk = ""; } } kanaChar = mRtoJ.get(chunkLC); if (kanaChar != null) { break; } chunkSize } if (kanaChar == null) { chunk = _convertPunctuation(String.valueOf(chunk.charAt(0))); kanaChar = chunk; } if (mOptions.get(OPTION_USE_OBSOLETE_KANA)) { if (chunkLC.equals("wi")) { kanaChar = ""; } if (chunkLC.equals("we")) { kanaChar = ""; } } if ((mOptions.get(OPTION_IME_MODE)) && String.valueOf(chunkLC.charAt(0)).equals("n")) { if ((String.valueOf(roma.charAt(position + 1)).toLowerCase().equals("y") && position == (len - 2)) || position == (len - 1)) { kanaChar = String.valueOf(chunk.charAt(0)); } } if (!ignoreCase) { if (_isCharInRange(chunk.charAt(0), UPPERCASE_START, UPPERCASE_END)) { kanaChar = _hiraganaToKatakana(kanaChar); } } kana += kanaChar; position += chunkSize > 0 ? chunkSize : 1; } return kana; } private String _convertPunctuation(String input) { if (input.equals(String.valueOf(('')))) { return String.valueOf(' '); } if (input.equals(String.valueOf('-'))) { return String.valueOf(''); } return input; } /** * Returns true if input is entirely hiragana. */ public boolean isHiragana(String input) { return _allTrue(input, new Command() { @Override public boolean run(String str) { return _isCharHiragana(str.charAt(0)); } }); } public boolean isKatakana(String input) { return _allTrue(input, new Command() { @Override public boolean run(String str) { return _isCharKatakana(str.charAt(0)); } }); } public boolean isKana(String input) { return _allTrue(input, new Command() { @Override public boolean run(String str) { return (isHiragana(str)) || (isKatakana(str)); } }); } public boolean isRomaji(String input) { return _allTrue(input, new Command() { @Override public boolean run(String str) { return (!isHiragana(str)) && (!isKatakana(str)); } }); } public String toHiragana(String input) { if (isRomaji(input)) { return _romajiToHiragana(input); } if (isKatakana(input)) { return _katakanaToHiragana(input); } return input; } public String toKatakana(String input) { if (isHiragana(input)) { return _hiraganaToKatakana(input); } if (isRomaji(input)) { return _hiraganaToKatakana(_romajiToHiragana(input)); } return input; } public String toKana(String input) { return _romajiToKana(input, false); } public String toRomaji(String input) { return _hiraganaToRomaji(input); } private void prepareRtoJ() { mRtoJ.put("a", ""); mRtoJ.put("i", ""); mRtoJ.put("u", ""); mRtoJ.put("e", ""); mRtoJ.put("o", ""); mRtoJ.put("yi", ""); mRtoJ.put("wu", ""); mRtoJ.put("whu", ""); mRtoJ.put("xa", ""); mRtoJ.put("xi", ""); mRtoJ.put("xu", ""); mRtoJ.put("xe", ""); mRtoJ.put("xo", ""); mRtoJ.put("xyi", ""); mRtoJ.put("xye", ""); mRtoJ.put("ye", ""); mRtoJ.put("wha", ""); mRtoJ.put("whi", ""); mRtoJ.put("whe", ""); mRtoJ.put("who", ""); mRtoJ.put("wi", ""); mRtoJ.put("we", ""); mRtoJ.put("va", ""); mRtoJ.put("vi", ""); mRtoJ.put("vu", ""); mRtoJ.put("ve", ""); mRtoJ.put("vo", ""); mRtoJ.put("vya", ""); mRtoJ.put("vyi", ""); mRtoJ.put("vyu", ""); mRtoJ.put("vye", ""); mRtoJ.put("vyo", ""); mRtoJ.put("ka", ""); mRtoJ.put("ki", ""); mRtoJ.put("ku", ""); mRtoJ.put("ke", ""); mRtoJ.put("ko", ""); mRtoJ.put("lka", ""); mRtoJ.put("lke", ""); mRtoJ.put("xka", ""); mRtoJ.put("xke", ""); mRtoJ.put("kya", ""); mRtoJ.put("kyi", ""); mRtoJ.put("kyu", ""); mRtoJ.put("kye", ""); mRtoJ.put("kyo", ""); mRtoJ.put("qya", ""); mRtoJ.put("qyu", ""); mRtoJ.put("qyo", ""); mRtoJ.put("qwa", ""); mRtoJ.put("qwi", ""); mRtoJ.put("qwu", ""); mRtoJ.put("qwe", ""); mRtoJ.put("qwo", ""); mRtoJ.put("qa", ""); mRtoJ.put("qi", ""); mRtoJ.put("qe", ""); mRtoJ.put("qo", ""); mRtoJ.put("kwa", ""); mRtoJ.put("qyi", ""); mRtoJ.put("qye", ""); mRtoJ.put("ga", ""); mRtoJ.put("gi", ""); mRtoJ.put("gu", ""); mRtoJ.put("ge", ""); mRtoJ.put("go", ""); mRtoJ.put("gya", ""); mRtoJ.put("gyi", ""); mRtoJ.put("gyu", ""); mRtoJ.put("gye", ""); mRtoJ.put("gyo", ""); mRtoJ.put("gwa", ""); mRtoJ.put("gwi", ""); mRtoJ.put("gwu", ""); mRtoJ.put("gwe", ""); mRtoJ.put("gwo", ""); mRtoJ.put("sa", ""); mRtoJ.put("si", ""); mRtoJ.put("shi", ""); mRtoJ.put("su", ""); mRtoJ.put("se", ""); mRtoJ.put("so", ""); mRtoJ.put("za", ""); mRtoJ.put("zi", ""); mRtoJ.put("zu", ""); mRtoJ.put("ze", ""); mRtoJ.put("zo", ""); mRtoJ.put("ji", ""); mRtoJ.put("sya", ""); mRtoJ.put("syi", ""); mRtoJ.put("syu", ""); mRtoJ.put("sye", ""); mRtoJ.put("syo", ""); mRtoJ.put("sha", ""); mRtoJ.put("shu", ""); mRtoJ.put("she", ""); mRtoJ.put("sho", ""); mRtoJ.put("swa", ""); mRtoJ.put("swi", ""); mRtoJ.put("swu", ""); mRtoJ.put("swe", ""); mRtoJ.put("swo", ""); mRtoJ.put("zya", ""); mRtoJ.put("zyi", ""); mRtoJ.put("zyu", ""); mRtoJ.put("zye", ""); mRtoJ.put("zyo", ""); mRtoJ.put("ja", ""); mRtoJ.put("ju", ""); mRtoJ.put("je", ""); mRtoJ.put("jo", ""); mRtoJ.put("jya", ""); mRtoJ.put("jyi", ""); mRtoJ.put("jyu", ""); mRtoJ.put("jye", ""); mRtoJ.put("jyo", ""); mRtoJ.put("ta", ""); mRtoJ.put("ti", ""); mRtoJ.put("tu", ""); mRtoJ.put("te", ""); mRtoJ.put("to", ""); mRtoJ.put("chi", ""); mRtoJ.put("tsu", ""); mRtoJ.put("ltu", ""); mRtoJ.put("xtu", ""); mRtoJ.put("tya", ""); mRtoJ.put("tyi", ""); mRtoJ.put("tyu", ""); mRtoJ.put("tye", ""); mRtoJ.put("tyo", ""); mRtoJ.put("cha", ""); mRtoJ.put("chu", ""); mRtoJ.put("che", ""); mRtoJ.put("cho", ""); mRtoJ.put("cya", ""); mRtoJ.put("cyi", ""); mRtoJ.put("cyu", ""); mRtoJ.put("cye", ""); mRtoJ.put("cyo", ""); mRtoJ.put("tsa", ""); mRtoJ.put("tsi", ""); mRtoJ.put("tse", ""); mRtoJ.put("tso", ""); mRtoJ.put("tha", ""); mRtoJ.put("thi", ""); mRtoJ.put("thu", ""); mRtoJ.put("the", ""); mRtoJ.put("tho", ""); mRtoJ.put("twa", ""); mRtoJ.put("twi", ""); mRtoJ.put("twu", ""); mRtoJ.put("twe", ""); mRtoJ.put("two", ""); mRtoJ.put("da", ""); mRtoJ.put("di", ""); mRtoJ.put("du", ""); mRtoJ.put("de", ""); mRtoJ.put("do", ""); mRtoJ.put("dya", ""); mRtoJ.put("dyi", ""); mRtoJ.put("dyu", ""); mRtoJ.put("dye", ""); mRtoJ.put("dyo", ""); mRtoJ.put("dha", ""); mRtoJ.put("dhi", ""); mRtoJ.put("dhu", ""); mRtoJ.put("dhe", ""); mRtoJ.put("dho", ""); mRtoJ.put("dwa", ""); mRtoJ.put("dwi", ""); mRtoJ.put("dwu", ""); mRtoJ.put("dwe", ""); mRtoJ.put("dwo", ""); mRtoJ.put("na", ""); mRtoJ.put("ni", ""); mRtoJ.put("nu", ""); mRtoJ.put("ne", ""); mRtoJ.put("no", ""); mRtoJ.put("nya", ""); mRtoJ.put("nyi", ""); mRtoJ.put("nyu", ""); mRtoJ.put("nye", ""); mRtoJ.put("nyo", ""); mRtoJ.put("ha", ""); mRtoJ.put("hi", ""); mRtoJ.put("hu", ""); mRtoJ.put("he", ""); mRtoJ.put("ho", ""); mRtoJ.put("fu", ""); mRtoJ.put("hya", ""); mRtoJ.put("hyi", ""); mRtoJ.put("hyu", ""); mRtoJ.put("hye", ""); mRtoJ.put("hyo", ""); mRtoJ.put("fya", ""); mRtoJ.put("fyu", ""); mRtoJ.put("fyo", ""); mRtoJ.put("fwa", ""); mRtoJ.put("fwi", ""); mRtoJ.put("fwu", ""); mRtoJ.put("fwe", ""); mRtoJ.put("fwo", ""); mRtoJ.put("fa", ""); mRtoJ.put("fi", ""); mRtoJ.put("fe", ""); mRtoJ.put("fo", ""); mRtoJ.put("fyi", ""); mRtoJ.put("fye", ""); mRtoJ.put("ba", ""); mRtoJ.put("bi", ""); mRtoJ.put("bu", ""); mRtoJ.put("be", ""); mRtoJ.put("bo", ""); mRtoJ.put("bya", ""); mRtoJ.put("byi", ""); mRtoJ.put("byu", ""); mRtoJ.put("bye", ""); mRtoJ.put("byo", ""); mRtoJ.put("pa", ""); mRtoJ.put("pi", ""); mRtoJ.put("pu", ""); mRtoJ.put("pe", ""); mRtoJ.put("po", ""); mRtoJ.put("pya", ""); mRtoJ.put("pyi", ""); mRtoJ.put("pyu", ""); mRtoJ.put("pye", ""); mRtoJ.put("pyo", ""); mRtoJ.put("ma", ""); mRtoJ.put("mi", ""); mRtoJ.put("mu", ""); mRtoJ.put("me", ""); mRtoJ.put("mo", ""); mRtoJ.put("mya", ""); mRtoJ.put("myi", ""); mRtoJ.put("myu", ""); mRtoJ.put("mye", ""); mRtoJ.put("myo", ""); mRtoJ.put("ya", ""); mRtoJ.put("yu", ""); mRtoJ.put("yo", ""); mRtoJ.put("xya", ""); mRtoJ.put("xyu", ""); mRtoJ.put("xyo", ""); mRtoJ.put("ra", ""); mRtoJ.put("ri", ""); mRtoJ.put("ru", ""); mRtoJ.put("re", ""); mRtoJ.put("ro", ""); mRtoJ.put("rya", ""); mRtoJ.put("ryi", ""); mRtoJ.put("ryu", ""); mRtoJ.put("rye", ""); mRtoJ.put("ryo", ""); mRtoJ.put("la", ""); mRtoJ.put("li", ""); mRtoJ.put("lu", ""); mRtoJ.put("le", ""); mRtoJ.put("lo", ""); mRtoJ.put("lya", ""); mRtoJ.put("lyi", ""); mRtoJ.put("lyu", ""); mRtoJ.put("lye", ""); mRtoJ.put("lyo", ""); mRtoJ.put("wa", ""); mRtoJ.put("wo", ""); mRtoJ.put("lwe", ""); mRtoJ.put("xwa", ""); mRtoJ.put("nn", ""); mRtoJ.put("'n '", ""); mRtoJ.put("xn", ""); mRtoJ.put("ltsu", ""); mRtoJ.put("xtsu", ""); } private void prepareJtoR() { mJtoR.put("", "a"); mJtoR.put("", "i"); mJtoR.put("", "u"); mJtoR.put("", "e"); mJtoR.put("", "o"); mJtoR.put("", "va"); mJtoR.put("", "vi"); mJtoR.put("", "vu"); mJtoR.put("", "ve"); mJtoR.put("", "vo"); mJtoR.put("", "ka"); mJtoR.put("", "ki"); mJtoR.put("", "kya"); mJtoR.put("", "kyi"); mJtoR.put("", "kyu"); mJtoR.put("", "ku"); mJtoR.put("", "ke"); mJtoR.put("", "ko"); mJtoR.put("", "ga"); mJtoR.put("", "gi"); mJtoR.put("", "gu"); mJtoR.put("", "ge"); mJtoR.put("", "go"); mJtoR.put("", "gya"); mJtoR.put("", "gyi"); mJtoR.put("", "gyu"); mJtoR.put("", "gye"); mJtoR.put("", "gyo"); mJtoR.put("", "sa"); mJtoR.put("", "su"); mJtoR.put("", "se"); mJtoR.put("", "so"); mJtoR.put("", "za"); mJtoR.put("", "zu"); mJtoR.put("", "ze"); mJtoR.put("", "zo"); mJtoR.put("", "shi"); mJtoR.put("", "sha"); mJtoR.put("", "shu"); mJtoR.put("", "sho"); mJtoR.put("", "ji"); mJtoR.put("", "ja"); mJtoR.put("", "ju"); mJtoR.put("", "jo"); mJtoR.put("", "ta"); mJtoR.put("", "chi"); mJtoR.put("", "cha"); mJtoR.put("", "chu"); mJtoR.put("", "cho"); mJtoR.put("", "tsu"); mJtoR.put("", "te"); mJtoR.put("", "to"); mJtoR.put("", "da"); mJtoR.put("", "di"); mJtoR.put("", "du"); mJtoR.put("", "de"); mJtoR.put("", "do"); mJtoR.put("", "na"); mJtoR.put("", "ni"); mJtoR.put("", "nya"); mJtoR.put("", "nyu"); mJtoR.put("", "nyo"); mJtoR.put("", "nu"); mJtoR.put("", "ne"); mJtoR.put("", "no"); mJtoR.put("", "ha"); mJtoR.put("", "hi"); mJtoR.put("", "fu"); mJtoR.put("", "he"); mJtoR.put("", "ho"); mJtoR.put("", "hya"); mJtoR.put("", "hyu"); mJtoR.put("", "hyo"); mJtoR.put("", "fa"); mJtoR.put("", "fi"); mJtoR.put("", "fe"); mJtoR.put("", "fo"); mJtoR.put("", "ba"); mJtoR.put("", "bi"); mJtoR.put("", "bu"); mJtoR.put("", "be"); mJtoR.put("", "bo"); mJtoR.put("", "bya"); mJtoR.put("", "byu"); mJtoR.put("", "byo"); mJtoR.put("", "pa"); mJtoR.put("", "pi"); mJtoR.put("", "pu"); mJtoR.put("", "pe"); mJtoR.put("", "po"); mJtoR.put("", "pya"); mJtoR.put("", "pyu"); mJtoR.put("", "pyo"); mJtoR.put("", "ma"); mJtoR.put("", "mi"); mJtoR.put("", "mu"); mJtoR.put("", "me"); mJtoR.put("", "mo"); mJtoR.put("", "mya"); mJtoR.put("", "myu"); mJtoR.put("", "myo"); mJtoR.put("", "ya"); mJtoR.put("", "yu"); mJtoR.put("", "yo"); mJtoR.put("", "ra"); mJtoR.put("", "ri"); mJtoR.put("", "ru"); mJtoR.put("", "re"); mJtoR.put("", "ro"); mJtoR.put("", "rya"); mJtoR.put("", "ryu"); mJtoR.put("", "ryo"); mJtoR.put("", "wa"); mJtoR.put("", "wo"); mJtoR.put("", "n"); mJtoR.put("", "wi"); mJtoR.put("", "we"); mJtoR.put("", "kye"); mJtoR.put("", "kyo"); mJtoR.put("", "jyi"); mJtoR.put("", "jye"); mJtoR.put("", "cyi"); mJtoR.put("", "che"); mJtoR.put("", "hyi"); mJtoR.put("", "hye"); mJtoR.put("", "byi"); mJtoR.put("", "bye"); mJtoR.put("", "pyi"); mJtoR.put("", "pye"); mJtoR.put("", "mye"); mJtoR.put("", "myi"); mJtoR.put("", "ryi"); mJtoR.put("", "rye"); mJtoR.put("", "nyi"); mJtoR.put("", "nye"); mJtoR.put("", "syi"); mJtoR.put("", "she"); mJtoR.put("", "ye"); mJtoR.put("", "wha"); mJtoR.put("", "who"); mJtoR.put("", "wi"); mJtoR.put("", "we"); mJtoR.put("", "vya"); mJtoR.put("", "vyu"); mJtoR.put("", "vyo"); mJtoR.put("", "swa"); mJtoR.put("", "swi"); mJtoR.put("", "swu"); mJtoR.put("", "swe"); mJtoR.put("", "swo"); mJtoR.put("", "qya"); mJtoR.put("", "qyu"); mJtoR.put("", "qyo"); mJtoR.put("", "qwa"); mJtoR.put("", "qwi"); mJtoR.put("", "qwu"); mJtoR.put("", "qwe"); mJtoR.put("", "qwo"); mJtoR.put("", "gwa"); mJtoR.put("", "gwi"); mJtoR.put("", "gwu"); mJtoR.put("", "gwe"); mJtoR.put("", "gwo"); mJtoR.put("", "tsa"); mJtoR.put("", "tsi"); mJtoR.put("", "tse"); mJtoR.put("", "tso"); mJtoR.put("", "tha"); mJtoR.put("", "thi"); mJtoR.put("", "thu"); mJtoR.put("", "the"); mJtoR.put("", "tho"); mJtoR.put("", "twa"); mJtoR.put("", "twi"); mJtoR.put("", "twu"); mJtoR.put("", "twe"); mJtoR.put("", "two"); mJtoR.put("", "dya"); mJtoR.put("", "dyi"); mJtoR.put("", "dyu"); mJtoR.put("", "dye"); mJtoR.put("", "dyo"); mJtoR.put("", "dha"); mJtoR.put("", "dhi"); mJtoR.put("", "dhu"); mJtoR.put("", "dhe"); mJtoR.put("", "dho"); mJtoR.put("", "dwa"); mJtoR.put("", "dwi"); mJtoR.put("", "dwu"); mJtoR.put("", "dwe"); mJtoR.put("", "dwo"); mJtoR.put("", "fwu"); mJtoR.put("", "fya"); mJtoR.put("", "fyu"); mJtoR.put("", "fyo"); mJtoR.put("", "a"); mJtoR.put("", "i"); mJtoR.put("", "e"); mJtoR.put("", "u"); mJtoR.put("", "o"); mJtoR.put("", "ya"); mJtoR.put("", "yu"); mJtoR.put("", "yo"); mJtoR.put("", ""); mJtoR.put("", "ka"); mJtoR.put("", "ka"); mJtoR.put("", "wa"); mJtoR.put("''", " "); mJtoR.put("", "n'a"); mJtoR.put("", "n'i"); mJtoR.put("", "n'u"); mJtoR.put("", "n'e"); mJtoR.put("", "n'o"); mJtoR.put("", "n'ya"); mJtoR.put("", "n'yu"); mJtoR.put("", "n'yo"); } }
package de.targodan.usb.ui; import de.targodan.usb.Program; import de.targodan.usb.data.Case; import de.targodan.usb.data.CaseManager; import de.targodan.usb.data.Client; import de.targodan.usb.data.Platform; import de.targodan.usb.data.Rat; import de.targodan.usb.data.Report; import java.awt.Dimension; import java.net.URI; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.Observable; import java.util.Observer; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Luca Corbatto */ public class MainWindow extends javax.swing.JFrame { public MainWindow(ConsoleWindow consoleWindow, CaseManager cm) { this.cm = cm; initComponents(); this.consoleWindow = consoleWindow; this.runRemoveClearedCasesThread = new AtomicBoolean(true); this.removeClearedCasesThread = new Thread(() -> { while(this.runRemoveClearedCasesThread.get()) { try { Thread t = Thread.currentThread(); synchronized(t) { t.wait(200); } } catch (InterruptedException ex) { Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex); } if(Program.CONFIG.secondsUntilClearedCasesAreRemoved > 0) { this.cm.removeClosedCasesOlderThan(LocalDateTime.now().minus((int)(Program.CONFIG.secondsUntilClearedCasesAreRemoved * 1000), ChronoUnit.MILLIS)); } } }); this.removeClearedCasesThread.setName("RemoveClearedCasesThread"); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jToolBar1 = new javax.swing.JToolBar(); caseBox = new javax.swing.JPanel(); caseWrapperPanel = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new CaseTable(this.cm); statusBar = new javax.swing.JPanel(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItem8 = new javax.swing.JMenuItem(); jSeparator2 = new javax.swing.JPopupMenu.Separator(); jMenuItem1 = new javax.swing.JMenuItem(); jMenu2 = new javax.swing.JMenu(); jMenuItem4 = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem3 = new javax.swing.JMenuItem(); jMenu3 = new javax.swing.JMenu(); jMenuItem5 = new javax.swing.JMenuItem(); jMenuItem6 = new javax.swing.JMenuItem(); jSeparator1 = new javax.swing.JPopupMenu.Separator(); jMenuItem7 = new javax.swing.JMenuItem(); jToolBar1.setRollover(true); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("USB - UberSpatchBoard"); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); caseBox.setBorder(javax.swing.BorderFactory.createTitledBorder("Cases")); caseWrapperPanel.setLayout(new java.awt.BorderLayout()); jTable1.setRowSelectionAllowed(false); jTable1.getTableHeader().setReorderingAllowed(false); jScrollPane1.setViewportView(jTable1); caseWrapperPanel.add(jScrollPane1, java.awt.BorderLayout.CENTER); javax.swing.GroupLayout caseBoxLayout = new javax.swing.GroupLayout(caseBox); caseBox.setLayout(caseBoxLayout); caseBoxLayout.setHorizontalGroup( caseBoxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(caseWrapperPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 918, Short.MAX_VALUE) ); caseBoxLayout.setVerticalGroup( caseBoxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(caseWrapperPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 524, Short.MAX_VALUE) ); javax.swing.GroupLayout statusBarLayout = new javax.swing.GroupLayout(statusBar); statusBar.setLayout(statusBarLayout); statusBarLayout.setHorizontalGroup( statusBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); statusBarLayout.setVerticalGroup( statusBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 26, Short.MAX_VALUE) ); jMenu1.setText("File"); jMenuItem8.setText("Settings"); jMenuItem8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { onSettingsClicked(evt); } }); jMenu1.add(jMenuItem8); jMenu1.add(jSeparator2); jMenuItem1.setText("Close"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { onCloseMenuClicked(evt); } }); jMenu1.add(jMenuItem1); jMenuBar1.add(jMenu1); jMenu2.setText("Test"); jMenu2.setToolTipText(""); jMenuItem4.setText("Show Console"); jMenuItem4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { onShowConsoleClicked(evt); } }); jMenu2.add(jMenuItem4); jMenuItem2.setText("Add test Case"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { onAddTestCaseClicked(evt); } }); jMenu2.add(jMenuItem2); jMenuItem3.setText("Open injection Window"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { onOpenInjectionWindowClicked(evt); } }); jMenu2.add(jMenuItem3); jMenuBar1.add(jMenu2); jMenu3.setText("Help"); jMenuItem5.setText("Report a Bug"); jMenuItem5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { onReportABugClicked(evt); } }); jMenu3.add(jMenuItem5); jMenuItem6.setText("Contribute"); jMenuItem6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { onContributeClicked(evt); } }); jMenu3.add(jMenuItem6); jMenu3.add(jSeparator1); jMenuItem7.setText("About"); jMenuItem7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { onAboutClicked(evt); } }); jMenu3.add(jMenuItem7); jMenuBar1.add(jMenu3); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(statusBar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(caseBox, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(caseBox, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(statusBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void onCloseMenuClicked(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onCloseMenuClicked this.dispose(); }//GEN-LAST:event_onCloseMenuClicked private void onAddTestCaseClicked(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onAddTestCaseClicked Case testCase = new Case(this.cm.getOpenCases().size()+1, new Client("Kies", "Kies", Platform.PC, "de"), new de.targodan.usb.data.System("Cubeo"), false, LocalDateTime.now()); Rat rat = new Rat("testRat"); rat.setJumps(5); rat.setAssigned(true); rat.insertReport(new Report(Report.Type.SYS, true)); testCase.assignRat(rat); this.cm.addCase(testCase); }//GEN-LAST:event_onAddTestCaseClicked private void onOpenInjectionWindowClicked(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onOpenInjectionWindowClicked MessageInjectionWindow window = new MessageInjectionWindow(this); window.setVisible(true); Program.dataConsumer.addDataSource(window); }//GEN-LAST:event_onOpenInjectionWindowClicked private void onShowConsoleClicked(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onShowConsoleClicked this.consoleWindow.setVisible(true); }//GEN-LAST:event_onShowConsoleClicked private void onReportABugClicked(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onReportABugClicked try { java.awt.Desktop.getDesktop().browse(new URI("https://github.com/targodan/UberSpatchBoard#Report-a-Bug")); } catch (Exception ex) { /* Seriously Java, bugger off with your checked exceptions! */ } }//GEN-LAST:event_onReportABugClicked private void onContributeClicked(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onContributeClicked try { java.awt.Desktop.getDesktop().browse(new URI("https://github.com/targodan/UberSpatchBoard#Contribute")); } catch (Exception ex) { /* Seriously Java, bugger off with your checked exceptions! */ } }//GEN-LAST:event_onContributeClicked private void onAboutClicked(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onAboutClicked java.awt.EventQueue.invokeLater(() -> { AboutWindow w = new AboutWindow(); w.setSize(new Dimension(400, 300)); w.setVisible(true); }); }//GEN-LAST:event_onAboutClicked private void onSettingsClicked(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onSettingsClicked java.awt.EventQueue.invokeLater(() -> { new SettingsWindow(this).setVisible(true); }); }//GEN-LAST:event_onSettingsClicked private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened this.removeClearedCasesThread.start(); }//GEN-LAST:event_formWindowOpened private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing this.runRemoveClearedCasesThread.set(false); try { this.removeClearedCasesThread.join(); } catch (InterruptedException ex) { Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_formWindowClosing private CaseManager cm; private ConsoleWindow consoleWindow; private final Thread removeClearedCasesThread; private AtomicBoolean runRemoveClearedCasesThread; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel caseBox; private javax.swing.JPanel caseWrapperPanel; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenu jMenu3; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JMenuItem jMenuItem4; private javax.swing.JMenuItem jMenuItem5; private javax.swing.JMenuItem jMenuItem6; private javax.swing.JMenuItem jMenuItem7; private javax.swing.JMenuItem jMenuItem8; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JPopupMenu.Separator jSeparator1; private javax.swing.JPopupMenu.Separator jSeparator2; private javax.swing.JTable jTable1; private javax.swing.JToolBar jToolBar1; private javax.swing.JPanel statusBar; // End of variables declaration//GEN-END:variables }
package info.faceland.loot; import info.faceland.api.FacePlugin; import info.faceland.facecore.shade.command.CommandHandler; import info.faceland.facecore.shade.nun.ivory.config.VersionedIvoryConfiguration; import info.faceland.facecore.shade.nun.ivory.config.VersionedIvoryYamlConfiguration; import info.faceland.facecore.shade.nun.ivory.config.settings.IvorySettings; import info.faceland.loot.api.creatures.CreatureMod; import info.faceland.loot.api.creatures.CreatureModBuilder; import info.faceland.loot.api.enchantments.EnchantmentStone; import info.faceland.loot.api.enchantments.EnchantmentStoneBuilder; import info.faceland.loot.api.groups.ItemGroup; import info.faceland.loot.api.items.CustomItem; import info.faceland.loot.api.items.CustomItemBuilder; import info.faceland.loot.api.items.ItemBuilder; import info.faceland.loot.api.managers.CreatureModManager; import info.faceland.loot.api.managers.CustomItemManager; import info.faceland.loot.api.managers.EnchantmentStoneManager; import info.faceland.loot.api.managers.ItemGroupManager; import info.faceland.loot.api.managers.NameManager; import info.faceland.loot.api.managers.SocketGemManager; import info.faceland.loot.api.managers.TierManager; import info.faceland.loot.api.sockets.SocketGem; import info.faceland.loot.api.sockets.SocketGemBuilder; import info.faceland.loot.api.sockets.effects.SocketEffect; import info.faceland.loot.api.tier.Tier; import info.faceland.loot.api.tier.TierBuilder; import info.faceland.loot.commands.LootCommand; import info.faceland.loot.creatures.LootCreatureModBuilder; import info.faceland.loot.enchantments.LootEnchantmentStoneBuilder; import info.faceland.loot.groups.LootItemGroup; import info.faceland.loot.io.SmartTextFile; import info.faceland.loot.items.LootCustomItemBuilder; import info.faceland.loot.items.LootItemBuilder; import info.faceland.loot.listeners.InteractListener; import info.faceland.loot.listeners.sockets.SocketsListener; import info.faceland.loot.listeners.spawning.EntityDeathListener; import info.faceland.loot.managers.LootCreatureModManager; import info.faceland.loot.managers.LootCustomItemManager; import info.faceland.loot.managers.LootEnchantmentStoneManager; import info.faceland.loot.managers.LootItemGroupManager; import info.faceland.loot.managers.LootNameManager; import info.faceland.loot.managers.LootSocketGemManager; import info.faceland.loot.managers.LootTierManager; import info.faceland.loot.sockets.LootSocketGemBuilder; import info.faceland.loot.sockets.effects.LootSocketPotionEffect; import info.faceland.loot.tier.LootTierBuilder; import info.faceland.loot.utils.converters.StringConverter; import info.faceland.utils.TextUtils; import net.nunnerycode.java.libraries.cannonball.DebugPrinter; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.EntityType; import org.bukkit.event.HandlerList; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; public final class LootPlugin extends FacePlugin { private DebugPrinter debugPrinter; private VersionedIvoryYamlConfiguration itemsYAML; private VersionedIvoryYamlConfiguration tierYAML; private VersionedIvoryYamlConfiguration corestatsYAML; private VersionedIvoryYamlConfiguration customItemsYAML; private VersionedIvoryYamlConfiguration socketGemsYAML; private VersionedIvoryYamlConfiguration languageYAML; private VersionedIvoryYamlConfiguration configYAML; private VersionedIvoryYamlConfiguration creaturesYAML; private VersionedIvoryYamlConfiguration identifyingYAML; private VersionedIvoryYamlConfiguration enchantmentStonesYAML; private IvorySettings settings; private ItemGroupManager itemGroupManager; private TierManager tierManager; private NameManager nameManager; private CustomItemManager customItemManager; private SocketGemManager socketGemManager; private CreatureModManager creatureModManager; private EnchantmentStoneManager enchantmentStoneManager; @Override public void preEnable() { debugPrinter = new DebugPrinter(getDataFolder().getPath(), "debug.log"); itemsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "items.yml"), getResource("items.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (itemsYAML.update()) { getLogger().info("Updating items.yml"); debug("Updating items.yml"); } tierYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "tier.yml"), getResource("tier.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (tierYAML.update()) { getLogger().info("Updating tier.yml"); debug("Updating tier.yml"); } corestatsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "corestats.yml"), getResource("corestats.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (corestatsYAML.update()) { getLogger().info("Updating corestats.yml"); debug("Updating corestats.yml"); } customItemsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "customItems.yml"), getResource("customItems.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (customItemsYAML.update()) { getLogger().info("Updating customItems.yml"); debug("Updating customItems.yml"); } socketGemsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "socketGems.yml"), getResource("socketGems.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (socketGemsYAML.update()) { getLogger().info("Updating socketGems.yml"); debug("Updating socketGems.yml"); } languageYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "language.yml"), getResource("language.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (languageYAML.update()) { getLogger().info("Updating language.yml"); debug("Updating language.yml"); } configYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "config.yml"), getResource("config.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (configYAML.update()) { getLogger().info("Updating config.yml"); debug("Updating config.yml"); } creaturesYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "creatures.yml"), getResource("creatures.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (creaturesYAML.update()) { getLogger().info("Updating creatures.yml"); debug("Updating creatures.yml"); } identifyingYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "identifying.yml"), getResource("identifying.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (identifyingYAML.update()) { getLogger().info("Updating identifying.yml"); debug("Updating identifying.yml"); } enchantmentStonesYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "enchantmentStones.yml"), getResource("enchantmentStones.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (enchantmentStonesYAML.update()) { getLogger().info("Updating enchantmentStones.yml"); debug("Updating enchantmentStones.yml"); } settings = IvorySettings.loadFromFiles(corestatsYAML, languageYAML, configYAML, identifyingYAML); itemGroupManager = new LootItemGroupManager(); tierManager = new LootTierManager(); nameManager = new LootNameManager(); customItemManager = new LootCustomItemManager(); socketGemManager = new LootSocketGemManager(); creatureModManager = new LootCreatureModManager(); enchantmentStoneManager = new LootEnchantmentStoneManager(); } @Override public void enable() { loadItemGroups(); loadTiers(); loadNames(); loadCustomItems(); loadSocketGems(); loadEnchantmentStones(); loadCreatureMods(); } @Override public void postEnable() { CommandHandler handler = new CommandHandler(this); handler.registerCommands(new LootCommand(this)); Bukkit.getPluginManager().registerEvents(new EntityDeathListener(this), this); Bukkit.getPluginManager().registerEvents(new SocketsListener(this), this); Bukkit.getPluginManager().registerEvents(new InteractListener(this), this); //Bukkit.getPluginManager().registerEvents(new LoginListener(this), this); debug("v" + getDescription().getVersion() + " enabled"); } @Override public void preDisable() { HandlerList.unregisterAll(this); } @Override public void disable() { } @Override public void postDisable() { enchantmentStoneManager = null; creatureModManager = null; socketGemManager = null; customItemManager = null; nameManager = null; tierManager = null; itemGroupManager = null; settings = null; identifyingYAML = null; creaturesYAML = null; configYAML = null; languageYAML = null; customItemsYAML = null; corestatsYAML = null; tierYAML = null; itemsYAML = null; debugPrinter = null; } public void debug(String... messages) { debug(Level.INFO, messages); } public void debug(Level level, String... messages) { if (debugPrinter != null) { debugPrinter.debug(level, messages); } } private void loadEnchantmentStones() { for (EnchantmentStone es : getEnchantmentStoneManager().getEnchantmentStones()) { getEnchantmentStoneManager().removeEnchantmentStone(es.getName()); } Set<EnchantmentStone> stones = new HashSet<>(); List<String> loadedStones = new ArrayList<>(); for (String key : enchantmentStonesYAML.getKeys(false)) { if (!enchantmentStonesYAML.isConfigurationSection(key)) { continue; } ConfigurationSection cs = enchantmentStonesYAML.getConfigurationSection(key); EnchantmentStoneBuilder builder = getNewEnchantmentStoneBuilder(key); builder.withWeight(cs.getDouble("weight")); builder.withDistanceWeight(cs.getDouble("distance-weight")); builder.withLore(cs.getStringList("lore")); builder.withMinStats(cs.getInt("min-stats")); builder.withMaxStats(cs.getInt("max-stats")); builder.withBroadcast(cs.getBoolean("broadcast")); List<ItemGroup> groups = new ArrayList<>(); for (String groop : cs.getStringList("item-groups")) { ItemGroup g = itemGroupManager.getItemGroup(groop); if (g == null) { continue; } groups.add(g); } builder.withItemGroups(groups); EnchantmentStone stone = builder.build(); stones.add(stone); loadedStones.add(stone.getName()); } for (EnchantmentStone es : stones) { getEnchantmentStoneManager().addEnchantmentStone(es); } debug("Loaded enchantment stones: " + loadedStones.toString()); } private void loadCreatureMods() { for (CreatureMod cm : getCreatureModManager().getCreatureMods()) { getCreatureModManager().removeCreatureMod(cm.getEntityType()); } Set<CreatureMod> mods = new HashSet<>(); List<String> loadedMods = new ArrayList<>(); for (String key : creaturesYAML.getKeys(false)) { if (!creaturesYAML.isConfigurationSection(key)) { continue; } ConfigurationSection cs = creaturesYAML.getConfigurationSection(key); CreatureModBuilder builder = getNewCreatureModBuilder(EntityType.valueOf(key)); if (cs.isConfigurationSection("custom-items")) { Map<CustomItem, Double> map = new HashMap<>(); for (String k : cs.getConfigurationSection("custom-items").getKeys(false)) { if (!cs.isConfigurationSection("custom-items." + k)) { continue; } CustomItem ci = customItemManager.getCustomItem(k); if (ci == null) { continue; } map.put(ci, cs.getDouble("custom-items." + k)); } builder.withCustomItemMults(map); } if (cs.isConfigurationSection("socket-gems")) { Map<SocketGem, Double> map = new HashMap<>(); for (String k : cs.getConfigurationSection("socket-gems").getKeys(false)) { if (!cs.isConfigurationSection("socket-gems." + k)) { continue; } SocketGem sg = socketGemManager.getSocketGem(k); if (sg == null) { continue; } map.put(sg, cs.getDouble("socket-gems." + k)); } builder.withSocketGemMults(map); } if (cs.isConfigurationSection("tiers")) { Map<Tier, Double> map = new HashMap<>(); for (String k : cs.getConfigurationSection("tiers").getKeys(false)) { if (!cs.isConfigurationSection("tiers." + k)) { continue; } Tier t = tierManager.getTier(k); if (t == null) { continue; } map.put(t, cs.getDouble("tiers." + k)); } builder.withTierMults(map); } if (cs.isConfigurationSection("enchantment-stone")) { Map<EnchantmentStone, Double> map = new HashMap<>(); for (String k : cs.getConfigurationSection("enchantment-stones").getKeys(false)) { if (!cs.isConfigurationSection("enchantment-stones." + k)) { continue; } EnchantmentStone es = enchantmentStoneManager.getEnchantmentStone(k); if (es == null) { continue; } map.put(es, cs.getDouble("enchantment-stones." + k)); } builder.withEnchantmentStoneMults(map); } CreatureMod mod = builder.build(); mods.add(mod); loadedMods.add(mod.getEntityType().name()); } for (CreatureMod cm : mods) { creatureModManager.addCreatureMod(cm); } debug("Loaded creature mods: " + loadedMods.toString()); } private void loadSocketGems() { for (SocketGem sg : getSocketGemManager().getSocketGems()) { getSocketGemManager().removeSocketGem(sg.getName()); } Set<SocketGem> gems = new HashSet<>(); List<String> loadedSocketGems = new ArrayList<>(); for (String key : socketGemsYAML.getKeys(false)) { if (!socketGemsYAML.isConfigurationSection(key)) { continue; } ConfigurationSection cs = socketGemsYAML.getConfigurationSection(key); SocketGemBuilder builder = getNewSocketGemBuilder(key); builder.withPrefix(cs.getString("prefix")); builder.withSuffix(cs.getString("suffix")); builder.withLore(cs.getStringList("lore")); builder.withWeight(cs.getDouble("weight")); builder.withDistanceWeight(cs.getDouble("distance-weight")); List<SocketEffect> effects = new ArrayList<>(); for (String eff : cs.getStringList("effects")) { effects.add(LootSocketPotionEffect.parseString(eff)); } builder.withSocketEffects(effects); List<ItemGroup> groups = new ArrayList<>(); for (String groop : cs.getStringList("item-groups")) { ItemGroup g = itemGroupManager.getItemGroup(groop); if (g == null) { continue; } groups.add(g); } builder.withItemGroups(groups); builder.withBroadcast(cs.getBoolean("broadcast")); SocketGem gem = builder.build(); gems.add(gem); loadedSocketGems.add(gem.getName()); } for (SocketGem sg : gems) { getSocketGemManager().addSocketGem(sg); } debug("Loaded socket gems: " + loadedSocketGems.toString()); } private void loadCustomItems() { for (CustomItem ci : getCustomItemManager().getCustomItems()) { getCustomItemManager().removeCustomItem(ci.getName()); } Set<CustomItem> customItems = new HashSet<>(); List<String> loaded = new ArrayList<>(); for (String key : customItemsYAML.getKeys(false)) { if (!customItemsYAML.isConfigurationSection(key)) { continue; } ConfigurationSection cs = customItemsYAML.getConfigurationSection(key); CustomItemBuilder builder = getNewCustomItemBuilder(key); builder.withMaterial(StringConverter.toMaterial(cs.getString("material"))); builder.withDisplayName(cs.getString("display-name")); builder.withLore(cs.getStringList("lore")); builder.withWeight(cs.getDouble("weight")); builder.withDistanceWeight(cs.getDouble("distance-weight")); builder.withBroadcast(cs.getBoolean("broadcast")); CustomItem ci = builder.build(); customItems.add(ci); loaded.add(ci.getName()); } for (CustomItem ci : customItems) { getCustomItemManager().addCustomItem(ci); } debug("Loaded custom items: " + loaded.toString()); } private void loadNames() { for (String s : getNameManager().getPrefixes()) { getNameManager().removePrefix(s); } for (String s : getNameManager().getSuffixes()) { getNameManager().removeSuffix(s); } File prefixFile = new File(getDataFolder(), "prefix.txt"); File suffixFile = new File(getDataFolder(), "suffix.txt"); SmartTextFile.writeToFile(getResource("prefix.txt"), prefixFile, true); SmartTextFile.writeToFile(getResource("suffix.txt"), suffixFile, true); SmartTextFile smartPrefixFile = new SmartTextFile(prefixFile); SmartTextFile smartSuffixFile = new SmartTextFile(suffixFile); for (String s : smartPrefixFile.read()) { getNameManager().addPrefix(s); } for (String s : smartSuffixFile.read()) { getNameManager().addSuffix(s); } debug("Loaded prefixes: " + getNameManager().getPrefixes().size(), "Loaded suffixes: " + getNameManager() .getSuffixes().size()); } private void loadItemGroups() { for (ItemGroup ig : getItemGroupManager().getItemGroups()) { getItemGroupManager().removeItemGroup(ig.getName()); } Set<ItemGroup> itemGroups = new HashSet<>(); List<String> loadedItemGroups = new ArrayList<>(); for (String key : itemsYAML.getKeys(false)) { if (!itemsYAML.isList(key)) { continue; } List<String> list = itemsYAML.getStringList(key); ItemGroup ig = new LootItemGroup(key, false); for (String s : list) { Material m = StringConverter.toMaterial(s); if (m == Material.AIR) { continue; } ig.addMaterial(m); } itemGroups.add(ig); loadedItemGroups.add(key); } for (ItemGroup ig : itemGroups) { getItemGroupManager().addItemGroup(ig); } debug("Loaded item groups: " + loadedItemGroups.toString()); } private void loadTiers() { for (Tier t : getTierManager().getLoadedTiers()) { getTierManager().removeTier(t.getName()); } Set<Tier> tiers = new HashSet<>(); List<String> loadedTiers = new ArrayList<>(); for (String key : tierYAML.getKeys(false)) { if (!tierYAML.isConfigurationSection(key)) { continue; } ConfigurationSection cs = tierYAML.getConfigurationSection(key); TierBuilder builder = getNewTierBuilder(key); builder.withDisplayName(cs.getString("display-name")); builder.withDisplayColor(TextUtils.convertTag(cs.getString("display-color"))); builder.withIdentificationColor(TextUtils.convertTag(cs.getString("identification-color"))); builder.withSpawnWeight(cs.getDouble("spawn-weight")); builder.withIdentifyWeight(cs.getDouble("identify-weight")); builder.withDistanceWeight(cs.getDouble("distance-weight")); builder.withMinimumSockets(cs.getInt("minimum-sockets")); builder.withMaximumSockets(cs.getInt("maximum-sockets")); builder.withMinimumBonusLore(cs.getInt("minimum-bonus-lore")); builder.withMaximumBonusLore(cs.getInt("maximum-bonus-lore")); builder.withBaseLore(cs.getStringList("base-lore")); builder.withBonusLore(cs.getStringList("bonus-lore")); List<String> sl = cs.getStringList("item-groups"); Set<ItemGroup> itemGroups = new HashSet<>(); for (String s : sl) { ItemGroup ig; if (s.startsWith("-")) { ig = getItemGroupManager().getItemGroup(s.substring(1)); if (ig == null) { continue; } ig = ig.getInverse(); } else { ig = getItemGroupManager().getItemGroup(s); if (ig == null) { continue; } } itemGroups.add(ig); } builder.withItemGroups(itemGroups); builder.withMinimumDurability(cs.getDouble("minimum-durability")); builder.withMaximumDurability(cs.getDouble("maximum-durability")); builder.withEnchantable(cs.getBoolean("enchantable")); builder.withBroadcast(cs.getBoolean("broadcast")); Tier t = builder.build(); loadedTiers.add(t.getName()); tiers.add(t); } for (Tier t : tiers) { getTierManager().addTier(t); } debug("Loaded tiers: " + loadedTiers.toString()); } public TierBuilder getNewTierBuilder(String name) { return new LootTierBuilder(name); } public ItemBuilder getNewItemBuilder() { return new LootItemBuilder(this); } public CustomItemBuilder getNewCustomItemBuilder(String name) { return new LootCustomItemBuilder(name); } public SocketGemBuilder getNewSocketGemBuilder(String name) { return new LootSocketGemBuilder(name); } public CreatureModBuilder getNewCreatureModBuilder(EntityType entityType) { return new LootCreatureModBuilder(entityType); } public EnchantmentStoneBuilder getNewEnchantmentStoneBuilder(String name) { return new LootEnchantmentStoneBuilder(name); } public TierManager getTierManager() { return tierManager; } public ItemGroupManager getItemGroupManager() { return itemGroupManager; } public NameManager getNameManager() { return nameManager; } public IvorySettings getSettings() { return settings; } public CustomItemManager getCustomItemManager() { return customItemManager; } public SocketGemManager getSocketGemManager() { return socketGemManager; } public CreatureModManager getCreatureModManager() { return creatureModManager; } public EnchantmentStoneManager getEnchantmentStoneManager() { return enchantmentStoneManager; } }
package info.faceland.loot; import info.faceland.api.FacePlugin; import info.faceland.facecore.shade.nun.ivory.config.VersionedIvoryConfiguration; import info.faceland.facecore.shade.nun.ivory.config.VersionedIvoryYamlConfiguration; import info.faceland.facecore.shade.nun.ivory.config.settings.IvorySettings; import info.faceland.loot.api.groups.ItemGroup; import info.faceland.loot.api.items.CustomItem; import info.faceland.loot.api.items.CustomItemBuilder; import info.faceland.loot.api.items.ItemBuilder; import info.faceland.loot.api.managers.CustomItemManager; import info.faceland.loot.api.managers.ItemGroupManager; import info.faceland.loot.api.managers.NameManager; import info.faceland.loot.api.managers.SocketGemManager; import info.faceland.loot.api.managers.TierManager; import info.faceland.loot.api.sockets.SocketGem; import info.faceland.loot.api.sockets.SocketGemBuilder; import info.faceland.loot.api.sockets.effects.SocketEffect; import info.faceland.loot.api.tier.Tier; import info.faceland.loot.api.tier.TierBuilder; import info.faceland.loot.groups.LootItemGroup; import info.faceland.loot.io.SmartTextFile; import info.faceland.loot.items.LootCustomItemBuilder; import info.faceland.loot.items.LootItemBuilder; import info.faceland.loot.listeners.LoginListener; import info.faceland.loot.managers.LootCustomItemManager; import info.faceland.loot.managers.LootItemGroupManager; import info.faceland.loot.managers.LootNameManager; import info.faceland.loot.managers.LootSocketGemManager; import info.faceland.loot.managers.LootTierManager; import info.faceland.loot.sockets.LootSocketGemBuilder; import info.faceland.loot.sockets.effects.LootSocketPotionEffect; import info.faceland.loot.tier.LootTierBuilder; import info.faceland.loot.utils.converters.StringConverter; import info.faceland.utils.TextUtils; import net.nunnerycode.java.libraries.cannonball.DebugPrinter; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.event.HandlerList; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; public final class LootPlugin extends FacePlugin { private DebugPrinter debugPrinter; private VersionedIvoryYamlConfiguration itemsYAML; private VersionedIvoryYamlConfiguration tierYAML; private VersionedIvoryYamlConfiguration corestatsYAML; private VersionedIvoryYamlConfiguration customItemsYAML; private VersionedIvoryYamlConfiguration socketGemsYAML; private VersionedIvoryYamlConfiguration languageYAML; private IvorySettings settings; private ItemGroupManager itemGroupManager; private TierManager tierManager; private NameManager nameManager; private CustomItemManager customItemManager; private SocketGemManager socketGemManager; @Override public void preEnable() { debugPrinter = new DebugPrinter(getDataFolder().getPath(), "debug.log"); itemsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "items.yml"), getResource("items.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (itemsYAML.update()) { getLogger().info("Updating items.yml"); debug("Updating items.yml"); } tierYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "tier.yml"), getResource("tier.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (tierYAML.update()) { getLogger().info("Updating tier.yml"); debug("Updating tier.yml"); } corestatsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "corestats.yml"), getResource("corestats.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (corestatsYAML.update()) { getLogger().info("Updating corestats.yml"); debug("Updating corestats.yml"); } customItemsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "customItems.yml"), getResource("customItems.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (customItemsYAML.update()) { getLogger().info("Updating customItems.yml"); debug("Updating customItems.yml"); } socketGemsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "socketGems.yml"), getResource("socketGems.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (socketGemsYAML.update()) { getLogger().info("Updating socketGems.yml"); debug("Updating socketGems.yml"); } languageYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "language.yml"), getResource("language.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (languageYAML.update()) { getLogger().info("Updating language.yml"); debug("Updating language.yml"); } settings = IvorySettings.loadFromFiles(corestatsYAML, languageYAML); itemGroupManager = new LootItemGroupManager(); tierManager = new LootTierManager(); nameManager = new LootNameManager(); customItemManager = new LootCustomItemManager(); socketGemManager = new LootSocketGemManager(); } @Override public void enable() { loadItemGroups(); loadTiers(); loadNames(); loadCustomItems(); loadSocketGems(); } private void loadSocketGems() { for (SocketGem sg : getSocketGemManager().getSocketGems()) { getSocketGemManager().removeSocketGem(sg.getName()); } Set<SocketGem> gems = new HashSet<>(); List<String> loadedSocketGems = new ArrayList<>(); for (String key : socketGemsYAML.getKeys(false)) { if (!socketGemsYAML.isConfigurationSection(key)) { continue; } ConfigurationSection cs = socketGemsYAML.getConfigurationSection(key); SocketGemBuilder builder = getNewSocketGemBuilder(key); builder.withPrefix(cs.getString("prefix")); builder.withSuffix(cs.getString("suffix")); builder.withLore(cs.getStringList("lore")); builder.withWeight(cs.getDouble("weight")); List<SocketEffect> effects = new ArrayList<>(); for (String eff : cs.getStringList("effects")) { effects.add(LootSocketPotionEffect.parseString(eff)); } builder.withSocketEffects(effects); SocketGem gem = builder.build(); gems.add(gem); loadedSocketGems.add(gem.getName()); } for (SocketGem sg : gems) { getSocketGemManager().addSocketGem(sg); } debug("Loaded socket gems: " + loadedSocketGems.toString()); } @Override public void postEnable() { Bukkit.getPluginManager().registerEvents(new LoginListener(this), this); debug("v" + getDescription().getVersion() + " enabled"); } @Override public void preDisable() { HandlerList.unregisterAll(this); } @Override public void disable() { } @Override public void postDisable() { socketGemManager = null; customItemManager = null; nameManager = null; tierManager = null; itemGroupManager = null; settings = null; languageYAML = null; customItemsYAML = null; corestatsYAML = null; tierYAML = null; itemsYAML = null; debugPrinter = null; } public void debug(String... messages) { debug(Level.INFO, messages); } public void debug(Level level, String... messages) { if (debugPrinter != null) { debugPrinter.debug(level, messages); } } private void loadCustomItems() { for (CustomItem ci : getCustomItemManager().getCustomItems()) { getCustomItemManager().removeCustomItem(ci.getName()); } Set<CustomItem> customItems = new HashSet<>(); List<String> loaded = new ArrayList<>(); for (String key : customItemsYAML.getKeys(false)) { if (!customItemsYAML.isConfigurationSection(key)) { continue; } ConfigurationSection cs = customItemsYAML.getConfigurationSection(key); CustomItemBuilder builder = getNewCustomItemBuilder(key); builder.withMaterial(StringConverter.toMaterial(cs.getString("material"))); builder.withDisplayName(cs.getString("display-name")); builder.withLore(cs.getStringList("lore")); CustomItem ci = builder.build(); customItems.add(ci); loaded.add(ci.getName()); } for (CustomItem ci : customItems) { getCustomItemManager().addCustomItem(ci); } debug("Loaded custom items: " + loaded.toString()); } private void loadNames() { for (String s : getNameManager().getPrefixes()) { getNameManager().removePrefix(s); } for (String s : getNameManager().getSuffixes()) { getNameManager().removeSuffix(s); } File prefixFile = new File(getDataFolder(), "prefix.txt"); File suffixFile = new File(getDataFolder(), "suffix.txt"); SmartTextFile.writeToFile(getResource("prefix.txt"), prefixFile, true); SmartTextFile.writeToFile(getResource("suffix.txt"), suffixFile, true); SmartTextFile smartPrefixFile = new SmartTextFile(prefixFile); SmartTextFile smartSuffixFile = new SmartTextFile(suffixFile); for (String s : smartPrefixFile.read()) { getNameManager().addPrefix(s); } for (String s : smartSuffixFile.read()) { getNameManager().addSuffix(s); } debug("Loaded prefixes: " + getNameManager().getPrefixes().size(), "Loaded suffixes: " + getNameManager() .getSuffixes().size()); } private void loadItemGroups() { for (ItemGroup ig : getItemGroupManager().getItemGroups()) { getItemGroupManager().removeItemGroup(ig.getName()); } Set<ItemGroup> itemGroups = new HashSet<>(); List<String> loadedItemGroups = new ArrayList<>(); for (String key : itemsYAML.getKeys(false)) { if (!itemsYAML.isList(key)) { continue; } List<String> list = itemsYAML.getStringList(key); ItemGroup ig = new LootItemGroup(key, false); for (String s : list) { Material m = StringConverter.toMaterial(s); if (m == Material.AIR) { continue; } ig.addMaterial(m); } itemGroups.add(ig); loadedItemGroups.add(key); } for (ItemGroup ig : itemGroups) { getItemGroupManager().addItemGroup(ig); } debug("Loaded item groups: " + loadedItemGroups.toString()); } private void loadTiers() { for (Tier t : getTierManager().getLoadedTiers()) { getTierManager().removeTier(t.getName()); } Set<Tier> tiers = new HashSet<>(); List<String> loadedTiers = new ArrayList<>(); for (String key : tierYAML.getKeys(false)) { if (!tierYAML.isConfigurationSection(key)) { continue; } ConfigurationSection cs = tierYAML.getConfigurationSection(key); TierBuilder builder = getNewTierBuilder(key); builder.withDisplayName(cs.getString("display-name")); builder.withDisplayColor(TextUtils.convertTag(cs.getString("display-color"))); builder.withIdentificationColor(TextUtils.convertTag(cs.getString("identification-color"))); builder.withSpawnWeight(cs.getDouble("spawn-weight")); builder.withIdentifyWeight(cs.getDouble("identify-weight")); builder.withDistanceWeight(cs.getDouble("distance-weight")); builder.withMinimumSockets(cs.getInt("minimum-sockets")); builder.withMaximumSockets(cs.getInt("maximum-sockets")); builder.withMinimumBonusLore(cs.getInt("minimum-bonus-lore")); builder.withMaximumBonusLore(cs.getInt("maximum-bonus-lore")); builder.withBaseLore(cs.getStringList("base-lore")); builder.withBonusLore(cs.getStringList("bonus-lore")); List<String> sl = cs.getStringList("item-groups"); Set<ItemGroup> itemGroups = new HashSet<>(); for (String s : sl) { ItemGroup ig; if (s.startsWith("-")) { ig = getItemGroupManager().getItemGroup(s.substring(1)); if (ig == null) { continue; } ig = ig.getInverse(); } else { ig = getItemGroupManager().getItemGroup(s); if (ig == null) { continue; } } itemGroups.add(ig.getInverse()); } builder.withItemGroups(itemGroups); builder.withMinimumDurability(cs.getDouble("minimum-durability")); builder.withMaximumDurability(cs.getDouble("maximum-durability")); Tier t = builder.build(); loadedTiers.add(t.getName()); tiers.add(t); } for (Tier t : tiers) { getTierManager().addTier(t); } debug("Loaded tiers: " + loadedTiers.toString()); } public TierBuilder getNewTierBuilder(String name) { return new LootTierBuilder(name); } public ItemBuilder getNewItemBuilder() { return new LootItemBuilder(this); } public CustomItemBuilder getNewCustomItemBuilder(String name) { return new LootCustomItemBuilder(name); } public SocketGemBuilder getNewSocketGemBuilder(String name) { return new LootSocketGemBuilder(name); } public TierManager getTierManager() { return tierManager; } public ItemGroupManager getItemGroupManager() { return itemGroupManager; } public NameManager getNameManager() { return nameManager; } public IvorySettings getSettings() { return settings; } public CustomItemManager getCustomItemManager() { return customItemManager; } public SocketGemManager getSocketGemManager() { return socketGemManager; } }
package io.ebean.typequery; import io.ebean.CacheMode; import io.ebean.DtoQuery; import io.ebean.Ebean; import io.ebean.EbeanServer; import io.ebean.ExpressionList; import io.ebean.FetchConfig; import io.ebean.FetchGroup; import io.ebean.FutureIds; import io.ebean.FutureList; import io.ebean.FutureRowCount; import io.ebean.PagedList; import io.ebean.PersistenceContextScope; import io.ebean.Query; import io.ebean.QueryIterator; import io.ebean.RawSql; import io.ebean.UpdateQuery; import io.ebean.Version; import io.ebean.search.MultiMatch; import io.ebean.search.TextCommonTerms; import io.ebean.search.TextQueryString; import io.ebean.search.TextSimple; import io.ebean.text.PathProperties; import io.ebeaninternal.server.util.ArrayStack; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.sql.Timestamp; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Consumer; import java.util.function.Predicate; /** * Base root query bean. * <p> * With code generation for each entity bean type a query bean is created that extends this. * <p> * Provides common features for all root query beans * </p> * <p> * <h2>Example - QCustomer extends TQRootBean</h2> * <p> * These 'query beans' like QCustomer are generated using the <code>avaje-ebeanorm-typequery-generator</code>. * </p> * <pre>{@code * * public class QCustomer extends TQRootBean<Customer,QCustomer> { * * // properties * public PLong<QCustomer> id; * * public PString<QCustomer> name; * ... * * }</pre> * <p> * <h2>Example - usage of QCustomer</h2> * <pre>{@code * * Date fiveDaysAgo = ... * * List<Customer> customers = * new QCustomer() * .name.ilike("rob") * .status.equalTo(Customer.Status.GOOD) * .registered.after(fiveDaysAgo) * .contacts.email.endsWith("@foo.com") * .orderBy() * .name.asc() * .registered.desc() * .findList(); * * }</pre> * <p> * <h2>Resulting SQL where</h2> * <p> * <pre>{@code sql * * where lower(t0.name) like ? and t0.status = ? and t0.registered > ? and u1.email like ? * order by t0.name, t0.registered desc; * * --bind(rob,GOOD,Mon Jul 27 12:05:37 NZST 2015,%@foo.com) * }</pre> * * @param <T> the entity bean type (normal entity bean type e.g. Customer) * @param <R> the specific root query bean type (e.g. QCustomer) */ public abstract class TQRootBean<T, R> { /** * The underlying query. */ private final Query<T> query; /** * The underlying expression lists held as a stack. Pushed and popped based on and/or (conjunction/disjunction). */ private ArrayStack<ExpressionList<T>> whereStack; /** * Stack of Text expressions ("query" section of ElasticSearch query rather than "filter" section). */ private ArrayStack<ExpressionList<T>> textStack; /** * When true expressions should be added to the "text" stack - ElasticSearch "query" section * rather than the "where" stack. */ private boolean textMode; /** * The root query bean instance. Used to provide fluid query construction. */ private R root; /** * Construct using the type of bean to query on and the default server. */ public TQRootBean(Class<T> beanType) { this(beanType, Ebean.getDefaultServer()); } /** * Construct using the type of bean to query on and a given server. */ public TQRootBean(Class<T> beanType, EbeanServer server) { this(server.find(beanType)); } /** * Construct using a query. */ public TQRootBean(Query<T> query) { this.query = query; } /** * Construct for using as an 'Alias' to use the properties as known string * values for select() and fetch(). */ public TQRootBean(boolean aliasDummy) { this.query = null; } /** * Sets the root query bean instance. Used to provide fluid query construction. */ protected void setRoot(R root) { this.root = root; } /** * Return the underlying query. * <p> * Generally it is not expected that you will need to do this but typically use * the find methods available on this 'root query bean' instance like findList(). * </p> */ @Nonnull public Query<T> query() { return query; } /** * Explicitly set a comma delimited list of the properties to fetch on the * 'main' root level entity bean (aka partial object). Note that '*' means all * properties. * <p> * You use {@link #fetch(String, String)} to specify specific properties to fetch * on other non-root level paths of the object graph. * </p> * <p> * <pre>{@code * * List<Customer> customers = * new QCustomer() * // Only fetch the customer id, name and status. * // This is described as a "Partial Object" * .select("name, status") * .name.ilike("rob%") * .findList(); * * }</pre> * * @param properties the properties to fetch for this bean (* = all properties). */ public R select(String properties) { query.select(properties); return root; } /** * Set a FetchGroup to control what part of the object graph is loaded. * <p> * This is an alternative to using select() and fetch() providing a nice clean separation * between what a query should load and the query predicates. * </p> * * <pre>{@code * * FetchGroup<Customer> fetchGroup = FetchGroup.of(Customer.class) * .select("name, status") * .fetch("contacts", "firstName, lastName, email") * .build(); * * List<Customer> customers = * * new QCustomer() * .select(fetchGroup) * .findList(); * * }</pre> */ public R select(FetchGroup<T> fetchGroup) { query.select(fetchGroup); return root; } /** * Tune the query by specifying the properties to be loaded on the * 'main' root level entity bean (aka partial object). * <pre>{@code * * // alias for the customer properties in select() * QCustomer cust = QCustomer.alias(); * * // alias for the contact properties in contacts.fetch() * QContact contact = QContact.alias(); * * List<Customer> customers = * new QCustomer() * // tune query * .select(cust.id, cust.name) * .contacts.fetch(contact.firstName, contact.lastName, contact.email) * * // predicates * .id.greaterThan(1) * .findList(); * * }</pre> * * @param properties the list of properties to fetch */ @SafeVarargs public final R select(TQProperty<R>... properties) { StringBuilder selectProps = new StringBuilder(50); for (int i = 0; i < properties.length; i++) { if (i > 0) { selectProps.append(","); } selectProps.append(properties[i].propertyName()); } query.select(selectProps.toString()); return root; } /** * Specify a path to load including all its properties. * <p> * The same as {@link #fetch(String, String)} with the fetchProperties as "*". * </p> * <pre>{@code * * List<Customer> customers = * new QCustomer() * // eager fetch the contacts * .fetch("contacts") * .findList(); * * }</pre> * * @param path the property path of an associated (OneToOne, OneToMany, ManyToOne or ManyToMany) bean. */ public R fetch(String path) { query.fetch(path); return root; } /** * Specify a path to load including all its properties using a "query join". * * <pre>{@code * * List<Customer> customers = * new QCustomer() * // eager fetch the contacts using a "query join" * .fetchQuery("contacts") * .findList(); * * }</pre> * * @param path the property path of an associated (OneToOne, OneToMany, ManyToOne or ManyToMany) bean. */ public R fetchQuery(String path) { query.fetchQuery(path); return root; } /** * Specify a path and properties to load using a "query join". * * <pre>{@code * * List<Customer> customers = * new QCustomer() * // eager fetch contacts using a "query join" * .fetchQuery("contacts", "email, firstName, lastName") * .findList(); * * }</pre> * * @param path the property path of an associated (OneToOne, OneToMany, ManyToOne or ManyToMany) bean. */ public R fetchQuery(String path, String properties) { query.fetchQuery(path, properties); return root; } /** * Specify a path to <em>fetch</em> with its specific properties to include * (aka partial object). * <p> * When you specify a join this means that property (associated bean(s)) will * be fetched and populated. If you specify "*" then all the properties of the * associated bean will be fetched and populated. You can specify a comma * delimited list of the properties of that associated bean which means that * only those properties are fetched and populated resulting in a * "Partial Object" - a bean that only has some of its properties populated. * </p> * <p> * <pre>{@code * * // query orders... * List<Order> orders = * new QOrder() * .fetch("customer", "name, phoneNumber") * .fetch("customer.billingAddress", "*") * .findList(); * * }</pre> * <p> * If columns is null or "*" then all columns/properties for that path are fetched. * </p> * * <pre>{@code * * List<Customer> customers = * new QCustomer() * .select("name, status") * .fetch("contacts", "firstName,lastName,email") * .findList(); * * }</pre> * * @param path the path of an associated (OneToOne, OneToMany, ManyToOne or ManyToMany) bean. * @param properties properties of the associated bean that you want to include in the * fetch (* means all properties, null also means all properties). */ public R fetch(String path, String properties) { query.fetch(path, properties); return root; } /** * Additionally specify a FetchConfig to use a separate query or lazy loading * to load this path. * <p> * <pre>{@code * * // fetch customers (their id, name and status) * List<Customer> customers = * new QCustomer() * .select("name, status") * .fetch("contacts", "firstName,lastName,email", new FetchConfig().lazy(10)) * .findList(); * * }</pre> */ public R fetch(String path, String properties, FetchConfig fetchConfig) { query.fetch(path, properties, fetchConfig); return root; } /** * Additionally specify a FetchConfig to specify a "query join" and or define * the lazy loading query. * <p> * <pre>{@code * * // fetch customers (their id, name and status) * List<Customer> customers = * new QCustomer() * // lazy fetch contacts with a batch size of 100 * .fetch("contacts", new FetchConfig().lazy(100)) * .findList(); * * }</pre> */ public R fetch(String path, FetchConfig fetchConfig) { query.fetch(path, fetchConfig); return root; } /** * Apply the path properties replacing the select and fetch clauses. * <p> * This is typically used when the PathProperties is applied to both the query and the JSON output. * </p> */ public R apply(PathProperties pathProperties) { query.apply(pathProperties); return root; } /** * Perform an 'As of' query using history tables to return the object graph * as of a time in the past. * <p> * To perform this query the DB must have underlying history tables. * </p> * * @param asOf the date time in the past at which you want to view the data */ public R asOf(Timestamp asOf) { query.asOf(asOf); return root; } /** * Execute the query against the draft set of tables. */ public R asDraft() { query.asDraft(); return root; } /** * Execute the query including soft deleted rows. */ public R setIncludeSoftDeletes() { query.setIncludeSoftDeletes(); return root; } /** * Set root table alias. */ public R alias(String alias) { query.alias(alias); return root; } /** * Set the maximum number of rows to return in the query. * * @param maxRows the maximum number of rows to return in the query. */ public R setMaxRows(int maxRows) { query.setMaxRows(maxRows); return root; } /** * Set the first row to return for this query. * * @param firstRow the first row to include in the query result. */ public R setFirstRow(int firstRow) { query.setFirstRow(firstRow); return root; } /** * Execute the query allowing properties with invalid JSON to be collected and not fail the query. * <pre>{@code * * // fetch a bean with JSON content * EBasicJsonList bean= new QEBasicJsonList() * .id.equalTo(42) * .setAllowLoadErrors() // collect errors into bean state if we have invalid JSON * .findOne(); * * * // get the invalid JSON errors from the bean state * Map<String, Exception> errors = server().getBeanState(bean).getLoadErrors(); * * // If this map is not empty tell we have invalid JSON * // and should try and fix the JSON content or inform the user * * }</pre> */ public R setAllowLoadErrors() { query.setAllowLoadErrors(); return root; } /** * Explicitly specify whether to use AutoTune for this query. * <p> * If you do not call this method on a query the "Implicit AutoTune mode" is * used to determine if AutoTune should be used for a given query. * </p> * <p> * AutoTune can add additional fetch paths to the query and specify which * properties are included for each path. If you have explicitly defined some * fetch paths AutoTune will not remove them. * </p> */ public R setAutoTune(boolean autoTune) { query.setAutoTune(autoTune); return root; } /** * A hint which for JDBC translates to the Statement.fetchSize(). * <p> * Gives the JDBC driver a hint as to the number of rows that should be * fetched from the database when more rows are needed for ResultSet. * </p> */ public R setBufferFetchSizeHint(int fetchSize) { query.setBufferFetchSizeHint(fetchSize); return root; } /** * Set whether this query uses DISTINCT. */ public R setDistinct(boolean distinct) { query.setDistinct(distinct); return root; } /** * Set the index(es) to search for a document store which uses partitions. * <p> * For example, when executing a query against ElasticSearch with daily indexes we can * explicitly specify the indexes to search against. * </p> * <pre>{@code * * // explicitly specify the indexes to search * query.setDocIndexName("logstash-2016.11.5,logstash-2016.11.6") * * // search today's index * query.setDocIndexName("$today") * * // search the last 3 days * query.setDocIndexName("$last-3") * * }</pre> * <p> * If the indexName is specified with ${daily} e.g. "logstash-${daily}" ... then we can use * $today and $last-x as the search docIndexName like the examples below. * </p> * <pre>{@code * * // search today's index * query.setDocIndexName("$today") * * // search the last 3 days * query.setDocIndexName("$last-3") * * }</pre> * * @param indexName The index or indexes to search against * @return This query */ public R setDocIndexName(String indexName) { query.setDocIndexName(indexName); return root; } /** * Restrict the query to only return subtypes of the given inherit type. * <pre>{@code * * List<Animal> animals = * new QAnimal() * .name.startsWith("Fluffy") * .setInheritType(Cat.class) * .findList(); * * }</pre> */ public R setInheritType(Class<? extends T> type) { query.setInheritType(type); return root; } /** * Set the base table to use for this query. * <p> * Typically this is used when a table has partitioning and we wish to specify a specific * partition/table to query against. * </p> * <pre>{@code * * QOrder() * .setBaseTable("order_2019_05") * .status.equalTo(Status.NEW) * .findList(); * * }</pre> */ public R setBaseTable(String baseTable) { query.setBaseTable(baseTable); return root; } /** * executed the select with "for update" which should lock the record "on read" */ public R forUpdate() { query.forUpdate(); return root; } /** * Execute using "for update" clause with "no wait" option. * <p> * This is typically a Postgres and Oracle only option at this stage. * </p> */ public R forUpdateNoWait() { query.forUpdateNoWait(); return root; } /** * Execute using "for update" clause with "skip locked" option. * <p> * This is typically a Postgres and Oracle only option at this stage. * </p> */ public R forUpdateSkipLocked() { query.forUpdateSkipLocked(); return root; } /** * Return this query as an UpdateQuery. * * <pre>{@code * * int rows = * new QCustomer() * .name.startsWith("Rob") * .organisation.id.equalTo(42) * .asUpdate() * .set("active", false) * .update() * * }</pre> * * @return This query as an UpdateQuery */ public UpdateQuery<T> asUpdate() { return query.asUpdate(); } /** * Convert the query to a DTO bean query. * <p> * We effectively use the underlying ORM query to build the SQL and then execute * and map it into DTO beans. */ public <D> DtoQuery<D> asDto(Class<D> dtoClass) { return query.asDto(dtoClass); } /** * Set the Id value to query. This is used with findOne(). * <p> * You can use this to have further control over the query. For example adding * fetch joins. * </p> * <p> * <pre>{@code * * Order order = * new QOrder() * .setId(1) * .fetch("details") * .findOne(); * * // the order details were eagerly fetched * List<OrderDetail> details = order.getDetails(); * * }</pre> */ public R setId(Object id) { query.setId(id); return root; } /** * Set a list of Id values to match. * <p> * <pre>{@code * * List<Order> orders = * new QOrder() * .setIdIn(42, 43, 44) * .findList(); * * // the order details were eagerly fetched * List<OrderDetail> details = order.getDetails(); * * }</pre> */ public R setIdIn(Object... ids) { query.where().idIn(ids); return root; } /** * Set the default lazy loading batch size to use. * <p> * When lazy loading is invoked on beans loaded by this query then this sets the * batch size used to load those beans. * * @param lazyLoadBatchSize the number of beans to lazy load in a single batch */ public R setLazyLoadBatchSize(int lazyLoadBatchSize) { query.setLazyLoadBatchSize(lazyLoadBatchSize); return root; } /** * When set to true all the beans from this query are loaded into the bean * cache. */ public R setLoadBeanCache(boolean loadBeanCache) { query.setLoadBeanCache(loadBeanCache); return root; } /** * Set the property to use as keys for a map. * <p> * If no property is set then the id property is used. * </p> * <p> * <pre>{@code * * // Assuming sku is unique for products... * * Map<String,Product> productMap = * new QProduct() * // use sku for keys... * .setMapKey("sku") * .findMap(); * * }</pre> * * @param mapKey the property to use as keys for a map. */ public R setMapKey(String mapKey) { query.setMapKey(mapKey); return root; } /** * Specify the PersistenceContextScope to use for this query. * <p> * When this is not set the 'default' configured on {@link io.ebean.config.ServerConfig#setPersistenceContextScope(PersistenceContextScope)} * is used - this value defaults to {@link io.ebean.PersistenceContextScope#TRANSACTION}. * <p> * Note that the same persistence Context is used for subsequent lazy loading and query join queries. * <p> * Note that #findEach uses a 'per object graph' PersistenceContext so this scope is ignored for * queries executed as #findIterate, #findEach, #findEachWhile. * * @param scope The scope to use for this query and subsequent lazy loading. */ public R setPersistenceContextScope(PersistenceContextScope scope) { query.setPersistenceContextScope(scope); return root; } /** * Set RawSql to use for this query. */ public R setRawSql(RawSql rawSql) { query.setRawSql(rawSql); return root; } /** * When set to true when you want the returned beans to be read only. */ public R setReadOnly(boolean readOnly) { query.setReadOnly(readOnly); return root; } /** * Set this to true to use the bean cache. * <p> * If the query result is in cache then by default this same instance is * returned. In this sense it should be treated as a read only object graph. * </p> */ public R setUseCache(boolean useCache) { query.setUseCache(useCache); return root; } /** * Set the mode to use the bean cache when executing this query. * <p> * By default "find by id" and "find by natural key" will use the bean cache * when bean caching is enabled. Setting this to false means that the query * will not use the bean cache and instead hit the database. * </p> * <p> * By default findList() with natural keys will not use the bean cache. In that * case we need to explicitly use the bean cache. * </p> */ public R setBeanCacheMode(CacheMode beanCacheMode) { query.setBeanCacheMode(beanCacheMode); return root; } /** * Set to true if this query should execute against the doc store. * <p> * When setting this you may also consider disabling lazy loading. * </p> */ public R setUseDocStore(boolean useDocStore) { query.setUseDocStore(useDocStore); return root; } /** * Set true if you want to disable lazy loading. * <p> * That is, once the object graph is returned further lazy loading is disabled. * </p> */ public R setDisableLazyLoading(boolean disableLazyLoading) { query.setDisableLazyLoading(disableLazyLoading); return root; } /** * Disable read auditing for this query. * <p> * This is intended to be used when the query is not a user initiated query and instead * part of the internal processing in an application to load a cache or document store etc. * In these cases we don't want the query to be part of read auditing. * </p> */ public R setDisableReadAuditing() { query.setDisableReadAuditing(); return root; } /** * Set this to true to use the query cache. */ public R setUseQueryCache(boolean useCache) { query.setUseQueryCache(useCache); return root; } /** * Set the {@link CacheMode} to use the query for executing this query. */ public R setUseQueryCache(CacheMode cacheMode) { query.setUseQueryCache(cacheMode); return root; } /** * Set a timeout on this query. * <p> * This will typically result in a call to setQueryTimeout() on a * preparedStatement. If the timeout occurs an exception will be thrown - this * will be a SQLException wrapped up in a PersistenceException. * </p> * * @param secs the query timeout limit in seconds. Zero means there is no limit. */ public R setTimeout(int secs) { query.setTimeout(secs); return root; } /** * Returns the set of properties or paths that are unknown (do not map to known properties or paths). * <p> * Validate the query checking the where and orderBy expression paths to confirm if * they represent valid properties or paths for the given bean type. * </p> */ public Set<String> validate() { return query.validate(); } /** * Add raw expression with no parameters. * <p> * When properties in the clause are fully qualified as table-column names * then they are not translated. logical property name names (not fully * qualified) will still be translated to their physical name. * </p> * <p> * <pre>{@code * * raw("orderQty < shipQty") * * }</pre> * * <h4>Subquery example:</h4> * <pre>{@code * * .raw("t0.customer_id in (select customer_id from customer_group where group_id = any(?::uuid[]))", groupIds) * * }</pre> */ public R raw(String rawExpression) { peekExprList().raw(rawExpression); return root; } /** * Add raw expression with an array of parameters. * <p> * The raw expression should contain the same number of ? as there are * parameters. * </p> * <p> * When properties in the clause are fully qualified as table-column names * then they are not translated. logical property name names (not fully * qualified) will still be translated to their physical name. * </p> */ public R raw(String rawExpression, Object... bindValues) { peekExprList().raw(rawExpression, bindValues); return root; } /** * Add raw expression with a single parameter. * <p> * The raw expression should contain a single ? at the location of the * parameter. * </p> * <p> * When properties in the clause are fully qualified as table-column names * then they are not translated. logical property name names (not fully * qualified) will still be translated to their physical name. * </p> * <p> * <h4>Example:</h4> * <pre>{@code * * // use a database function * raw("add_days(orderDate, 10) < ?", someDate) * * }</pre> * * <h4>Subquery example:</h4> * <pre>{@code * * .raw("t0.customer_id in (select customer_id from customer_group where group_id = any(?::uuid[]))", groupIds) * * }</pre> */ public R raw(String rawExpression, Object bindValue) { peekExprList().raw(rawExpression, bindValue); return root; } /** * Marker that can be used to indicate that the order by clause is defined after this. * <p> * order() and orderBy() are synonyms and both exist for historic reasons. * </p> * <p> * <h2>Example: order by customer name, order date</h2> * <pre>{@code * List<Order> orders = * new QOrder() * .customer.name.ilike("rob") * .orderBy() * .customer.name.asc() * .orderDate.asc() * .findList(); * * }</pre> */ public R orderBy() { // Yes this does not actually do anything! We include it because style wise it makes // the query nicer to read and suggests that order by definitions are added after this return root; } /** * Marker that can be used to indicate that the order by clause is defined after this. * <p> * order() and orderBy() are synonyms and both exist for historic reasons. * </p> * <p> * <h2>Example: order by customer name, order date</h2> * <pre>{@code * List<Order> orders = * new QOrder() * .customer.name.ilike("rob") * .order() * .customer.name.asc() * .orderDate.asc() * .findList(); * * }</pre> */ public R order() { // Yes this does not actually do anything! We include it because style wise it makes // the query nicer to read and suggests that order by definitions are added after this return root; } /** * Set the full raw order by clause replacing the existing order by clause if there is one. * <p> * This follows SQL syntax using commas between each property with the * optional asc and desc keywords representing ascending and descending order * respectively. * </p> * <p> * This is EXACTLY the same as {@link #order(String)}. * </p> */ public R orderBy(String orderByClause) { query.orderBy(orderByClause); return root; } /** * Set the full raw order by clause replacing the existing order by clause if there is one. * <p> * This follows SQL syntax using commas between each property with the * optional asc and desc keywords representing ascending and descending order * respectively. * </p> * <p> * This is EXACTLY the same as {@link #orderBy(String)}. * </p> */ public R order(String orderByClause) { query.order(orderByClause); return root; } /** * Begin a list of expressions added by 'OR'. * <p> * Use endOr() or endJunction() to stop added to OR and 'pop' to the parent expression list. * </p> * <p> * <h2>Example</h2> * <p> * This example uses an 'OR' expression list with an inner 'AND' expression list. * </p> * <pre>{@code * * List<Customer> customers = * new QCustomer() * .status.equalTo(Customer.Status.GOOD) * .or() * .id.greaterThan(1000) * .and() * .name.startsWith("super") * .registered.after(fiveDaysAgo) * .endAnd() * .endOr() * .orderBy().id.desc() * .findList(); * * }</pre> * <h2>Resulting SQL where clause</h2> * <pre>{@code sql * * where t0.status = ? and (t0.id > ? or (t0.name like ? and t0.registered > ? ) ) * order by t0.id desc; * * --bind(GOOD,1000,super%,Wed Jul 22 00:00:00 NZST 2015) * * }</pre> */ public R or() { pushExprList(peekExprList().or()); return root; } /** * Begin a list of expressions added by 'AND'. * <p> * Use endAnd() or endJunction() to stop added to AND and 'pop' to the parent expression list. * </p> * <p> * Note that typically the AND expression is only used inside an outer 'OR' expression. * This is because the top level expression list defaults to an 'AND' expression list. * </p> * <h2>Example</h2> * <p> * This example uses an 'OR' expression list with an inner 'AND' expression list. * </p> * <pre>{@code * * List<Customer> customers = * new QCustomer() * .status.equalTo(Customer.Status.GOOD) * .or() // OUTER 'OR' * .id.greaterThan(1000) * .and() // NESTED 'AND' expression list * .name.startsWith("super") * .registered.after(fiveDaysAgo) * .endAnd() * .endOr() * .orderBy().id.desc() * .findList(); * * }</pre> * <h2>Resulting SQL where clause</h2> * <pre>{@code sql * * where t0.status = ? and (t0.id > ? or (t0.name like ? and t0.registered > ? ) ) * order by t0.id desc; * * --bind(GOOD,1000,super%,Wed Jul 22 00:00:00 NZST 2015) * * }</pre> */ public R and() { pushExprList(peekExprList().and()); return root; } /** * Begin a list of expressions added by NOT. * <p> * Use endNot() or endJunction() to stop added to NOT and 'pop' to the parent expression list. * </p> */ public R not() { pushExprList(peekExprList().not()); return root; } /** * Begin a list of expressions added by MUST. * <p> * This automatically makes this query a document store query. * </p> * <p> * Use endJunction() to stop added to MUST and 'pop' to the parent expression list. * </p> */ public R must() { pushExprList(peekExprList().must()); return root; } /** * Begin a list of expressions added by MUST NOT. * <p> * This automatically makes this query a document store query. * </p> * <p> * Use endJunction() to stop added to MUST NOT and 'pop' to the parent expression list. * </p> */ public R mustNot() { return pushExprList(peekExprList().mustNot()); } /** * Begin a list of expressions added by SHOULD. * <p> * This automatically makes this query a document store query. * </p> * <p> * Use endJunction() to stop added to SHOULD and 'pop' to the parent expression list. * </p> */ public R should() { return pushExprList(peekExprList().should()); } /** * End a list of expressions added by 'OR'. */ public R endJunction() { if (textMode) { textStack.pop(); } else { whereStack.pop(); } return root; } /** * End OR junction - synonym for endJunction(). */ public R endOr() { return endJunction(); } /** * End AND junction - synonym for endJunction(). */ public R endAnd() { return endJunction(); } /** * End NOT junction - synonym for endJunction(). */ public R endNot() { return endJunction(); } /** * Push the expression list onto the appropriate stack. */ private R pushExprList(ExpressionList<T> list) { if (textMode) { textStack.push(list); } else { whereStack.push(list); } return root; } /** * Add expression after this to the WHERE expression list. * <p> * For queries against the normal database (not the doc store) this has no effect. * </p> * <p> * This is intended for use with Document Store / ElasticSearch where expressions can be put into either * the "query" section or the "filter" section of the query. Full text expressions like MATCH are in the * "query" section but many expression can be in either - expressions after the where() are put into the * "filter" section which means that they don't add to the relevance and are also cache-able. * </p> */ public R where() { textMode = false; return root; } /** * Begin added expressions to the 'Text' expression list. * <p> * This automatically makes the query a document store query. * </p> * <p> * For ElasticSearch expressions added to 'text' go into the ElasticSearch 'query context' * and expressions added to 'where' go into the ElasticSearch 'filter context'. * </p> */ public R text() { textMode = true; return root; } /** * Add a Text Multi-match expression (document store only). * <p> * This automatically makes the query a document store query. * </p> */ public R multiMatch(String query, MultiMatch multiMatch) { peekExprList().multiMatch(query, multiMatch); return root; } /** * Add a Text Multi-match expression (document store only). * <p> * This automatically makes the query a document store query. * </p> */ public R multiMatch(String query, String... properties) { peekExprList().multiMatch(query, properties); return root; } /** * Add a Text common terms expression (document store only). * <p> * This automatically makes the query a document store query. * </p> */ public R textCommonTerms(String query, TextCommonTerms options) { peekExprList().textCommonTerms(query, options); return root; } /** * Add a Text simple expression (document store only). * <p> * This automatically makes the query a document store query. * </p> */ public R textSimple(String query, TextSimple options) { peekExprList().textSimple(query, options); return root; } /** * Add a Text query string expression (document store only). * <p> * This automatically makes the query a document store query. * </p> */ public R textQueryString(String query, TextQueryString options) { peekExprList().textQueryString(query, options); return root; } /** * Execute the query returning true if a row is found. * <p> * The query is executed using max rows of 1 and will only select the id property. * This method is really just a convenient way to optimise a query to perform a * 'does a row exist in the db' check. * </p> * * <h2>Example using a query bean:</h2> * <pre>{@code * * boolean userExists = * new QContact() * .email.equalTo("rob@foo.com") * .exists(); * * }</pre> * * <h2>Example:</h2> * <pre>{@code * * boolean userExists = query() * .where().eq("email", "rob@foo.com") * .exists(); * * }</pre> * * @return True if the query finds a matching row in the database */ public boolean exists() { return query.exists(); } /** * Execute the query returning either a single bean or null (if no matching * bean is found). * <p> * If more than 1 row is found for this query then a PersistenceException is * thrown. * </p> * <p> * This is useful when your predicates dictate that your query should only * return 0 or 1 results. * </p> * <p> * <pre>{@code * * // assuming the sku of products is unique... * Product product = * new QProduct() * .sku.equalTo("aa113") * .findOne(); * ... * }</pre> * <p> * <p> * It is also useful with finding objects by their id when you want to specify * further join information to optimise the query. * </p> * <p> * <pre>{@code * * // Fetch order 42 and additionally fetch join its order details... * Order order = * new QOrder() * .fetch("details") // eagerly load the order details * .id.equalTo(42) * .findOne(); * * // the order details were eagerly loaded * List<OrderDetail> details = order.getDetails(); * ... * }</pre> */ @Nullable public T findOne() { return query.findOne(); } /** * Execute the query returning an optional bean. */ @Nonnull public Optional<T> findOneOrEmpty() { return query.findOneOrEmpty(); } /** * Execute the query returning the list of objects. * <p> * This query will execute against the EbeanServer that was used to create it. * </p> * <p> * <pre>{@code * * List<Customer> customers = * new QCustomer() * .name.ilike("rob%") * .findList(); * * }</pre> * * @see Query#findList() */ @Nonnull public List<T> findList() { return query.findList(); } /** * Execute the query returning the set of objects. * <p> * This query will execute against the EbeanServer that was used to create it. * </p> * <p> * <pre>{@code * * Set<Customer> customers = * new QCustomer() * .name.ilike("rob%") * .findSet(); * * }</pre> * * @see Query#findSet() */ @Nonnull public Set<T> findSet() { return query.findSet(); } /** * Execute the query returning the list of Id's. * <p> * This query will execute against the EbeanServer that was used to create it. * </p> * * @see Query#findIds() */ @Nonnull public <A> List<A> findIds() { return query.findIds(); } /** * Execute the query returning a map of the objects. * <p> * This query will execute against the EbeanServer that was used to create it. * </p> * <p> * You can use setMapKey() or asMapKey() to specify the property to be used as keys * on the map. If one is not specified then the id property is used. * </p> * <p> * <pre>{@code * * Map<String, Product> map = * new QProduct() * .sku.asMapKey() * .findMap(); * * }</pre> * * @see Query#findMap() */ @Nonnull public <K> Map<K, T> findMap() { return query.findMap(); } /** * Execute the query iterating over the results. * <p> * Note that findIterate (and findEach and findEachWhile) uses a "per graph" * persistence context scope and adjusts jdbc fetch buffer size for large * queries. As such it is better to use findList for small queries. * </p> * <p> * Remember that with {@link QueryIterator} you must call {@link QueryIterator#close()} * when you have finished iterating the results (typically in a finally block). * </p> * <p> * findEach() and findEachWhile() are preferred to findIterate() as they ensure * the jdbc statement and resultSet are closed at the end of the iteration. * </p> * <p> * This query will execute against the EbeanServer that was used to create it. * </p> * <pre>{@code * * Query<Customer> query = * new QCustomer() * .status.equalTo(Customer.Status.NEW) * .order() * id.asc() * .query(); * * try (QueryIterator<Customer> it = query.findIterate()) { * while (it.hasNext()) { * Customer customer = it.next(); * // do something with customer ... * } * } * * }</pre> */ @Nonnull public QueryIterator<T> findIterate() { return query.findIterate(); } /** * Execute the query returning a list of values for a single property. * <p> * <h3>Example</h3> * <pre>{@code * * List<String> names = * new QCustomer() * .setDistinct(true) * .select(name) * .findSingleAttributeList(); * * }</pre> * * @return the list of values for the selected property */ @Nonnull public <A> List<A> findSingleAttributeList() { return query.findSingleAttributeList(); } /** * Execute the query returning a single value for a single property. * <p> * <h3>Example</h3> * <pre>{@code * * LocalDate maxDate = * new QCustomer() * .select("max(startDate)") * .findSingleAttribute(); * * }</pre> * * @return the list of values for the selected property */ public <A> A findSingleAttribute() { return query.findSingleAttribute(); } /** * Execute the query processing the beans one at a time. * <p> * This method is appropriate to process very large query results as the * beans are consumed one at a time and do not need to be held in memory * (unlike #findList #findSet etc) * </p> * <p> * Note that internally Ebean can inform the JDBC driver that it is expecting larger * resultSet and specifically for MySQL this hint is required to stop it's JDBC driver * from buffering the entire resultSet. As such, for smaller resultSets findList() is * generally preferable. * </p> * <p> * Compared with #findEachWhile this will always process all the beans where as * #findEachWhile provides a way to stop processing the query result early before * all the beans have been read. * </p> * <p> * This method is functionally equivalent to findIterate() but instead of using an * iterator uses the QueryEachConsumer (SAM) interface which is better suited to use * with Java8 closures. * </p> * <p> * <pre>{@code * * new QCustomer() * .status.equalTo(Status.NEW) * .orderBy().id.asc() * .findEach((Customer customer) -> { * * // do something with customer * System.out.println("-- visit " + customer); * }); * * }</pre> * * @param consumer the consumer used to process the queried beans. */ public void findEach(Consumer<T> consumer) { query.findEach(consumer); } /** * Execute the query using callbacks to a visitor to process the resulting * beans one at a time. * <p> * This method is functionally equivalent to findIterate() but instead of using an * iterator uses the QueryEachWhileConsumer (SAM) interface which is better suited to use * with Java8 closures. * </p> * <p> * <p> * <pre>{@code * * new QCustomer() * .status.equalTo(Status.NEW) * .order().id.asc() * .findEachWhile((Customer customer) -> { * * // do something with customer * System.out.println("-- visit " + customer); * * // return true to continue processing or false to stop * return (customer.getId() < 40); * }); * * }</pre> * * @param consumer the consumer used to process the queried beans. */ public void findEachWhile(Predicate<T> consumer) { query.findEachWhile(consumer); } /** * Return versions of a @History entity bean. * <p> * Generally this query is expected to be a find by id or unique predicates query. * It will execute the query against the history returning the versions of the bean. * </p> */ @Nonnull public List<Version<T>> findVersions() { return query.findVersions(); } /** * Return versions of a @History entity bean between a start and end timestamp. * <p> * Generally this query is expected to be a find by id or unique predicates query. * It will execute the query against the history returning the versions of the bean. * </p> */ @Nonnull public List<Version<T>> findVersionsBetween(Timestamp start, Timestamp end) { return query.findVersionsBetween(start, end); } /** * Return the count of entities this query should return. * <p> * This is the number of 'top level' or 'root level' entities. * </p> */ @Nonnull public int findCount() { return query.findCount(); } /** * Execute find row count query in a background thread. * <p> * This returns a Future object which can be used to cancel, check the * execution status (isDone etc) and get the value (with or without a * timeout). * </p> * * @return a Future object for the row count query */ @Nonnull public FutureRowCount<T> findFutureCount() { return query.findFutureCount(); } /** * Execute find Id's query in a background thread. * <p> * This returns a Future object which can be used to cancel, check the * execution status (isDone etc) and get the value (with or without a * timeout). * </p> * * @return a Future object for the list of Id's */ @Nonnull public FutureIds<T> findFutureIds() { return query.findFutureIds(); } /** * Execute find list query in a background thread. * <p> * This query will execute in it's own PersistenceContext and using its own transaction. * What that means is that it will not share any bean instances with other queries. * </p> * * @return a Future object for the list result of the query */ @Nonnull public FutureList<T> findFutureList() { return query.findFutureList(); } /** * Return a PagedList for this query using firstRow and maxRows. * <p> * The benefit of using this over findList() is that it provides functionality to get the * total row count etc. * </p> * <p> * If maxRows is not set on the query prior to calling findPagedList() then a * PersistenceException is thrown. * </p> * <p> * <pre>{@code * * PagedList<Order> pagedList = * new QOrder() * .setFirstRow(50) * .setMaxRows(20) * .findPagedList(); * * // fetch the total row count in the background * pagedList.loadRowCount(); * * List<Order> orders = pagedList.getList(); * int totalRowCount = pagedList.getTotalRowCount(); * * }</pre> * * @return The PagedList */ @Nonnull public PagedList<T> findPagedList() { return query.findPagedList(); } /** * Execute as a delete query deleting the 'root level' beans that match the predicates * in the query. * <p> * Note that if the query includes joins then the generated delete statement may not be * optimal depending on the database platform. * </p> * * @return the number of beans/rows that were deleted. */ public int delete() { return query.delete(); } /** * Return the sql that was generated for executing this query. * <p> * This is only available after the query has been executed and provided only * for informational purposes. * </p> */ public String getGeneratedSql() { return query.getGeneratedSql(); } /** * Return the type of beans being queried. */ @Nonnull public Class<T> getBeanType() { return query.getBeanType(); } /** * Return the expression list that has been built for this query. */ @Nonnull public ExpressionList<T> getExpressionList() { return query.where(); } /** * Start adding expressions to the having clause when using @Aggregation properties. * * <pre>{@code * * new QMachineUse() * // where ... * .date.inRange(fromDate, toDate) * * .having() * .sumHours.greaterThan(1) * .findList() * * // The sumHours property uses @Aggregation * // e.g. @Aggregation("sum(hours)") * * }</pre> */ public R having() { if (whereStack == null) { whereStack = new ArrayStack<>(); } // effectively putting having expression list onto stack // such that expression now add to the having clause whereStack.push(query.having()); return root; } /** * Return the underlying having clause to typically when using dynamic aggregation formula. * <p> * Note that after this we no longer have the query bean so typically we use this right * at the end of the query. * </p> * * <pre>{@code * * // sum(distanceKms) ... is a "dynamic formula" * // so we use havingClause() for it like: * * List<MachineUse> machineUse = * * new QMachineUse() * .select("machine, sum(fuelUsed), sum(distanceKms)") * * // where ... * .date.greaterThan(LocalDate.now().minusDays(7)) * * .havingClause() * .gt("sum(distanceKms)", 2) * .findList(); * * }</pre> */ public ExpressionList<T> havingClause() { return query.having(); } /** * Return the current expression list that expressions should be added to. */ protected ExpressionList<T> peekExprList() { if (textMode) { // return the current text expression list return _peekText(); } if (whereStack == null) { whereStack = new ArrayStack<>(); whereStack.push(query.where()); } // return the current expression list return whereStack.peek(); } protected ExpressionList<T> _peekText() { if (textStack == null) { textStack = new ArrayStack<>(); // empty so push on the queries base expression list textStack.push(query.text()); } // return the current expression list return textStack.peek(); } }
package io.leonrd.webdav; import fi.iki.elonen.NanoHTTPD; import java.io.*; import java.net.URLEncoder; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; public class WebDavServer extends NanoHTTPD { /** * Common mime type for dynamic content: binary */ public static final String MIME_DEFAULT_BINARY = "application/octet-stream"; /** * Hashtable mapping (String)FILENAME_EXTENSION -> (String)MIME_TYPE */ @SuppressWarnings("serial") private static final Map<String, String> MIME_TYPES = new HashMap<String, String>() { { put("css", "text/css"); put("htm", "text/html"); put("html", "text/html"); put("xml", "text/xml"); put("java", "text/x-java-source, text/java"); put("md", "text/plain"); put("txt", "text/plain"); put("asc", "text/plain"); put("gif", "image/gif"); put("jpg", "image/jpeg"); put("jpeg", "image/jpeg"); put("png", "image/png"); put("svg", "image/svg+xml"); put("mp3", "audio/mpeg"); put("m3u", "audio/mpeg-url"); put("mp4", "video/mp4"); put("ogv", "video/ogg"); put("flv", "video/x-flv"); put("mov", "video/quicktime"); put("swf", "application/x-shockwave-flash"); put("js", "application/javascript"); put("pdf", "application/pdf"); put("doc", "application/msword"); put("ogg", "application/x-ogg"); put("zip", "application/octet-stream"); put("exe", "application/octet-stream"); put("class", "application/octet-stream"); put("m3u8", "application/vnd.apple.mpegurl"); put("ts", " video/mp2t"); } }; private final static String ALLOWED_METHODS = "GET, DELETE, OPTIONS, HEAD, PROPFIND, MKCOL, COPY, MOVE, PUT, LOCK, UNLOCK"; private static final DateFormat DATE_FORMAT = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.getDefault()); private boolean quiet; protected File rootDir; public WebDavServer(String host, int port, File rootDir, boolean quiet) { super(host, port); this.quiet = quiet; this.rootDir = rootDir; if (this.rootDir == null) { this.rootDir = new File("").getAbsoluteFile(); } init(); } private String appendPathComponent(final String path, final String component) { if (path.endsWith("/")) { return path + component; } else { return path + "/" + component; } } private boolean canServeUri(String uri) { return new File(rootDir, uri).exists(); } /** * URL-encodes everything between "/"-characters. Encodes spaces as '%20' * instead of '+'. */ private String encodeUri(String uri) { String newUri = ""; StringTokenizer st = new StringTokenizer(uri, "/ ", true); while (st.hasMoreTokens()) { String tok = st.nextToken(); if (tok.equals("/")) { newUri += "/"; } else if (tok.equals(" ")) { newUri += "%20"; } else { try { newUri += URLEncoder.encode(tok, "UTF-8"); } catch (UnsupportedEncodingException ignored) { } } } return newUri; } // Get MIME type from file name extension, if possible private String getMimeTypeForFile(String uri) { int dot = uri.lastIndexOf('.'); String mime = null; if (dot >= 0) { mime = WebDavServer.MIME_TYPES.get(uri.substring(dot + 1).toLowerCase()); } return mime == null ? WebDavServer.MIME_DEFAULT_BINARY : mime; } protected Response getBadRequestErrorResponse(String s) { return newFixedLengthResponse(Response.Status.BAD_REQUEST, NanoHTTPD.MIME_PLAINTEXT, "BAD REQUEST: " + s); } protected Response getNotFoundErrorResponse(String s) { return newFixedLengthResponse(Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "NOT FOUND: " + s); } protected Response getForbiddenErrorResponse(String s) { return newFixedLengthResponse(Response.Status.FORBIDDEN, NanoHTTPD.MIME_PLAINTEXT, "FORBIDDEN: " + s); } protected Response getInternalErrorResponse(String s) { return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "INTERNAL ERROR: " + s); } public static Response newFixedLengthResponse(Response.IStatus status, String mimeType, String message) { Response response = NanoHTTPD.newFixedLengthResponse(status, mimeType, message); response.addHeader("Accept-Ranges", "bytes"); return response; } /** * Used to initialize and customize the server. */ public void init() { } @Override public Response serve(IHTTPSession session) { String uri = session.getUri(); // Remove URL arguments uri = uri.trim().replace(File.separatorChar, '/'); if (uri.indexOf('?') >= 0) { uri = uri.substring(0, uri.indexOf('?')); } // Prohibit getting out of current directory if (uri.contains("../")) { return getForbiddenErrorResponse("Won't serve ../ for security reasons."); } final Method method = session.getMethod(); final Map<String, String> headers = Collections.unmodifiableMap(session.getHeaders()); final Map<String, String> parms = session.getParms(); if (!this.quiet) { System.out.println(session.getMethod() + " '" + uri + "' "); Iterator<String> e = headers.keySet().iterator(); while (e.hasNext()) { String value = e.next(); System.out.println(" HDR: '" + value + "' = '" + headers.get(value) + "'"); } e = parms.keySet().iterator(); while (e.hasNext()) { String value = e.next(); System.out.println(" PRM: '" + value + "' = '" + parms.get(value) + "'"); } } if (!rootDir.isDirectory()) { return getInternalErrorResponse("Given root path is not a directory."); } Response response; switch (method) { case OPTIONS: response = handleOPTIONS(headers); break; case PROPFIND: response = handlePROPFIND(uri, headers); break; case GET:case HEAD: response = handleGET(uri, headers); break; case DELETE: response = handleDELETE(uri, headers); break; case MKCOL: response = handleMKCOL(uri); break; case COPY: response = handleCOPYorMOVE(uri, headers, false); break; case MOVE: response = handleCOPYorMOVE(uri, headers, true); break; case PUT: response = handlePUT(session); break; case LOCK: response = handleLOCK(uri); break; case UNLOCK: response = handleUNLOCK(uri); break; default: response = getForbiddenErrorResponse(""); break; } if (!this.quiet) { System.out.println(" STATUS: " + response.getStatus()); } return response; } protected boolean isMacFinder(Map<String, String> headers) { final String userAgent = headers.get("user-agent"); return userAgent != null && (userAgent.startsWith("WebDAVFS/") || userAgent.startsWith("WebDAVLib/")); } protected Response handleOPTIONS(final Map<String, String> headers) { Response response = newFixedLengthResponse(Response.Status.OK, MIME_PLAINTEXT, ""); if (isMacFinder(headers)) { response.addHeader("DAV", "1, 2"); } else { response.addHeader("DAV", "1"); } response.addHeader("Allow", ALLOWED_METHODS); return response; } protected Response handlePROPFIND(String uri, final Map<String, String> headers) { // Remove URL arguments uri = uri.trim().replace(File.separatorChar, '/'); if (uri.indexOf('?') >= 0) { uri = uri.substring(0, uri.indexOf('?')); } // Prohibit getting out of current directory if (uri.contains("../")) { return getForbiddenErrorResponse("Won't serve ../ for security reasons."); } if (!canServeUri(uri)) { return getNotFoundErrorResponse(""); } final int depth; String depthHeader = headers.get("depth"); // TODO: Return 403 / propfind-finite-depth for "infinity" depth if (depthHeader != null && depthHeader.equalsIgnoreCase("0")) { depth = 0; } else if (depthHeader != null && depthHeader.equalsIgnoreCase("1")) { depth = 1; } else { return getBadRequestErrorResponse("Unsupported 'Depth' header: " + depthHeader); } final String absolutePath = appendPathComponent(rootDir.getAbsolutePath(), uri); final File file = new File(absolutePath); if (file.isDirectory() && depth > 0) { if (!file.canRead()) { return getInternalErrorResponse("Failed listing directory " + uri); } } final StringBuilder xmlStringBuilder = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<D:multistatus xmlns:D=\"DAV:\">"); if (file.isDirectory()) { if (file.list() == null) { return getInternalErrorResponse("Failed listing directory " + uri); } appendCollectionResource(xmlStringBuilder, uri, file, depth); } else { appendFileResource(xmlStringBuilder, uri, file); } xmlStringBuilder.append("</D:multistatus>"); final String content = xmlStringBuilder.toString(); return newFixedLengthResponse(Response.Status.MULTI_STATUS, MIME_TYPES.get("xml"), content); } /** * Appends directory info as xml to a StringBuilder */ protected void appendCollectionResource(final StringBuilder output, final String uri, final File directory, final int depth) { final String displayName = directory.getName(); // TODO: if possible, properly handle creation date final String creationDate = DATE_FORMAT.format(new Date(directory.lastModified())); final String lastModified = DATE_FORMAT.format(new Date(directory.lastModified())); output.append("<D:response>" + "<D:href>" + uri + "</D:href>" + "<D:propstat>" + "<D:prop>" + "<D:displayname>" + displayName + "</D:displayname>" + "<D:creationdate>" + creationDate + "</D:creationdate>" + "<D:getlastmodified>" + lastModified + "</D:getlastmodified>" + "<D:resourcetype><D:collection/></D:resourcetype>" + "</D:prop>" + "<D:status>HTTP/1.1 200 OK</D:status>" + "</D:propstat>" + "</D:response>"); if (depth > 0) { final File files[] = directory.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; String subUri = appendPathComponent(uri, encodeUri(file.getName())); if (file.isDirectory()) { appendCollectionResource(output, subUri, file, depth - 1); } else { appendFileResource(output, subUri, file); } } } } /** * Appends file info as xml to a StringBuilder */ protected void appendFileResource(final StringBuilder output, final String uri, final File file) { final String displayName = file.getName(); // TODO: if possible, properly handle creation date final String creationDate = DATE_FORMAT.format(new Date(file.lastModified())); final String lastModified = DATE_FORMAT.format(new Date(file.lastModified())); final long contentLength = file.length(); output.append("<D:response>" + "<D:href>" + uri + "</D:href>" + "<D:propstat>" + "<D:prop>" + "<D:displayname>" + displayName + "</D:displayname>" + "<D:creationdate>" + creationDate + "</D:creationdate>" + "<D:getlastmodified>" + lastModified + "</D:getlastmodified>" + "<D:getcontentlength>" + contentLength + "</D:getcontentlength>" + "<D:resourcetype/>" + "</D:prop>" + "<D:status>HTTP/1.1 200 OK</D:status>" + "</D:propstat>" + "</D:response>"); } protected Response handleGET(final String uri, final Map<String, String> headers) { if (!canServeUri(uri)) { return getNotFoundErrorResponse(""); } final String absolutePath = appendPathComponent(rootDir.getAbsolutePath(), uri); final File file = new File(absolutePath); // Because HEAD requests are mapped to GET ones, we need to handle directories but it's OK to return nothing per http://webdav.org/specs/rfc4918.html#rfc.section.9.4 if (file.isDirectory()) { return newFixedLengthResponse(Response.Status.OK, MIME_PLAINTEXT, ""); } String mimeTypeForFile = getMimeTypeForFile(uri); return serveFile(uri, headers, file, mimeTypeForFile); } /** * Serves file from homeDir and its' subdirectories (only). Uses only URI, * ignores all headers and HTTP parameters. */ Response serveFile(String uri, Map<String, String> header, File file, String mime) { Response res; try { // Calculate etag String etag = Integer.toHexString((file.getAbsolutePath() + file.lastModified() + "" + file.length()).hashCode()); // Support (simple) skipping: long startFrom = 0; long endAt = -1; String range = header.get("range"); if (range != null) { if (range.startsWith("bytes=")) { range = range.substring("bytes=".length()); int minus = range.indexOf('-'); try { if (minus > 0) { startFrom = Long.parseLong(range.substring(0, minus)); endAt = Long.parseLong(range.substring(minus + 1)); } } catch (NumberFormatException ignored) { } } } // get if-range header. If present, it must match etag or else we // should ignore the range request String ifRange = header.get("if-range"); boolean headerIfRangeMissingOrMatching = (ifRange == null || etag.equals(ifRange)); String ifNoneMatch = header.get("if-none-match"); boolean headerIfNoneMatchPresentAndMatching = ifNoneMatch != null && (ifNoneMatch.equals("*") || ifNoneMatch.equals(etag)); // Change return code and add Content-Range header when skipping is // requested long fileLen = file.length(); if (headerIfRangeMissingOrMatching && range != null && startFrom >= 0 && startFrom < fileLen) { // range request that matches current etag // and the startFrom of the range is satisfiable if (headerIfNoneMatchPresentAndMatching) { // range request that matches current etag // and the startFrom of the range is satisfiable // would return range from file // respond with not-modified res = newFixedLengthResponse(Response.Status.NOT_MODIFIED, mime, ""); res.addHeader("ETag", etag); } else { if (endAt < 0) { endAt = fileLen - 1; } long newLen = endAt - startFrom + 1; if (newLen < 0) { newLen = 0; } FileInputStream fis = new FileInputStream(file); fis.skip(startFrom); res = newFixedLengthResponse(Response.Status.PARTIAL_CONTENT, mime, fis, newLen); res.addHeader("Accept-Ranges", "bytes"); res.addHeader("Content-Length", "" + newLen); res.addHeader("Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen); res.addHeader("ETag", etag); } } else { if (headerIfRangeMissingOrMatching && range != null && startFrom >= fileLen) { // return the size of the file // 4xx responses are not trumped by if-none-match res = newFixedLengthResponse(Response.Status.RANGE_NOT_SATISFIABLE, NanoHTTPD.MIME_PLAINTEXT, ""); res.addHeader("Content-Range", "bytes */" + fileLen); res.addHeader("ETag", etag); } else if (range == null && headerIfNoneMatchPresentAndMatching) { // full-file-fetch request // would return entire file // respond with not-modified res = newFixedLengthResponse(Response.Status.NOT_MODIFIED, mime, ""); res.addHeader("ETag", etag); } else if (!headerIfRangeMissingOrMatching && headerIfNoneMatchPresentAndMatching) { // range request that doesn't match current etag // would return entire (different) file // respond with not-modified res = newFixedLengthResponse(Response.Status.NOT_MODIFIED, mime, ""); res.addHeader("ETag", etag); } else { // supply the file res = newFixedFileResponse(file, mime); res.addHeader("Content-Length", "" + fileLen); res.addHeader("ETag", etag); } } } catch (IOException ioe) { res = getForbiddenErrorResponse("Reading file failed."); } return res; } protected Response handleDELETE(final String uri, final Map<String, String> headers) { String depthHeader = headers.get("depth"); if (depthHeader != null && !depthHeader.equalsIgnoreCase("infinity")) { return getBadRequestErrorResponse("Unsupported 'Depth' header: " + depthHeader); } if (!canServeUri(uri)) { return getNotFoundErrorResponse(""); } final String absolutePath = appendPathComponent(rootDir.getAbsolutePath(), uri); final File file = new File(absolutePath); if (!file.delete()) { return getInternalErrorResponse("Failed deleting " + uri); } return newFixedLengthResponse(Response.Status.NO_CONTENT, MIME_PLAINTEXT, ""); } protected Response handleMKCOL(final String uri) { final String absolutePath = appendPathComponent(rootDir.getAbsolutePath(), uri); final File file = new File(absolutePath); if (!file.mkdirs()) { return getInternalErrorResponse("Failed creating directory " + uri); } return newFixedLengthResponse(Response.Status.NO_CONTENT, MIME_PLAINTEXT, ""); } protected Response handleCOPYorMOVE(final String uri, final Map<String, String> headers, final boolean move) { if (!move) { String depthHeader = headers.get("depth"); // TODO: Support "Depth: 0" if (depthHeader != null && !depthHeader.equalsIgnoreCase("infinity")) { return getBadRequestErrorResponse("Unsupported 'Depth' header: " + depthHeader); } } if (!canServeUri(uri)) { return getNotFoundErrorResponse(""); } final String srcRelativePath = uri; final String srcAbsolutePath = appendPathComponent(rootDir.getAbsolutePath(), uri); String dstRelativePath = headers.get("destination"); final String hostHeader = headers.get("host"); if (dstRelativePath == null || hostHeader == null || !dstRelativePath.contains(hostHeader)) { return getBadRequestErrorResponse("Malformed 'Destination' header: " + dstRelativePath); } dstRelativePath = dstRelativePath.substring(dstRelativePath.indexOf(hostHeader) + hostHeader.length()); final String dstAbsolutePath = appendPathComponent(rootDir.getAbsolutePath(), dstRelativePath); final File srcFile = new File(srcAbsolutePath); final File dstFile = new File(dstAbsolutePath); final File dstParent = dstFile.getParentFile(); final boolean existing = dstFile.exists(); if (!dstParent.exists() || !dstParent.isDirectory()) { return newFixedLengthResponse(Response.Status.CONFLICT, MIME_PLAINTEXT, "Invalid destination " + dstRelativePath); } boolean overwrite = false; final String overwriteHeader = headers.get("overwrite"); if (overwriteHeader == null || (move && !overwriteHeader.equalsIgnoreCase("T")) || (!move && overwriteHeader.equalsIgnoreCase("F"))) { overwrite = true; } if (existing && !overwrite) { return newFixedLengthResponse(Response.Status.PRECONDITION_FAILED, MIME_PLAINTEXT, "Destination " + dstRelativePath + " already exists"); } if (existing) { dstFile.delete(); } if (move) { if (!srcFile.renameTo(dstFile)) { return getForbiddenErrorResponse("Failed moving " + srcRelativePath + " to " + dstRelativePath); } } else { if (!copyFileOrDirectory(srcFile, dstFile)) { return getForbiddenErrorResponse("Failed copying " + srcRelativePath + " to " + dstRelativePath); } } return newFixedLengthResponse(existing ? Response.Status.NO_CONTENT : Response.Status.CREATED, MIME_PLAINTEXT, ""); } public static boolean copyFileOrDirectory(final File srcFile, final File dstFile) { boolean result = true; try { if (srcFile.isDirectory()) { String files[] = srcFile.list(); int filesLength = files.length; for (int i = 0; i < filesLength; i++) { File src1 = new File(srcFile, files[i]); copyFileOrDirectory(src1, dstFile); } } else { copyFile(srcFile, dstFile); } } catch (IOException e) { result = false; e.printStackTrace(); } return result; } public static boolean copyFile(File srcFile, File dstFile) throws IOException { boolean result = true; if (!dstFile.getParentFile().exists()) dstFile.getParentFile().mkdirs(); if (!dstFile.exists()) { dstFile.createNewFile(); } FileInputStream in = null; FileOutputStream out = null; try { // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } catch (IOException e) { result = false; e.printStackTrace(); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } return result; } protected Response handlePUT(final IHTTPSession session) { String uri = session.getUri(); // Remove URL arguments uri = uri.trim().replace(File.separatorChar, '/'); if (uri.indexOf('?') >= 0) { uri = uri.substring(0, uri.indexOf('?')); } // Prohibit getting out of current directory if (uri.contains("../")) { return getForbiddenErrorResponse("Won't serve ../ for security reasons."); } final String dstRelativePath = uri; final String dstAbsolutePath = appendPathComponent(rootDir.getAbsolutePath(), uri); final File dstFile = new File(dstAbsolutePath); final boolean existing = dstFile.exists(); final File dstParent = dstFile.getParentFile(); if (!dstParent.exists() || !dstParent.isDirectory()) { return newFixedLengthResponse(Response.Status.CONFLICT, MIME_PLAINTEXT, "Missing intermediate collection(s) for " + dstRelativePath); } if (existing && dstFile.isDirectory()) { return newFixedLengthResponse(Response.Status.METHOD_NOT_ALLOWED, MIME_PLAINTEXT, "PUT not allowed on existing collection " + dstRelativePath); } try { Map<String, String> files = new HashMap<String, String>(); session.parseBody(files); Set<String> keys = files.keySet(); for(String key: keys){ String tempLocation = files.get(key); File tempfile = new File(tempLocation); if (existing) { dstFile.delete(); } copyFileOrDirectory(tempfile, dstFile); } } catch (IOException e) { return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, e.getMessage()); } catch (ResponseException e) { return newFixedLengthResponse(e.getStatus(), MIME_PLAINTEXT, e.getMessage()); } return newFixedLengthResponse(Response.Status.OK, MIME_PLAINTEXT, ""); } protected Response handleLOCK(final String uri) { return null; } protected Response handleUNLOCK(final String uri) { return null; } private Response newFixedFileResponse(File file, String mime) throws FileNotFoundException { Response res; res = newFixedLengthResponse(Response.Status.OK, mime, new FileInputStream(file), (int) file.length()); res.addHeader("Accept-Ranges", "bytes"); return res; } }
package javaslang.collection; import javaslang.Tuple; import javaslang.Tuple2; import javaslang.control.None; import javaslang.control.Option; import javaslang.control.Some; import java.util.Collections; import java.util.Comparator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.function.*; /** * {@code javaslang.collection.Iterator} is a powerful replacement for {@code java.util.Iterator}. * Javaslang's {@code Iterator} extends Java's, so it integrates seemlessly in existing code. * Both are data structures whose purpose is to iterate <em>once</em> over a sequence of elements. * <p> * <strong>Note:</strong> Iterators encapsulate mutable state. * They are not meant to used concurrently by differnet threads. * <p> * There are two abstract methods: {@code hasNext} for checking if there is a next element available, * and {@code next} which removes the next element from the iterator and returns it. They can be called * an arbitrary amount of times. If {@code hasNext} returns false, a call of {@code next} will throw * a {@code NoSuchElementException}. * <p> * <strong>Caution:</strong> Other methods than {@code hasNext} and {@code next} can be called only once (exclusively). * More specifically, after calling a method it cannot be guaranteed that the next call will succeed. * * An Iterator that can be only used once because it is a traversal pointer into a collection, and not a collection * itself. * * @param <T> Component type * @since 2.0.0 */ public interface Iterator<T> extends java.util.Iterator<T>, TraversableOnce<T> { // DEV-NOTE: we prefer returning empty() over this if !hasNext() == true in order to free memory. /** * The empty Iterator. */ Iterator<Object> EMPTY = new AbstractIterator<Object>() { @Override public boolean hasNext() { return false; } @Override public Object next() { throw new NoSuchElementException("next() on empty iterator"); } }; /** * Returns the empty Iterator. * * @param <T> Component type * @return The empty Iterator */ @SuppressWarnings("unchecked") static <T> Iterator<T> empty() { return (Iterator<T>) EMPTY; } /** * Creates an infinite Iterator which returns the same element. * * @param element An element * @param <T> Component type. * @return A new Iterator */ static <T> Iterator<T> constant(T element) { return new AbstractIterator<T>() { @Override public boolean hasNext() { return true; } @Override public T next() { return element; } }; } /** * Creates an Iterator which traverses one element. * * @param element An element * @param <T> Component type. * @return A new Iterator */ static <T> Iterator<T> of(T element) { return new AbstractIterator<T>() { boolean hasNext = true; @Override public boolean hasNext() { return hasNext; } @Override public T next() { if (!hasNext) { EMPTY.next(); } hasNext = false; return element; } }; } /** * Creates an Iterator which traverses the given elements. * * @param elements Zero or more elements * @param <T> Component type * @return A new Iterator */ @SafeVarargs static <T> Iterator<T> of(T... elements) { Objects.requireNonNull(elements, "elements is null"); return new AbstractIterator<T>() { int index = 0; @Override public boolean hasNext() { return index < elements.length; } @Override public T next() { if (!hasNext()) { EMPTY.next(); } return elements[index++]; } }; } /** * Creates an Iterator which traverses along all given iterators. * * @param iterators The list of iterators * @param <T> Component type. * @return A new {@code javaslang.collection.Iterator} */ @SafeVarargs @SuppressWarnings({ "unchecked", "varargs" }) static <T> Iterator<T> ofIterators(Iterator<? extends T>... iterators) { Objects.requireNonNull(iterators, "iterators is null"); return iterators.length == 0 ? empty() : new ConcatIterator<>(Stream.of(iterators).iterator()); } /** * Creates an Iterator which traverses along all given iterables. * * @param iterables The list of iterables * @param <T> Component type. * @return A new {@code javaslang.collection.Iterator} */ @SafeVarargs @SuppressWarnings({ "unchecked", "varargs" }) static <T> Iterator<T> ofIterables(java.lang.Iterable<? extends T>... iterables) { Objects.requireNonNull(iterables, "iterables is null"); return iterables.length == 0 ? empty() : new ConcatIterator<>(Stream.of(iterables).map(Iterator::ofAll).iterator()); } /** * Creates an Iterator which traverses along all given iterators. * * @param iterators The iterator over iterators * @param <T> Component type. * @return A new {@code javaslang.collection.Iterator} */ static <T> Iterator<T> ofIterators(Iterator<? extends Iterator<? extends T>> iterators) { Objects.requireNonNull(iterators, "iterators is null"); return iterators.isEmpty() ? empty() : new ConcatIterator<>(Stream.ofAll(iterators).iterator()); } /** * Creates an Iterator which traverses along all given iterables. * * @param iterables The iterator over iterables * @param <T> Component type. * @return A new {@code javaslang.collection.Iterator} */ static <T> Iterator<T> ofIterables(Iterator<? extends java.lang.Iterable<? extends T>> iterables) { Objects.requireNonNull(iterables, "iterables is null"); return iterables.isEmpty() ? empty() : new ConcatIterator<>(Stream.ofAll(iterables).map(Iterator::ofAll).iterator()); } /** * Creates an Iterator which traverses along all given iterators. * * @param iterators The iterable of iterators * @param <T> Component type. * @return A new {@code javaslang.collection.Iterator} */ static <T> Iterator<T> ofIterators(java.lang.Iterable<? extends Iterator<? extends T>> iterators) { Objects.requireNonNull(iterators, "iterators is null"); if (!iterators.iterator().hasNext()) { return empty(); } return new ConcatIterator<>(Stream.ofAll(iterators).iterator()); } /** * Creates an Iterator which traverses along all given iterables. * * @param iterables The iterable of iterables * @param <T> Component type. * @return A new {@code javaslang.collection.Iterator} */ static <T> Iterator<T> ofIterables(java.lang.Iterable<? extends java.lang.Iterable<? extends T>> iterables) { Objects.requireNonNull(iterables, "iterables is null"); if (!iterables.iterator().hasNext()) { return empty(); } return new ConcatIterator<>(Stream.ofAll(iterables).map(Iterator::ofAll).iterator()); } /** * Creates an Iterator based on the given java.lang.Iterable. This is a convenience method for * {@code Iterator.of(iterable.iterator()}. * * @param iterable A {@link java.lang.Iterable} * @param <T> Component type. * @return A new {@code javaslang.collection.Iterator} */ static <T> Iterator<T> ofAll(java.lang.Iterable<? extends T> iterable) { Objects.requireNonNull(iterable, "iterable is null"); return Iterator.ofAll(iterable.iterator()); } /** * Creates a an Iterator based on the given Iterator by * delegating calls of {@code hasNext()} and {@code next()} to it. * * @param iterator A {@link java.util.Iterator} * @param <T> Component type. * @return A new {@code javaslang.collection.Iterator} */ static <T> Iterator<T> ofAll(java.util.Iterator<? extends T> iterator) { Objects.requireNonNull(iterator, "iterator is null"); return new AbstractIterator<T>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { if (!hasNext()) { EMPTY.next(); } return iterator.next(); } }; } /** * Creates a Iterator based on the elements of a boolean array. * * @param array a boolean array * @return A new Iterator of Boolean values */ static Iterator<Boolean> ofAll(boolean[] array) { Objects.requireNonNull(array, "array is null"); return new AbstractIterator<Boolean>() { int i = 0; @Override public boolean hasNext() { return i < array.length; } @Override public Boolean next() { return array[i++]; } }; } /** * Creates a Iterator based on the elements of a byte array. * * @param array a byte array * @return A new Iterator of Byte values */ static Iterator<Byte> ofAll(byte[] array) { Objects.requireNonNull(array, "array is null"); return new AbstractIterator<Byte>() { int i = 0; @Override public boolean hasNext() { return i < array.length; } @Override public Byte next() { return array[i++]; } }; } /** * Creates a Iterator based on the elements of a char array. * * @param array a char array * @return A new Iterator of Character values */ static Iterator<Character> ofAll(char[] array) { Objects.requireNonNull(array, "array is null"); return new AbstractIterator<Character>() { int i = 0; @Override public boolean hasNext() { return i < array.length; } @Override public Character next() { return array[i++]; } }; } /** * Creates a Iterator based on the elements of a double array. * * @param array a double array * @return A new Iterator of Double values */ static Iterator<Double> ofAll(double[] array) { Objects.requireNonNull(array, "array is null"); return new AbstractIterator<Double>() { int i = 0; @Override public boolean hasNext() { return i < array.length; } @Override public Double next() { return array[i++]; } }; } /** * Creates a Iterator based on the elements of a float array. * * @param array a float array * @return A new Iterator of Float values */ static Iterator<Float> ofAll(float[] array) { Objects.requireNonNull(array, "array is null"); return new AbstractIterator<Float>() { int i = 0; @Override public boolean hasNext() { return i < array.length; } @Override public Float next() { return array[i++]; } }; } /** * Creates a Iterator based on the elements of an int array. * * @param array an int array * @return A new Iterator of Integer values */ static Iterator<Integer> ofAll(int[] array) { Objects.requireNonNull(array, "array is null"); return new AbstractIterator<Integer>() { int i = 0; @Override public boolean hasNext() { return i < array.length; } @Override public Integer next() { return array[i++]; } }; } /** * Creates a Iterator based on the elements of a long array. * * @param array a long array * @return A new Iterator of Long values */ static Iterator<Long> ofAll(long[] array) { Objects.requireNonNull(array, "array is null"); return new AbstractIterator<Long>() { int i = 0; @Override public boolean hasNext() { return i < array.length; } @Override public Long next() { return array[i++]; } }; } /** * Creates a Iterator based on the elements of a short array. * * @param array a short array * @return A new Iterator of Short values */ static Iterator<Short> ofAll(short[] array) { Objects.requireNonNull(array, "array is null"); return new AbstractIterator<Short>() { int i = 0; @Override public boolean hasNext() { return i < array.length; } @Override public Short next() { return array[i++]; } }; } /** * Creates a List of int numbers starting from {@code from}, extending to {@code toExclusive - 1}. * <p> * Examples: * <pre> * <code> * List.range(0, 0) // = List() * List.range(2, 0) // = List() * List.range(-2, 2) // = List(-2, -1, 0, 1) * </code> * </pre> * * @param from the first number * @param toExclusive the last number + 1 * @return a range of int values as specified or the empty range if {@code from >= toExclusive} */ static Iterator<Integer> range(int from, int toExclusive) { return Iterator.rangeBy(from, toExclusive, 1); } static Iterator<Integer> rangeBy(int from, int toExclusive, int step) { if (step == 0) { throw new IllegalArgumentException("step cannot be 0"); } else if (from == toExclusive || step * (from - toExclusive) > 0) { return Iterator.empty(); } else { final int one = (from < toExclusive) ? 1 : -1; return Iterator.rangeClosedBy(from, toExclusive - one, step); } } /** * Creates a List of long numbers starting from {@code from}, extending to {@code toExclusive - 1}. * <p> * Examples: * <pre> * <code> * List.range(0L, 0L) // = List() * List.range(2L, 0L) // = List() * List.range(-2L, 2L) // = List(-2L, -1L, 0L, 1L) * </code> * </pre> * * @param from the first number * @param toExclusive the last number + 1 * @return a range of long values as specified or the empty range if {@code from >= toExclusive} */ static Iterator<Long> range(long from, long toExclusive) { return Iterator.rangeBy(from, toExclusive, 1); } static Iterator<Long> rangeBy(long from, long toExclusive, long step) { if (step == 0) { throw new IllegalArgumentException("step cannot be 0"); } else if (from == toExclusive || step * (from - toExclusive) > 0) { return Iterator.empty(); } else { final int one = (from < toExclusive) ? 1 : -1; return Iterator.rangeClosedBy(from, toExclusive - one, step); } } /** * Creates a List of int numbers starting from {@code from}, extending to {@code toInclusive}. * <p> * Examples: * <pre> * <code> * List.rangeClosed(0, 0) // = List(0) * List.rangeClosed(2, 0) // = List() * List.rangeClosed(-2, 2) // = List(-2, -1, 0, 1, 2) * </code> * </pre> * * @param from the first number * @param toInclusive the last number * @return a range of int values as specified or the empty range if {@code from > toInclusive} */ static Iterator<Integer> rangeClosed(int from, int toInclusive) { return Iterator.rangeClosedBy(from, toInclusive, 1); } static Iterator<Integer> rangeClosedBy(int from, int toInclusive, int step) { if (step == 0) { throw new IllegalArgumentException("step cannot be 0"); } else if (from == toInclusive) { return Iterator.of(from); } else if (step * (from - toInclusive) > 0) { return Iterator.empty(); } else { return new AbstractIterator<Integer>() { int i = from; boolean hasNext = (step > 0) ? i <= toInclusive : i >= toInclusive; @Override public boolean hasNext() { return hasNext; } @Override public Integer next() { if (!hasNext) { EMPTY.next(); } final int next = i; if ((step > 0 && i > toInclusive - step) || (step < 0 && i < toInclusive - step)) { hasNext = false; } else { i += step; } return next; } }; } } /** * Creates a List of long numbers starting from {@code from}, extending to {@code toInclusive}. * <p> * Examples: * <pre> * <code> * List.rangeClosed(0L, 0L) // = List(0L) * List.rangeClosed(2L, 0L) // = List() * List.rangeClosed(-2L, 2L) // = List(-2L, -1L, 0L, 1L, 2L) * </code> * </pre> * * @param from the first number * @param toInclusive the last number * @return a range of long values as specified or the empty range if {@code from > toInclusive} */ static Iterator<Long> rangeClosed(long from, long toInclusive) { return Iterator.rangeClosedBy(from, toInclusive, 1L); } static Iterator<Long> rangeClosedBy(long from, long toInclusive, long step) { if (step == 0) { throw new IllegalArgumentException("step cannot be 0"); } else if (from == toInclusive) { return Iterator.of(from); } else if (step * (from - toInclusive) > 0) { return Iterator.empty(); } else { return new AbstractIterator<Long>() { long i = from; boolean hasNext = (step > 0) ? i <= toInclusive : i >= toInclusive; @Override public boolean hasNext() { return hasNext; } @Override public Long next() { if (!hasNext) { EMPTY.next(); } final long next = i; if ((step > 0 && i > toInclusive - step) || (step < 0 && i < toInclusive - step)) { hasNext = false; } else { i += step; } return next; } }; } } // TODO: add static factory methods similar to Stream.from, Stream.gen, ... @Override default Iterator<T> clear() { return empty(); } @Override default Iterator<T> distinct() { if (!hasNext()) { return empty(); } else { return new DistinctIterator<>(this, HashSet.empty(), Function.identity()); } } @Override default Iterator<T> distinctBy(Comparator<? super T> comparator) { Objects.requireNonNull(comparator, "comparator is null"); if (!hasNext()) { return empty(); } else { return new DistinctIterator<>(this, TreeSet.empty(comparator), Function.identity()); } } @Override default <U> Iterator<T> distinctBy(Function<? super T, ? extends U> keyExtractor) { Objects.requireNonNull(keyExtractor, "keyExtractor is null"); if (!hasNext()) { return empty(); } else { return new DistinctIterator<>(this, HashSet.empty(), keyExtractor); } } /** * Removes up to n elements from this iterator. * * @param n A number * @return The empty iterator, if {@code n <= 0} or this is empty, otherwise a new iterator without the first n elements. */ default Iterator<T> drop(int n) { if (n <= 0) { return this; } else if (!hasNext()) { return empty(); } else { final Iterator<T> that = this; return new AbstractIterator<T>() { int count = n; @Override public boolean hasNext() { while (count > 0 && that.hasNext()) { that.next(); // discarded count } return that.hasNext(); } @Override public T next() { if (!hasNext()) { EMPTY.next(); } return that.next(); } }; } } @Override default Iterator<T> dropRight(int n) { if (n <= 0) { return this; } else if (!hasNext()) { return empty(); } else { final Iterator<T> that = this; return new Iterator<T>() { private Queue<T> queue = Queue.empty(); @Override public boolean hasNext() { while (queue.length() < n && that.hasNext()) { queue = queue.append(that.next()); } return queue.length() == n && that.hasNext(); } @Override public T next() { if (!hasNext()) { EMPTY.next(); } Tuple2<T, Queue<T>> t = queue.append(that.next()).dequeue(); queue = t._2; return t._1; } }; } } @Override default Iterator<T> dropWhile(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); if (!hasNext()) { return empty(); } else { final Iterator<T> that = this; return new AbstractIterator<T>() { private T next = null; @Override public boolean hasNext() { while (next == null && that.hasNext()) { final T value = that.next(); if(!predicate.test(value)) { next = value; } } return next != null; } @Override public T next() { if (!hasNext()) { EMPTY.next(); } final T result = next; next = null; return result; } }; } } default boolean equals(Iterator<? extends T> that) { Objects.requireNonNull(that, "that is null"); while (this.hasNext() && that.hasNext()) { if (!Objects.equals(this.next(), that.next())) { return false; } } return this.hasNext() == that.hasNext(); } /** * Returns an Iterator that contains elements that satisfy the given {@code predicate}. * * @param predicate A predicate * @return A new Iterator */ @Override default Iterator<T> filter(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); if (!hasNext()) { return empty(); } else { final Iterator<T> that = this; return new AbstractIterator<T>() { Option<T> next = None.instance(); @Override public boolean hasNext() { while (next.isEmpty() && that.hasNext()) { final T candidate = that.next(); if (predicate.test(candidate)) { next = new Some<>(candidate); } } return next.isDefined(); } @Override public T next() { if (!hasNext()) { EMPTY.next(); } T result = next.get(); next = None.instance(); return result; } }; } } @Override default Option<T> findLast(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); T last = null; while (hasNext()) { final T elem = next(); if (predicate.test(elem)) { last = elem; } } return Option.of(last); } /** * FlatMaps the elements of this Iterator to java.lang.Iterables, which are iterated in the order of occurrence. * * @param mapper A mapper * @param <U> Component type * @return A new java.lang.Iterable */ default <U> Iterator<U> flatMap(Function<? super T, ? extends java.lang.Iterable<? extends U>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); if (!hasNext()) { return empty(); } else { final Iterator<T> that = this; return new AbstractIterator<U>() { final Iterator<? extends T> inputs = that; java.util.Iterator<? extends U> current = Collections.emptyIterator(); @Override public boolean hasNext() { boolean currentHasNext; while (!(currentHasNext = current.hasNext()) && inputs.hasNext()) { current = mapper.apply(inputs.next()).iterator(); } return currentHasNext; } @Override public U next() { return current.next(); } }; } } /** * Flattens the elements of this Iterator. * * @return A flattened Iterator */ @Override default Iterator<Object> flatten() { if (!hasNext()) { return empty(); } else { return flatMap(t -> () -> (t instanceof java.lang.Iterable) ? ofAll((java.lang.Iterable<?>) t).flatten() : of(t)); } } @Override default <U> U foldRight(U zero, BiFunction<? super T, ? super U, ? extends U> f) { Objects.requireNonNull(f, "f is null"); // TODO throw new UnsupportedOperationException("TODO"); } @Override default T get() { return head(); } @Override default <C> Map<C, Iterator<T>> groupBy(Function<? super T, ? extends C> classifier) { Objects.requireNonNull(classifier, "classifier is null"); // TODO throw new UnsupportedOperationException("TODO"); } default T head() { if (!hasNext()) { EMPTY.next(); } return next(); } default Option<T> headOption() { return hasNext() ? new Some<>(next()) : None.instance(); } @Override default Iterator<T> init() { // TODO throw new UnsupportedOperationException("TODO"); } @Override default Option<Iterator<T>> initOption() { return hasNext() ? new Some<>(init()) : None.instance(); } /** * Inserts an element between all elements of this Iterator. * * @param element An element. * @return an interspersed version of this */ default Iterator<T> intersperse(T element) { if (!hasNext()) { return empty(); } else { final Iterator<T> that = this; return new AbstractIterator<T>() { boolean insertElement = false; @Override public boolean hasNext() { return that.hasNext(); } @Override public T next() { if (!that.hasNext()) { EMPTY.next(); } if (insertElement) { insertElement = false; return element; } else { insertElement = true; return that.next(); } } }; } } @Override default boolean isEmpty() { return !hasNext(); } @Override default Iterator<T> iterator() { return this; } @Override default int length() { return foldLeft(0, (n, ignored) -> n + 1); } /** * Maps the elements of this Iterator lazily using the given {@code mapper}. * * @param mapper A mapper. * @param <U> Component type * @return A new Iterator */ default <U> Iterator<U> map(Function<? super T, ? extends U> mapper) { Objects.requireNonNull(mapper, "mapper is null"); if (!hasNext()) { return empty(); } else { final Iterator<T> that = this; return new AbstractIterator<U>() { @Override public boolean hasNext() { return that.hasNext(); } @Override public U next() { if (!that.hasNext()) { EMPTY.next(); } return mapper.apply(that.next()); } }; } } @Override default Tuple2<Iterator<T>, Iterator<T>> partition(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); // TODO throw new UnsupportedOperationException("TODO"); } @Override default Iterator<T> peek(Consumer<? super T> action) { Objects.requireNonNull(action, "action is null"); if (!hasNext()) { return empty(); } else { final Iterator<T> that = this; return new AbstractIterator<T>() { @Override public boolean hasNext() { return that.hasNext(); } @Override public T next() { if (!hasNext()) { EMPTY.next(); } final T next = that.next(); action.accept(next); return next; } }; } } @Override default T reduceRight(BiFunction<? super T, ? super T, ? extends T> op) { Objects.requireNonNull(op, "op is null"); // TODO throw new UnsupportedOperationException("TODO"); } @Override default Iterator<T> replace(T currentElement, T newElement) { if (!hasNext()) { return empty(); } else { final Iterator<T> that = this; return new AbstractIterator<T>() { boolean done = false; @Override public boolean hasNext() { return that.hasNext(); } @Override public T next() { if (!that.hasNext()) { EMPTY.next(); } final T elem = that.next(); if (done || !Objects.equals(currentElement, elem)) { return elem; } else { done = true; return newElement; } } }; } } @Override default Iterator<T> replaceAll(T currentElement, T newElement) { if (!hasNext()) { return empty(); } else { final Iterator<T> that = this; return new AbstractIterator<T>() { @Override public boolean hasNext() { return that.hasNext(); } @Override public T next() { if (!that.hasNext()) { EMPTY.next(); } final T elem = that.next(); if (Objects.equals(currentElement, elem)) { return newElement; } else { return elem; } } }; } } @Override default Iterator<T> replaceAll(UnaryOperator<T> operator) { Objects.requireNonNull(operator, "operator is null"); if (!hasNext()) { return empty(); } else { final Iterator<T> that = this; return new AbstractIterator<T>() { @Override public boolean hasNext() { return that.hasNext(); } @Override public T next() { if (!that.hasNext()) { EMPTY.next(); } return operator.apply(that.next()); } }; } } @Override default Iterator<T> retainAll(java.lang.Iterable<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); return hasNext() ? filter(HashSet.ofAll(elements)::contains) : empty(); } @Override default Iterator<IndexedSeq<T>> sliding(int size, int step) { if (size <= 0 || step <= 0) { throw new IllegalArgumentException(String.format("size: %s or step: %s not positive", size, step)); } if (!hasNext()) { return empty(); } else { final Stream<T> source = Stream.ofAll(this); return new AbstractIterator<IndexedSeq<T>>() { private Stream<T> that = source; private IndexedSeq<T> next = null; @Override public boolean hasNext() { while (next == null && !that.isEmpty()) { final Tuple2<Stream<T>, Stream<T>> split = that.splitAt(size); next = split._1.toVector(); that = split._2.isEmpty() ? Stream.<T>empty() : that.drop(step); } return next != null; } @Override public IndexedSeq<T> next() { if (!hasNext()) { EMPTY.next(); } final IndexedSeq<T> result = next; next = null; return result; } }; } } @Override default Tuple2<Iterator<T>, Iterator<T>> span(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); if (!hasNext()) { return Tuple.of(empty(), empty()); } else { Stream<T> init = Stream.empty(); T firstImproper = null; while (hasNext()) { final T element = next(); if (predicate.test(element)) { init = init.append(element); } else { firstImproper = element; break; } } return Tuple.of(init.iterator(), firstImproper == null ? empty() : Stream.of(firstImproper).appendAll(this).iterator()); } } default Iterator<T> tail() { if (!hasNext()) { throw new UnsupportedOperationException(); } else { next(); // remove first element return this; } } @Override default Option<Iterator<T>> tailOption() { if (hasNext()) { next(); return new Some<>(this); } else { return None.instance(); } } /** * Take the first n elements from this iterator. * * @param n A number * @return The empty iterator, if {@code n <= 0} or this is empty, otherwise a new iterator without the first n elements. */ default Iterator<T> take(int n) { if (n <= 0 || !hasNext()) { return empty(); } else { final Iterator<T> that = this; return new AbstractIterator<T>() { int count = n; @Override public boolean hasNext() { return count > 0 && that.hasNext(); } @Override public T next() { if (!hasNext()) { EMPTY.next(); } count return that.next(); } }; } } @Override default Iterator<T> takeRight(int n) { // TODO throw new UnsupportedOperationException("TODO"); } @Override default Iterator<T> takeWhile(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); if (!hasNext()) { return empty(); } else { final Iterator<T> that = this; return new AbstractIterator<T>() { private T next = null; private boolean finished = false; @Override public boolean hasNext() { while (!finished && next == null && that.hasNext()) { final T value = that.next(); if (predicate.test(value)) { next = value; } else { finished = true; } } return next != null; } @Override public T next() { if (!hasNext()) { EMPTY.next(); } final T result = next; next = null; return result; } }; } } default <U> Iterator<Tuple2<T, U>> zip(java.lang.Iterable<U> that) { Objects.requireNonNull(that, "that is null"); if(isEmpty()) { return empty(); } else { final Iterator<T> it1 = this; final java.util.Iterator<U> it2 = that.iterator(); return new AbstractIterator<Tuple2<T, U>>() { @Override public boolean hasNext() { return it1.hasNext() && it2.hasNext(); } @Override public Tuple2<T, U> next() { if (!hasNext()) { EMPTY.next(); } return Tuple.of(it1.next(), it2.next()); } }; } } default <U> Iterator<Tuple2<T, U>> zipAll(java.lang.Iterable<U> that, T thisElem, U thatElem) { Objects.requireNonNull(that, "that is null"); if(isEmpty()) { return empty(); } else { final Iterator<T> it1 = this; final java.util.Iterator<U> it2 = that.iterator(); return new AbstractIterator<Tuple2<T, U>>() { @Override public boolean hasNext() { return it1.hasNext() || it2.hasNext(); } @Override public Tuple2<T, U> next() { if (!hasNext()) { EMPTY.next(); } T v1 = it1.hasNext() ? it1.next() : thisElem; U v2 = it2.hasNext() ? it2.next() : thatElem; return Tuple.of(v1, v2); } }; } } default Iterator<Tuple2<T, Integer>> zipWithIndex() { if(isEmpty()) { return empty(); } else { final Iterator<T> it1 = this; return new AbstractIterator<Tuple2<T, Integer>>() { private int index = 0; @Override public boolean hasNext() { return it1.hasNext(); } @Override public Tuple2<T, Integer> next() { if (!hasNext()) { EMPTY.next(); } return Tuple.of(it1.next(), index++); } }; } } default <T1, T2> Tuple2<Iterator<T1>, Iterator<T2>> unzip(Function<? super T, Tuple2<? extends T1, ? extends T2>> unzipper) { Objects.requireNonNull(unzipper, "unzipper is null"); if (!hasNext()) { return Tuple.of(empty(), empty()); } else { final Stream<Tuple2<? extends T1, ? extends T2>> source = Stream.ofAll(this.map(unzipper::apply)); return Tuple.of(source.map(t -> (T1) t._1).iterator(), source.map(t -> (T2) t._2).iterator()); } } class ConcatIterator<T> extends AbstractIterator<T> { private final Iterator<? extends Iterator<? extends T>> iterators; private Iterator<? extends T> current; private ConcatIterator(Iterator<? extends Iterator<? extends T>> iterators) { this.current = empty(); this.iterators = iterators; } @Override public boolean hasNext() { while (!current.hasNext() && !iterators.isEmpty()) { current = iterators.next(); } return current.hasNext(); } @Override public T next() { if (!hasNext()) { EMPTY.next(); } return current.next(); } } class DistinctIterator<T, U> extends AbstractIterator<T> { private final Iterator<? extends T> that; Set<U> known; Function<? super T, ? extends U> keyExtractor; T next = null; private DistinctIterator(Iterator<? extends T> that, Set<U> set, Function<? super T, ? extends U> keyExtractor) { this.that = that; this.known = set; this.keyExtractor = keyExtractor; } @Override public boolean hasNext() { while (next == null && that.hasNext()) { T elem = that.next(); U key = keyExtractor.apply(elem); if (!known.contains(key)) { known = known.add(key); next = elem; } } return next != null; } @Override public T next() { if (!hasNext()) { EMPTY.next(); } final T result = next; next = null; return result; } } abstract class AbstractIterator<T> implements Iterator<T> { @Override public String toString() { return (isEmpty() ? "" : "non-") + "empty iterator"; } } }
package la.funka.subteio; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.os.Build; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()) .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); return rootView; } } }
package minefantasy.system; import static net.minecraftforge.event.terraingen.DecorateBiomeEvent.Decorate.EventType.FLOWERS; import java.util.ConcurrentModificationException; import java.util.Random; import minefantasy.block.BlockListMF; import minefantasy.block.special.WorldGenIronbarkTree; import net.minecraft.block.Block; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.feature.WorldGenMinable; import net.minecraftforge.common.BiomeDictionary; import net.minecraftforge.common.BiomeDictionary.Type; import net.minecraftforge.event.ForgeSubscribe; import net.minecraftforge.event.Event.Result; import net.minecraftforge.event.terraingen.OreGenEvent; import net.minecraftforge.event.terraingen.OreGenEvent.GenerateMinable; import net.minecraftforge.event.terraingen.TerrainGen; import cpw.mods.fml.common.IWorldGenerator; public class WorldGenMF implements IWorldGenerator{ @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) { generateMisc(random, chunkX, chunkZ, world); generateOres(random, chunkX, chunkZ, world, false); } public void generateOres(Random random, int chunkX, int chunkZ, World world, boolean HC) { try { /**BiomeDecorator * Vanilla Veins: size, abundance, minY, maxY * Coal: 16, 20, 0, 128 * Iron: 8, 20, 0, 64 * Gold: 8, 2, 0, 32 * Lapis: 6, 1, 16, 16 * Diamond: 7, 1, 0, 16 * Red: 7, 8, 0, 16 */ if(random.nextInt(250) == 0 && cfg.spawnIgnot) { addOre(random, chunkX, chunkZ, world, BlockListMF.oreIgnotumite.blockID, 0, 8, 1, 0, 16); } if (cfg.spawnSilver) { addOre(random, chunkX, chunkZ, world, BlockListMF.oreUtil.blockID, 0, 8, 2, 0, 32); } if (cfg.spawnNitre) { addOreWithNeighbour(random, chunkX, chunkZ, world, BlockListMF.oreUtil.blockID, 1, 8, 4, 0, 64, Block.stone.blockID, 0); } if (cfg.spawnSulfur) { addOre(random, chunkX, chunkZ, world, BlockListMF.oreUtil.blockID, 2, 6, 3, 0, 16); } if (cfg.spawnCopper) { addOre(random, chunkX, chunkZ, world, BlockListMF.oreCopper.blockID, 0, 8, 10, 0, 96); } if (cfg.spawnTin) { addOre(random, chunkX, chunkZ, world, BlockListMF.oreTin.blockID, 0, 8, 7, 0, 96); } if (cfg.spawnMithril) { addRangedOre(random, chunkX, chunkZ, world, BlockListMF.oreMythic.blockID, 0, 6, 2, 0, 16, Block.stone.blockID, cfg.mithrilDistance); } if (cfg.spawnDeepIron) { addOre(random, chunkX, chunkZ, world, BlockListMF.oreMythic.blockID, 1, 8, 3, 0, 32); addOre(random, chunkX, chunkZ, world, BlockListMF.oreMythic.blockID, 2, 8, 5, 0, 128, Block.netherrack.blockID); } addOre(random, chunkX, chunkZ, world, BlockListMF.oreInferno.blockID, 0, 12, 10, 0, 128, Block.netherrack.blockID); addOre(random, chunkX, chunkZ, world, BlockListMF.oreInferno.blockID, 1, 10, 6, 0, 64, Block.netherrack.blockID); } catch(ConcurrentModificationException e) { System.err.println("MineFantasy: WorldGen Failed"); } } private void addOre(Random rand, int chunkX, int chunkZ, World world, int id, int meta, int size, int abundance, int min, int max) { addOre(rand, chunkX, chunkZ, world, id, meta, size, abundance, min, max, Block.stone.blockID); } private void addOre(Random rand, int chunkX, int chunkZ, World world, int id, int meta, int size, int abundance, int min, int max, int inside) { for(int a = 0; a < abundance; a ++) { int x = chunkX*16 + rand.nextInt(16); int y = min + rand.nextInt(max-min+1); int z = chunkZ*16 + rand.nextInt(16); (new WorldGenMinable(id, meta, size, inside)).generate(world, rand, x, y, z); } } private void addRangedOre(Random rand, int chunkX, int chunkZ, World world, int id, int meta, int size, int abundance, int min, int max, int inside, double range) { for(int a = 0; a < abundance; a ++) { int x = chunkX*16 + rand.nextInt(16); int y = min + rand.nextInt(max-min+1); int z = chunkZ*16 + rand.nextInt(16); if(getDistance(world, x, z) > range) { (new WorldGenMinable(id, meta, size, inside)).generate(world, rand, x, y, z); } } } private double getDistance(World world, int x, int z) { ChunkCoordinates spawn = world.getSpawnPoint(); int xd = x - spawn.posX; int zd = z - spawn.posZ; if(xd < 0)xd = -xd; if(zd < 0)zd = -zd; double dist = Math.hypot((double)xd, (double)zd); return dist; } private void addOreWithNeighbour(Random rand, int chunkX, int chunkZ, World world, int id, int meta, int size, int abundance, int min, int max, int inside, int neighbour) { for(int a = 0; a < abundance; a ++) { int x = chunkX*16 + rand.nextInt(16); int y = min + rand.nextInt(max-min+1); int z = chunkZ*16 + rand.nextInt(16); if(isNeibourNear(world, x, y, z, neighbour)) { if(neighbour == Block.lavaStill.blockID) { System.out.println("Gen By Lava: " + x + " " + y + " " + z); } (new WorldGenMinable(id, meta, size, inside)).generate(world, rand, x, y, z); } } } private boolean isNeibourNear(World world, int x, int y, int z, int neighbour) { return world.getBlockId(x-1, y, z) == neighbour || world.getBlockId(+1, y, z) == neighbour || world.getBlockId(x, y-1, z) == neighbour || world.getBlockId(x, y+1, z) == neighbour || world.getBlockId(x, y, z-1) == neighbour || world.getBlockId(x, y, z+1) == neighbour; } public void generateMisc(Random random, int chunkX, int chunkZ, World world) { try { if (random.nextInt(100) == 0) { for (int k = 0; k < 1; k++) { int k1 = chunkX*16 + random.nextInt(16); int k2 = random.nextInt(32); int k3 = chunkZ*16 + random.nextInt(16); (new WorldGenMinable(BlockListMF.granite.blockID, 128)) .generate(world, random, k1, k2, k3); } } if (cfg.generateSlate && random.nextInt(25) == 0) { for (int k = 0; k < 1; k++) { int k1 = chunkX*16 + random.nextInt(16); int k2 = random.nextInt(64); int k3 = chunkZ*16 + random.nextInt(16); (new WorldGenMinable(BlockListMF.slate.blockID, 0, 64, Block.stone.blockID)) .generate(world, random, k1, k2, k3); } } BiomeGenBase b = world.getBiomeGenForCoords(chunkX*16, chunkZ*16); if (BiomeDictionary.isBiomeOfType(b, Type.MOUNTAIN)) { for (int k = 0; k < 1; k++) { int k1 = chunkX*16 + random.nextInt(16); int k2 = random.nextInt(128); int k3 = chunkZ*16 + random.nextInt(16); (new WorldGenMinable(BlockListMF.granite.blockID, 64)) .generate(world, random, k1, k2, k3); } } if(cfg.spawnIBark) if(BiomeDictionary.isBiomeOfType(b, Type.JUNGLE)) { if(random.nextInt(100) < 15) for (int x = 0; x < 3+2; x++) { int Xcoord = chunkX*16 + random.nextInt(16); int Zcoord = chunkZ*16 + random.nextInt(16); int i2 = world.getHeightValue(Xcoord, Zcoord); new WorldGenIronbarkTree().generate(world, random, Xcoord, i2, Zcoord); //System.out.println("Gen Tree: " + b.biomeName); } } if(cfg.spawnIBark) if(BiomeDictionary.isBiomeOfType(b, Type.FOREST)) { if(random.nextInt(100) < 5) for (int x = 0; x < 3; x++) { int Xcoord = chunkX*16 + random.nextInt(16); int Zcoord = chunkZ*16 + random.nextInt(16); int i2 = world.getHeightValue(Xcoord, Zcoord); new WorldGenIronbarkTree().generate(world, random, Xcoord, i2, Zcoord); //System.out.println("Gen Tree: " + b.biomeName + " Gen " + Xcoord + " " + Zcoord + " Chunk " + chunkX + " " + chunkZ); } } if(cfg.spawnEbony) if(BiomeDictionary.isBiomeOfType(b, Type.JUNGLE)) { if(random.nextInt(100) < 1) { for (int x = 0; x < 1; x++) { int Xcoord = chunkX*16 + random.nextInt(16); int Zcoord = chunkZ*16 + random.nextInt(16); int i2 = world.getHeightValue(Xcoord, Zcoord); new WorldGenEbony(false).generate(world, random, Xcoord, i2, Zcoord); //System.out.println("Gen Tree: " + b.biomeName); } } } if(cfg.spawnEbony) if(BiomeDictionary.isBiomeOfType(b, Type.FOREST)) { if(random.nextInt(250) < 1) { for (int x = 0; x < 1; x++) { int Xcoord = chunkX*16 + random.nextInt(16); int Zcoord = chunkZ*16 + random.nextInt(16); int i2 = world.getHeightValue(Xcoord, Zcoord); new WorldGenEbony(false).generate(world, random, Xcoord, i2, Zcoord); //System.out.println("Gen Tree: " + b.biomeName + " Gen " + Xcoord + " " + Zcoord + " Chunk " + chunkX + " " + chunkZ); } } } if(BiomeDictionary.isBiomeOfType(b, Type.WATER)) { if(random.nextInt(100) < 10) for (int x = 0; x < 1; x++) { int Xcoord = chunkX*16 + random.nextInt(16); int Zcoord = chunkZ*16 + random.nextInt(16); int i2 = world.getHeightValue(Xcoord, Zcoord); new WorldGenLimestone(4, 8, 12).generate(world, random, Xcoord, i2, Zcoord); //System.out.println("Gen Tree: " + b.biomeName + " Gen " + Xcoord + " " + Zcoord + " Chunk " + chunkX + " " + chunkZ); } } if(BiomeDictionary.isBiomeOfType(b, Type.SWAMP)) { if(random.nextInt(100) < 8) for (int x = 0; x < 1; x++) { int Xcoord = chunkX*16 + random.nextInt(16); int Zcoord = chunkZ*16 + random.nextInt(16); int i2 = world.getHeightValue(Xcoord, Zcoord); new WorldGenLimestone(4, 5, 10).generate(world, random, Xcoord, i2, Zcoord); //System.out.println("Gen Tree: " + b.biomeName + " Gen " + Xcoord + " " + Zcoord + " Chunk " + chunkX + " " + chunkZ); } } if(BiomeDictionary.isBiomeOfType(b, Type.BEACH)) { if(random.nextInt(100) < 5) for (int x = 0; x < 1; x++) { int Xcoord = chunkX*16 + random.nextInt(16); int Zcoord = chunkZ*16 + random.nextInt(16); int i2 = world.getHeightValue(Xcoord, Zcoord); new WorldGenLimestone(4, 4, 8).generate(world, random, Xcoord, i2, Zcoord); //System.out.println("Gen Tree: " + b.biomeName + " Gen " + Xcoord + " " + Zcoord + " Chunk " + chunkX + " " + chunkZ); } } if (cfg.limeCavern && random.nextInt(480) == 0) { for (int k = 0; k < 1; k++) { int k1 = chunkX*16 + random.nextInt(16); int k2 = 32+random.nextInt(64); int k3 = chunkZ*16 + random.nextInt(16); (new WorldGenHole(48)) .generate(world, random, k1, k2+8, k3); (new WorldGenHole(64)) .generate(world, random, k1, k2, k3); (new WorldGenMinable(BlockListMF.limestone.blockID, 128)) .generate(world, random, k1, k2, k3); } } } catch(ConcurrentModificationException e) { System.err.println("MineFantasy: WorldGen Failed"); } } }
package mirror; import io.grpc.stub.CallStreamObserver; import io.grpc.stub.ServerCallStreamObserver; import io.grpc.stub.StreamObserver; /** * Provides flow control feedback to the application by blocking on {@code onNext} * if the underlying {@link CallStreamObserver} is not ready. * * Typically blocking a thread is considered bad form, e.g. you could block your client * UI thread or your server-side request-serving thread, but for Mirror's purposes, we * only write to BlockingStreamObserver from our own dedicated application threads. These * application threads are typically processing a queue, so blocking is actually what we * want to do, as then the work will build up in the queue. */ class BlockingStreamObserver<T> implements StreamObserver<T> { private final CallStreamObserver<T> delegate; private final Object lock = new Object(); BlockingStreamObserver(CallStreamObserver<T> delegate) { this.delegate = delegate; final Runnable notifyAll = () -> { synchronized (lock) { lock.notifyAll(); // wake up our thread } }; this.delegate.setOnReadyHandler(notifyAll); if (delegate instanceof ServerCallStreamObserver) { ((ServerCallStreamObserver<T>) delegate).setOnCancelHandler(notifyAll); } } @Override public void onNext(T value) { synchronized (lock) { // in theory we could implement ServerCallStreamObserver and expose isCancelled to our client, // but for current purposes we only need the StreamObserver API, so treat a cancelled observer // as something we just want to un-block from and return, and we'll trust the rest of our session // to shutdown accordingly. if (delegate instanceof ServerCallStreamObserver && ((ServerCallStreamObserver<T>) delegate).isCancelled()) { return; } while (!delegate.isReady()) { try { lock.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } } } delegate.onNext(value); } @Override public void onError(Throwable t) { delegate.onError(t); } @Override public void onCompleted() { delegate.onCompleted(); } }
package net.intelie.disq; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public class DiskRawQueue implements RawQueue { public static final int FAILED_READ_THRESHOLD = 64; private static final Logger LOGGER = LoggerFactory.getLogger(DiskRawQueue.class); private final long maxSize; private final long dataFileLimit; private final boolean flushOnRead; private final boolean flushOnWrite; private final boolean deleteOldestOnOverflow; private boolean temp; private Path directory; private boolean closed = false; private StateFile state; private DataFileReader reader; private DataFileWriter writer; private int failedReads = 0; private long flushCount = 0; public DiskRawQueue(Path directory, long maxSize) { this(directory, maxSize, true, true, true); } public DiskRawQueue(Path directory, long maxSize, boolean flushOnPop, boolean flushOnPush, boolean deleteOldestOnOverflow) { this.directory = directory; this.maxSize = Math.max(Math.min(maxSize, StateFile.MAX_QUEUE_SIZE), StateFile.MIN_QUEUE_SIZE); this.dataFileLimit = Math.max(512, this.maxSize / StateFile.MAX_FILES + (this.maxSize % StateFile.MAX_FILES > 0 ? 1 : 0)); this.flushOnRead = flushOnPop; this.flushOnWrite = flushOnPush; this.deleteOldestOnOverflow = deleteOldestOnOverflow; this.temp = false; reopen(); } @Override public synchronized void reopen() { internalClose(); closed = false; } public Path path() { return directory; } private void internalOpen() throws IOException { internalClose(); if (this.directory == null) { this.directory = Files.createTempDirectory("disq"); this.temp = true; } Files.createDirectories(this.directory); this.state = new StateFile(this.directory.resolve("state")); this.writer = null; this.reader = null; gc(); } private synchronized boolean safeTouch() { try { touch(); return true; } catch (Throwable e) { return false; } } public synchronized void touch() throws IOException { checkNotClosed(); if (state == null) internalOpen(); } private void checkNotClosed() { if (closed) throw new IllegalStateException("This queue is already closed."); } @Override public synchronized long bytes() { if (!safeTouch()) return 0; return state.getBytes(); } @Override public synchronized long count() { if (!safeTouch()) return 0; return state.getCount(); } public synchronized long files() { if (!safeTouch()) return 0; return state.getNumberOfFiles(); } @Override public synchronized long remainingBytes() { if (!safeTouch()) return 0; return maxSize - state.getBytes(); } public long flushCount() { return flushCount; } @Override public synchronized long remainingCount() { if (!safeTouch()) return 0; if (state.getCount() == 0) return maxSize / 4; double bytesPerElement = state.getBytes() / (double) state.getCount(); return (long) ((maxSize - state.getBytes()) / bytesPerElement); } @Override public synchronized void clear() throws IOException { touch(); state.clear(); internalFlush(); reopen(); } @Override public synchronized boolean pop(Buffer buffer) throws IOException { touch(); if (!checkFailedReads()) return false; if (checkReadEOF()) return false; int read = innerRead(buffer); state.addReadCount(read); if (flushOnRead) internalFlush(); checkReadEOF(); return true; } private boolean checkFailedReads() throws IOException { if (failedReads >= FAILED_READ_THRESHOLD) { LOGGER.info("Detected corrupted file #{}, backing up and moving on.", state.getReadFile()); boolean wasSame = state.sameFileReadWrite(); deleteOldestFile(true); if (wasSame) { clear(); return false; } } return true; } private int innerRead(Buffer buffer) throws IOException { try { int read = reader().read(buffer); failedReads = 0; return read; } catch (Throwable e) { failedReads++; throw e; } } @Override public synchronized boolean peek(Buffer buffer) throws IOException { touch(); if (checkReadEOF()) return false; reader().peek(buffer); return true; } private void deleteOldestFile(boolean renameFile) throws IOException { int currentFile = state.getReadFile(); state.advanceReadFile(reader().size()); reader.close(); failedReads = 0; internalFlush(); reader = null; tryDeleteFile(currentFile, renameFile); } @Override public synchronized boolean push(Buffer buffer) throws IOException { touch(); checkWriteEOF(); if (checkFutureQueueOverflow(buffer.count())) return false; int written = writer().write(buffer); state.addWriteCount(written); if (flushOnWrite) internalFlush(); checkWriteEOF(); return true; } private boolean checkFutureQueueOverflow(int count) throws IOException { if (deleteOldestOnOverflow) { while (!state.sameFileReadWrite() && willOverflow(count)) deleteOldestFile(false); return false; } else { return willOverflow(count); } } @Override public synchronized void flush() throws IOException { touch(); internalFlush(); } private void internalFlush() throws IOException { if (writer != null) writer.flush(); state.flush(); flushCount++; } @Override public synchronized void close() { closed = true; internalClose(); } private void internalClose() { Lenient.safeClose(reader); reader = null; Lenient.safeClose(writer); writer = null; Lenient.safeClose(state); state = null; if (temp) { Lenient.safeDelete(directory); directory = null; temp = false; } } private boolean willOverflow(int count) throws IOException { return bytes() + count + DataFileWriter.OVERHEAD > maxSize || files() >= StateFile.MAX_FILES; } private boolean checkReadEOF() throws IOException { while (!state.sameFileReadWrite() && state.readFileEof()) deleteOldestFile(false); if (state.needsFlushBeforePop()) internalFlush(); return state.getCount() == 0; } private DataFileReader reader() throws IOException { return reader != null ? reader : (reader = openReader()); } private void checkWriteEOF() throws IOException { if (state.getWritePosition() >= dataFileLimit) advanceWriteFile(); } private DataFileWriter writer() throws IOException { return writer != null ? writer : (writer = openWriter()); } private void advanceWriteFile() throws IOException { writer().close(); state.advanceWriteFile(); internalFlush(); writer = null; } private void gc() throws IOException { Path file = makeDataPath(state.getReadFile()); boolean shouldFlush = false; while (!Files.exists(file) && !state.sameFileReadWrite()) { state.advanceReadFile(0); file = makeDataPath(state.getReadFile()); shouldFlush = true; } long totalBytes = 0; long totalCount = 0; for (int i = 0; i < StateFile.MAX_FILES; i++) { Path path = makeDataPath(i); if (Files.exists(path)) { if (!state.isInUse(i)) { tryDeleteFile(i, false); } else { totalBytes += Files.size(path); totalCount += state.getFileCount(i); } } } shouldFlush |= state.fixCounts(totalCount, totalBytes); if (shouldFlush) internalFlush(); } private void tryDeleteFile(int file, boolean renameFile) { Path from = makeDataPath(file); try { if (renameFile) { Path to = makeCorruptedPath(file); LOGGER.info("Backing up {} as {}", from, to); Files.move(from, to); } else { Files.delete(from); } } catch (Exception e) { LOGGER.info("Unable to delete file {}", from); LOGGER.info("Stacktrace", e); } } private Path makeDataPath(int state) { return directory.resolve(String.format("data%02x", state)); } private Path makeCorruptedPath(int state) { return directory.resolve(String.format("data%02x.%d.corrupted", state, System.currentTimeMillis())); } private DataFileReader openReader() throws IOException { return new DataFileReader(makeDataPath(state.getReadFile()), state.getReadPosition()); } private DataFileWriter openWriter() throws IOException { Files.createDirectories(directory); return new DataFileWriter(makeDataPath(state.getWriteFile()), state.getWritePosition()); } }
package net.jodah.recurrent; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import net.jodah.recurrent.internal.util.Assert; /** * Performs invocations with synchronous or asynchronous retries according to a {@link RetryPolicy}. Asynchronous * retries can optionally be performed on a {@link ContextualRunnable} or {@link ContextualCallable} which allow * invocations to be manually retried or completed. * * @author Jonathan Halterman */ public class Recurrent { Recurrent() { } /** * Invokes the {@code callable}, scheduling retries with the {@code executor} according to the {@code retryPolicy}. * * @throws NullPointerException if any argument is null */ public static <T> java.util.concurrent.CompletableFuture<T> future( Callable<java.util.concurrent.CompletableFuture<T>> callable, RetryPolicy retryPolicy, ScheduledExecutorService executor) { return future(callable, retryPolicy, Schedulers.of(executor)); } /** * Invokes the {@code callable}, scheduling retries with the {@code executor} according to the {@code retryPolicy}. * * @throws NullPointerException if any argument is null */ public static <T> java.util.concurrent.CompletableFuture<T> future( Callable<java.util.concurrent.CompletableFuture<T>> callable, RetryPolicy retryPolicy, ScheduledExecutorService executor, AsyncListeners<T> listeners) { return future(callable, retryPolicy, Schedulers.of(executor), listeners); } /** * Invokes the {@code callable}, scheduling retries with the {@code scheduler} according to the {@code retryPolicy}. * * @throws NullPointerException if any argument is null */ public static <T> java.util.concurrent.CompletableFuture<T> future( Callable<java.util.concurrent.CompletableFuture<T>> callable, RetryPolicy retryPolicy, Scheduler scheduler) { final java.util.concurrent.CompletableFuture<T> response = new java.util.concurrent.CompletableFuture<T>(); call(AsyncCallable.ofFuture(callable), retryPolicy, scheduler, RecurrentFuture.of(response, scheduler, null), null); return response; } /** * Invokes the {@code callable}, scheduling retries with the {@code scheduler} according to the {@code retryPolicy}. * * @throws NullPointerException if any argument is null */ public static <T> java.util.concurrent.CompletableFuture<T> future( Callable<java.util.concurrent.CompletableFuture<T>> callable, RetryPolicy retryPolicy, Scheduler scheduler, AsyncListeners<T> listeners) { Assert.notNull(listeners, "listeners"); final java.util.concurrent.CompletableFuture<T> response = new java.util.concurrent.CompletableFuture<T>(); call(AsyncCallable.ofFuture(callable), retryPolicy, scheduler, RecurrentFuture.of(response, scheduler, listeners), listeners); return response; } /** * Invokes the {@code callable}, scheduling retries with the {@code executor} according to the {@code retryPolicy}. * Allows asynchronous invocations to manually perform retries or completion via the {@code callable}'s * {@link AsyncInvocation} reference. * <p> * If the {@code callable} throws an exception or its resulting future is completed with an exception, the invocation * will be retried automatically, else if the {@code retryPolicy} has been exceeded the resulting future will be * completed exceptionally. * <p> * For non-exceptional results, retries or completion can be performed manually via the {@code callable}'s * {@link AsyncInvocation} reference. * * @throws NullPointerException if any argument is null */ public static <T> java.util.concurrent.CompletableFuture<T> future( ContextualCallable<java.util.concurrent.CompletableFuture<T>> callable, RetryPolicy retryPolicy, ScheduledExecutorService executor) { return future(callable, retryPolicy, Schedulers.of(executor)); } /** * Invokes the {@code callable}, scheduling retries with the {@code executor} according to the {@code retryPolicy}. * Allows asynchronous invocations to manually perform retries or completion via the {@code callable}'s * {@link AsyncInvocation} reference. * <p> * If the {@code callable} throws an exception or its resulting future is completed with an exception, the invocation * will be retried automatically, else if the {@code retryPolicy} has been exceeded the resulting future will be * completed exceptionally. * <p> * For non-exceptional results, retries or completion can be performed manually via the {@code callable}'s * {@link AsyncInvocation} reference. * * @throws NullPointerException if any argument is null */ public static <T> java.util.concurrent.CompletableFuture<T> future( ContextualCallable<java.util.concurrent.CompletableFuture<T>> callable, RetryPolicy retryPolicy, ScheduledExecutorService executor, AsyncListeners<T> listeners) { return future(callable, retryPolicy, Schedulers.of(executor), listeners); } /** * Invokes the {@code callable}, scheduling retries with the {@code scheduler} according to the {@code retryPolicy}. * Allows asynchronous invocations to manually perform retries or completion via the {@code callable}'s * {@link AsyncInvocation} reference. * <p> * If the {@code callable} throws an exception or its resulting future is completed with an exception, the invocation * will be retried automatically, else if the {@code retryPolicy} has been exceeded the resulting future will be * completed exceptionally. * <p> * For non-exceptional results, retries or completion can be performed manually via the {@code callable}'s * {@link AsyncInvocation} reference. * * @throws NullPointerException if any argument is null */ public static <T> java.util.concurrent.CompletableFuture<T> future( ContextualCallable<java.util.concurrent.CompletableFuture<T>> callable, RetryPolicy retryPolicy, Scheduler scheduler) { final java.util.concurrent.CompletableFuture<T> response = new java.util.concurrent.CompletableFuture<T>(); call(AsyncCallable.ofFuture(callable), retryPolicy, scheduler, RecurrentFuture.of(response, scheduler, null), null); return response; } /** * Invokes the {@code callable}, scheduling retries with the {@code scheduler} according to the {@code retryPolicy}. * Allows asynchronous invocations to manually perform retries or completion via the {@code callable}'s * {@link AsyncInvocation} reference. * <p> * If the {@code callable} throws an exception or its resulting future is completed with an exception, the invocation * will be retried automatically, else if the {@code retryPolicy} has been exceeded the resulting future will be * completed exceptionally. * <p> * For non-exceptional results, retries or completion can be performed manually via the {@code callable}'s * {@link AsyncInvocation} reference. * * @throws NullPointerException if any argument is null */ public static <T> java.util.concurrent.CompletableFuture<T> future( ContextualCallable<java.util.concurrent.CompletableFuture<T>> callable, RetryPolicy retryPolicy, Scheduler scheduler, AsyncListeners<T> listeners) { Assert.notNull(listeners, "listeners"); final java.util.concurrent.CompletableFuture<T> response = new java.util.concurrent.CompletableFuture<T>(); call(AsyncCallable.ofFuture(callable), retryPolicy, scheduler, RecurrentFuture.of(response, scheduler, listeners), listeners); return response; } /** * Invokes the {@code callable}, sleeping between invocation attempts according to the {@code retryPolicy}. * * @throws NullPointerException if any argument is null * @throws RecurrentException if the {@code callable} fails with a Throwable and the retry policy is exceeded or if * interrupted while waiting to perform a retry. */ public static <T> T get(Callable<T> callable, RetryPolicy retryPolicy) { return call(callable, retryPolicy, null); } /** * Invokes the {@code callable}, sleeping between invocation attempts according to the {@code retryPolicy}, and * calling the {@code listeners} on recurrent events. * * @throws NullPointerException if any argument is null * @throws RecurrentException if the {@code callable} fails with a Throwable and the retry policy is exceeded or if * interrupted while waiting to perform a retry. */ public static <T> T get(Callable<T> callable, RetryPolicy retryPolicy, Listeners<T> listeners) { return call(callable, retryPolicy, Assert.notNull(listeners, "listeners")); } /** * Invokes the {@code callable}, scheduling retries with the {@code executor} according to the {@code retryPolicy}. * * @throws NullPointerException if any argument is null */ public static <T> RecurrentFuture<T> get(Callable<T> callable, RetryPolicy retryPolicy, ScheduledExecutorService executor) { return call(AsyncCallable.of(callable), retryPolicy, Schedulers.of(executor), null, null); } /** * Invokes the {@code callable}, scheduling retries with the {@code executor} according to the {@code retryPolicy}. * * @throws NullPointerException if any argument is null */ public static <T> RecurrentFuture<T> get(Callable<T> callable, RetryPolicy retryPolicy, ScheduledExecutorService executor, AsyncListeners<T> listeners) { return call(AsyncCallable.of(callable), retryPolicy, Schedulers.of(executor), null, Assert.notNull(listeners, "listeners")); } /** * Invokes the {@code callable}, scheduling retries with the {@code scheduler} according to the {@code retryPolicy}. * * @throws NullPointerException if any argument is null */ public static <T> RecurrentFuture<T> get(Callable<T> callable, RetryPolicy retryPolicy, Scheduler scheduler) { return call(AsyncCallable.of(callable), retryPolicy, scheduler, null, null); } /** * Invokes the {@code callable}, scheduling retries with the {@code scheduler} according to the {@code retryPolicy}. * * @throws NullPointerException if any argument is null */ public static <T> RecurrentFuture<T> get(Callable<T> callable, RetryPolicy retryPolicy, Scheduler scheduler, AsyncListeners<T> listeners) { return call(AsyncCallable.of(callable), retryPolicy, scheduler, null, Assert.notNull(listeners, "listeners")); } /** * Invokes the {@code callable}, scheduling retries with the {@code executor} according to the {@code retryPolicy}. * Allows asynchronous invocations to manually perform retries or completion via the {@code callable}'s * {@link AsyncInvocation} reference. * <p> * If the {@code callable} throws an exception, the invocation will be retried automatically, else if the * {@code retryPolicy} has been exceeded the resulting future will be completed exceptionally. * <p> * For non-exceptional results, retries or completion can be performed manually via the {@code callable}'s * {@link AsyncInvocation} reference. * * @throws NullPointerException if any argument is null */ public static <T> RecurrentFuture<T> get(ContextualCallable<T> callable, RetryPolicy retryPolicy, ScheduledExecutorService executor) { return call(AsyncCallable.of(callable), retryPolicy, Schedulers.of(executor), null, null); } /** * Invokes the {@code callable}, scheduling retries with the {@code executor} according to the {@code retryPolicy}. * Allows asynchronous invocations to manually perform retries or completion via the {@code callable}'s * {@link AsyncInvocation} reference. * <p> * If the {@code callable} throws an exception, the invocation will be retried automatically, else if the * {@code retryPolicy} has been exceeded the resulting future will be completed exceptionally. * <p> * For non-exceptional results, retries or completion can be performed manually via the {@code callable}'s * {@link AsyncInvocation} reference. * * @throws NullPointerException if any argument is null */ public static <T> RecurrentFuture<T> get(ContextualCallable<T> callable, RetryPolicy retryPolicy, ScheduledExecutorService executor, AsyncListeners<T> listeners) { return call(AsyncCallable.of(callable), retryPolicy, Schedulers.of(executor), null, Assert.notNull(listeners, "listeners")); } /** * Invokes the {@code callable}, scheduling retries with the {@code scheduler} according to the {@code retryPolicy}. * Allows asynchronous invocations to manually perform retries or completion via the {@code callable}'s * {@link AsyncInvocation} reference. * <p> * If the {@code callable} throws an exception, the invocation will be retried automatically, else if the * {@code retryPolicy} has been exceeded the resulting future will be completed exceptionally. * <p> * For non-exceptional results, retries or completion can be performed manually via the {@code callable}'s * {@link AsyncInvocation} reference. * * @throws NullPointerException if any argument is null */ public static <T> RecurrentFuture<T> get(ContextualCallable<T> callable, RetryPolicy retryPolicy, Scheduler scheduler) { return call(AsyncCallable.of(callable), retryPolicy, scheduler, null, null); } /** * Invokes the {@code callable}, scheduling retries with the {@code scheduler} according to the {@code retryPolicy}. * Allows asynchronous invocations to manually perform retries or completion via the {@code callable}'s * {@link AsyncInvocation} reference. * <p> * If the {@code callable} throws an exception, the invocation will be retried automatically, else if the * {@code retryPolicy} has been exceeded the resulting future will be completed exceptionally. * <p> * For non-exceptional results, retries or completion can be performed manually via the {@code callable}'s * {@link AsyncInvocation} reference. * * @throws NullPointerException if any argument is null */ public static <T> RecurrentFuture<T> get(ContextualCallable<T> callable, RetryPolicy retryPolicy, Scheduler scheduler, AsyncListeners<T> listeners) { return call(AsyncCallable.of(callable), retryPolicy, scheduler, null, Assert.notNull(listeners, "listeners")); } /** * Invokes the {@code runnable}, scheduling retries with the {@code executor} according to the {@code retryPolicy}. * Allows asynchronous invocations to manually perform retries or completion via the {@code runnable}'s * {@link AsyncInvocation} reference. * <p> * If the {@code runnable} throws an exception, the invocation will be retried automatically, else if the * {@code retryPolicy} has been exceeded the resulting future will be completed exceptionally. * <p> * For non-exceptional results, retries or completion can be performed manually via the {@code runnable}'s * {@link AsyncInvocation} reference. * * @throws NullPointerException if any argument is null */ public static RecurrentFuture<?> run(ContextualRunnable runnable, RetryPolicy retryPolicy, ScheduledExecutorService executor) { return call(AsyncCallable.of(runnable), retryPolicy, Schedulers.of(executor), null, null); } /** * Invokes the {@code runnable}, scheduling retries with the {@code executor} according to the {@code retryPolicy}. * Allows asynchronous invocations to manually perform retries or completion via the {@code runnable}'s * {@link AsyncInvocation} reference. * <p> * If the {@code runnable} throws an exception, the invocation will be retried automatically, else if the * {@code retryPolicy} has been exceeded the resulting future will be completed exceptionally. * <p> * For non-exceptional results, retries or completion can be performed manually via the {@code runnable}'s * {@link AsyncInvocation} reference. * * @throws NullPointerException if any argument is null */ public static <T> RecurrentFuture<T> run(ContextualRunnable runnable, RetryPolicy retryPolicy, ScheduledExecutorService executor, AsyncListeners<T> listeners) { return call(AsyncCallable.<T>of(runnable), retryPolicy, Schedulers.of(executor), null, Assert.notNull(listeners, "listeners")); } /** * Invokes the {@code runnable}, scheduling retries with the {@code scheduler} according to the {@code retryPolicy}. * Allows asynchronous invocations to manually perform retries or completion via the {@code runnable}'s * {@link AsyncInvocation} reference. * <p> * If the {@code runnable} throws an exception, the invocation will be retried automatically, else if the * {@code retryPolicy} has been exceeded the resulting future will be completed exceptionally. * <p> * For non-exceptional results, retries or completion can be performed manually via the {@code runnable}'s * {@link AsyncInvocation} reference. * * @throws NullPointerException if any argument is null */ public static RecurrentFuture<?> run(ContextualRunnable runnable, RetryPolicy retryPolicy, Scheduler scheduler) { return call(AsyncCallable.of(runnable), retryPolicy, scheduler, null, null); } /** * Invokes the {@code runnable}, scheduling retries with the {@code scheduler} according to the {@code retryPolicy}. * Allows asynchronous invocations to manually perform retries or completion via the {@code runnable}'s * {@link AsyncInvocation} reference. * <p> * If the {@code runnable} throws an exception, the invocation will be retried automatically, else if the * {@code retryPolicy} has been exceeded the resulting future will be completed exceptionally. * <p> * For non-exceptional results, retries or completion can be performed manually via the {@code runnable}'s * {@link AsyncInvocation} reference. * * @throws NullPointerException if any argument is null */ public static <T> RecurrentFuture<T> run(ContextualRunnable runnable, RetryPolicy retryPolicy, Scheduler scheduler, AsyncListeners<T> listeners) { return call(AsyncCallable.<T>of(runnable), retryPolicy, scheduler, null, Assert.notNull(listeners, "listeners")); } /** * Invokes the {@code runnable}, sleeping between invocation attempts according to the {@code retryPolicy}. * * @throws NullPointerException if any argument is null * @throws RecurrentException if the {@code callable} fails with a Throwable and the retry policy is exceeded or if * interrupted while waiting to perform a retry. */ public static void run(CheckedRunnable runnable, RetryPolicy retryPolicy) { call(Callables.of(runnable), retryPolicy, null); } /** * Invokes the {@code runnable}, sleeping between invocation attempts according to the {@code retryPolicy}, and * calling the {@code listeners} on recurrent events. * * @throws NullPointerException if any argument is null * @throws RecurrentException if the {@code callable} fails with a Throwable and the retry policy is exceeded or if * interrupted while waiting to perform a retry. */ @SuppressWarnings("unchecked") public static void run(CheckedRunnable runnable, RetryPolicy retryPolicy, Listeners<?> listeners) { call(Callables.of(runnable), retryPolicy, (Listeners<Object>) Assert.notNull(listeners, "listeners")); } /** * Invokes the {@code runnable}, scheduling retries with the {@code executor} according to the {@code retryPolicy}. * * @throws NullPointerException if any argument is null */ public static RecurrentFuture<?> run(CheckedRunnable runnable, RetryPolicy retryPolicy, ScheduledExecutorService executor) { return call(AsyncCallable.of(runnable), retryPolicy, Schedulers.of(executor), null, null); } /** * Invokes the {@code runnable}, scheduling retries with the {@code executor} according to the {@code retryPolicy}. * * @throws NullPointerException if any argument is null */ public static <T> RecurrentFuture<T> run(CheckedRunnable runnable, RetryPolicy retryPolicy, ScheduledExecutorService executor, AsyncListeners<T> listeners) { return call(AsyncCallable.<T>of(runnable), retryPolicy, Schedulers.of(executor), null, Assert.notNull(listeners, "listeners")); } /** * Invokes the {@code runnable}, scheduling retries with the {@code scheduler} according to the {@code retryPolicy}. * * @throws NullPointerException if any argument is null */ public static RecurrentFuture<?> run(CheckedRunnable runnable, RetryPolicy retryPolicy, Scheduler scheduler) { return call(AsyncCallable.of(runnable), retryPolicy, scheduler, null, null); } /** * Invokes the {@code runnable}, scheduling retries with the {@code scheduler} according to the {@code retryPolicy}. * * @throws NullPointerException if any argument is null * @throws RecurrentException if the {@code callable} fails with a Throwable and the retry policy is exceeded or if * interrupted while waiting to perform a retry. */ public static <T> RecurrentFuture<T> run(CheckedRunnable runnable, RetryPolicy retryPolicy, Scheduler scheduler, AsyncListeners<T> listeners) { return call(AsyncCallable.<T>of(runnable), retryPolicy, scheduler, null, Assert.notNull(listeners, "listeners")); } /** * Calls the {@code callable} via the {@code executor}, performing retries according to the {@code retryPolicy}. * * @throws NullPointerException if any argument is null */ @SuppressWarnings("unchecked") private static <T> RecurrentFuture<T> call(final AsyncCallable<T> callable, final RetryPolicy retryPolicy, Scheduler scheduler, RecurrentFuture<T> future, AsyncListeners<T> listeners) { Assert.notNull(callable, "callable"); Assert.notNull(retryPolicy, "retryPolicy"); Assert.notNull(scheduler, "scheduler"); if (future == null) future = new RecurrentFuture<T>(scheduler, listeners); AsyncInvocation invocation = new AsyncInvocation(callable, retryPolicy, scheduler, future, listeners); future.initialize(invocation); callable.initialize(invocation); future.setFuture((Future<T>) scheduler.schedule(callable, 0, TimeUnit.MILLISECONDS)); return future; } /** * Calls the {@code callable} synchronously, performing retries according to the {@code retryPolicy}. * * @throws RecurrentException if the {@code callable} fails with a Throwable and the retry policy is exceeded or if * interrupted while waiting to perform a retry. */ private static <T> T call(Callable<T> callable, RetryPolicy retryPolicy, Listeners<T> listeners) { Assert.notNull(callable, "callable"); Assert.notNull(retryPolicy, "retryPolicy"); Invocation invocation = new Invocation(retryPolicy); T result = null; Throwable failure; while (true) { try { failure = null; result = callable.call(); } catch (Throwable t) { failure = t; } boolean completed = invocation.complete(result, failure, true); boolean success = completed && failure == null; boolean shouldRetry = completed ? false : invocation.canRetryForInternal(result, failure); // Handle failure if (!success && listeners != null) listeners.handleFailedAttempt(result, failure, invocation); // Handle retry needed if (shouldRetry) { try { Thread.sleep(TimeUnit.NANOSECONDS.toMillis(invocation.waitTime)); } catch (InterruptedException e) { throw new RecurrentException(e); } if (listeners != null) listeners.handleRetry(result, failure, invocation); } // Handle completion if (completed || !shouldRetry) { if (listeners != null) listeners.complete(result, failure, invocation, success); if (success || failure == null) return result; RecurrentException re = failure instanceof RecurrentException ? (RecurrentException) failure : new RecurrentException(failure); throw re; } } } }
package nl.mpi.kinnate.svg; import nl.mpi.kinnate.ui.GraphPanelContextMenu; import nl.mpi.kinnate.ui.KinTypeEgoSelectionTestPanel; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.geom.AffineTransform; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import javax.swing.JPanel; import nl.mpi.arbil.GuiHelper; import nl.mpi.arbil.ImdiTableModel; import nl.mpi.arbil.clarin.CmdiComponentBuilder; import nl.mpi.kinnate.entityindexer.IndexerParameters; import nl.mpi.kinnate.SavePanel; import nl.mpi.kinnate.kintypestrings.KinTerms; import org.apache.batik.bridge.UpdateManager; import org.apache.batik.dom.svg.SAXSVGDocumentFactory; import org.apache.batik.dom.svg.SVGDOMImplementation; import org.apache.batik.swing.JSVGCanvas; import org.apache.batik.swing.JSVGScrollPane; import org.apache.batik.util.XMLResourceDescriptor; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; import org.w3c.dom.events.EventTarget; import org.w3c.dom.svg.SVGDocument; import org.w3c.dom.svg.SVGLocatable; import org.w3c.dom.svg.SVGRect; public class GraphPanel extends JPanel implements SavePanel { private JSVGScrollPane jSVGScrollPane; protected JSVGCanvas svgCanvas; private SVGDocument doc; private KinTerms kinTerms; protected ImdiTableModel imdiTableModel; private GraphData graphData; private boolean requiresSave = false; private File svgFile = null; private GraphPanelSize graphPanelSize; protected ArrayList<String> selectedGroupElement; private String svgNameSpace = SVGDOMImplementation.SVG_NAMESPACE_URI; private DataStoreSvg dataStoreSvg; public GraphPanel(KinTypeEgoSelectionTestPanel egoSelectionPanel) { dataStoreSvg = new DataStoreSvg(); selectedGroupElement = new ArrayList<String>(); graphPanelSize = new GraphPanelSize(); kinTerms = new KinTerms(); this.setLayout(new BorderLayout()); svgCanvas = new JSVGCanvas(); // svgCanvas.setMySize(new Dimension(600, 400)); svgCanvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC); // drawNodes(); svgCanvas.setEnableImageZoomInteractor(false); svgCanvas.setEnablePanInteractor(false); svgCanvas.setEnableRotateInteractor(false); svgCanvas.setEnableZoomInteractor(false); svgCanvas.addMouseWheelListener(new MouseWheelListener() { public void mouseWheelMoved(MouseWheelEvent e) { AffineTransform at = new AffineTransform(); // System.out.println("R: " + e.getWheelRotation()); // System.out.println("A: " + e.getScrollAmount()); // System.out.println("U: " + e.getUnitsToScroll()); at.scale(1 + e.getUnitsToScroll() / 10.0, 1 + e.getUnitsToScroll() / 10.0); // at.translate(e.getX()/10.0, e.getY()/10.0); // System.out.println("x: " + e.getX()); // System.out.println("y: " + e.getY()); at.concatenate(svgCanvas.getRenderingTransform()); svgCanvas.setRenderingTransform(at); } }); // svgCanvas.setEnableResetTransformInteractor(true); // svgCanvas.setDoubleBufferedRendering(true); // todo: look into reducing the noticable aliasing on the canvas MouseListenerSvg mouseListenerSvg = new MouseListenerSvg(this); svgCanvas.addMouseListener(mouseListenerSvg); svgCanvas.addMouseMotionListener(mouseListenerSvg); jSVGScrollPane = new JSVGScrollPane(svgCanvas); this.add(BorderLayout.CENTER, jSVGScrollPane); svgCanvas.setComponentPopupMenu(new GraphPanelContextMenu(egoSelectionPanel, this, graphPanelSize)); } public void setImdiTableModel(ImdiTableModel imdiTableModelLocal) { imdiTableModel = imdiTableModelLocal; } public void readSvg(File svgFilePath) { svgFile = svgFilePath; String parser = XMLResourceDescriptor.getXMLParserClassName(); SAXSVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(parser); try { doc = (SVGDocument) documentFactory.createDocument(svgFilePath.toURI().toString()); svgCanvas.setDocument(doc); requiresSave = false; } catch (IOException ioe) { GuiHelper.linorgBugCatcher.logError(ioe); } // svgCanvas.setURI(svgFilePath.toURI().toString()); dataStoreSvg.loadDataFromSvg(doc); } private void saveSvg(File svgFilePath) { svgFile = svgFilePath; new CmdiComponentBuilder().savePrettyFormatting(doc, svgFilePath); requiresSave = false; } private void printNodeNames(Node nodeElement) { System.out.println(nodeElement.getLocalName()); System.out.println(nodeElement.getNamespaceURI()); Node childNode = nodeElement.getFirstChild(); while (childNode != null) { printNodeNames(childNode); childNode = childNode.getNextSibling(); } } public String[] getKinTypeStrigs() { return dataStoreSvg.kinTypeStrings; } public void setKinTypeStrigs(String[] kinTypeStringArray) { // strip out any white space, blank lines and remove duplicates HashSet<String> kinTypeStringSet = new HashSet<String>(); for (String kinTypeString : kinTypeStringArray) { if (kinTypeString != null && kinTypeString.trim().length() > 0) { kinTypeStringSet.add(kinTypeString.trim()); } } dataStoreSvg.kinTypeStrings = kinTypeStringSet.toArray(new String[]{}); } public IndexerParameters getIndexParameters() { return dataStoreSvg.indexParameters; } public KinTerms getkinTerms() { return kinTerms; } public String[] getEgoUniquiIdentifiersList() { return dataStoreSvg.egoIdentifierSet.toArray(new String[]{}); } public URI[] getEgoList() { return dataStoreSvg.egoSet.toArray(new URI[]{}); } public void setEgoList(URI[] egoListArray, String[] egoIdentifierArray) { dataStoreSvg.egoSet = new HashSet<URI>(Arrays.asList(egoListArray)); dataStoreSvg.egoIdentifierSet = new HashSet<String>(Arrays.asList(egoIdentifierArray)); } public String[] getSelectedPaths() { return selectedGroupElement.toArray(new String[]{}); } public void resetZoom() { AffineTransform at = new AffineTransform(); at.scale(1, 1); at.setToTranslation(1, 1); svgCanvas.setRenderingTransform(at); } public void drawNodes() { drawNodes(graphData); } protected void updateDragNode(final int updateDragNodeX, final int updateDragNodeY) { UpdateManager updateManager = svgCanvas.getUpdateManager(); updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() { public void run() { System.out.println("updateDragNodeX: " + updateDragNodeX); System.out.println("updateDragNodeY: " + updateDragNodeY); if (doc != null) { for (String entityId : selectedGroupElement) { new EntitySvg().moveEntity(doc, entityId, updateDragNodeX, updateDragNodeY); } // Element entityGroup = doc.getElementById("EntityGroup"); // for (Node currentChild = entityGroup.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) { // if ("g".equals(currentChild.getLocalName())) { // Node idAttrubite = currentChild.getAttributes().getNamedItem("id"); // if (idAttrubite != null) { // String entityPath = idAttrubite.getTextContent(); // if (selectedGroupElement.contains(entityPath)) { // SVGRect bbox = ((SVGLocatable) currentChild).getBBox(); //// ((SVGLocatable) currentDraggedElement).g // // drageboth x and y //// ((Element) currentChild).setAttribute("transform", "translate(" + String.valueOf(updateDragNodeX * svgCanvas.getRenderingTransform().getScaleX() - bbox.getX()) + ", " + String.valueOf(updateDragNodeY - bbox.getY()) + ")"); // // limit drag to x only // ((Element) currentChild).setAttribute("transform", "translate(" + String.valueOf(updateDragNodeX * svgCanvas.getRenderingTransform().getScaleX() - bbox.getX()) + ", 0)"); //// updateDragNodeElement.setAttribute("x", String.valueOf(updateDragNodeX)); //// updateDragNodeElement.setAttribute("y", String.valueOf(updateDragNodeY)); // // SVGRect bbox = ((SVGLocatable) currentDraggedElement).getBBox(); //// System.out.println("bbox X: " + bbox.getX()); //// System.out.println("bbox Y: " + bbox.getY()); //// System.out.println("bbox W: " + bbox.getWidth()); //// System.out.println("bbox H: " + bbox.getHeight()); //// todo: look into transform issues when dragging ellements eg when the canvas is scaled or panned //// SVGLocatable.getTransformToElement() //// SVGPoint.matrixTransform() int vSpacing = graphPanelSize.getVerticalSpacing(graphData.gridHeight); int hSpacing = graphPanelSize.getHorizontalSpacing(graphData.gridWidth); new RelationSvg().updateRelationLines(doc, selectedGroupElement, svgNameSpace, hSpacing, vSpacing); //new CmdiComponentBuilder().savePrettyFormatting(doc, new File("/Users/petwit/Documents/SharedInVirtualBox/mpi-co-svn-mpi-nl/LAT/Kinnate/trunk/src/main/resources/output.svg")); } } }); } protected void addHighlightToGroup() { UpdateManager updateManager = svgCanvas.getUpdateManager(); updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() { public void run() { if (doc != null) { Element entityGroup = doc.getElementById("EntityGroup"); for (Node currentChild = entityGroup.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) { if ("g".equals(currentChild.getLocalName())) { Node idAttrubite = currentChild.getAttributes().getNamedItem("id"); if (idAttrubite != null) { String entityPath = idAttrubite.getTextContent(); System.out.println("group id (entityPath): " + entityPath); Node existingHighlight = null; // find any existing highlight for (Node subGoupNode = currentChild.getFirstChild(); subGoupNode != null; subGoupNode = subGoupNode.getNextSibling()) { if ("rect".equals(subGoupNode.getLocalName())) { Node subGroupIdAttrubite = subGoupNode.getAttributes().getNamedItem("id"); if (subGroupIdAttrubite != null) { if ("highlight".equals(subGroupIdAttrubite.getTextContent())) { existingHighlight = subGoupNode; } } } } if (!selectedGroupElement.contains(entityPath)) { // remove all old highlights if (existingHighlight != null) { currentChild.removeChild(existingHighlight); } // add the current highlights } else { if (existingHighlight == null) { // svgCanvas.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); SVGRect bbox = ((SVGLocatable) currentChild).getBBox(); // System.out.println("bbox X: " + bbox.getX()); // System.out.println("bbox Y: " + bbox.getY()); // System.out.println("bbox W: " + bbox.getWidth()); // System.out.println("bbox H: " + bbox.getHeight()); Element symbolNode = doc.createElementNS(svgNameSpace, "rect"); int paddingDistance = 20; symbolNode.setAttribute("id", "highlight"); symbolNode.setAttribute("x", Float.toString(bbox.getX() - paddingDistance)); symbolNode.setAttribute("y", Float.toString(bbox.getY() - paddingDistance)); symbolNode.setAttribute("width", Float.toString(bbox.getWidth() + paddingDistance * 2)); symbolNode.setAttribute("height", Float.toString(bbox.getHeight() + paddingDistance * 2)); symbolNode.setAttribute("fill", "none"); symbolNode.setAttribute("stroke-width", "1"); symbolNode.setAttribute("stroke", "blue"); symbolNode.setAttribute("stroke-dasharray", "3"); symbolNode.setAttribute("stroke-dashoffset", "0"); // symbolNode.setAttribute("id", "Highlight"); // symbolNode.setAttribute("id", "Highlight"); // symbolNode.setAttribute("id", "Highlight"); // symbolNode.setAttribute("style", ":none;fill-opacity:1;fill-rule:nonzero;stroke:#6674ff;stroke-opacity:1;stroke-width:1;stroke-miterlimit:4;" // + "stroke-dasharray:1, 1;stroke-dashoffset:0"); currentChild.appendChild(symbolNode); } } } } } } } }); } private Element createEntitySymbol(GraphDataNode currentNode, int hSpacing, int vSpacing, int symbolSize) { Element groupNode = doc.createElementNS(svgNameSpace, "g"); groupNode.setAttribute("id", currentNode.getEntityPath()); // counterTest++; Element symbolNode; String symbolType = currentNode.getSymbolType(); if (symbolType == null) { symbolType = "cross"; } // todo: check that if an entity is already placed in which case do not recreate // todo: do not create a new dom each time but reuse it instead, or due to the need to keep things up to date maybe just store an array of entity locations instead symbolNode = doc.createElementNS(svgNameSpace, "use"); symbolNode.setAttribute("id", currentNode.getEntityPath() + "symbol"); symbolNode.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + symbolType); // the xlink: of "xlink:href" is required for some svg viewers to render correctly groupNode.setAttribute("transform", "translate(" + Integer.toString(currentNode.xPos * hSpacing + hSpacing - symbolSize / 2) + ", " + Integer.toString(currentNode.yPos * vSpacing + vSpacing - symbolSize / 2) + ")"); if (currentNode.isEgo) { symbolNode.setAttribute("fill", "black"); } else { symbolNode.setAttribute("fill", "white"); } symbolNode.setAttribute("stroke", "black"); symbolNode.setAttribute("stroke-width", "2"); groupNode.appendChild(symbolNode); ////////////////////////////// tspan method appears to fail in batik rendering process unless saved and reloaded //////////////////////////////////////////////// // Element labelText = doc.createElementNS(svgNS, "text"); //// labelText.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing + symbolSize / 2)); //// labelText.setAttribute("y", Integer.toString(currentNode.yPos * vSpacing + vSpacing - symbolSize / 2)); // labelText.setAttribute("fill", "black"); // labelText.setAttribute("fill-opacity", "1"); // labelText.setAttribute("stroke-width", "0"); // labelText.setAttribute("font-size", "14px"); //// labelText.setAttribute("text-anchor", "end"); //// labelText.setAttribute("style", "font-size:14px;text-anchor:end;fill:black;fill-opacity:1"); // //labelText.setNodeValue(currentChild.toString()); // //String textWithUni = "\u0041"; // int textSpanCounter = 0; // int lineSpacing = 10; // for (String currentTextLable : currentNode.getLabel()) { // Text textNode = doc.createTextNode(currentTextLable); // Element tspanElement = doc.createElement("tspan"); // tspanElement.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing + symbolSize / 2)); // tspanElement.setAttribute("y", Integer.toString((currentNode.yPos * vSpacing + vSpacing - symbolSize / 2) + textSpanCounter)); //// tspanElement.setAttribute("y", Integer.toString(textSpanCounter * lineSpacing)); // tspanElement.appendChild(textNode); // labelText.appendChild(tspanElement); // textSpanCounter += lineSpacing; // groupNode.appendChild(labelText); ////////////////////////////// end tspan method appears to fail in batik rendering process //////////////////////////////////////////////// ////////////////////////////// alternate method //////////////////////////////////////////////// // todo: this method has the draw back that the text is not selectable as a block int textSpanCounter = 0; int lineSpacing = 15; for (String currentTextLable : currentNode.getLabel()) { Element labelText = doc.createElementNS(svgNameSpace, "text"); labelText.setAttribute("x", Double.toString(symbolSize * 1.5)); labelText.setAttribute("y", Integer.toString(textSpanCounter)); labelText.setAttribute("fill", "black"); labelText.setAttribute("stroke-width", "0"); labelText.setAttribute("font-size", "14"); Text textNode = doc.createTextNode(currentTextLable); labelText.appendChild(textNode); textSpanCounter += lineSpacing; groupNode.appendChild(labelText); } ////////////////////////////// end alternate method //////////////////////////////////////////////// ((EventTarget) groupNode).addEventListener("mousedown", new MouseListenerSvg(this), false); return groupNode; } public void drawNodes(GraphData graphDataLocal) { requiresSave = true; graphData = graphDataLocal; DOMImplementation impl = SVGDOMImplementation.getDOMImplementation(); doc = (SVGDocument) impl.createDocument(svgNameSpace, "svg", null); new EntitySvg().insertSymbols(doc, svgNameSpace); // Document doc = impl.createDocument(svgNS, "svg", null); // SVGDocument doc = svgCanvas.getSVGDocument(); // Get the root element (the 'svg' element). Element svgRoot = doc.getDocumentElement(); // todo: set up a kinnate namespace so that the ego list and kin type strings can have more permanent storage places // int maxTextLength = 0; // for (GraphDataNode currentNode : graphData.getDataNodes()) { // if (currentNode.getLabel()[0].length() > maxTextLength) { // maxTextLength = currentNode.getLabel()[0].length(); int vSpacing = graphPanelSize.getVerticalSpacing(graphData.gridHeight); // todo: find the real text size from batik // todo: get the user selected canvas size and adjust the hSpacing and vSpacing to fit // int hSpacing = maxTextLength * 10 + 100; int hSpacing = graphPanelSize.getHorizontalSpacing(graphData.gridWidth); int symbolSize = 15; int strokeWidth = 2; // int preferedWidth = graphData.gridWidth * hSpacing + hSpacing * 2; // int preferedHeight = graphData.gridHeight * vSpacing + vSpacing * 2; // Set the width and height attributes on the root 'svg' element. svgRoot.setAttribute("width", Integer.toString(graphPanelSize.getWidth(graphData.gridWidth, hSpacing))); svgRoot.setAttribute("height", Integer.toString(graphPanelSize.getHeight(graphData.gridHeight, vSpacing))); this.setPreferredSize(new Dimension(graphPanelSize.getHeight(graphData.gridHeight, vSpacing), graphPanelSize.getWidth(graphData.gridWidth, hSpacing))); // store the selected kin type strings and other data in the dom dataStoreSvg.storeAllData(doc); svgCanvas.setSVGDocument(doc); // svgCanvas.setDocument(doc); // int counterTest = 0; // add the relation symbols in a group below the relation lines Element relationGroupNode = doc.createElementNS(svgNameSpace, "g"); relationGroupNode.setAttribute("id", "RelationGroup"); for (GraphDataNode currentNode : graphData.getDataNodes()) { // set up the mouse listners on the group node // ((EventTarget) groupNode).addEventListener("mouseover", new EventListener() { // public void handleEvent(Event evt) { // System.out.println("OnMouseOverCircleAction: " + evt.getCurrentTarget()); // if (currentDraggedElement == null) { // ((Element) evt.getCurrentTarget()).setAttribute("fill", "green"); // }, false); // ((EventTarget) groupNode).addEventListener("mouseout", new EventListener() { // public void handleEvent(Event evt) { // System.out.println("mouseout: " + evt.getCurrentTarget()); // if (currentDraggedElement == null) { // ((Element) evt.getCurrentTarget()).setAttribute("fill", "none"); // }, false); for (GraphDataNode.EntityRelation graphLinkNode : currentNode.getVisiblyRelateNodes()) { new RelationSvg().insertRelation(doc, svgNameSpace, relationGroupNode, currentNode, graphLinkNode, hSpacing, vSpacing, strokeWidth); } } svgRoot.appendChild(relationGroupNode); // add the entity symbols in a group on top of the relation lines Element entityGroupNode = doc.createElementNS(svgNameSpace, "g"); entityGroupNode.setAttribute("id", "EntityGroup"); for (GraphDataNode currentNode : graphData.getDataNodes()) { entityGroupNode.appendChild(createEntitySymbol(currentNode, hSpacing, vSpacing, symbolSize)); } svgRoot.appendChild(entityGroupNode); //new CmdiComponentBuilder().savePrettyFormatting(doc, new File("/Users/petwit/Documents/SharedInVirtualBox/mpi-co-svn-mpi-nl/LAT/Kinnate/trunk/src/main/resources/output.svg")); // svgCanvas.revalidate(); // todo: populate this correctly with the available symbols dataStoreSvg.indexParameters.symbolFieldsFields.setAvailableValues(new EntitySvg().listSymbolNames(doc)); } public boolean hasSaveFileName() { return svgFile != null; } public boolean requiresSave() { return requiresSave; } public void saveToFile() { saveSvg(svgFile); } public void saveToFile(File saveAsFile) { saveSvg(saveAsFile); } public void updateGraph() { throw new UnsupportedOperationException("Not supported yet."); } }
package com.dmnlk.sample; import com.codahale.metrics.annotation.Timed; import com.google.common.base.Optional; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import java.util.concurrent.atomic.AtomicLong; /** * @author dmnlk */ @Path("/hello") @Produces(MediaType.APPLICATION_JSON) public class SampleResource { private final String template; private final String defaultName; private final AtomicLong counter; public SampleResource(String template, String defaultName, AtomicLong counter) { this.template = template; this.defaultName = defaultName; this.counter = counter; } @GET @Timed public Saying sayHello(@QueryParam("name")Optional<String> name) { final String value = String.format(template, name.or(defaultName)); return new Saying(counter.incrementAndGet(), value); } }
package org.arkanos.aos.api.data; import java.sql.ResultSet; import java.sql.SQLException; import org.arkanos.aos.api.controllers.Database; /** * @author arkanos * */ public class User { static final private String FIELD_USER_NAME = "user_name"; static final private String FIELD_FIRST_NAME = "first_name"; static final private String FIELD_LAST_NAME = "last_name"; static final private String FIELD_EMAIL = "email"; static final private String FIELD_HASHED_PASSWORD = "hashed_password"; static public boolean create(String user_name, String first_name, String last_name, String email, String hashed_password) { return Database.execute("INSERT INTO user(" + User.FIELD_USER_NAME + "," + User.FIELD_FIRST_NAME + "," + User.FIELD_LAST_NAME + "," + User.FIELD_EMAIL + "," + User.FIELD_HASHED_PASSWORD + ") VALUES " + "('" + user_name + "','" + first_name + "','" + last_name + "','" + email + "','" + hashed_password + "');"); } /** * @param user_name * @param hashed_password * @return */ public static boolean credentialsMatch(String user_name, String hashed_password) { try { ResultSet rs = Database.query("SELECT " + User.FIELD_HASHED_PASSWORD + " FROM user WHERE " + User.FIELD_USER_NAME + " = '" + user_name + "';"); rs.next(); String pass = rs.getString(User.FIELD_HASHED_PASSWORD); if ((pass != null) && (pass.compareTo(hashed_password) == 0)) return true; else return false; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } static public boolean exists(String user_name) { try { ResultSet rs = Database.query("SELECT COUNT(*) FROM user WHERE " + User.FIELD_USER_NAME + " = '" + user_name + "';"); rs.next(); if (rs.getInt(1) > 0) return true; else return false; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; } /** * @param s * @return */ static public boolean isLegalUsername(String user_name) { for (char c : user_name.toCharArray()) { if ((c > 'z') || (c < 'a')) { if ((c < '0') || (c > '9')) { if ((c != '_') && (c != '-') && (c != '.')) return false; } } } return true; } }
package org.b3log.symphony.util; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.b3log.latke.logging.Level; import org.b3log.latke.logging.Logger; import org.b3log.symphony.model.Common; import org.b3log.symphony.model.Link; import org.json.JSONObject; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import javax.servlet.http.HttpServletResponse; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLEncoder; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class Links { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(Links.class); public static List<JSONObject> getLinks(final String baseURL, final String html) { final Document doc = Jsoup.parse(html, baseURL); final Elements urlElements = doc.select("a"); final Set<String> urls = new HashSet<>(); final List<Spider> spiders = new ArrayList<>(); String url = null; for (final Element urlEle : urlElements) { try { url = urlEle.absUrl("href"); if (StringUtils.isBlank(url) || !StringUtils.contains(url, ": url = StringUtils.substringBeforeLast(baseURL, "/") + url; } final URL formedURL = new URL(url); final String protocol = formedURL.getProtocol(); final String host = formedURL.getHost(); final int port = formedURL.getPort(); final String path = formedURL.getPath(); url = protocol + "://" + host; if (-1 != port && 80 != port && 443 != port) { url += ":" + port; } url += path; if (StringUtils.endsWith(url, "/")) { url = StringUtils.substringBeforeLast(url, "/"); } urls.add(url); } catch (final Exception e) { LOGGER.warn("Can't parse [" + url + "]"); } } final List<JSONObject> ret = new ArrayList<>(); try { for (final String u : urls) { spiders.add(new Spider(u)); } final List<Future<JSONObject>> results = Symphonys.EXECUTOR_SERVICE.invokeAll(spiders); for (final Future<JSONObject> result : results) { final JSONObject link = result.get(); if (null == link) { continue; } ret.add(link); } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Parses URLs failed", e); } Collections.sort(ret, Comparator.comparingInt(link -> link.optInt(Link.LINK_BAIDU_REF_CNT))); return ret; } private static boolean containsChinese(final String str) { if (StringUtils.isBlank(str)) { return false; } final Pattern p = Pattern.compile("[\u4e00-\u9fa5]"); final Matcher m = p.matcher(str); return m.find(); } static class Spider implements Callable<JSONObject> { private final String url; Spider(final String url) { this.url = url; } @Override public JSONObject call() throws Exception { final int TIMEOUT = 2000; try { final JSONObject ret = new JSONObject(); // Get meta info of the URL final Connection.Response res = Jsoup.connect(url).timeout(TIMEOUT).followRedirects(false).execute(); if (HttpServletResponse.SC_OK != res.statusCode()) { return null; } String charset = res.charset(); if (StringUtils.isBlank(charset)) { charset = "UTF-8"; } final String html = new String(res.bodyAsBytes(), charset); String title = StringUtils.substringBetween(html, "<title>", "</title>"); title = StringUtils.trim(title); if (!containsChinese(title)) { return null; } title = Emotions.toAliases(title); final String keywords = StringUtils.substringBetween(html, "eywords\" content=\"", "\""); ret.put(Link.LINK_ADDR, url); ret.put(Link.LINK_TITLE, title); ret.put(Link.LINK_T_KEYWORDS, keywords); ret.put(Link.LINK_T_HTML, html); final Document doc = Jsoup.parse(html); doc.select("pre").remove(); ret.put(Link.LINK_T_TEXT, doc.text()); // Evaluate the URL URL baiduURL = new URL("https: HttpURLConnection conn = (HttpURLConnection) baiduURL.openConnection(); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); conn.addRequestProperty(Common.USER_AGENT, Symphonys.USER_AGENT_BOT); InputStream inputStream = conn.getInputStream(); String baiduRes = IOUtils.toString(inputStream, "UTF-8"); IOUtils.closeQuietly(inputStream); conn.disconnect(); int baiduRefCnt = StringUtils.countMatches(baiduRes, "<em>" + url + "</em>"); if (1 > baiduRefCnt) { ret.put(Link.LINK_BAIDU_REF_CNT, baiduRefCnt); LOGGER.debug(ret.optString(Link.LINK_ADDR)); return ret; } else { baiduURL = new URL("https: conn = (HttpURLConnection) baiduURL.openConnection(); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); conn.addRequestProperty(Common.USER_AGENT, Symphonys.USER_AGENT_BOT); inputStream = conn.getInputStream(); baiduRes = IOUtils.toString(inputStream, "UTF-8"); IOUtils.closeQuietly(inputStream); conn.disconnect(); baiduRefCnt += StringUtils.countMatches(baiduRes, "<em>" + url + "</em>"); ret.put(Link.LINK_BAIDU_REF_CNT, baiduRefCnt); LOGGER.debug(ret.optString(Link.LINK_ADDR)); return ret; } } catch (final SocketTimeoutException e) { return null; } catch (final Exception e) { LOGGER.log(Level.WARN, "Parses URL [" + url + "] failed", e); return null; } } } }
package org.basex.query.path; import static org.basex.query.QueryText.*; import org.basex.data.Data; import org.basex.index.Stats; import org.basex.index.path.PathNode; import org.basex.query.QueryContext; import org.basex.query.QueryException; import org.basex.query.expr.Expr; import org.basex.query.expr.Filter; import org.basex.query.expr.Pos; import org.basex.query.item.Bln; import org.basex.query.item.Empty; import org.basex.query.item.ANode; import org.basex.query.item.NodeType; import org.basex.query.item.SeqType; import org.basex.query.item.Value; import org.basex.query.iter.Iter; import org.basex.query.iter.NodeCache; import org.basex.query.iter.NodeIter; import org.basex.query.path.Test.Name; import static org.basex.query.util.Err.*; import org.basex.query.util.IndexContext; import org.basex.query.util.Var; import org.basex.util.Array; import org.basex.util.InputInfo; import org.basex.util.list.ObjList; public class AxisPath extends Path { /** Flag for result caching. */ private boolean cache; /** Cached result. */ private NodeCache citer; /** Last visited item. */ private Value lvalue; /** * Constructor. * @param ii input info * @param r root expression; can be a {@code null} reference * @param s axis steps */ AxisPath(final InputInfo ii, final Expr r, final Expr... s) { super(ii, r, s); } /** * If possible, converts this path expression to a path iterator. * @param ctx query context * @return resulting operator */ final AxisPath finish(final QueryContext ctx) { // evaluate number of results size = size(ctx); type = SeqType.get(steps[steps.length - 1].type().type, size); return useIterator() ? new IterPath(input, root, steps, type, size) : this; } /** * Checks if the path can be rewritten for iterative evaluation. * @return resulting operator */ private boolean useIterator() { if(root == null || root.uses(Use.VAR) || !root.iterable()) return false; final int sl = steps.length; for(int s = 0; s < sl; ++s) { switch(step(s).axis) { // reverse axes - don't iterate case ANC: case ANCORSELF: case PREC: case PRECSIBL: return false; // multiple, unsorted results - only iterate at last step, // or if last step uses attribute axis case DESC: case DESCORSELF: case FOLL: case FOLLSIBL: return s + 1 == sl || s + 2 == sl && step(s + 1).axis == Axis.ATTR; // allow iteration for CHILD, ATTR, PARENT and SELF default: } } return true; } @Override protected final Expr compPath(final QueryContext ctx) throws QueryException { for(final Expr s : steps) checkUp(s, ctx); // merge two axis paths if(root instanceof AxisPath) { Expr[] st = ((AxisPath) root).steps; root = ((AxisPath) root).root; for(final Expr s : steps) st = Array.add(st, s); steps = st; // refresh root context ctx.compInfo(OPTMERGE); ctx.value = root(ctx); } final AxisStep s = voidStep(steps); if(s != null) COMPSELF.thrw(input, s); for(int i = 0; i != steps.length; ++i) { final Expr e = steps[i].comp(ctx); if(!(e instanceof AxisStep)) return e; steps[i] = e; } optSteps(ctx); // retrieve data reference final Data data = ctx.data(); if(data != null && ctx.value.type == NodeType.DOC) { // check index access Expr e = index(ctx, data); // check children path rewriting if(e == this) e = children(ctx, data); // return optimized expression if(e != this) return e.comp(ctx); } // analyze if result set can be cached - no predicates/variables... cache = root != null && !uses(Use.VAR); // if applicable, use iterative evaluation final Path path = finish(ctx); // heuristics: wrap with filter expression if only one result is expected return size() != 1 ? path : new Filter(input, this, Pos.get(1, size(), input)).comp2(ctx); } /** * If possible, returns an expression which accesses the index. * Otherwise, returns the original expression. * @param ctx query context * @param data data reference * @return resulting expression * @throws QueryException query exception */ private Expr index(final QueryContext ctx, final Data data) throws QueryException { // disallow relative paths and numeric predicates if(root == null || uses(Use.POS)) return this; // cache index access costs IndexContext ics = null; // cheapest predicate and step int pmin = 0; int smin = 0; // check if path can be converted to an index access for(int s = 0; s < steps.length; ++s) { // find cheapest index access final AxisStep stp = step(s); if(!stp.axis.down) break; // check if resulting index path will be duplicate free final boolean i = pathNodes(data, s) != null; // choose cheapest index access for(int p = 0; p < stp.preds.length; ++p) { final IndexContext ic = new IndexContext(ctx, data, stp, i); if(!stp.preds[p].indexAccessible(ic)) continue; if(ic.costs() == 0) { if(ic.not) { // not operator... accept all results stp.preds[p] = Bln.TRUE; continue; } // no results... ctx.compInfo(OPTNOINDEX, this); return Empty.SEQ; } if(ics == null || ics.costs() > ic.costs()) { ics = ic; pmin = p; smin = s; } } } // skip if no index access is possible, or if it is too expensive if(ics == null || ics.costs() > data.meta.size) return this; // replace expressions for index access final AxisStep stp = step(smin); final Expr ie = stp.preds[pmin].indexEquivalent(ics); if(ics.seq) { // sequential evaluation; do not invert path stp.preds[pmin] = ie; } else { // inverted path, which will be represented as predicate AxisStep[] invSteps = {}; // collect remaining predicates final Expr[] newPreds = new Expr[stp.preds.length - 1]; int c = 0; for(int p = 0; p != stp.preds.length; ++p) { if(p != pmin) newPreds[c++] = stp.preds[p]; } // check if path before index step needs to be inverted and traversed final Test test = DocTest.get(ctx, data); boolean inv = true; if(test == Test.DOC && data.meta.pathindex && data.meta.uptodate) { int j = 0; for(; j <= smin; ++j) { final AxisStep s = axisStep(j); // step must use child axis and name test, and have no predicates if(s == null || s.test.test != Name.NAME || s.axis != Axis.CHILD || j != smin && s.preds.length > 0) break; // support only unique paths with nodes on the correct level final int name = data.tagindex.id(s.test.name.local()); final ObjList<PathNode> pn = data.paths.desc(name, Data.ELEM); if(pn.size() != 1 || pn.get(0).level() != j + 1) break; } inv = j <= smin; } // invert path before index step if(inv) { for(int j = smin; j >= 0; --j) { final Axis ax = step(j).axis.invert(); if(ax == null) break; if(j != 0) { final AxisStep prev = step(j - 1); invSteps = Array.add(invSteps, AxisStep.get(input, ax, prev.test, prev.preds)); } else { // add document test for collections and axes other than ancestors if(test != Test.DOC || ax != Axis.ANC && ax != Axis.ANCORSELF) invSteps = Array.add(invSteps, AxisStep.get(input, ax, test)); } } } // create resulting expression final AxisPath result; final boolean simple = invSteps.length == 0 && newPreds.length == 0; if(ie instanceof AxisPath) { result = (AxisPath) ie; } else if(smin + 1 < steps.length || !simple) { result = simple ? new AxisPath(input, ie) : new AxisPath(input, ie, AxisStep.get(input, Axis.SELF, Test.NOD)); } else { return ie; } // add remaining predicates to last step final int ls = result.steps.length - 1; if(ls >= 0) { result.steps[ls] = result.step(ls).addPreds(newPreds); // add inverted path as predicate to last step if(invSteps.length != 0) result.steps[ls] = result.step(ls).addPreds(Path.get(input, null, invSteps)); } // add remaining steps for(int s = smin + 1; s < steps.length; ++s) { result.steps = Array.add(result.steps, steps[s]); } return result; } return this; } @Override public Iter iter(final QueryContext ctx) throws QueryException { final Value cv = ctx.value; final long cs = ctx.size; final long cp = ctx.pos; try { Value r = root != null ? ctx.value(root) : cv; if(!cache || citer == null || lvalue.type != NodeType.DOC || r.type != NodeType.DOC || !((ANode) lvalue).is((ANode) r)) { lvalue = r; citer = new NodeCache().random(); if(r != null) { final Iter ir = ctx.iter(r); while((r = ir.next()) != null) { ctx.value = r; iter(0, citer, ctx); } } else { ctx.value = null; iter(0, citer, ctx); } citer.sort(); } else { citer.reset(); } return citer; } finally { ctx.value = cv; ctx.size = cs; ctx.pos = cp; } } /** * Recursive step iterator. * @param l current step * @param nc node cache * @param ctx query context * @throws QueryException query exception */ private void iter(final int l, final NodeCache nc, final QueryContext ctx) throws QueryException { // cast is safe (steps will always return a {@link NodIter} instance final NodeIter ni = (NodeIter) ctx.iter(steps[l]); final boolean more = l + 1 != steps.length; for(ANode node; (node = ni.next()) != null;) { if(more) { ctx.value = node; iter(l + 1, nc, ctx); } else { ctx.checkStop(); nc.add(node); } } } /** * Inverts a location path. * @param r new root node * @param curr current location step * @return inverted path */ public final AxisPath invertPath(final Expr r, final AxisStep curr) { // hold the steps to the end of the inverted path int s = steps.length; final Expr[] e = new Expr[s // add predicates of last step to new root node final Expr rt = step(s).preds.length != 0 ? new Filter(input, r, step(s).preds) : r; // add inverted steps in a backward manner int c = 0; while(--s >= 0) { e[c++] = AxisStep.get(input, step(s + 1).axis.invert(), step(s).test, step(s).preds); } e[c] = AxisStep.get(input, step(s + 1).axis.invert(), curr.test); return new AxisPath(input, rt, e); } @Override public final Expr addText(final QueryContext ctx) { final AxisStep s = step(steps.length - 1); if(s.preds.length != 0 || !s.axis.down || s.test.type == NodeType.ATT || s.test.test != Name.NAME && s.test.test != Name.STD) return this; final Data data = ctx.data(); if(data == null || !data.meta.uptodate) return this; final Stats stats = data.tagindex.stat( data.tagindex.id(s.test.name.local())); if(stats != null && stats.isLeaf()) { steps = Array.add(steps, AxisStep.get(input, Axis.CHILD, Test.TXT)); ctx.compInfo(OPTTEXT, this); } return this; } /** * Returns the specified axis step. * @param i index * @return step */ public final AxisStep step(final int i) { return (AxisStep) steps[i]; } /** * Returns a copy of the path expression. * @return copy */ public final Path copy() { final Expr[] stps = new Expr[steps.length]; for(int s = 0; s < steps.length; ++s) stps[s] = AxisStep.get(step(s)); return get(input, root, stps); } /** * Returns the path nodes that will result from this path. * @param ctx query context * @return path nodes, or {@code null} if nodes cannot be evaluated */ public ObjList<PathNode> nodes(final QueryContext ctx) { final Value rt = root(ctx); final Data data = rt != null && rt.type == NodeType.DOC ? rt.data() : null; if(data == null || !data.meta.pathindex || !data.meta.uptodate) return null; ObjList<PathNode> nodes = data.paths.root(); for(int s = 0; s < steps.length; s++) { final AxisStep curr = axisStep(s); if(curr == null) return null; nodes = curr.nodes(nodes, data); if(nodes == null) return null; } return nodes; } @Override public final int count(final Var v) { int c = 0; for(final Expr s : steps) c += s.count(v); return c + super.count(v); } @Override public final boolean removable(final Var v) { for(final Expr s : steps) if(!s.removable(v)) return false; return super.removable(v); } @Override public final Expr remove(final Var v) { for(int s = 0; s != steps.length; ++s) steps[s].remove(v); return super.remove(v); } @Override public final boolean iterable() { return true; } @Override public final boolean sameAs(final Expr cmp) { if(!(cmp instanceof AxisPath)) return false; final AxisPath ap = (AxisPath) cmp; if((root == null || ap.root == null) && root != ap.root || steps.length != ap.steps.length || root != null && !root.sameAs(ap.root)) return false; for(int s = 0; s < steps.length; ++s) { if(!steps[s].sameAs(ap.steps[s])) return false; } return true; } }
package org.jassetmanager; import com.sun.istack.internal.NotNull; import javax.servlet.ServletContext; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.PrivateKey; import java.util.*; public class AssetBundle { private byte[] content; private boolean built; private final ServletContext context; private final AssetBundleConfiguration config; private static final byte[] ASSET_SEPARATOR = new byte[] { '\r', '\n' }; public AssetBundle(@NotNull AssetBundleConfiguration config, @NotNull ServletContext context) { this.context = context; this.config = config; this.content = new byte[0]; this.built = false; } public boolean isBuilt() { return this.built; } public byte[] getContent() { return this.content; } public void build(@NotNull List<String> allFilePaths) throws IOException { this.content = new byte[0]; this.built = false; Map<Integer, List<String>> contentMap = createContentMap(allFilePaths); readAndAppendFilesFromContentMap(contentMap); this.built = true; } private void readAndAppendFilesFromContentMap(Map<Integer, List<String>> contentMap) throws IOException { List<Integer> keys = new ArrayList<Integer>(contentMap.keySet()); Collections.sort(keys); ByteArrayOutputStream to = new ByteArrayOutputStream(); for (Integer position : keys) { List<String> files = contentMap.get(position); readAndAppendFiles(files, to); } this.content = to.toByteArray(); } private void readAndAppendFiles(List<String> files, ByteArrayOutputStream to) throws IOException { for (String file : files) { readAndAppendFile(file, to); } } private Map<Integer, List<String>> createContentMap(List<String> allFilePaths) { Map<Integer, List<String>> contentMap = new HashMap<Integer, List<String>>(); for (String filePath : allFilePaths) { int position = this.config.getContentPosition(filePath); if (position == -1) { continue; } if (!(contentMap.containsKey(position))) { contentMap.put(position, new ArrayList<String>()); } contentMap.get(position).add(filePath); } return contentMap; } private void readAndAppendFile(String filePath, ByteArrayOutputStream to) throws IOException { byte[] buffer = new byte[1024]; InputStream is = null; try { is = this.context.getResourceAsStream(filePath); if (is == null) { throw new IOException("Could not open stream to asset '" + filePath + "'"); } to.write(ResourceUtil.readInputStream(is)); to.write(ASSET_SEPARATOR); } finally { try { if (is != null) { is.close(); } } catch (Exception e) { } } } }
package org.lightmare.utils; import java.io.IOException; /** * Interface which should be implemented for phantom reference to close unused * resouyrces * * @author levan * @see CleanUtils */ public interface Cleanable { void clean() throws IOException; }
package org.msgpack.rpc.client; import java.io.IOException; public class Future { protected Exception error; protected Object result; protected boolean isJoined; public Future() { this.error = null; this.result = null; this.isJoined = false; } public synchronized void join() { try { while (error == null && result == null) this.wait(); } catch (Exception e) { e.printStackTrace(); error = e; } isJoined = true; } public void setResult(Object result) { set(null, result); } public void setError(Object error) { Exception e; if (error instanceof String) e = new IOException((String)error); else if (error instanceof Exception) e = (Exception)error; else e = new IOException("Unknown Error"); set(e, null); } protected synchronized void set(Exception error, Object result) { this.error = error; this.result = result; this.notifyAll(); } public synchronized Object getResult() throws Exception { if (!isJoined) throw new IOException("Calling getResult() without join()"); if (error != null) throw error; return result; } }
package org.myrobotlab.service; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.TreeMap; import java.util.concurrent.LinkedBlockingQueue; import org.myrobotlab.codec.CodecUtils; import org.myrobotlab.framework.Message; import org.myrobotlab.framework.Platform; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.interfaces.ServiceInterface; import org.myrobotlab.framework.repo.ServiceData; import org.myrobotlab.io.FileIO; import org.myrobotlab.io.FindFile; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.service.data.Script; import org.myrobotlab.service.meta.abstracts.MetaData; import org.python.core.Py; import org.python.core.PyException; import org.python.core.PyFloat; import org.python.core.PyInteger; import org.python.core.PyList; import org.python.core.PyObject; import org.python.core.PyString; import org.python.core.PySystemState; import org.python.modules.thread.thread; import org.python.util.PythonInterpreter; import org.slf4j.Logger; public class Python extends Service { /** * this thread handles all callbacks to Python process all input and sets msg * handles * */ public class InputQueue implements Runnable { transient protected Python python; protected volatile boolean running = false; transient protected Thread myThread = null; public InputQueue(Python python) { this.python = python; } @Override public void run() { try { running = true; while (running) { Message msg = inputQueue.take(); try { // FIXME - remove all msg_ .. its the old way .. :P // serious bad bug in it which I think I fixed - the // msgHandle is really the data coming from a callback // it can originate from the same calling function such // as Sphinx.send - but we want the callback to // call a different method - this means the data needs // to go to a data structure which is keyed by only the // sending method, but must call the appropriate method // in Sphinx StringBuffer msgHandle = new StringBuffer().append("msg_").append(CodecUtils.getSafeReferenceName(msg.sender)).append("_").append(msg.sendingMethod); PyObject compiledObject = null; // TODO - getCompiledMethod(msg.method SHOULD BE // getCompiledMethod(methodSignature // without it - no overloading is possible if (msg.data == null || msg.data.length == 0) { compiledObject = getCompiledMethod(msg.method, String.format("%s()", msg.method), interp); } else { StringBuffer methodWithParams = new StringBuffer(); methodWithParams.append(String.format("%s(", msg.method)); for (int i = 0; i < msg.data.length; ++i) { String paramHandle = String.format("%s_p%d", msgHandle, i); interp.set(paramHandle.toString(), msg.data[i]); methodWithParams.append(paramHandle); if (i < msg.data.length - 1) { methodWithParams.append(","); } } methodWithParams.append(")"); compiledObject = getCompiledMethod(msg.method, methodWithParams.toString(), interp); } interp.exec(compiledObject); } catch (Exception e) { log.error("InputQueueThread threw", e.toString()); python.error(String.format("%s %s", e.getClass().getSimpleName(), e.getMessage())); } } } catch (Exception e) { if (e instanceof InterruptedException) { info("shutting down %s", getName()); } else { log.error("InputQueueThread while loop threw", e); } } log.info("shutting down python queue"); } synchronized public void stop() { if (myThread != null) { running = false; myThread.interrupt(); myThread = null; } } synchronized public void start() { if (myThread == null) { myThread = new Thread(this, String.format("python.%s.input", python.getName())); myThread.start(); } else { log.warn("python input queue already running"); } } } class PIThread extends Thread { private String code; public boolean executing = false; PIThread(String name, String code) { super(name); this.code = code; } @Override public void run() { try { if (interp == null) { log.warn("cannot run script - python interpreter is null - not initialized yet ?"); return; } executing = true; interp.exec(code); } catch (Exception e) { log.error("python exec threw", e); String error = Logging.stackToString(e); if (error.contains("KeyboardInterrupt")) { warn("Python process killed !"); } else { error(e); String filtered = error; filtered = filtered.replace("'", ""); filtered = filtered.replace("\"", ""); filtered = filtered.replace("\n", ""); filtered = filtered.replace("\r", ""); filtered = filtered.replace("<", ""); filtered = filtered.replace(">", ""); if (interp != null) { interp.exec(String.format("print '%s'", filtered)); } log.error("following script errored \n{}", code); log.error("interp.exec threw", e); if (filtered.length() > 40) { filtered = filtered.substring(0, 40); } } } finally { executing = false; log.info("script completed"); invoke("finishedExecutingScript"); } } } public final static transient Logger log = LoggerFactory.getLogger(Python.class); // TODO this needs to be moved into an actual cache if it is to be used // Cache of compile python code private static final transient HashMap<String, PyObject> objectCache = new HashMap<String, PyObject>(); private static final long serialVersionUID = 1L; protected int newScriptCnt = 0; /** * Any script executed is put in a openedScripts map... Helpful in IDE * displays */ protected boolean openOnExecute = true; /** * Get a compiled version of the python call. * * @param name * @param code * @param interp * @return */ private static synchronized PyObject getCompiledMethod(String name, String code, PythonInterpreter interp) { // TODO change this from a synchronized method to a few blocks to // improve concurrent performance if (objectCache.containsKey(name)) { return objectCache.get(name); } PyObject compiled = interp.compile(code); if (objectCache.size() > 25) { // keep the size to 6 objectCache.remove(objectCache.keySet().iterator().next()); } objectCache.put(name, compiled); return compiled; } /** * Set a Python variable with a value from Java e.g. python.set("my_var", 5) */ public void set(String pythonRefName, Object o) { interp.set(pythonRefName, o); } /** * Get a Python value from Python into Java return type is PyObject wrapper * around the value * * @param pythonRefName * - name of variable * @return the PyObject wrapper */ public PyObject getPyObject(String pythonRefName) { return interp.get(pythonRefName); } /** * Get the value of the Python variable e.g. Integer x = * (Integer)python.getValue("my_var") * * @param pythonRefName * @return */ public Object get(String pythonRefName) { PyObject o = getPyObject(pythonRefName); if (o == null) { return null; } if (o instanceof PyString) { return o.toString(); } else if (o instanceof PyFloat) { return ((PyFloat) o).getValue(); } else if (o instanceof PyInteger) { return ((PyInteger) o).getValue(); } else if (o instanceof PyList) { return ((PyList) o).getArray(); } return o; } /** * FIXME - buildtime package in resources pyrobotlab python service urls - * created for referencing script */ Map<String, String> exampleFiles = new TreeMap<String, String>(); transient LinkedBlockingQueue<Message> inputQueue = new LinkedBlockingQueue<Message>(); final transient InputQueue inputQueueThread; transient PythonInterpreter interp = null; transient Map<String, PIThread> interpThreads = new HashMap<String, PIThread>(); int interpreterThreadCount = 0; /** * local current directory of python script any new python script will get * localScriptDir prefix */ String localScriptDir = new File(FileIO.getCfgDir()).getAbsolutePath(); /** * local pthon files of current script directory */ List<String> localPythonFiles = new ArrayList<String>(); /** * default location for python modules */ String modulesDir = "pythonModules"; // String configDir = "data" + fs + "config"; boolean pythonConsoleInitialized = false; /** * opened scripts */ HashMap<String, Script> openedScripts = new HashMap<String, Script>(); String activeScript = null; public Python(String n, String id) { super(n, id); log.info("created python {}", getName()); log.info("creating module directory pythonModules"); new File("pythonModules").mkdir(); inputQueueThread = new InputQueue(this); // I love ServiceData ! ServiceData sd = ServiceData.getLocalInstance(); // I love Platform ! Platform p = Platform.getLocalInstance(); List<MetaData> sdt = sd.getAvailableServiceTypes(); for (int i = 0; i < sdt.size(); ++i) { MetaData st = sdt.get(i); // FIXME - cache in "data" dir Or perhaps it should be pulled into // resource directory during build time and packaged with jar String file = String.format("%s/%s.py", st.getSimpleName(), st.getSimpleName()); exampleFiles.put(st.getSimpleName(), file); } localPythonFiles = getFileListing(); log.info("creating module directory pythonModules"); new File("pythonModules").mkdir(); //////// was in startService createPythonInterpreter(); attachPythonConsole(); String selfReferenceScript = "from time import sleep\nfrom org.myrobotlab.framework import Platform\n" + "from org.myrobotlab.service import Runtime\n" + "from org.myrobotlab.framework import Service\n" + "from org.myrobotlab.service import Python\n" + String.format("%s = Runtime.getService(\"%s\")\n\n", CodecUtils.getSafeReferenceName(getName()), getName()) + "Runtime = Runtime.getInstance()\n\n" + String.format("runtime = Runtime.getInstance()\n") + String.format("myService = Runtime.getService(\"%s\")\n", getName()); // FIXME !!! myService is SO WRONG it will collide on more than 1 python // service :( PyObject compiled = getCompiledMethod("initializePython", selfReferenceScript, interp); interp.exec(compiled); // initialize all the pre-existing service before python was created Map<String, ServiceInterface> services = Runtime.getLocalServices(); for (ServiceInterface service : services.values()) { if (service.isRunning()) { onStarted(service.getName()); } } log.info("starting python {}", getName()); inputQueueThread.start(); log.info("started python {}", getName()); } public void newScript() { if (!openedScripts.containsKey("script.py")) { openScript("script.py", ""); } } public void openScript(String scriptName, String code) { activeScript = scriptName; openedScripts.put(scriptName, new Script(scriptName, code)); broadcastState(); } public void closeScript(String scriptName) { openedScripts.remove(scriptName); broadcastState(); } /** * append more Python to the current script * * @param data * the code to append * @return the resulting concatenation */ public Script appendScript(String data) { return new Script("append", data); } /** * runs the pythonConsole.py script which creates a Python Console object and * redirect stdout &amp; stderr to published data - these are hooked by the * SwingGui */ public void attachPythonConsole() { if (!pythonConsoleInitialized) { // FIXME - this console script has hardcoded globals to // reference this service that will break with more than on python service String consoleScript = getResourceAsString("pythonConsole.py"); exec(consoleScript, false); pythonConsoleInitialized = true; } } synchronized public void createPythonInterpreter() { if (interp != null) { log.info("interpreter already created"); return; } // TODO: If the username on windows contains non-ascii characters // the Jython interpreter will blow up. // The APPDATA environment variable contains the username. // as a result, jython sees the non ascii chars and it causes a utf-8 // decoding error. // overriding of the APPDATA environment variable is done in the agent // as a work around. // work around for 2.7.0 // ??? - do we need to extract {jar}/Lib/site.py ??? Properties props = new Properties(); /* * Used to prevent: console: Failed to install '': * java.nio.charset.UnsupportedCharsetException: cp0. */ props.put("python.console.encoding", "UTF-8"); /* * don't respect java accessibility, so that we can access protected members * on subclasses - NO ! - future versions of java will not allow this ! * removing (GroG 20210404) */ // props.put("python.security.respectJavaAccessibility", "false"); props.put("python.import.site", "false"); Properties preprops = System.getProperties(); PythonInterpreter.initialize(preprops, props, new String[0]); interp = new PythonInterpreter(); PySystemState sys = Py.getSystemState(); if (modulesDir != null) { sys.path.append(new PyString(modulesDir)); } sys.path.append(new PyString(Runtime.getConfigDir())); log.info("Python System Path: {}", sys.path); } public String eval(String method) { String jsonMethod = String.format("%s()", method); PyObject o = interp.eval(jsonMethod); String ret = o.toString(); return ret; } /** * execute code */ public boolean exec(String code) { return exec(code, true); } /** * FIXME - isn't "blocking" exec == eval ??? * * This method will execute a string that represents a python script. When * called with blocking=false, the return code will likely return true even if * there is a syntax error because it doesn't wait for the response. * * @param code * - the script to execute * @param blocking * - if true, this method will wait until all of the code has been * evaluated. * @return - returns true if execution of the code was successful. returns * false if there was an exception. */ public boolean exec(String code, boolean blocking) { log.info("exec(String) \n{}", code); try { if (!blocking) { String name = String.format("%s.interpreter.%d", getName(), ++interpreterThreadCount); PIThread interpThread = new PIThread(name, code); interpThread.start(); interpThreads.put(name, interpThread); } else { interp.exec(code); } return true; } catch (PyException pe) { // something specific with a python error error(pe.toString()); invoke("publishStdError", pe.toString()); } catch (Exception e) { error(e); } finally { if (blocking) { invoke("finishedExecutingScript"); } } return false; } /** * This method will execute and block a string that represents a python * script. Python return statement as return * * @param code * - the script to execute * @return - returns String of python return statement */ public String evalAndWait(String code) { // moz4r : eval() no worky for what I want, don't want to mod it & break // things String pyOutput = null; log.info("eval(String) \n{}", code); if (interp == null) { createPythonInterpreter(); } try { pyOutput = interp.eval(code).toString(); } catch (PyException pe) { // something specific with a python error error(pe.toString()); log.error("evalAndWait threw python exception", pe); } catch (Exception e) { // more general error handling. error(e.getMessage()); // dump stack trace to log log.error("evalAndWait threw", e); } return pyOutput; } public void execAndWait(String code) { exec(code, true); } /** * executes an external Python file * * @param filename * the full path name of the python file to execute */ public boolean execFile(String filename) throws IOException { return execFile(filename, true); } /** * executes an external Python file * * @param filename * @param block * @throws IOException */ public boolean execFile(String filename, boolean block) throws IOException { String script = FileIO.toString(filename); if (openOnExecute) { openScript(filename, script); } return exec(script); } /** * execute an "already" defined python method directly * * @param method * - the name of the method */ public void execMethod(String method) { execMethod(method, (Object[]) null); } public void execMethod(String method, Object... parms) { Message msg = Message.createMessage(getName(), getName(), method, parms); inputQueue.add(msg); } public void execResource(String filename) { String script = FileIO.resourceToString(filename); exec(script); } /** * publishing method when a script is finished */ public void finishedExecutingScript() { log.info("finishedExecutingScript"); } /** * DEPRECATE - use online examples only ... (possibly you can package &amp; * include filename listing during build process) * * gets the listing of current example python scripts in the myrobotlab.jar * under /Python/examples * * @return list of python examples */ public List<File> getExampleListing() { List<File> r = null; try { // expensive method - searches through entire jar r = FileIO.listResourceContents("Python/examples"); } catch (Exception e) { Logging.logError(e); } return r; } /** * list files from user directory user directory is located where MRL was * unzipped (dot) .myrobotlab directory these are typically hidden on Linux * systems * * @return returns list of files with .py extension */ public List<String> getFileListing() { try { // FileIO.listResourceContents(path); List<File> files = FindFile.findByExtension(localScriptDir, "py", false); localPythonFiles = new ArrayList<String>(); for (int i = 0; i < files.size(); ++i) { localPythonFiles.add(files.get(i).getName()); } return localPythonFiles; } catch (Exception e) { Logging.logError(e); } return null; } /** * load a official "service" script maintained in myrobotlab * * @param serviceType */ public void loadServiceScript(String serviceType) { String filename = getResourceRoot() + fs + serviceType + fs + String.format("%s.py", serviceType); String serviceScript = null; try { serviceScript = FileIO.toString(filename); } catch (Exception e) { error("%s.py not found", serviceType); log.error("getting service file script example threw {}", e); } openScript(filename, serviceScript); } @Deprecated public void loadPyRobotLabServiceScript(String serviceType) { loadServiceScript(serviceType); } /* * this method can be used to load a Python script from the Python's local * file system, which may not be the SwingGui's local system. Because it can * be done programatically on a different machine we want to broadcast our * changed state to other listeners (possibly the SwingGui) * * @param filename - name of file to load */ public void openScriptFromFile(String filename) throws IOException { log.info("loadScriptFromFile {}", filename); String data = FileIO.toString(filename); openScript(filename, data); } public void onStarted(String serviceName) { ServiceInterface s = Runtime.getService(serviceName); if (s == null) { error("%s got started event from %s yet does not exist in registry", getName(), serviceName); return; } String registerScript = "from org.myrobotlab.framework import Platform\n" + "from org.myrobotlab.service import Runtime\n" + "from org.myrobotlab.framework import Service\n"; // load the import // RIXME - RuntimeGlobals & static values for unknown if (!"unknown".equals(s.getSimpleName())) { registerScript += String.format("from org.myrobotlab.service import %s\n", s.getSimpleName()); } registerScript += String.format("%s = Runtime.getService(\"%s\")\n", CodecUtils.getSafeReferenceName(s.getName()), s.getName()); exec(registerScript, false); } /** * preProcessHook is used to intercept messages and process or route them * before being processed/invoked in the Service. * * Here all messages allowed to go and effect the Python service will be let * through. However, all messages not found in this filter will go "into" they * Python script. There they can be handled in the scripted users code. * * @see org.myrobotlab.framework.Service#preProcessHook(org.myrobotlab.framework.Message) */ @Override public boolean preProcessHook(Message msg) { // let the messages for this service // get processed normally if (methodSet.contains(msg.method)) { return true; } // otherwise its target is for the // scripting environment // set the data - and call the call-back function if (interp == null) { createPythonInterpreter(); } // handling call-back input needs to be // done by another thread - in case its doing blocking // or is executing long tasks - the inbox thread needs to // be freed of such tasks - it has to do all the inbound routing inputQueue.add(msg); return false; } public String publishStdOut(String data) { return data; } public String publishStdError(String data) { return data; } public void setLocalScriptDir(String path) { File dir = new File(path); if (!dir.isDirectory()) { error("%s is not a directory"); } localScriptDir = dir.getAbsolutePath(); getFileListing(); save(); broadcastState(); } @Override synchronized public void startService() { super.startService(); Map<String, ServiceInterface> services = Runtime.getLocalServices(); for (ServiceInterface s : services.values()) { onStarted(s.getName()); } } @Override public void releaseService() { super.releaseService(); stop(); if (interp != null) { // PySystemState.exit(); // the big hammar' throws like Thor interp.cleanup(); interp = null; } inputQueueThread.stop(); thread.interruptAllThreads(); Py.getSystemState()._systemRestart = true; } /** * stop all scripts (not sure the pros/cons of this management vs * thread.interruptAllThreads()) * * @return */ public boolean stop() { log.info("stopping all scripts"); for (PIThread pt : interpThreads.values()) { if (pt.isAlive()) { pt.interrupt(); } } interpThreads.clear(); return false; } /** * stops threads releases interpreter */ @Override public void stopService() { super.stopService(); stop();// release the interpeter } public boolean isOpenOnExecute() { return openOnExecute; } public void setOpenOnExecute(boolean openOnExecute) { this.openOnExecute = openOnExecute; } public static void main(String[] args) { try { Runtime.main(new String[] { "--id", "admin", "--from-launcher" }); LoggingFactory.init("INFO"); // Runtime.start("i01.head.rothead", "Servo"); // Runtime.start("i01.head.neck", "Servo"); WebGui webgui = (WebGui) Runtime.create("webgui", "WebGui"); webgui.autoStartBrowser(false); webgui.startService(); Python python = (Python) Runtime.start("python", "Python"); // python.execFile("data/adafruit.py"); // Runtime.start("i01", "InMoov2"); } catch (Exception e) { log.error("main threw", e); } } }
package org.yidu.novel.dto; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.apache.struts2.ServletActionContext; import org.yidu.novel.action.ChapterListAction; import org.yidu.novel.action.ReaderAction; import org.yidu.novel.constant.YiDuConfig; import org.yidu.novel.constant.YiDuConstants; import org.yidu.novel.entity.TChapter; public class ChapterDTO extends TChapter { private static final long serialVersionUID = -9171385880720383954L; private int nextChapterno; private int preChapterno; private String content; /** * nextChapterno * * @return nextChapterno */ public int getNextChapterno() { return nextChapterno; } /** * * nextChapterno * * * @param nextChapterno * nextChapterno */ public void setNextChapterno(int nextChapterno) { this.nextChapterno = nextChapterno; } /** * preChapterno * * @return preChapterno */ public int getPreChapterno() { return preChapterno; } /** * * preChapterno * * * @param preChapterno * preChapterno */ public void setPreChapterno(int preChapterno) { this.preChapterno = preChapterno; } /** * content * * @return content */ public String getContent() { String keywords = YiDuConstants.yiduConf.getString(YiDuConfig.FILTER_KEYWORD); String[] keywordArr = StringUtils.split(keywords, ","); for (String string : keywordArr) { content = content.replaceAll(string, ""); } return content == null ? "" : content; } public String getEsccapeContent() { String escapeContent = StringUtils.replace(this.getContent(), "<", "&lt;"); escapeContent = StringUtils.replace(escapeContent, ">", "&gt;"); return escapeContent; } public String getReplacedContent() { String keywords = YiDuConstants.yiduConf.getString("filterKeyWord"); String[] keywordArr = StringUtils.split(keywords, ","); String replaced = getContent(); for (String string : keywordArr) { replaced = replaced.replaceAll(string, ""); } return replaced; } /** * * content * * * @param content * content */ public void setContent(String content) { this.content = content; } /** * URL * * @return URL */ public String getChapterListUrl() { HttpServletResponse response = ServletActionContext.getResponse(); return response.encodeURL(ChapterListAction.URL + "?subdir=" + getSubdir() + "&articleno=" + getArticleno()); } /** * URL * * @return URL */ public String getNextChapterUrl() { if (getNextChapterno() != 0) { HttpServletResponse response = ServletActionContext.getResponse(); return response.encodeURL(ReaderAction.URL + "?subdir=" + getSubdir() + "&articleno=" + getArticleno() + "&chapterno=" + getNextChapterno()); } else { if (YiDuConstants.yiduConf.getBoolean(YiDuConfig.ENABLE_CHAPTER_INDEX_PAGE, false)) { return getChapterListUrl(); } else { return getInfoUrl(); } } } /** * URL * * @return URL */ public String getPreChapterUrl() { if (getPreChapterno() != 0) { HttpServletResponse response = ServletActionContext.getResponse(); return response.encodeURL(ReaderAction.URL + "?subdir=" + getSubdir() + "&articleno=" + getArticleno() + "&chapterno=" + getPreChapterno()); } else { if (YiDuConstants.yiduConf.getBoolean(YiDuConfig.ENABLE_CHAPTER_INDEX_PAGE, false)) { return getChapterListUrl(); } else { return getInfoUrl(); } } } /** * URL * * @return URL */ public String getNextChapterThumbnailUrl() { HttpServletResponse response = ServletActionContext.getResponse(); return response.encodeURL(ReaderAction.URL + "?chapterno=" + getNextChapterno()); } /** * URL * * @return URL */ public String getPreChapterThumbnailUrl() { HttpServletResponse response = ServletActionContext.getResponse(); return response.encodeURL(ReaderAction.URL + "?chapterno=" + getPreChapterno()); } }
package physics; import java.util.HashMap; import java.util.Map; import javafx.animation.AnimationTimer; import javafx.collections.SetChangeListener; import javafx.scene.Node; import layout.PhysLayout; import org.jbox2d.common.Vec2; import org.jbox2d.dynamics.Body; import org.jbox2d.dynamics.BodyDef; import org.jbox2d.dynamics.BodyType; import org.jbox2d.dynamics.World; /** * Manage a JBox2D simulation of multiple JavaFX nodes. Nodes have no collision, * and are moved by applying forces (from mechanical springs and forcefields). * * @author Christoph Burschka &lt;christoph@burschka.de&gt; */ public class Box2DSpringSimulation { private final PhysLayout layout; private final Map<Node, Body> bodies; private final World world; private double friction = 0.5; private AnimationTimer animation; private long timeStep = (long) 1e7, timeStamp = 0; private static final int ITER_VELOCITY = 6, ITER_POS = 3; private boolean running; public Box2DSpringSimulation(PhysLayout layout) { this.layout = layout; bodies = new HashMap<>(); // New zero-gravity world: world = new World(new Vec2(0, 0)); layout.getNodes().stream().forEach((node) -> { createBody(node); }); layout.addNodeListener((SetChangeListener.Change<? extends Node> change) -> { if (change.wasAdded()) { createBody(change.getElementAdded()); } if (change.wasRemoved()) { world.destroyBody(bodies.get(change.getElementRemoved())); bodies.remove(change.getElementRemoved()); } }); this.createAnimation(); } public Box2DSpringSimulation(PhysLayout layout, double dt, double friction) { this(layout); setTimeStep(dt); setFriction(friction); } private void createBody(Node node) { BodyDef def = new BodyDef(); def.position.set((float) node.getLayoutX(), (float) node.getLayoutY()); // Infinite-mass bodies are immovable. def.type = layout.getMass(node) == Double.POSITIVE_INFINITY ? BodyType.STATIC : BodyType.DYNAMIC; Body body = world.createBody(def); // Attach an infinitely dense point mass to the body: body.createFixture(new ShapelessShape((layout.getMass(node))), Float.POSITIVE_INFINITY); bodies.put(node, body); } public double getFriction(double friction) { return this.friction; } public void setFriction(double friction) { this.friction = friction; } public void step(double dt) { // Box2D physics work by applying a fixed force on every timestep. applyAllForces(); // 6 iterations of u' and 3 iterations of u (recommended value). world.step((float) dt, ITER_VELOCITY, ITER_POS); } private void createAnimation() { animation = new AnimationTimer() { @Override public void handle(long now) { long nextTimeStamp = timeStamp + timeStep; // Simulate in dt-sized steps until caught up. while (nextTimeStamp < now) { bodies.entrySet().stream().forEach((e) -> { Vec2 relative = new Vec2((float) e.getKey().getLayoutX(), (float) e.getKey().getLayoutY()); relative.subLocal(e.getValue().getPosition()); // If the node has been moved externally or pressed, update. if (relative.length() > 0 || e.getKey().isPressed()) { Vec2 p = e.getValue().getTransform().p; e.getValue().setTransform(p.add(relative), e.getValue().getAngle()); // Reset its momentum, since the user is "holding" it. e.getValue().setLinearVelocity(new Vec2()); } }); step(timeStep * 1e-9); bodies.entrySet().stream().forEach((e) -> { Vec2 p = e.getValue().getWorldCenter(); e.getKey().setLayoutX(p.x); e.getKey().setLayoutY(p.y); }); timeStamp = nextTimeStamp; nextTimeStamp = timeStamp + timeStep; } } }; } public void startSimulation() { running = true; timeStamp = System.nanoTime(); animation.start(); } public void stopSimulation() { running = false; animation.stop(); } public boolean isRunning() { return running; } /** * Set the simulated time step. * * This is distinct from the frame rate, and will always be fixed. * * @param dt time step in seconds. */ public void setTimeStep(double dt) { timeStep = (long) (dt * 1e9); } /** * Set the simulated time step. * * This is distinct from the frame rate, and will always be fixed. * * @param dt time step in seconds. */ public double getTimeStep() { return timeStep * 1e-9; } /** * Applies spring force between a and b. * * @param a * @param b * @param spring */ private void applySpring(Body a, Body b, Spring spring) { Vec2 pA = a.getWorldCenter(); Vec2 pB = b.getWorldCenter(); Vec2 force = spring.getForce(pA, pB); a.applyForceToCenter(force); b.applyForceToCenter(force.negate()); } private void applyFriction(Body a) { Vec2 v = a.getLinearVelocity(); a.applyForceToCenter(v.mul((float) -friction)); } private void applyAllForces() { layout.getAllConnections().stream().forEach((e) -> { applySpring(bodies.get(e.getKey().getA()), bodies.get(e.getKey().getB()), e.getValue()); }); bodies.values().stream().forEach((a) -> { applyFriction(a); layout.fields.stream().forEach((field) -> { a.applyForceToCenter(field.force(a.getWorldCenter())); }); }); } }
package ru.r2cloud.util; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.PosixFilePermission; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.r2cloud.ddns.DDNSType; import ru.r2cloud.model.PpmType; public class Configuration { private static final Logger LOG = LoggerFactory.getLogger(Configuration.class); private final Properties userSettings = new Properties(); private final Path userSettingsLocation; private final FileSystem fs; private static final Set<PosixFilePermission> MODE600 = new HashSet<>(); private final Properties systemSettings = new Properties(); private final Map<String, List<ConfigListener>> listeners = new ConcurrentHashMap<>(); private final Set<String> changedProperties = new HashSet<>(); static { MODE600.add(PosixFilePermission.OWNER_READ); MODE600.add(PosixFilePermission.OWNER_WRITE); } public Configuration(InputStream systemSettingsLocation, String userSettingsLocation, FileSystem fs) throws IOException { systemSettings.load(systemSettingsLocation); this.userSettingsLocation = fs.getPath(userSettingsLocation); this.fs = fs; loadUserSettings(); } private void loadUserSettings() throws IOException { if (Files.exists(userSettingsLocation)) { try (InputStream is = Files.newInputStream(userSettingsLocation)) { userSettings.load(is); } } } public String setProperty(String key, Long value) { return setProperty(key, String.valueOf(value)); } public String setProperty(String key, Integer value) { return setProperty(key, String.valueOf(value)); } public String setProperty(String key, boolean value) { return setProperty(key, String.valueOf(value)); } public Path getSatellitesBasePath() { return fs.getPath(getProperty("satellites.basepath.location")); } public Path getPathFromProperty(String propertyName) { return fs.getPath(getProperty(propertyName)); } public String setProperty(String key, String value) { synchronized (changedProperties) { changedProperties.add(key); } return (String) userSettings.put(key, value); } public void update() { Path tempPath = userSettingsLocation.getParent().resolve("user.properties.tmp"); try (BufferedWriter fos = Files.newBufferedWriter(tempPath)) { userSettings.store(fos, "updated"); } catch (IOException e) { throw new IllegalArgumentException(e); } try { Files.setPosixFilePermissions(tempPath, MODE600); } catch (IOException e) { throw new IllegalArgumentException(e); } try { // temp and dest are on the same filestore // AtomicMoveNotSupportedException shouldn't happen Files.move(tempPath, userSettingsLocation, StandardCopyOption.ATOMIC_MOVE); } catch (IOException e) { throw new IllegalArgumentException(e); } Set<ConfigListener> toNotify = new HashSet<>(); synchronized (changedProperties) { for (String cur : changedProperties) { List<ConfigListener> curListener = listeners.get(cur); if (curListener == null) { continue; } toNotify.addAll(curListener); } changedProperties.clear(); } for (ConfigListener cur : toNotify) { try { cur.onConfigUpdated(); } catch (Exception e) { LOG.error("unable to notify listener: {}", cur, e); } } } public long getThreadPoolShutdownMillis() { return getLong("threadpool.shutdown.millis"); } public Long getLong(String name) { String strValue = getProperty(name); if (strValue == null) { return null; } return Long.valueOf(strValue); } public Integer getInteger(String name) { String strValue = getProperty(name); if (strValue == null) { return null; } return Integer.valueOf(strValue); } public boolean getBoolean(String string) { String str = getProperty(string); if (str == null) { return false; } return Boolean.valueOf(str); } public PpmType getPpmType() { String str = getProperty("ppm.calculate.type"); if (str == null) { return PpmType.AUTO; } try { return PpmType.valueOf(str); } catch (Exception e) { LOG.error("invalid ppm type: {} default to: AUTO", str, e); return PpmType.AUTO; } } public Double getDouble(String name) { String str = getProperty(name); if (str == null) { return null; } return Double.valueOf(str); } public String getProperty(String name) { String result = userSettings.getProperty(name); if (result != null && result.trim().length() != 0) { return result; } result = systemSettings.getProperty(name); if (result == null || result.trim().length() == 0) { return null; } return result; } public List<String> getProperties(String name) { String rawValue = getProperty(name); if (rawValue == null) { return Collections.emptyList(); } return Util.splitComma(rawValue); } public DDNSType getDdnsType(String name) { String str = getProperty(name); if (str == null || str.trim().length() == 0) { return null; } return DDNSType.valueOf(str); } public void remove(String name) { synchronized (changedProperties) { changedProperties.add(name); } userSettings.remove(name); } public void subscribe(ConfigListener listener, String... names) { for (String cur : names) { List<ConfigListener> previous = this.listeners.get(cur); if (previous == null) { previous = new ArrayList<>(); this.listeners.put(cur, previous); } previous.add(listener); } } public File getTempDirectory() { String tmpDirectory = getProperty("server.tmp.directory"); if (tmpDirectory != null) { return new File(tmpDirectory); } return new File(System.getProperty("java.io.tmpdir")); } public Path getTempDirectoryPath() { String tmpDirectory = getProperty("server.tmp.directory"); if (tmpDirectory != null) { return fs.getPath(tmpDirectory); } return fs.getPath(System.getProperty("java.io.tmpdir")); } public Path getPath(String filename) { return fs.getPath(filename); } }
package seedu.manager.model.task; import seedu.manager.commons.exceptions.IllegalValueException; /** * Represents whether a task is done. * Guarantees: immutable; is valid as declared in {@link #isValid(String)} */ public class Done extends TaskProperty { public static final String MESSAGE_DONE_CONSTRAINTS = "Task done indicator should be in the form \"Yes\" or \"No\""; public static final String DONE_VALIDATION_REGEX = "Yes|No"; public static final String COMMAND_WORD = "done"; private boolean value; public Done(String done) throws IllegalValueException { super(done, DONE_VALIDATION_REGEX, MESSAGE_DONE_CONSTRAINTS); value = done.equals("Yes") ? true : false; } @Override public String toString() { return value ? "Yes" : "No"; } /** * Checks if the task property matches with that of the search function's input */ @Override public boolean matches(String done) { if (done.equals("Yes")) { return true; } return false; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof Done // instanceof handles nulls && this.value == ((Done) other).value); // state check } }
package ssd.app.helper; import java.sql.SQLException; import java.sql.Timestamp; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import ssd.app.dao.DbHelper; import ssd.app.model.Expense; public class ExpensesHelper { private static final ExpensesHelper INSTANCE = new ExpensesHelper(); public static ExpensesHelper getInstance(){ return INSTANCE; } private ExpensesHelper(){ } @SuppressWarnings("unchecked") public List<Expense> getExpenses() throws SQLException{ List<Expense> expenses = new ArrayList<Expense>(); Session session = DbHelper.getInstance().openSession(); Transaction tx = null; try{ tx = session.beginTransaction(); Query query = session.createQuery("FROM Expense"); expenses = (List<Expense>)query.list(); tx.commit(); }catch (HibernateException e) { if(tx != null){ tx.rollback(); } e.printStackTrace(); }finally { session.close(); } return expenses; } @SuppressWarnings("unchecked") public List<Expense> getExpenses(int year) throws SQLException, ParseException{ List<Expense> expenses = new ArrayList<Expense>(); Session session = DbHelper.getInstance().openSession(); Transaction tx = null; try{ tx = session.beginTransaction(); Query query = null; if(year > 1970){ // is it a year we can work with? DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); Date date = dateFormat.parse("01/01/" + year); // start long time = date.getTime(); Timestamp start = new Timestamp(time); date = dateFormat.parse("31/12/" + year); time = date.getTime(); Timestamp end = new Timestamp(time); query = session.createQuery("FROM Expense WHERE date BETWEEN :start AND :end").setParameter("start", start).setParameter("end", end); } if(query == null){ query = session.createQuery("FROM Expense"); } expenses = (List<Expense>)query.list(); tx.commit(); }catch (HibernateException e) { if(tx != null){ tx.rollback(); } e.printStackTrace(); }finally { session.close(); } return expenses; } public Expense getExpense(Long expenseId){ Expense expense = new Expense(); Session session = DbHelper.getInstance().openSession(); Transaction tx = null; try{ tx = session.beginTransaction(); expense = (Expense) session.get(Expense.class, expenseId); tx.commit(); }catch (HibernateException e) { if(tx != null){ tx.rollback(); } e.printStackTrace(); }finally { session.close(); } return expense; } }
package wasdev.sample.servlet; import java.io.IOException; import java.net.URLDecoder; import java.security.SecureRandom; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.watson.developer_cloud.conversation.v1.Conversation; import com.ibm.watson.developer_cloud.conversation.v1.model.InputData; import com.ibm.watson.developer_cloud.conversation.v1.model.MessageOptions; import com.ibm.watson.developer_cloud.conversation.v1.model.MessageResponse; import dhbw.timetable.rapla.data.event.Appointment; import dhbw.timetable.rapla.date.DateUtilities; import dhbw.timetable.rapla.exceptions.NoConnectionException; import dhbw.timetable.rapla.parser.DataImporter; @WebServlet("/ChatBot") @MultipartConfig public class ChatBot extends HttpServlet { private static final long serialVersionUID = 791798790786547540L; private MessageResponse response = null; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String messageToWatson = req.getParameter("text"); Conversation service = new Conversation(Conversation.VERSION_DATE_2017_05_26); service.setUsernameAndPassword("f1e1a1c3-da01-4592-a92c-d63003148de2", "c1yTAF028iUH"); service.setEndPoint("https://gateway-fra.watsonplatform.net/conversation/api"); InputData input = new InputData.Builder(messageToWatson).build(); MessageOptions options; if (response != null) { options = new MessageOptions.Builder("bd8f3a37-1517-42a9-ad49-f82cb1400ba0").input(input) .context(response.getContext()).build(); } else { options = new MessageOptions.Builder("bd8f3a37-1517-42a9-ad49-f82cb1400ba0").input(input).build(); } response = service.message(options).execute(); String answer = response.getOutput().getText().get(0); if (answer.contains("At datePart uni starts at logicPart for you.")) { String date = response.getEntities().get(0).getValue(); final String url = URLDecoder.decode(req.getParameter("url").replace("+", "%2B"), "UTF-8").replace("%2B", "+"); LocalDate searchedDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd")); LocalDate week = DateUtilities.Normalize(searchedDate); // Load data Map<LocalDate, ArrayList<Appointment>> data; try { data = DataImporter.ImportWeekRange(week, week, url); Appointment first = null; for (Appointment a : data.get(week)) if (a.getStartDate().toLocalDate().equals(searchedDate) && (first == null || a.getStartDate().isBefore(first.getStartDate()))) first = a; if (first == null) { answer = "You have no lessons on " + searchedDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy")) + "."; } else { answer = answer.replace("logicPart", first.getStartTime()); answer = answer.replace("datePart", searchedDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy"))); } } catch (IllegalAccessException | NoConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (answer.contains("At datePart you have the following lessons: logicPart")) { String date = response.getEntities().get(0).getValue(); final String url = URLDecoder.decode(req.getParameter("url").replace("+", "%2B"), "UTF-8").replace("%2B", "+"); LocalDate searchedDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd")); LocalDate week = DateUtilities.Normalize(searchedDate); // Load data Map<LocalDate, ArrayList<Appointment>> data; try { data = DataImporter.ImportWeekRange(week, week, url); String lessons = ""; Boolean foundalesson = false; for (Appointment a : data.get(week)) if (a.getStartDate().toLocalDate().equals(searchedDate)) { lessons = lessons + a.getTitle() + ", "; foundalesson = true; } lessons = lessons.trim(); if (lessons.endsWith(",")) { lessons = lessons.substring(0, lessons.length() - 1); } answer = answer.replace("logicPart", lessons); answer = answer.replace("datePart", searchedDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy"))); if (!foundalesson) { answer = "You have no lessons on " + searchedDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy")) + "."; } } catch (IllegalAccessException | NoConnectionException e) { e.printStackTrace(); } } else if (answer.contains("todayFlagAt datePart uni ends at logicPart for you.")) { final String url = URLDecoder.decode(req.getParameter("url").replace("+", "%2B"), "UTF-8").replace("%2B", "+"); LocalDate searchedDate = LocalDate.now(); LocalDate week = DateUtilities.Normalize(searchedDate); // Load data Map<LocalDate, ArrayList<Appointment>> data; try { data = DataImporter.ImportWeekRange(week, week, url); Appointment last = null; for (Appointment a : data.get(week)) if (a.getStartDate().toLocalDate().equals(searchedDate) && (last == null || a.getStartDate().isAfter(last.getStartDate()))) last = a; if (last == null) { answer = "You have no lessons on " + searchedDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy")) + "."; } else { answer = answer.replace("logicPart", last.getEndTime()); answer = answer.replace("datePart", searchedDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy"))); answer = answer.substring(9); } } catch (IllegalAccessException | NoConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (answer.contains("At datePart uni ends at logicPart for you.")) { String date = response.getEntities().get(0).getValue(); final String url = URLDecoder.decode(req.getParameter("url").replace("+", "%2B"), "UTF-8").replace("%2B", "+"); LocalDate searchedDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd")); LocalDate week = DateUtilities.Normalize(searchedDate); // Load data Map<LocalDate, ArrayList<Appointment>> data; try { data = DataImporter.ImportWeekRange(week, week, url); Appointment last = null; for (Appointment a : data.get(week)) if (a.getStartDate().toLocalDate().equals(searchedDate) && (last == null || a.getStartDate().isAfter(last.getStartDate()))) last = a; if (last == null) { answer = "You have no lessons on " + searchedDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy")) + "."; } else { answer = answer.replace("logicPart", last.getEndTime()); answer = answer.replace("datePart", searchedDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy"))); } } catch (IllegalAccessException | NoConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (answer.contains("The coin logicPart Throw again?")) { SecureRandom sr = new SecureRandom(); int i = sr.nextInt(100); if (i < 50) { answer = answer.replace("logicPart", "shows heads."); } else if (i > 50) { answer = answer.replace("logicPart", "shows tails."); } else { answer = answer.replace("logicPart", "stands on the edge!"); } } resp.getWriter().println(answer); } }
package wasdev.sample.servlet; import java.io.IOException; import java.net.URLDecoder; import java.security.SecureRandom; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.watson.developer_cloud.conversation.v1.Conversation; import com.ibm.watson.developer_cloud.conversation.v1.model.InputData; import com.ibm.watson.developer_cloud.conversation.v1.model.MessageOptions; import com.ibm.watson.developer_cloud.conversation.v1.model.MessageResponse; import dhbw.timetable.rapla.data.event.Appointment; import dhbw.timetable.rapla.date.DateUtilities; import dhbw.timetable.rapla.exceptions.NoConnectionException; import dhbw.timetable.rapla.parser.DataImporter; @WebServlet("/ChatBot") @MultipartConfig public class ChatBot extends HttpServlet { private static final long serialVersionUID = 791798790786547540L; private MessageResponse response = null; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String messageToWatson = req.getParameter("text"); Conversation service = new Conversation(Conversation.VERSION_DATE_2017_05_26); service.setUsernameAndPassword("f1e1a1c3-da01-4592-a92c-d63003148de2", "c1yTAF028iUH"); service.setEndPoint("https://gateway-fra.watsonplatform.net/conversation/api"); InputData input = new InputData.Builder(messageToWatson).build(); MessageOptions options; if (response != null) { options = new MessageOptions.Builder("bd8f3a37-1517-42a9-ad49-f82cb1400ba0").input(input) .context(response.getContext()).build(); } else { options = new MessageOptions.Builder("bd8f3a37-1517-42a9-ad49-f82cb1400ba0").input(input).build(); } response = service.message(options).execute(); String answer = response.getOutput().getText().get(0); if (response.getIntents().get(0).getIntent().equals("#startingTime")) { String date = response.getEntities().get(0).getValue(); final String url = URLDecoder.decode(req.getParameter("url").replace("+", "%2B"), "UTF-8").replace("%2B", "+"); LocalDate searchedDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd")); LocalDate week = DateUtilities.Normalize(searchedDate); // Load data Map<LocalDate, ArrayList<Appointment>> data; try { data = DataImporter.ImportWeekRange(week, week, url); Appointment first = null; for (Appointment a : data.get(week)) if (a.getStartDate().toLocalDate().equals(searchedDate) && (first == null || a.getStartDate().isBefore(first.getStartDate()))) first = a; answer = answer.replace("logicPart", first.getStartTime()); } catch (IllegalAccessException | NoConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (response.getIntents().get(0).getIntent().equals("#timetable")) { String date = response.getEntities().get(0).getValue(); final String url = URLDecoder.decode(req.getParameter("url").replace("+", "%2B"), "UTF-8").replace("%2B", "+"); LocalDate searchedDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd")); LocalDate week = DateUtilities.Normalize(searchedDate); // Load data Map<LocalDate, ArrayList<Appointment>> data; try { data = DataImporter.ImportWeekRange(week, week, url); String lessons = ""; for (Appointment a : data.get(week)) if (a.getStartDate().toLocalDate().equals(searchedDate)) lessons = lessons + " " + a.getTitle(); answer = answer.replace("logicPart", lessons.trim()); } catch (IllegalAccessException | NoConnectionException e) { e.printStackTrace(); } } else if (response.getIntents().get(0).getIntent().equals("#throwCoin")) { SecureRandom sr = new SecureRandom(); int i = sr.nextInt(100); if(i<50) { answer.replace("logicPart", "shows heads."); } else if(i>50) { answer.replace("logicPart", "shows tails."); } else { answer.replace("logicPart", "stands on the edge!"); } } resp.getWriter().println(answer); } }
package wasdev.sample.servlet; import java.io.IOException; import java.net.URLDecoder; import java.security.SecureRandom; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.watson.developer_cloud.conversation.v1.Conversation; import com.ibm.watson.developer_cloud.conversation.v1.model.InputData; import com.ibm.watson.developer_cloud.conversation.v1.model.MessageOptions; import com.ibm.watson.developer_cloud.conversation.v1.model.MessageResponse; import dhbw.timetable.rapla.data.event.Appointment; import dhbw.timetable.rapla.date.DateUtilities; import dhbw.timetable.rapla.exceptions.NoConnectionException; import dhbw.timetable.rapla.parser.DataImporter; @WebServlet("/ChatBot") @MultipartConfig public class ChatBot extends HttpServlet { private static final long serialVersionUID = 791798790786547540L; private MessageResponse response = null; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String messageToWatson = req.getParameter("text"); Conversation service = new Conversation(Conversation.VERSION_DATE_2017_05_26); service.setUsernameAndPassword("f1e1a1c3-da01-4592-a92c-d63003148de2", "c1yTAF028iUH"); service.setEndPoint("https://gateway-fra.watsonplatform.net/conversation/api"); InputData input = new InputData.Builder(messageToWatson).build(); MessageOptions options; if (response != null) { options = new MessageOptions.Builder("bd8f3a37-1517-42a9-ad49-f82cb1400ba0").input(input) .context(response.getContext()).build(); } else { options = new MessageOptions.Builder("bd8f3a37-1517-42a9-ad49-f82cb1400ba0").input(input).build(); } response = service.message(options).execute(); String answer = response.getOutput().getText().get(0); if (response.getIntents().get(0).getIntent().equals("startingTime")) { String date = response.getEntities().get(0).getValue(); final String url = URLDecoder.decode(req.getParameter("url").replace("+", "%2B"), "UTF-8").replace("%2B", "+"); LocalDate searchedDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd")); LocalDate week = DateUtilities.Normalize(searchedDate); // Load data Map<LocalDate, ArrayList<Appointment>> data; try { data = DataImporter.ImportWeekRange(week, week, url); Appointment first = null; for (Appointment a : data.get(week)) if (a.getStartDate().toLocalDate().equals(searchedDate) && (first == null || a.getStartDate().isBefore(first.getStartDate()))) first = a; answer = answer.replace("logicPart", first.getStartTime()); answer = answer.replace("datePart", searchedDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy"))); } catch (IllegalAccessException | NoConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (response.getIntents().get(0).getIntent().equals("timetable")) { String date = response.getEntities().get(0).getValue(); final String url = URLDecoder.decode(req.getParameter("url").replace("+", "%2B"), "UTF-8").replace("%2B", "+"); LocalDate searchedDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd")); LocalDate week = DateUtilities.Normalize(searchedDate); // Load data Map<LocalDate, ArrayList<Appointment>> data; try { data = DataImporter.ImportWeekRange(week, week, url); String lessons = ""; for (Appointment a : data.get(week)) if (a.getStartDate().toLocalDate().equals(searchedDate)) lessons = lessons + " " + a.getTitle(); answer = answer.replace("logicPart", lessons.trim()); answer = answer.replace("datePart", searchedDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy"))); } catch (IllegalAccessException | NoConnectionException e) { e.printStackTrace(); } } else if (response.getIntents().get(0).getIntent().equals("#throwCoin")) { SecureRandom sr = new SecureRandom(); int i = sr.nextInt(100); if(i<50) { answer.replace("logicPart", "shows heads."); } else if(i>50) { answer.replace("logicPart", "shows tails."); } else { answer.replace("logicPart", "stands on the edge!"); } } resp.getWriter().println(answer); } }
package org.testng.internal; import org.testng.ITestNGMethod; public class MethodInstance { private ITestNGMethod m_method; private Object[] m_instances; public MethodInstance(ITestNGMethod method, Object[] instances) { m_method = method; m_instances = instances; } public ITestNGMethod getMethod() { return m_method; } public Object[] getInstances() { return m_instances; } public String toString() { return "[MethodInstance m:" + m_method + " i:" + m_instances[0]; } }
package jolie.net.http.json; import java.io.IOException; import java.io.Reader; import java.util.Map; import java.util.Map.Entry; import jolie.runtime.Value; import jolie.runtime.ValueVector; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.json.simple.parser.ParseException; /** * * @author Fabrizio Montesi */ public class JsonUtils { private final static String ROOT_SIGN = "$"; private final static String JSONARRAY_KEY = "_"; private final static String JSONULL = "__NULL__"; public static void valueToJsonString( Value value, StringBuilder builder ) throws IOException { if ( value.children().isEmpty() ) { if ( value.isDefined() ) { builder.append( nativeValueToJsonString( value ) ); } else { builder.append("{}"); } } else { if ( value.hasChildren( JSONARRAY_KEY )) { valueVectorToJsonString( value.children().get( JSONARRAY_KEY ), builder, true ); } else { builder.append( '{' ); if ( value.isDefined() ) { appendKeyColon( builder, ROOT_SIGN ); builder.append( nativeValueToJsonString( value ) ); } int size = value.children().size(); int i = 0; for( Entry< String, ValueVector > child : value.children().entrySet() ) { appendKeyColon( builder, child.getKey() ); valueVectorToJsonString( child.getValue(), builder, false ); if ( i++ < size - 1 ) { builder.append( ',' ); } } builder.append( '}' ); } } } private static void valueVectorToJsonString( ValueVector vector, StringBuilder builder, boolean isArray ) throws IOException { if ( isArray || ( !isArray && vector.size() > 1 )) { builder.append( '[' ); for( int i = 0; i < vector.size(); i++ ) { valueToJsonString( vector.get( i ), builder ); if ( i < vector.size() - 1 ) { builder.append( ',' ); } } builder.append( ']' ); } else { valueToJsonString( vector.first(), builder ); } } private static void appendKeyColon( StringBuilder builder, String key ) { builder.append( '"' ) .append( key ) .append( "\":" ); } private static String nativeValueToJsonString( Value value ) throws IOException { if ( value.isInt() || value.isDouble() ) { return value.strValue(); } else { if ( value.strValue().equals( JSONULL )) { return "null"; } else { return '"' + JSONValue.escape( value.strValue() ) + '"'; } } } public static void parseJsonIntoValue( Reader reader, Value value ) throws IOException { try { Object obj = JSONValue.parseWithException( reader ); if ( obj instanceof JSONArray ) { value.children().put( JSONARRAY_KEY, jsonArrayToValueVector( (JSONArray) obj ) ); } else { jsonObjectToValue( (JSONObject) obj, value ); } } catch( ParseException e ) { throw new IOException( e ); } catch( ClassCastException e ) { throw new IOException( e ); } } private static void jsonObjectToValue( JSONObject obj, Value value ) { Map< String, Object > map = (Map< String, Object >)obj; ValueVector vec; for( Entry< String, Object > entry : map.entrySet() ) { if ( entry.getKey().equals( ROOT_SIGN ) ) { if ( entry.getValue() instanceof String ) { value.setValue( (String) entry.getValue() ); } else if ( entry.getValue() instanceof Double ) { value.setValue( (Double)entry.getValue() ); } else if ( entry.getValue() instanceof Integer ) { value.setValue( (Integer)entry.getValue() ); } else if ( entry.getValue() instanceof Long ) { value.setValue( ((Long)entry.getValue()).intValue() ); } else if ( entry.getValue() instanceof Boolean ){ Boolean b = (Boolean)entry.getValue(); if ( b ) { value.setValue( 1 ); } else { value.setValue( 0 ); } } else { value.setValue( entry.getValue().toString() ); } } else { vec = jsonObjectToValueVector( entry.getValue() ); value.children().put( entry.getKey(), vec ); } } } private static ValueVector jsonObjectToValueVector( Object obj ) { ValueVector vec = ValueVector.create(); if ( obj instanceof JSONObject ) { Value val = Value.create(); jsonObjectToValue( (JSONObject)obj, val ); vec.add( val ); } else if ( obj instanceof JSONArray ) { Value arrayValue = Value.create(); vec.add( arrayValue ); arrayValue.children().put( JSONARRAY_KEY, jsonArrayToValueVector( (JSONArray) obj ) ); } else { vec.add( getBasicValue( obj ) ); } return vec; } private static ValueVector jsonArrayToValueVector( JSONArray array ) { ValueVector vec = ValueVector.create(); for ( Object element : array ) { if ( element instanceof JSONObject ) { Value val = Value.create(); jsonObjectToValue( (JSONObject)element, val ); vec.add( val ); } else { vec.add( getBasicValue( element ) ); } } return vec; } private static Value getBasicValue( Object obj ) { Value val = Value.create(); if ( obj instanceof String ) { val.setValue( (String) obj ); } else if ( obj instanceof Double ) { val.setValue( (Double) obj ); } else if ( obj instanceof Integer ) { val.setValue( (Integer) obj ); } else if ( obj instanceof Long ) { val.setValue( ((Long) obj).intValue() ); } else if ( obj instanceof Boolean ) { Boolean b = (Boolean) obj; if ( b ) { val.setValue( 1 ); } else { val.setValue( 0 ); } } else if ( obj == null ) { val.setValue( JSONULL ); } else { val.setValue( obj.toString() ); } return val; } }
/** * BFS */ public class BFS { public static void main(String[] args) { Graph graph = new Graph(8); graph.addEdge(0,1); graph.addEdge(0,3); graph.addEdge(1,2); graph.addEdge(1,4); graph.addEdge(3,4); graph.addEdge(2,5); graph.addEdge(4,5); graph.addEdge(4,6); graph.addEdge(5,7); graph.addEdge(6,7); graph.bfs(0, 7); } }
package tatai; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Random; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.concurrent.WorkerStateEvent; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.ProgressBar; import javafx.scene.control.TableView; import javafx.scene.control.Alert.AlertType; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.text.Text; import javafx.stage.Stage; /** ** Controller class. Controls behaviour of the application. **/ public class TataiController { // Stage to swap scenes in and out of. private Stage _stage = null; // Scenes. private TataiLoader _loader; // Current level. private int _level = 1; // Total number of questions. final static private int NUM_QUESTIONS = 10; // Current question number up to. private int _currentQuestionNumber = 0; // Number of correct answers this level. private int _numCorrect = 0; // Number of previous attempts. private int _tries = 0; // List of statistics. private List<TataiStatistic> _statistics = new ArrayList<TataiStatistic>(); // Statistics table to update. private TableView<TataiStatistic> _table = new TableView<TataiStatistic>(); // Number that user has to pronounce in Maori private int _numToSay = 0; // Filename. final static private String FILENAME = "recording.wav"; // Mode. private String _mode; // Correct streak. private int _streak; // Scene to return to. private Scene _returnScene; // Statistics. private int _personalBest1 = 0; private int _personalBest2 = 0; private int _longestStreakPractice = 0; private int _longestStreakAssess = 0; private int _longestPractice = 0; // FXML-injected nodes. @FXML private Text number; @FXML private Button recordButton; @FXML private Button returnButton; @FXML private Button redoButton; @FXML private Button playButton; @FXML private Button nextButton; @FXML private Text announceRight; @FXML private Text announceWrong; @FXML private Text announceRecording; @FXML private Text numberCorrect; @FXML private Button nextLevelButton; @FXML private HBox statsPanel; @FXML private Text questionNumber; @FXML private ProgressBar progressBar; @FXML private HBox imageRight; @FXML private HBox imageWrong; @FXML private BorderPane root; @FXML private Button chooseLevel1Button; @FXML private Button chooseLevel2Button; @FXML private Text personalBest1; @FXML private Text personalBest2; @FXML private Text longestStreakPractice; @FXML private Text longestStreakAssess; @FXML private Text longestPractice; @FXML private Text achievementText; /** ** Constructor. Sets the stage to a private field so that it is usable everywhere. Loads the scenes. ** @arg Stage stage The stage to display the application on. **/ public TataiController(Stage stage) { _stage = stage; _loader = new TataiLoader(this); } /** ** Executed after initialization of FXML-injected nodes. **/ @FXML private void initialize() { // Bind "managed" to "visible", so that hiding a node also removes it from the flow of the scene. if (recordButton != null) { recordButton.managedProperty().bind(recordButton.visibleProperty()); returnButton.managedProperty().bind(returnButton.visibleProperty()); redoButton.managedProperty().bind(redoButton.visibleProperty()); playButton.managedProperty().bind(playButton.visibleProperty()); nextButton.managedProperty().bind(nextButton.visibleProperty()); announceRight.managedProperty().bind(announceRight.visibleProperty()); announceWrong.managedProperty().bind(announceWrong.visibleProperty()); announceRecording.managedProperty().bind(announceRecording.visibleProperty()); imageRight.managedProperty().bind(imageRight.visibleProperty()); imageWrong.managedProperty().bind(imageWrong.visibleProperty()); } if (nextLevelButton != null) { nextLevelButton.managedProperty().bind(nextLevelButton.visibleProperty()); } } /** ** Initialization script to show the main menu and set up scenes and data. **/ public void init() { // Initialize the statistics page with a table. ObservableList<TataiStatistic> data = FXCollections.observableArrayList(_statistics); _table = TataiFactory.makeTable(); _table.setItems(data); // Add the table to the panel. statsPanel.getChildren().addAll(_table); // Show menu. Scene scene = _loader.getScene("menu"); _stage.setTitle("Welcome to Tatai!"); _stage.setScene(scene); _stage.show(); } /** ** Shows the first level. ** @arg ActionEvent event The event that caused this method to be called. **/ @FXML protected void showLevel1(ActionEvent event) { _level = 1; initLevel(); } /** ** Shows the second level. ** @arg ActionEvent event The event that caused this method to be called. **/ @FXML protected void showLevel2(ActionEvent event) { _level = 2; initLevel(); } /** ** Initializes each level at the start of a round. **/ private void initLevel() { _numCorrect = 0; _currentQuestionNumber = 1; _tries = 0; showLevel(); } /** ** Pops up an achievement unlocked modal box. **/ private void showAchievement(String achieved) { _returnScene = _stage.getScene(); achievementText.setText(achieved); Scene scene = _loader.getScene("achievement"); _stage.setScene(scene); _stage.show(); } /** ** Returns to the previously stored scene. ** @arg ActionEvent event The event that caused this method to be called. **/ @FXML protected void returnToScene(ActionEvent event) { _stage.setScene(_returnScene); _stage.show(); } /** ** Shows the menu. ** @arg ActionEvent event The event that caused this method to be called. **/ @FXML protected void showMenu(ActionEvent event) { if(_stage.getScene().equals(_loader.getScene("level"))) { Alert alert = new Alert(AlertType.CONFIRMATION); alert.setTitle("Return to menu?"); alert.setHeaderText("Return to menu?"); alert.setContentText("Are you sure you wish to return to the main menu? You may lose unsaved progress."); Optional<ButtonType> result = alert.showAndWait(); // Confirmed if (result.get() == ButtonType.OK){ showMenu(); } else { // Cancelled } } else { showMenu(); } } /** ** Shows the menu. **/ private void showMenu() { Scene scene = _loader.getScene("menu"); _stage.setScene(scene); _stage.show(); // Check for achievements - practice length. if (_mode == "practice" && _currentQuestionNumber > _longestPractice) { _longestPractice = _currentQuestionNumber; longestPractice.setText(Integer.toString(_longestPractice)); showAchievement("Longest practice session!"); return; } } /** ** Records the user and processes the recording. ** @arg ActionEvent event The event that caused this method to be called. **/ @FXML protected void record(ActionEvent event) { // Hide recording button, show recording dialog. minimizeButtons(); announceRecording.setVisible(true); // Ensure GUI concurrency by doing in background Task<Void> task = new Task<Void>() { @Override public Void call(){ SpeechHandler.recordAndProcess(); return null; } }; new Thread(task).start(); // When recording has finished: task.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent t) { minimizeButtons(); // Process recording. boolean isCorrect = SpeechHandler.isRecordingCorrect(_numToSay); // If correct, hide the redo button and increase the number correct. if (isCorrect) { _streak++; _numCorrect++; announceRight.setVisible(true); imageRight.setVisible(true); root.setStyle("-fx-background-color:#388E3C;"); } else { _streak = 0; // If wrong, show the redo button and allow the user to try again. announceWrong.setVisible(true); imageWrong.setVisible(true); root.setStyle("-fx-background-color:#D32F2F;"); // If this is your first time wrong, you get to try again. if (_tries == 0) { redoButton.setVisible(true); } } // Always show the play button and the next button and hide the record button. // Show next button. nextButton.setVisible(true); // Show play button. playButton.setVisible(true); // Check for achievements. if(_mode == "practice" && _streak > _longestStreakPractice) { _longestStreakPractice = _streak; showAchievement("Longest practice streak!"); longestStreakPractice.setText(Integer.toString(_longestStreakPractice)); return; } if(_mode == "assess" && _streak > _longestStreakAssess) { _longestStreakAssess = _streak; showAchievement("Longest test streak!"); longestStreakAssess.setText(Integer.toString(_longestStreakAssess)); return; } } }); } /** ** Allows a user to redo their recording. ** @arg ActionEvent event The event that caused this method to be called. **/ @FXML protected void redo(ActionEvent event) { _tries++; record(null); } /** ** Plays audio. ** @arg ActionEvent event The event that caused this method to be called. **/ @FXML protected void play(ActionEvent event) { // Play audio here. // Ensure GUI concurrency by doing in background. Task<Void> task = new Task<Void>() { @Override public Void call(){ String cmd = "aplay " + FILENAME; ProcessBuilder builder = new ProcessBuilder("/bin/bash", "-c", cmd); try { builder.start(); } catch (Exception e) { } return null; } }; new Thread(task).start(); } /** ** Shows the next question, or the end level screen, depending on which question the user is on. ** @arg ActionEvent event The event that caused this method to be called. **/ @FXML protected void next(ActionEvent event) { _tries = 0; // If the current question number is the last question, show the end level screen. if(_currentQuestionNumber >= NUM_QUESTIONS) { showEndLevel(_numCorrect); } else { // Show the next question. _currentQuestionNumber++; showLevel(); } } /** ** Shows the next level. Only two levels, so show level 2. ** @arg ActionEvent event The event that caused this method to be called. **/ @FXML protected void nextLevel(ActionEvent event) { showLevel2(null); } /** ** Replays the current level. ** @arg ActionEvent event The event that caused this method to be called. **/ @FXML protected void replay(ActionEvent event) { initLevel(); } /** ** Function to minimize all the buttons. Show as necessary. **/ private void minimizeButtons() { // Hide redo button. redoButton.setVisible(false); // Hide next button. nextButton.setVisible(false); // Hide play button. playButton.setVisible(false); recordButton.setVisible(false); // Hide announcements. announceRight.setVisible(false); announceRecording.setVisible(false); announceWrong.setVisible(false); // Hide images. imageRight.setVisible(false); imageWrong.setVisible(false); } /** ** Show a question for this level. **/ private void showLevel() { Scene scene = _loader.getScene("level"); // Hide all buttons. minimizeButtons(); // Reset colour of background. root.setStyle("-fx-background-color:#37474F;"); // Show record button recordButton.setVisible(true); // Question setup here. // Numbers to test for current question. List<String> questionNums; if (_mode == "assess") { // Show progress bar. progressBar.setProgress((float) _currentQuestionNumber/NUM_QUESTIONS); // Show question number. questionNumber.setText(Integer.toString(_currentQuestionNumber) + "/" + Integer.toString(NUM_QUESTIONS)); // Test Division TODO Make division have up to 99 as an answer // Temporarily make operation choice random. Random rand = new Random(); String operand = TataiFactory._operands.get(rand.nextInt(TataiFactory._operands.size())); // Generate assessment questions. questionNums = TataiFactory.generateQuestionAssess(operand, _level); } else { progressBar.setProgress((float) 0); // Show question number. questionNumber.setText(Integer.toString(_currentQuestionNumber) + "/?"); // Generate assessment questions. questionNums = TataiFactory.generateQuestionPractice(_level); } // Number to say. _numToSay = Integer.parseInt(questionNums.get(1)); // Edit display text to display question. number.setText(questionNums.get(0)); _stage.setScene(scene); _stage.show(); } /** ** Show the end level screen. ** @arg int numCorrect The number correct to display. **/ private void showEndLevel(int numCorrect) { // If on level 1 and number correct is greater than or equal to 8, show next level button, else hide it if (_level == 1 && numCorrect >= 8) { nextLevelButton.setVisible(true); } else { nextLevelButton.setVisible(false); } // Show number correct. numberCorrect.setText(Integer.toString(numCorrect) + "/" + NUM_QUESTIONS); // Create a new TataiStatistic entry. TataiStatistic entry = new TataiStatistic(numCorrect, _level); // Add it to the statistics list. _statistics.add(entry); Scene scene = _loader.getScene("endlevel"); _stage.setScene(scene); _stage.show(); // Check for achievements - personal best. if (_level == 1 && _numCorrect > _personalBest2) { _personalBest1 = _numCorrect; showAchievement("Most correct for level 1!"); personalBest1.setText(Integer.toString(_personalBest1)); return; } if (_level == 2 && _numCorrect > _personalBest2) { _personalBest1 = _numCorrect; showAchievement("Most correct for level 2!"); personalBest2.setText(Integer.toString(_personalBest2)); return; } } /** ** Show the statistics page. ** @arg ActionEvent event The event that caused this method to be called. **/ @FXML private void showStatistics() { // Update the table with the new list of data. ObservableList<TataiStatistic> data = FXCollections.observableArrayList(_statistics); _table.setItems(data); // Show the scene. Scene scene = _loader.getScene("statistics"); _stage.setScene(scene); _stage.show(); } /** ** Show the practice level. ** @arg ActionEvent event The event that caused this method to be called. **/ @FXML private void showPractice() { // Show the scene. _mode = "practice"; initLevel(); } /** ** Show the assess page. ** @arg ActionEvent event The event that caused this method to be called. **/ @FXML private void showAssess() { // Show the scene. _mode = "assess"; initLevel(); } /** ** Show the settings page. ** @arg ActionEvent event The event that caused this method to be called. **/ @FXML private void showSettings() { // Show the scene. Scene scene = _loader.getScene("settings"); if (_level == 1) { setLevel1(); } else { setLevel2(); } _stage.setScene(scene); _stage.show(); } /** ** Set the level to level 1. Make the level 1 button depressed and the level 2 button not depressed. ** @arg ActionEvent event The event that caused this method to be called. **/ @FXML private void setLevel1() { // Show the scene. _level = 1; chooseLevel1Button.getStyleClass().clear(); chooseLevel1Button.getStyleClass().add("button"); chooseLevel1Button.getStyleClass().add("depressedbutton"); chooseLevel2Button.getStyleClass().clear(); chooseLevel2Button.getStyleClass().add("button"); } /** ** Set the level to level 2. Make the level 2 button depressed and the level 2 button not depressed. ** @arg ActionEvent event The event that caused this method to be called. **/ @FXML private void setLevel2() { // Show the scene. _level = 2; chooseLevel1Button.getStyleClass().clear(); chooseLevel1Button.getStyleClass().add("button"); chooseLevel2Button.getStyleClass().clear(); chooseLevel2Button.getStyleClass().add("button"); chooseLevel2Button.getStyleClass().add("depressedbutton"); } /** ** Quits the application. ** @arg ActionEvent event The event that caused this method to be called. **/ @FXML protected void quit() { Alert alert = new Alert(AlertType.CONFIRMATION); alert.setTitle("Quit Tātai?"); alert.setHeaderText("Quit Tātai?"); alert.setContentText("Are you sure you wish to quit Tātai? You may lose unsaved progress."); Optional<ButtonType> result = alert.showAndWait(); // Confirmed if (result.get() == ButtonType.OK){ Platform.exit(); } else { // Cancelled } } }
package harvester; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; /** * Utility to harvest ASGS regional statistics from the ABS.Stat web service, in * JSON format, and then process the data into a more compact format more * suitable for transmission. * * @author Michael de Hoog */ public class Harvester { private final static String LINE_SEPARATOR = System.getProperty("line.separator"); private final static boolean OVERWRITE_PROCESSED = false; private final static String REGION_CONCEPT_ID = "REGION"; private final static String REGION_TYPE_CONCEPT_ID = "REGIONTYPE"; private final static String SA2_REGION_TYPE_CODE = "SA2"; private final static int PROCESSING_THREAD_COUNT = 5; public static class Dataset { public final String id; public final String description; public final List<Concept> concepts = new ArrayList<>(); public final Map<String, Concept> conceptMap = new HashMap<>(); public Dataset(String id, String description) { this.id = id; this.description = description; } @Override public String toString() { return "Dataset(" + id + ")"; } } public static class Concept { public final Dataset dataset; public final String id; public final List<Code> codes = new ArrayList<>(); public final List<Code> rootCodes = new ArrayList<>(); public final Map<String, Code> allCodesMap = new HashMap<>(); public final Set<Code> usedCodes = new HashSet<>(); public Concept(Dataset dataset, String id) { this.dataset = dataset; this.id = id; } @Override public String toString() { return "Concept(" + id + ")"; } } public static class Code { public final Concept concept; public final String id; public final String description; public final String parentId; public Code parent; public final List<Code> children = new ArrayList<>(); public Code(Concept concept, String id, String description, String parentId) { this.concept = concept; this.id = id; this.description = description; this.parentId = parentId; } @Override public String toString() { return "Code(" + id + ")"; } } public static class Data { public final Concept childConcept; public final DataValues values; public final List<Code> codes = new ArrayList<>(); public final Map<Code, Data> data = new HashMap<>(); public double min = Double.MAX_VALUE; public double max = -Double.MAX_VALUE; public Data(Concept childConcept, DataValues values) { this.childConcept = childConcept; this.values = values; } } public static class DataValues { public final List<String> times = new ArrayList<>(); public final Map<String, String> values = new HashMap<>(); } public static void main(String[] args) throws IOException, ParseException { File rootDir = new File("downloaded"); Writer errorWriter = new FileWriter(new File(rootDir, "errors.txt")); System.out.println("Loading datasets"); File datasetFile = new File(rootDir, "datasetList.json"); JSONObject datasetsJson = downloadDatasetList(datasetFile); final List<Dataset> datasets = new ArrayList<>(); JSONArray datasetsArray = (JSONArray) datasetsJson.get("datasets"); for (int i = 0; i < datasetsArray.size(); i++) { JSONObject datasetObject = (JSONObject) datasetsArray.get(i); String datasetId = (String) datasetObject.get("id"); String datasetDescription = (String) datasetObject.get("description"); Dataset dataset = new Dataset(datasetId, datasetDescription); File conceptsFile = conceptsFile(rootDir, datasetId); JSONObject conceptsJson = downloadDatasetConcepts(datasetId, conceptsFile); JSONArray concepts = (JSONArray) conceptsJson.get("concepts"); if (concepts == null) { continue; } boolean regionTypeCorrect = false; if (concepts.contains(REGION_TYPE_CONCEPT_ID) && concepts.contains(REGION_CONCEPT_ID)) { File codeListFile = codeListFile(rootDir, datasetId, REGION_TYPE_CONCEPT_ID); JSONObject regionTypesJson = downloadCodeListValue(datasetId, REGION_TYPE_CONCEPT_ID, codeListFile); JSONArray codes = (JSONArray) regionTypesJson.get("codes"); for (int j = 0; j < codes.size(); j++) { JSONObject code = (JSONObject) codes.get(j); String codeId = (String) code.get("code"); if (SA2_REGION_TYPE_CODE.equals(codeId)) { regionTypeCorrect = true; break; } } } if (!regionTypeCorrect) { continue; } datasets.add(dataset); for (int j = 0; j < concepts.size(); j++) { String conceptId = (String) concepts.get(j); Concept concept = new Concept(dataset, conceptId); dataset.concepts.add(concept); dataset.conceptMap.put(conceptId, concept); File codeListFile = codeListFile(rootDir, datasetId, conceptId); JSONObject codeListJson = downloadCodeListValue(datasetId, conceptId, codeListFile); JSONArray codes = (JSONArray) codeListJson.get("codes"); for (int k = 0; k < codes.size(); k++) { JSONObject codeJson = (JSONObject) codes.get(k); String codeId = (String) codeJson.get("code"); if (dataset.description.equals(codeId)) { //for some reason the ABS returns the dataset description for one of the codes? continue; } String parentId = (String) codeJson.get("parentCode"); String codeDescription = (String) codeJson.get("description"); Code code = new Code(concept, codeId, codeDescription, parentId); concept.codes.add(code); concept.allCodesMap.put(codeId, code); } for (Code code : concept.codes) { if (code.parentId == null || code.parentId.length() == 0) { concept.rootCodes.add(code); } else { Code parent = concept.allCodesMap.get(code.parentId); assertTrue(parent != null, "Could not find parent code '" + code.parentId + "' for code '" + code.id + "' (dataset = '" + datasetId + "', concept = '" + conceptId + "')"); code.parent = parent; parent.children.add(code); } } } } List<Thread> threads = new ArrayList<>(); final AtomicInteger datasetIndex = new AtomicInteger(0); for (int t = 0; t < PROCESSING_THREAD_COUNT; t++) { Thread thread = new Thread(new Runnable() { @Override public void run() { while (true) { int index = datasetIndex.getAndIncrement(); if (index >= datasets.size()) { break; } Dataset dataset = datasets.get(index); try { processDataset(dataset, rootDir, errorWriter); } catch (Exception e) { try { errorWriter.write("Error processing dataset " + dataset.id + ": " + e.getLocalizedMessage()); errorWriter.flush(); } catch (IOException e1) { e1.printStackTrace(); } } } } }); thread.start(); threads.add(thread); } for (Thread thread : threads) { try { thread.join(); } catch (InterruptedException e) { } } errorWriter.close(); System.out.println("Done"); } private static void processDataset(Dataset dataset, File rootDir, Writer errorWriter) throws IOException { File processedDirectory = new File(rootDir, "processed/" + dataset.id); File summaryFile = new File(processedDirectory, "summary.json"); if (summaryFile.exists() && !OVERWRITE_PROCESSED) { return; } /*if (!"ABS_NRP9_ASGS".equals(dataset.id)) { continue; }*/ System.out.println("Processing data for dataset '" + dataset.id + "'"); List<Concept> combinationConcepts = new ArrayList<>(); Set<Concept> ignoredConcepts = new HashSet<>(); for (Concept concept : dataset.concepts) { if (REGION_CONCEPT_ID.equals(concept.id)) { continue; } else if (REGION_TYPE_CONCEPT_ID.equals(concept.id) || "STATE".equals(concept.id) || "FREQUENCY".equals(concept.id)) { ignoredConcepts.add(concept); } else { combinationConcepts.add(concept); } } //region is the last dimension in the cube: Concept regionConcept = dataset.conceptMap.get(REGION_CONCEPT_ID); combinationConcepts.add(regionConcept); Data rootData = new Data(combinationConcepts.get(0), null); //5 levels to download: String[] regionTypes = { "AUS", "STE", "SA4", "SA3", "SA2" }; int[] orParentLevels = { -1, 0, 1, 2, 3 }; Code parentRegionCode = regionConcept.allCodesMap.get("0"); for (int level = 0; level < 5; level++) { String regionType = regionTypes[level]; List<Code> codes = new ArrayList<>(); if (level == 0) { codes.add(parentRegionCode); } else { addCodeChildrenToListAtLevel0(parentRegionCode, codes, orParentLevels[level]); } for (Code code : codes) { String url = "http://stat.abs.gov.au/itt/query.jsp?method=GetGenericData&datasetid=" + dataset.id; url += level == 0 ? ("&and=REGION.0") : ("&and=REGIONTYPE." + regionType + "&orParent=REGION." + code.id); File file = new File(rootDir, "data/" + dataset.id + "/" + regionType + "/" + (level == 0 ? "" : "parent") + code.id + ".json"); JSONObject data = null; JSONArray series = null; int retries = 5; for (int retry = 0; retry < retries; retry++) { if (retry > 0) { System.out.println("Downloading from " + url + " failed, retrying (attempt " + (retry + 1) + "/" + retries + ")"); } try { data = downloadJSONObject(new URL(url), file); series = (JSONArray) data.get("series"); if (series != null) { break; } } catch (Exception e) { } file.delete(); } if (series == null) { String message = "Error downloading from " + url + ", data = " + data; System.err.println(message); errorWriter.write(dataset.id + ": " + message + LINE_SEPARATOR); errorWriter.flush(); //try next URL (we can always rerun) continue; } //assertTrue(series != null, "Error downloading from " + url); for (int i = 0; i < series.size(); i++) { JSONObject serie = (JSONObject) series.get(i); JSONArray conceptsArray = (JSONArray) serie.get("concepts"); Map<Concept, Code> codesFromCombinations = new HashMap<>(); for (int j = 0; j < conceptsArray.size(); j++) { JSONObject conceptJson = (JSONObject) conceptsArray.get(j); String conceptName = (String) conceptJson.get("name"); String conceptValue = (String) conceptJson.get("Value"); Concept concept = dataset.conceptMap.get(conceptName); assertTrue(concept != null, "Unknown concept returned in data: " + conceptName); if (ignoredConcepts.contains(concept)) { continue; } assertTrue(!codesFromCombinations.containsKey(concept), "A value for concept '" + conceptName + "' has already been defined for this data"); Code conceptCode = concept.allCodesMap.get(conceptValue); assertTrue(code != null, "Unknown concept code returned in data '" + conceptValue + "' for concept '" + conceptName + "'"); concept.usedCodes.add(conceptCode); codesFromCombinations.put(concept, conceptCode); } assertTrue(codesFromCombinations.keySet().containsAll(combinationConcepts), "Not all concepts from the combination were included in the data"); DataValues values = new DataValues(); JSONArray observationsArray = (JSONArray) serie.get("observations"); for (int j = 0; j < observationsArray.size(); j++) { JSONObject observationJson = (JSONObject) observationsArray.get(j); String observationTime = (String) observationJson.get("Time"); String observationValue = (String) observationJson.get("Value"); assertTrue(!values.values.containsKey(observationTime), "Value for time '" + observationTime + "' has already been added"); values.times.add(observationTime); values.values.put(observationTime, observationValue); } insertData(combinationConcepts, 0, codesFromCombinations, rootData, values); } } } System.out.println("Saving processed data for dataset '" + dataset.id + "'"); saveData(rootData, processedDirectory, combinationConcepts.get(combinationConcepts.size() - 1)); saveSummary(dataset, summaryFile, combinationConcepts); } private static void assertTrue(boolean value, String message) { if (!value) { throw new IllegalStateException(message); } } private static void addCodeChildrenToListAtLevel0(Code parentCode, List<Code> list, int level) { if (level == 0) { list.add(parentCode); } else if (level > 0) { for (Code code : parentCode.children) { addCodeChildrenToListAtLevel0(code, list, level - 1); } } } private static File conceptsFile(File rootDir, String datasetId) { return new File(rootDir, "concepts/" + datasetId + ".json"); } private static File codeListFile(File rootDir, String datasetId, String conceptId) { return new File(rootDir, "codeLists/" + datasetId + "/" + conceptId + ".json"); } private static JSONObject downloadDatasetList(File path) throws IOException, ParseException { URL url = new URL("http://stat.abs.gov.au/itt/query.jsp?method=GetDatasetList"); return downloadJSONObject(url, path); } private static JSONObject downloadDatasetConcepts(String datasetId, File path) throws IOException, ParseException { URL url = new URL("http://stat.abs.gov.au/itt/query.jsp?method=GetDatasetConcepts&datasetid=" + datasetId); return downloadJSONObject(url, path); } private static JSONObject downloadCodeListValue(String datasetId, String concept, File path) throws IOException, ParseException { URL url = new URL("http://stat.abs.gov.au/itt/query.jsp?method=GetCodeListValue&datasetid=" + datasetId + "&concept=" + concept + "&format=json"); return downloadJSONObject(url, path); } private static JSONObject downloadJSONObject(URL url, File path) throws IOException, ParseException { if (!path.exists()) { downloadFile(url, path); } JSONParser parser = new JSONParser(); try (FileReader reader = new FileReader(path)) { return (JSONObject) parser.parse(reader); } } private static void downloadFile(URL url, File file) throws IOException { if (file.getParentFile() != null) { file.getParentFile().mkdirs(); } System.out.println("Downloading " + url); ReadableByteChannel rbc = Channels.newChannel(url.openStream()); FileOutputStream fos = new FileOutputStream(file); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); } private static void insertData(List<Concept> combinationConcepts, int conceptIndex, Map<Concept, Code> codes, Data into, DataValues values) { Concept concept = combinationConcepts.get(conceptIndex); Code code = codes.get(concept); Data data = into.data.get(code); if (conceptIndex >= combinationConcepts.size() - 1) { //last one, insert values assertTrue(data == null, "Already a data value for " + code.id); data = new Data(null, values); into.codes.add(code); into.data.put(code, data); } else { if (data == null) { data = new Data(combinationConcepts.get(conceptIndex + 1), null); into.codes.add(code); into.data.put(code, data); } insertData(combinationConcepts, conceptIndex + 1, codes, data, values); } } private static void saveData(Data data, File file, Concept lastConcept) throws IOException { if (data.childConcept == lastConcept) { File jsonFile = new File(file.getParentFile(), file.getName() + ".json"); JSONObject json = saveData(data); jsonFile.getParentFile().mkdirs(); try (FileWriter writer = new FileWriter(jsonFile)) { json.writeJSONString(writer); } } else { for (Code code : data.codes) { Data child = data.data.get(code); File childFile = new File(file, data.childConcept.id + "." + code.id); saveData(child, childFile, lastConcept); } } } @SuppressWarnings("unchecked") private static JSONObject saveData(Data data) { Map<String, Integer> timeCounts = new HashMap<>(); fillTimeCounts(data, timeCounts); int dataCount = dataCount(data); calculateMinMax(data, data); List<String> times = new ArrayList<>(timeCounts.keySet()); Collections.sort(times); //if a certain time only appears in less than 10% of the records, then ignore it for (int i = 0; i < times.size(); i++) { String time = times.get(i); int timeCount = timeCounts.get(time); if (timeCount / (double) dataCount < 0.1) { times.remove(i timeCounts.remove(time); } } Map<String, Object> json = new HashMap<>(); json.put("c", data.childConcept.id); json.put("min", (Double) data.min); json.put("max", (Double) data.max); JSONArray timeArray = new JSONArray(); for (String time : times) { timeArray.add(tryConvertToNumber(time)); } json.put("t", timeArray); JSONArray dataArray = new JSONArray(); for (Code code : data.codes) { Data child = data.data.get(code); DataValues values = child.values; assertTrue(values != null, "DataValues is null"); boolean foundNonNull = false; for (String time : times) { String value = values.values.get(time); if (value != null) { foundNonNull = true; break; } } if (!foundNonNull) { //don't save observations that have no values continue; } Map<String, Object> dataJson = new HashMap<>(); dataJson.put("k", tryConvertToNumber(code.id)); JSONArray valueArray = new JSONArray(); for (String time : times) { String value = values.values.get(time); valueArray.add(tryConvertToNumber(value)); } dataJson.put("v", valueArray); dataArray.add(new JSONObject(dataJson)); } json.put("d", dataArray); return new JSONObject(json); } @SuppressWarnings("unchecked") private static void saveSummary(Dataset dataset, File file, List<Concept> conceptsOrder) throws IOException { Map<String, Object> json = new HashMap<>(); json.put("id", dataset.id); json.put("description", dataset.description); JSONArray conceptArray = new JSONArray(); for (Concept concept : conceptsOrder) { if ("REGION".equals(concept.id)) { //don't write region concept to summary file continue; } Map<String, Object> conceptJson = new HashMap<>(); conceptJson.put("name", concept.id); JSONArray codesArray = new JSONArray(); for (Code code : concept.codes) { if (!concept.usedCodes.contains(code)) { //skip unused codes continue; } Map<String, Object> codeJson = new HashMap<>(); codeJson.put("k", code.id); codeJson.put("v", code.description); codesArray.add(new JSONObject(codeJson)); } conceptJson.put("codes", codesArray); conceptArray.add(new JSONObject(conceptJson)); } json.put("concepts", conceptArray); JSONObject jsonObject = new JSONObject(json); try (FileWriter writer = new FileWriter(file)) { jsonObject.writeJSONString(writer); } } private static Object tryConvertToNumber(String s) { if (s == null) { return s; } try { return Long.valueOf(s); } catch (NumberFormatException e) { try { return Double.valueOf(s); } catch (NumberFormatException e2) { return s; } } } private static void fillTimeCounts(Data data, Map<String, Integer> counts) { if (data.values != null) { for (String time : data.values.times) { Integer count = counts.get(time); count = count == null ? 0 : count; counts.put(time, count + 1); } } for (Data child : data.data.values()) { fillTimeCounts(child, counts); } } private static void calculateMinMax(Data data, Data store) { if (data.values != null) { for (String value : data.values.values.values()) { if (value == null) { continue; } try { double d = Double.parseDouble(value); store.min = Math.min(store.min, d); store.max = Math.max(store.max, d); } catch (NumberFormatException e) { } } } for (Data child : data.data.values()) { calculateMinMax(child, store); } } private static int dataCount(Data data) { int count = 0; if (data.values != null) { count++; } for (Data child : data.data.values()) { count += dataCount(child); } return count; } }
package client.controllers; import client.windows.*; import common.*; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Pos; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.paint.Color; import javafx.scene.text.Text; import javafx.stage.Stage; import javafx.util.Callback; import java.io.IOException; import java.math.BigDecimal; import java.net.URL; import java.rmi.RemoteException; import java.util.*; public class BudgetController implements Initializable, SelfUpdating { @FXML private Text txtBudgetName; @FXML private Text txtBudgetDescription; @FXML private Text txtSum, txtSumPerPerson; @FXML private Button btnAddPayment, btnSettle, btnAddParticipant, btnBudgetClose, btnBudgetDelete; @FXML private TableView<Payment> tabUnaccPayments, tabAccPayments; @FXML private TableView<User> tabParticipants; @FXML private TableView<Settlement> tabSettleHistory; @FXML private TableColumn colDate,colAmount,colStatus; @FXML private TableColumn colUnaccWhat, colUnaccWho, colUnaccAmount, colConfirm; @FXML private TableColumn colAccWhat, colAccWho, colAccAmount; @FXML private TableColumn colUserName, colUserMail, colUserBalance; private static DBHandler dbController = LoginController.dbController; private final ObservableList<User> participantsList = FXCollections.observableArrayList(); private final ObservableList<Payment> accountedPayments = FXCollections.observableArrayList(); private final ObservableList<Payment> unaccountedPayments = FXCollections.observableArrayList(); private final ObservableList<Settlement> settleHistory = FXCollections.observableArrayList(); private final User currentUser = LoginController.currentUser; private Stage currentStage; private Budget budget; double spentMoneySum = 0; public Stage getStage() {return currentStage;} public void setStage(Stage stage) { currentStage = stage; } public void setBudget(Budget budget) { this.budget = budget; txtBudgetName.setText(budget.getName()); txtBudgetDescription.setText(budget.getDescription()); if (!currentUser.equals(budget.getOwner())) { btnAddParticipant.setDisable(true); btnSettle.setDisable(true); btnBudgetDelete.setDisable(true); } } @Override public void initialize(URL location, ResourceBundle resources) { //Buttons btnSettle.setOnAction(event -> { try { ObservableList<Payment> paymentsToSettle = FXCollections.observableArrayList(); for (Payment p : unaccountedPayments) if (p.getAccept()) paymentsToSettle.add(p); SettleWindow settleWindow = new SettleWindow(budget, paymentsToSettle, this); settleWindow.initOwner(currentStage); settleWindow.showAndWait(); paymentsToSettle.clear(); settleHistory.clear(); fillTabSettleHistory(); } catch(Exception e){ e.printStackTrace(); } }); btnAddPayment.setOnAction(event -> { try { AddPaymentWindow addPaymentWindow = new AddPaymentWindow(budget, participantsList); addPaymentWindow.initOwner(currentStage); addPaymentWindow.setOnHidden(e -> fillTabUnaccPayments()); addPaymentWindow.show(); } catch (IOException e) { e.printStackTrace(); } }); btnAddParticipant.setOnAction(event -> { try { AddUserToBudgetWindow addUserToBudgetWindow = new AddUserToBudgetWindow((BudgetWindow) currentStage); addUserToBudgetWindow.initOwner(currentStage); addUserToBudgetWindow.setOnHidden(e -> fillTabUnaccPayments()); addUserToBudgetWindow.show(); } catch (IOException e) { e.printStackTrace(); } }); btnBudgetClose.setOnAction(event -> currentStage.close()); btnBudgetDelete.setOnAction(event -> { Alert deleteBudgetAlert = new Alert(Alert.AlertType.CONFIRMATION); deleteBudgetAlert.setTitle("Confirm deletion"); deleteBudgetAlert.setHeaderText("Are you sure you want to delete this budget?"); deleteBudgetAlert.setContentText("This operation cannot be undone."); Optional<ButtonType> result = deleteBudgetAlert.showAndWait(); if (result.isPresent() && result.get() == ButtonType.OK) { try { try { dbController.deleteBudget(budget); } catch (RemoteException e) { e.printStackTrace(); } currentStage.close(); } catch (Exception e) { e.printStackTrace(); } } }); //Table colUnaccWhat.setCellValueFactory(new PropertyValueFactory<Payment, String>("what")); colAccWhat.setCellValueFactory(new PropertyValueFactory<Payment, String>("what")); colUnaccWho.setCellValueFactory(new PropertyValueFactory<Payment, String>("who")); colAccWho.setCellValueFactory(new PropertyValueFactory<Payment, String>("who")); colUnaccAmount.setCellValueFactory(new PropertyValueFactory<Payment, Integer>("amount")); colAccAmount.setCellValueFactory(new PropertyValueFactory<Payment, Integer>("amount")); colUserName.setCellValueFactory(new PropertyValueFactory<User, String>("name")); colUserMail.setCellValueFactory(new PropertyValueFactory<User, String>("email")); colConfirm.setCellFactory(param -> new CheckBoxTableCell()); colDate.setCellValueFactory(new PropertyValueFactory<Settlement,String>("date")); colAmount.setCellValueFactory(new PropertyValueFactory<Settlement,Double>("amount")); colStatus.setCellValueFactory(new PropertyValueFactory<Settlement,String>("status")); colStatus.setCellFactory(new Callback<TableColumn, TableCell>() { public TableCell call(TableColumn param) { return new TableCell<Settlement, String>() { @Override public void updateItem(String item, boolean empty) { super.updateItem(item, empty); if (!isEmpty()) { this.setStyle("-fx-background-color:red"); if (item.equals("OK")) this.setStyle("-fx-background-color:green"); setText(item); } } }; } }); colUserBalance.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<User, BigDecimal>, ObservableValue<BigDecimal>>() { public ObservableValue<BigDecimal> call(TableColumn.CellDataFeatures<User, BigDecimal> p) { User participant = p.getValue(); double balance = 0; if (participant != null) balance = participant.getSpentMoney() - spentMoneySum / participantsList.size(); return new ReadOnlyObjectWrapper<>(new BigDecimal(balance).setScale(2, BigDecimal.ROUND_FLOOR)); } }); tabSettleHistory.setItems(settleHistory); tabParticipants.setItems(participantsList); tabParticipants.setRowFactory(param -> { TableRow<User> row = new TableRow<>(); row.setOnMouseClicked(mouseEvent -> { if (mouseEvent.getClickCount() == 2 && !row.isEmpty()) { User participant = row.getItem(); try { boolean hasUnaccountedPayments = unaccountedPayments.filtered( payment -> payment.getUserId() == participant.getId() ).size() > 0; ParticipantDetailsWindow participantWindow = new ParticipantDetailsWindow(budget, participant, hasUnaccountedPayments); participantWindow.initOwner(currentStage); participantWindow.setOnHidden(event -> { fillTabParticipants(); fillTabUnaccPayments(); }); participantWindow.show(); } catch (IOException e) { e.printStackTrace(); } } }); return row; }); tabSettleHistory.setRowFactory(param -> { TableRow<Settlement> row = new TableRow<>(); row.setOnMouseClicked(mouseEvent -> { if (mouseEvent.getClickCount() == 2 && !row.isEmpty()) { Settlement settlement = row.getItem(); try { SettlementDetailsWindow settlementDetailsWindow = new SettlementDetailsWindow(settlement,budget); settlementDetailsWindow.initOwner(currentStage); settlementDetailsWindow.setOnHidden(event->fillTabSettleHistory()); settlementDetailsWindow.show(); } catch (IOException e) { e.printStackTrace(); } } }); return row; }); tabUnaccPayments.setItems(unaccountedPayments); tabAccPayments.setItems(accountedPayments); tabUnaccPayments.setRowFactory(param -> { TableRow<Payment> row = new TableRow<>(); row.setOnMouseClicked(mouseEvent -> { if (row.isEmpty()) return; Payment payment = row.getItem(); if (currentUser.equals(budget.getOwner()) || payment.getUserId() == currentUser.getId()) { if (mouseEvent.getClickCount() == 2) { try { PaymentWindow paymentWindow = new PaymentWindow(budget, payment, participantsList); paymentWindow.initOwner(currentStage); paymentWindow.setOnHidden(event -> fillTabUnaccPayments()); paymentWindow.show(); } catch (IOException e) { e.printStackTrace(); } } } // TODO else: you have no rights to edit this payment (special color or information) }); return row; }); } void addParticipants(List<User> users) { users.removeAll(participantsList); participantsList.addAll(users); try { List<User> usersSerializable = new ArrayList<>(users); dbController.addBudgetParticipants(budget.getId(), usersSerializable); } catch (RemoteException e) { e.printStackTrace(); } } public void update() { fillTabParticipants(); fillTabUnaccPayments(); fillTabAccPayments(); fillTabSettleHistory(); } void fillTabSettleHistory(){ settleHistory.clear(); try { List<Settlement> settlements = dbController.getAllSettlements(budget.getId()); int it = 0; for(int i=0;i<settlements.size();i++) if(!settlements.get(i).getStatus().equals("OK")) Collections.swap(settlements,it++,i); settleHistory.addAll(settlements); } catch(Exception e) { System.out.println("Access denied"); e.printStackTrace(); } } void fillTabParticipants() { participantsList.clear(); try { participantsList.addAll(dbController.getBudgetParticipants(budget.getId())); } catch (RemoteException e) { e.printStackTrace(); } } void fillTabAccPayments() { accountedPayments.clear(); try { accountedPayments.addAll(dbController.getAllPayments(budget.getId(), true)); } catch (RemoteException e) { e.printStackTrace(); } } void fillTabUnaccPayments() { unaccountedPayments.clear(); try { unaccountedPayments.addAll(dbController.getAllPayments(budget.getId(), false)); } catch (RemoteException e) { e.printStackTrace(); } spentMoneySum = 0; for (User participant : participantsList) participant.setSpentMoney(0); for (Payment p : unaccountedPayments) { spentMoneySum += p.getAmount(); FilteredList<User> filtered = participantsList.filtered(user -> user.getId() == p.getUserId()); if (!filtered.isEmpty()) { User participant = filtered.get(0); participant.addSpentMoney(p.getAmount()); } } refreshBalanceCells(); txtSum.setText("SUM: " + spentMoneySum + "$"); String perPerson = String.format("%.2f", spentMoneySum / participantsList.size()); txtSumPerPerson.setText("Sum / Person: " + perPerson + "$"); } private void refreshBalanceCells() { tabParticipants.getColumns().get(2).setVisible(false); tabParticipants.getColumns().get(2).setVisible(true); } public class CheckBoxTableCell extends TableCell<Payment, Boolean> { private final CheckBox checkBox = new CheckBox(); public CheckBoxTableCell() { setAlignment(Pos.CENTER); checkBox.setOnAction(event -> { Payment payment = (Payment)CheckBoxTableCell.this.getTableRow().getItem(); payment.setAccept(!payment.getAccept()); }); } @Override public void updateItem(Boolean item, boolean empty) { super.updateItem(item, empty); if(!empty) { checkBox.setSelected(true); setGraphic(checkBox); if (currentUser.equals(budget.getOwner())) checkBox.setDisable(false); else checkBox.setDisable(true); } else setGraphic(null); } } }
package com.newsblur.util; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.app.FragmentManager; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.TextView; import com.newsblur.R; import com.newsblur.activity.Profile; import com.newsblur.domain.Classifier; import com.newsblur.fragment.ClassifierDialogFragment; import com.newsblur.view.FlowLayout; public class ViewUtils { private static Drawable tag_green_background, tag_red_background; private static int tag_green_text, tag_red_text; public static void setupShareCount(Context context, View storyView, int sharedUserCount) { String sharedBy = context.getResources().getString(R.string.reading_shared_count); TextView sharesText = (TextView) storyView.findViewById(R.id.shared_by); if (sharedUserCount > 0) { sharedBy = String.format(sharedBy, sharedUserCount); sharesText.setText(sharedUserCount > 1 ? sharedBy : sharedBy.substring(0, sharedBy.length() - 1)); } else { sharesText.setVisibility(View.INVISIBLE); } } public static void setupCommentCount(Context context, View storyView, int sharedCommentCount) { if (context == null || context.getResources() == null) return; String commentsBy = context.getResources().getString(R.string.reading_comment_count); TextView sharesText = (TextView) storyView.findViewById(R.id.comment_by); if (sharedCommentCount > 0) { commentsBy = String.format(commentsBy, sharedCommentCount); sharesText.setText(sharedCommentCount > 1 ? commentsBy : commentsBy.substring(0, commentsBy.length() - 1)); } else { sharesText.setVisibility(View.INVISIBLE); } } public static ImageView createSharebarImage(final Context context, final ImageLoader imageLoader, final String photoUrl, final String userId) { ImageView image = new ImageView(context); int imageLength = UIUtils.convertDPsToPixels(context, 15); image.setMaxHeight(imageLength); image.setMaxWidth(imageLength); FlowLayout.LayoutParams imageParameters = new FlowLayout.LayoutParams(5, 5); imageParameters.height = imageLength; imageParameters.width = imageLength; image.setMaxHeight(imageLength); image.setMaxWidth(imageLength); image.setLayoutParams(imageParameters); imageLoader.displayImage(photoUrl, image, 10f); image.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(context, Profile.class); i.putExtra(Profile.USER_ID, userId); context.startActivity(i); } }); return image; } public static void setupTags(Context context) { tag_green_text = context.getResources().getColor(R.color.tag_green_text); tag_red_text = context.getResources().getColor(R.color.tag_red_text); tag_green_background = context.getResources().getDrawable(R.drawable.tag_background_positive); tag_red_background = context.getResources().getDrawable(R.drawable.tag_background_negative); } public static View createTagView(final LayoutInflater inflater, final FragmentManager fragmentManager, final String tag, final Classifier classifier, final ClassifierDialogFragment.TagUpdateCallback callback, final String feedId) { View v = inflater.inflate(R.layout.tag_view, null); TextView tagText = (TextView) v.findViewById(R.id.tag_text); tagText.setText(tag); if (classifier != null && classifier.tags.containsKey(tag)) { switch (classifier.tags.get(tag)) { case Classifier.LIKE: setViewBackground(tagText, R.drawable.tag_background_positive); tagText.setTextColor(tag_green_text); break; case Classifier.DISLIKE: setViewBackground(tagText, R.drawable.tag_background_negative); tagText.setTextColor(tag_red_text); break; } } v.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { ClassifierDialogFragment classifierFragment = ClassifierDialogFragment.newInstance(callback, feedId, classifier, tag, Classifier.TAG); classifierFragment.show(fragmentManager, "dialog"); } }); return v; } /** * Sets the background resource of a view, working around a platform bug that causes the declared * padding to get reset. */ public static void setViewBackground(View v, int resId) { // due to a framework bug, the below modification of background resource also resets the declared // padding on the view. save a copy of said padding so it can be re-applied after the change. int oldPadL = v.getPaddingLeft(); int oldPadT = v.getPaddingTop(); int oldPadR = v.getPaddingRight(); int oldPadB = v.getPaddingBottom(); v.setBackgroundResource(resId); v.setPadding(oldPadL, oldPadT, oldPadR, oldPadB); } public static void showSystemUI(View view) { // Some layout/drawing artifacts as we don't use the FLAG_LAYOUT flags but otherwise the overlays wouldn't appear // and the action bar would overlap the content view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE); } public static void hideSystemUI(View view) { view.setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE); } public static boolean isSystemUIHidden(View view) { return (view.getSystemUiVisibility() & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0; } public static boolean immersiveViewExitedViaSystemGesture(View view) { return view.getSystemUiVisibility() == (View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE); } }
// FILE: c:/projects/jetel/org/jetel/graph/TransformationGraph.java package org.jetel.graph; import java.util.*; import java.io.*; import java.text.DateFormat; import org.jetel.exception.ComponentNotReadyException; import org.jetel.database.DBConnection; import org.jetel.util.StringUtils; import org.jetel.data.Defaults; import java.util.logging.Logger; /* import org.apache.log4j.Logger; import org.apache.log4j.BasicConfigurator; */ /** * A class that represents Transformation Graph - all the Nodes and connecting Edges * * @author D.Pavlis * @since April 2, 2002 * @see OtherClasses */ /* TODO: enumerateNodes called too many times. The result should be preserved somewhere. It is not a big problem now, but with increasing complexity of graph, the time needed to complete this task will grow. However, it affects only initialization phase. */ public final class TransformationGraph { // Attributes // Associations /** * @since April 2, 2002 */ private List nodes; /** * @since April 2, 2002 */ private List edges; private Map dbConnections; private String name; private static TransformationGraph graph = new TransformationGraph(""); static Logger logger=Logger.getLogger("org.jetel"); static PrintStream log=System.out; // default info messages to stdout // Operations /** *Constructor for the TransformationGraph object * * @param _name Name of the graph * @since April 2, 2002 */ private TransformationGraph(String _name) { this.name = new String(_name); nodes = new ArrayList(); edges = new ArrayList(); dbConnections = new HashMap(); // initialize logger - just basic //BasicConfigurator.configure(); } /** * Sets the Name attribute of the TransformationGraph object * * @param _name The new Name value * @since April 10, 2002 */ public void setName(String _name) { this.name = new String(_name); } /** * Gets the Name attribute of the TransformationGraph object * * @return The Name value * @since April 10, 2002 */ public String getName() { return name; } /** * Gets the DBConnection object asssociated with the name provided * * @param name Description of Parameter * @return The DBConnection object (if found) or null * @since October 1, 2002 */ public DBConnection getDBConnection(String name) { return (DBConnection)dbConnections.get(name); } /** * An operation that starts execution of graph * * @param out OutputStream - if defined, info messages are printed there * @return True if all nodes successfully started, otherwise False * @since April 2, 2002 */ public boolean run() { WatchDog watchDog; watchDog = new WatchDog(log, Defaults.WatchDog.DEFAULT_WATCHDOG_TRACKING_INTERVAL); log.println("[Clover] starting WatchDog thread ..."); watchDog.start(); try { watchDog.join(); } catch (InterruptedException ex) { logger.severe(ex.getMessage()); return false; } log.println("[Clover] WatchDog thread finished"); return watchDog.getStatus() == 0 ? true : false; } /** * Returns linked list of all Nodes. The order of Nodes listed is such that * any parent Node is guaranteed to be listed befor child Node. * The circular references between nodes should be detected. * * @return Description of the Returned Value * @since July 29, 2002 */ public Iterator enumerateNodes() { Set set1 = new HashSet(); Set set2 = new HashSet(); Set actualSet; Set enumerationOfNodes = new LinkedHashSet(); int totalNodesEncountered = 0; Node node; Iterator iterator; // initial populating of set1 - with root Nodes only iterator = nodes.iterator(); while (iterator.hasNext()) { node = (Node) iterator.next(); if (node.isRoot()) { set1.add(node); } } if (set1.isEmpty()) { logger.severe("No root Nodes detected!"); throw new RuntimeException(); } actualSet = set1; // initialize - actualSet is set1 for the very first run while (!actualSet.isEmpty()) { totalNodesEncountered += actualSet.size(); // if there is some Node from actualSet already in the "global" list, it will // be removed which indicates circular reference if (enumerationOfNodes.removeAll(actualSet)) { logger.severe("Circular reference found in graph !"); throw new RuntimeException(); } // did we process already more nodes than we have in total ?? // that indicates we have circular graph if (totalNodesEncountered > nodes.size()) { logger.severe("Circular reference found in graph !"); throw new RuntimeException(); } // add individual nodes from set enumerationOfNodes.addAll(actualSet); // find successors , switch actualSet if (actualSet == set1) { findNodesSuccessors(set1, set2); actualSet = set2; } else { findNodesSuccessors(set2, set1); actualSet = set1; } } return enumerationOfNodes.iterator(); } /** * An operation that aborts execution of graph * * @param out OutputStream - if defined, info messages are printed there * @since April 2, 2002 */ public void abort(OutputStream out) { } /** * An operation that ends execution of graph * * @param out OutputStream - if defined, info messages are printed there * @since April 10, 2002 */ public void end(OutputStream out) { } /** * Description of the Method * * @param out OutputStream - if defined, info messages are printed thereDescription of Parameter * @return returns TRUE if succeeded or FALSE if some Node or Edge failed initialization * @since April 10, 2002 */ public boolean init(OutputStream out) { Iterator nodeIterator; ListIterator edgeIterator = edges.listIterator(); Iterator dbConnectionIterator=dbConnections.values().iterator(); Node node; Edge edge; // if the output stream is specified, create logging possibility information if (out != null) { log = new PrintStream(out); } // iterate through all dbConnection(s) and initialize them - try to connect to db while(dbConnectionIterator.hasNext()){ try{ ((DBConnection)dbConnectionIterator.next()).connect(); }catch(Exception ex){ logger.severe("Can't connect to database: "+ex.getMessage()); return false; } } // iterate through all nodes and initialize them try { nodeIterator = enumerateNodes(); } catch (RuntimeException ex) { logger.severe(ex.getMessage()); return false; } while (nodeIterator.hasNext()) { try { node = (Node) nodeIterator.next(); node.init(); } catch (ComponentNotReadyException ex) { logger.severe(ex.getMessage()); return false; } // if logger exists, print some out information if (log != null) { log.print("[Clover] Initialized node: "); log.println(node.getID()); } } // iterate through all edges and initialize them while (edgeIterator.hasNext()) { try { edge = (Edge) edgeIterator.next(); edge.init(); } catch (IOException ex) { ex.printStackTrace(); return false; } // if logger exists, print some out information if (log != null) { log.print("[Clover] Initialized edge: "); log.println(edge.getID()); } } return true; // initialized OK } /** * An operation that registers Node within current graph * * @param node The feature to be added to the Node attribute * @since April 2, 2002 */ public void addNode(Node node) { nodes.add(node); node.setGraph(this); // assign this graph referenco to Node } /** * An operation that registeres Edge within current graph * * @param edge The feature to be added to the Edge attribute * @since April 2, 2002 */ public void addEdge(Edge edge) { edges.add(edge); edge.setGraph(this); // assign this graph reference to Edge } /** * Removes all Edges from graph * * @since April 2, 2002 */ public void deleteEdges() { edges.clear(); } /** * Removes all Nodes from graph * * @since April 2, 2002 */ public void deleteNodes() { nodes.clear(); } /** * Adds a feature to the DBConnection attribute of the TransformationGraph object * * @param name Name(ID) under which the DBConnection is registered * @param connection DBConnection object to associate with ID * @since October 1, 2002 */ public void addDBConnection(String name, DBConnection connection) { dbConnections.put(name, connection); } /** * Removes all DBConnection objects from Map * * @since October 1, 2002 */ public void deleteDBConnections() { dbConnections.clear(); } /** * Finds all the successors of Nodes from source Set * * @param source Set of source Nodes * @param destination Set of all immediate successors of Nodes from <source> set * @since April 18, 2002 */ protected void findNodesSuccessors(Set source, Set destination) { Iterator nodeIterator = source.iterator(); Iterator portIterator; OutputPort outPort; // remove all previous items from dest. destination.clear(); // iterate through all source nodes while (nodeIterator.hasNext()) { portIterator = ((Node) nodeIterator.next()).getOutPorts().iterator(); // iterate through all output ports // some other node is perhaps connected to these ports while (portIterator.hasNext()) { outPort = (OutputPort) portIterator.next(); // is some Node reading data produced by our source node ? if (outPort.getReader() != null) { destination.add(outPort.getReader()); } } } } /** * Gets the reference to the TransformationGraph class * * @return The Reference value * @since April 10, 2002 */ public static TransformationGraph getReference() { return graph; } /** * Description of the Class * * @author dpavlis * @since July 29, 2002 */ class WatchDog extends Thread { PrintStream log; int trackingInterval; int watchDogStatus; /** *Constructor for the WatchDog object * * @since July 29, 2002 */ WatchDog() { super("WatchDog"); log = System.out; trackingInterval = Defaults.WatchDog.DEFAULT_WATCHDOG_TRACKING_INTERVAL; setDaemon(true); } /** *Constructor for the WatchDog object * * @param out Description of Parameter * @param tracking Description of Parameter * @since July 29, 2002 */ WatchDog(PrintStream out, int tracking) { super("WatchDog"); log = out; trackingInterval = tracking; setDaemon(true); } /** * Execute transformation - start-up all Nodes & watch them running * * @since July 29, 2002 */ public void run() { List leafNodesList = new LinkedList(); List orderedNodes = new LinkedList(); // nodes in order the are in graph ListIterator leafNodesIterator; ListIterator nodesIterator; Node node; int ticker = Defaults.WatchDog.NUMBER_OF_TICKS_BETWEEN_STATUS_CHECKS; long lastTimestamp; long currentTimestamp; long startTimestamp; // first, start-up all Nodes & build list of leaf nodes log.println("[WatchDog] Thread started."); startUpNodes(enumerateNodes(), leafNodesList, orderedNodes); startTimestamp = lastTimestamp = System.currentTimeMillis(); // entering the loop awaiting completion of work by all leaf nodes while (true) { if (leafNodesList.isEmpty()) { watchDogStatus = 0; log.print("[WatchDog] Execution sucessfully finished - elapsed time(sec): "); log.println((System.currentTimeMillis() - startTimestamp) / 1000); printProcessingStatus(orderedNodes.listIterator()); return; // nothing else to do } leafNodesIterator = leafNodesList.listIterator(); while (leafNodesIterator.hasNext()) { node = (Node) leafNodesIterator.next(); // is this Node still alive - ? doing something if (!node.isAlive()) { leafNodesIterator.remove(); } } // check that no Node finished with some fatal error if ((ticker ticker = Defaults.WatchDog.NUMBER_OF_TICKS_BETWEEN_STATUS_CHECKS; nodesIterator = orderedNodes.listIterator(); while (nodesIterator.hasNext()) { node = (Node) nodesIterator.next(); if ((!node.isAlive()) && (node.getResultCode() != Node.RESULT_OK)) { log.println("[WatchDog] !!! Fatal Error !!! - graph execution is aborting"); logger.severe("Node " + node.getID() + " finished with fatal error: "+node.getResultMsg()); abort(); printProcessingStatus(orderedNodes.listIterator()); return; } } } // Display processing status, if it is time currentTimestamp = System.currentTimeMillis(); if ((currentTimestamp - lastTimestamp) >= Defaults.WatchDog.DEFAULT_WATCHDOG_TRACKING_INTERVAL) { printProcessingStatus(orderedNodes.listIterator()); lastTimestamp = currentTimestamp; } // rest for some time try { sleep(Defaults.WatchDog.WATCHDOG_SLEEP_INTERVAL); } catch (InterruptedException ex) { watchDogStatus = -1; return; } } } /** * Gets the Status of the WatchDog * * @return 0 if successful, -1 otherwise * @since July 30, 2002 */ int getStatus() { return watchDogStatus; } /** * Outputs basic LOG information about graph processing * * @param iterator Description of Parameter * @since July 30, 2002 */ void printProcessingStatus(ListIterator iterator) { int i; int recCount; Node node; StringBuffer stringBuf; stringBuf = new StringBuffer(90); log.println(" log.print("Time: "); // France is here just to get 24hour time format log.println(DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.MEDIUM,Locale.FRANCE). format(Calendar.getInstance().getTime())); log.println("Node Status Port #Records"); log.println(" while (iterator.hasNext()) { node = (Node) iterator.next(); Object nodeInfo[]={node.getID(),node.getStatus()}; int nodeSizes[]={-28,-15}; log.println(StringUtils.formatString(nodeInfo,nodeSizes)); //in ports i=0; while((recCount=node.getRecordCount(Node.INPUT_PORT,i))!=-1) { Object portInfo[]={"In:",Integer.toString(i),Integer.toString(recCount)}; int portSizes[]={47,-2,32}; log.println(StringUtils.formatString(portInfo,portSizes)); i++; } //out ports i=0; while((recCount=node.getRecordCount(Node.OUTPUT_PORT,i))!=-1) { Object portInfo[]={"Out:",Integer.toString(i),Integer.toString(recCount)}; int portSizes[]={47,-2,32}; log.println(StringUtils.formatString(portInfo,portSizes)); i++; } } log.println(" log.flush(); } /** *Constructor for the abort object * * @since July 29, 2002 */ void abort() { ListIterator iterator = nodes.listIterator(); Node node; // iterate through all the nodes and start them while (iterator.hasNext()) { node = (Node) iterator.next(); node.abort(); log.print("[WatchDog] Interrupted node: "); log.println(node.getID()); log.flush(); } } /** * Description of the Method * * @param nodesIterator Description of Parameter * @param leafNodesList Description of Parameter * @since July 31, 2002 */ private void startUpNodes(Iterator nodesIterator, List leafNodesList, List orderedNodes) { Node node; log.println("[WatchDog] Starting up all Nodes:"); while (nodesIterator.hasNext()) { node = (Node) nodesIterator.next(); orderedNodes.add(node); node.start(); if (node.isLeaf()) { leafNodesList.add(node); } log.print("[WatchDog] started node: "); log.println(node.getID()); log.flush(); } log.println("[WatchDog] Sucessfully started All Nodes !"); } } } /* * end class TransformationGraph */
package org.jetel.metadata; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import org.jetel.test.CloverTestCase; public class XsdMetadataTest extends CloverTestCase { private String xmlMetadata = "<Record name=\"rec\" type=\"fixed\" recordDelimiter=\"\n\" recordSize=\"40\">" + "<Field name=\"00\" size=\"1\" shift=\"0\" type=\"decimal\"/>" + "<Field name=\"01\" size=\"2\" shift=\"0\" type=\"numeric\"/>" + "<Field name=\"02\" size=\"3\" shift=\"0\" type=\"byte\"/>" + "<Field name=\"03\" size=\"4\" shift=\"0\" type=\"cbyte\"/>" + "<Field name=\"04\" size=\"3\" shift=\"0\" type=\"date\"/>" + "<Field name=\"05\" size=\"1\" shift=\"0\" type=\"datetime\"/>" + "<Field name=\"06\" size=\"1\" shift=\"0\" type=\"integer\"/>" + "<Field name=\"07\" size=\"1\" shift=\"0\" type=\"long\"/>" + "<Field name=\"08\" size=\"1\" shift=\"0\" type=\"decimal\"/>" + "<Field name=\"09\" size=\"2\" shift=\"0\" type=\"decimal\"/>" + "</Record>"; private DataRecordMetadata metadata; private final static String TEST_FILE = "XsdTest.xsd"; protected void setUp() throws Exception { initEngine(); DataRecordMetadataXMLReaderWriter xmlReader = new DataRecordMetadataXMLReaderWriter(); metadata = xmlReader.read(new ByteArrayInputStream(xmlMetadata.getBytes())); } public void test_1(){ try { (new XsdMetadata(metadata)).write(TEST_FILE); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } } protected void tearDown(){ boolean deleted = (new File(TEST_FILE)).delete(); assertTrue("can't delete "+ TEST_FILE, deleted ); } }
package com.vogella.tasks.model; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.Date; import java.util.Objects; public class Todo { private PropertyChangeSupport changes = new PropertyChangeSupport(this); public static final String FIELD_ID = "id"; public static final String FIELD_SUMMARY = "summary"; public static final String FIELD_DESCRIPTION = "description"; public static final String FIELD_DONE = "done"; public static final String FIELD_DUEDATE = "dueDate"; private final long id; private String summary = ""; private String description = ""; private boolean done = false; private Date dueDate = new Date(); public Todo(long id, String summary, String description, boolean done, Date dueDate) { this.id = id; this.summary = summary; this.description = description; this.done = done; this.dueDate = dueDate; } public Todo(long id) { this.id = id; } public String getSummary() { return summary; } public void setSummary(String summary) { changes.firePropertyChange(FIELD_SUMMARY, this.summary, this.summary = summary); } public String getDescription() { return description; } public void setDescription(String description) { changes.firePropertyChange(FIELD_DESCRIPTION, this.description, this.description = description); } public boolean isDone() { return done; } public void setDone(boolean isDone) { changes.firePropertyChange(FIELD_DONE, this.done, this.done = isDone); } public Date getDueDate() { return new Date(dueDate.getTime()); } public void setDueDate(Date dueDate) { changes.firePropertyChange(FIELD_DUEDATE, this.dueDate, this.dueDate = new Date(dueDate.getTime())); } public long getId() { return id; } @Override public String toString() { return "Todo [id=" + id + ", summary=" + summary + "]"; } @Override public int hashCode() { return Objects.hash(id); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Todo other = (Todo) obj; return id == other.id; } public Todo copy() { return new Todo(this.id, this.summary, this.description, this.done, getDueDate()); } public void addPropertyChangeListener(PropertyChangeListener l) { changes.addPropertyChangeListener(l); } public void removePropertyChangeListener(PropertyChangeListener l) { changes.removePropertyChangeListener(l); } }
package com.emc.pravega.common; public final class MetricsNames { // Metrics in Segment Store Service // host stats public static final String SEGMENT_CREATE_LATENCY = "segment_create_latency_ms"; // Timer public static final String SEGMENT_READ_BYTES = "segment_read_bytes"; // Dynamic Counter public static final String SEGMENT_READ_LATENCY = "segment_read_latency_ms"; // Dynamic Gauge public static final String SEGMENT_WRITE_BYTES = "segment_write_bytes"; // Dynamic Counter public static final String SEGMENT_WRITE_LATENCY = "segment_write_latency_ms"; // Dynamic Gauge //hdfs stats public static final String HDFS_READ_LATENCY = "hdfs_read_latency_ms"; // Timer public static final String HDFS_WRITE_LATENCY = "hdfs_write_latency_ms"; // Timer public static final String HDFS_READ_BYTES = "hdfs_read_bytes"; // Counter public static final String HDFS_WRITE_BYTES = "hdfs_write_bytes"; // Counter //DurableLog stats public static final String DURABLE_DATALOG_WRITE_LATENCY = "durable_datalog_write_latency"; // Timer public static final String DURABLE_DATALOG_WRITE_BYTES = "durable_datalog_write_bytes"; // Counter // Metrics in Controller // Stream request counts (Static) public static final String CREATE_STREAM = "stream_created"; // Histogram public static final String SEAL_STREAM = "stream_sealed"; // Histogram // Transaction request Operations (Dynamic) public static final String CREATE_TRANSACTION = "transactions_created"; // Dynamic Meter public static final String COMMIT_TRANSACTION = "transactions_committed"; // Dynamic Meter public static final String ABORT_TRANSACTION = "transactions_aborted"; // Dynamic Meter public static final String OPEN_TRANSACTIONS = "transactions_opened"; // Dynamic Gauge // Stream segment counts (Dynamic) //public static final String SEGMENTS_COUNT = "segments_count"; // Dynamic Counter //public static final String SEGMENTS_SPLITS = "segments_splits"; // Dynamic Guage //public static final String SEGMENTS_MERGES = "segments_merges"; // Dynamic Guage private static String escapeSpecialChar(String name) { return name.replace('/', '.').replace(':', '.').replace('|','.').replaceAll("\\s+", "_"); } public static String nameFromStream(String metric, String scope, String stream) { String name = scope + "." + stream + "." + metric; return escapeSpecialChar(name); } public static String nameFromSegment(String metric, String segmentName) { String name = segmentName + "." + metric; return escapeSpecialChar(name); } }
package org.openecard.common; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentSkipListMap; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.openecard.common.util.FuturePromise; import org.openecard.common.util.Promise; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Thread local dynamic context implemented as a singleton. * Dynamic context information is needed at various places in the app. Perhaps the most important use case is the * eService certificate validation as defined in TR-03112-7.<br> * The underlying datastructure does permit {@code null} values to be saved. * * @author Tobias Wich */ public class DynamicContext { private static final Logger LOG = LoggerFactory.getLogger(DynamicContext.class); private static final InheritableThreadLocal<Map<String, DynamicContext>> LOCAL_MAP; private final Map<String, Promise<Object>> context; static { LOCAL_MAP = new InheritableThreadLocal<Map<String, DynamicContext>>() { @Override protected Map<String, DynamicContext> initialValue() { return new ConcurrentSkipListMap<>(); } @Override protected Map<String, DynamicContext> childValue(Map<String, DynamicContext> parentValue) { return parentValue; } }; } /** * Gets the thread local instance of the context. * If no instance exists yet, a new one is created possibly based on the one from the parent thread. * * @param key Lookup key for the desired variable. * @return The DynamicContext instance of this thread. */ @Nonnull public static DynamicContext getInstance(@Nonnull String key) { final Map<String, DynamicContext> local = LOCAL_MAP.get(); synchronized (local) { DynamicContext inst; if (local.containsKey(key)) { inst = local.get(key); } else { inst = new DynamicContext(); local.put(key, inst); } return inst; } } /** * Removes the value from this thread. * This does not clear the values saved in the context, it just makes the context inaccessible for further invocations * of the {@link #getInstance(String)} method. * * @see ThreadLocal#remove() */ public static synchronized void remove() { LOG.debug("Removing DynamicContext which contains {} map entries.", LOCAL_MAP.get().size()); LOCAL_MAP.remove(); } private DynamicContext() { this.context = new HashMap<>(); } /** * Gets the promise which represents the given key. * If no promise exists yet, a new one will be created. Retrieving the promise value blocks until a value is * delivered to it. * * @param key Key for which the promise should be retrieved. * @return Promise for the given key. */ public synchronized @Nonnull Promise<Object> getPromise(@Nonnull String key) { Promise<Object> p = context.get(key); if (p != null) { return p; } else { p = new Promise<>(); context.put(key, p); return p; } } /** * Gets the value saved for the given key. * The method does not block and returns null if no value is in the promise represented by this key * * @see Map#get(java.lang.Object) * @param key Key for which the value should be retrieved. * @return The value for the given key, or {@code null} if no value is defined yet or {@code null} is mapped. */ public @Nullable Object get(@Nonnull String key) { Promise<Object> p = getPromise(key); return p.derefNonblocking(); } /** * Saves the given value for the given key. * This method writes the value into the promise of the given key, or in case the promise already has a value, * overwrites the promise and sets the value in the new instance. By doing that, the function mimics the exact * behaviour of the Map class. * * @see Map#put(java.lang.Object, java.lang.Object) * @param key Key for which the value should be saved. * @param value Value which should be saved for the given key. * @return The previous value for key or {@code null} if there was no previous mapping or {@code null} was mapped. */ @Nullable public synchronized Object put(@Nonnull String key, @Nullable Object value) { Promise<Object> p = getPromise(key); if (p.isDelivered()) { remove(key); p = getPromise(key); } p.deliver(value); return value; } /** * Saves the given promise so that it its result is available for later use. * This function does not use the default {@link Promise} class and allows to override the behaviour of the * Promise. An example of such a modified behaviour can be found in {@link FuturePromise}. * * @see #put(java.lang.String, java.lang.Object) * @param key Key for which the value should be saved. * @param p Promise yielding the value which should be saved for the given key. */ public synchronized void putPromise(@Nonnull String key, @Nonnull Promise p) { if (context.get(key) != null) { throw new IllegalStateException("Promise already exists and can therefore not be delivered anymore."); } else { context.put(key, p); } } /** * Removes the mapping for the given key. * * @see Map#remove(java.lang.Object) * @param key Key for which to remove the mapping. * @return The previous value for key or {@code null} if there was no previous mapping or {@code null} was mapped. */ @Nullable public Object remove(@Nonnull String key) { Promise<Object> p = context.remove(key); if (p != null) { return p.derefNonblocking(); } return null; } /** * Removes all mappings from the context. * * @see Map#clear() */ public void clear() { context.clear(); } }
// OMEXMLWriter.java package loci.formats.out; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.*; import java.util.Vector; import loci.common.*; import loci.formats.*; import loci.formats.codec.Base64Codec; import loci.formats.codec.JPEG2000Codec; import loci.formats.codec.JPEGCodec; import loci.formats.codec.ZlibCodec; import loci.formats.meta.MetadataRetrieve; import org.xml.sax.Attributes; import org.xml.sax.helpers.DefaultHandler; public class OMEXMLWriter extends FormatWriter { // -- Fields -- private Vector xmlFragments; private RandomAccessFile out; private String currentFragment; // -- Constructor -- public OMEXMLWriter() { super("OME-XML", new String[] {"ome"}); compressionTypes = new String[] {"none", "zlib","J2K","JPEG"}; compression = compressionTypes[0]; } // -- IFormatHandler API methods -- /* @see loci.formats.IFormatHandler#close() */ public void close() throws IOException { if (out != null) out.close(); out = null; xmlFragments = null; } // -- IFormatWriter API methods -- /* @see loci.formats.IFormatWriter#saveImage(Image, int, boolean, boolean) */ public void saveImage(Image image, int series, boolean lastInSeries, boolean last) throws FormatException, IOException { MetadataRetrieve retrieve = getMetadataRetrieve(); if (!initialized) { out = new RandomAccessFile(currentId, "rw"); String xml = MetadataTools.getOMEXML(retrieve); xmlFragments = new Vector(); currentFragment = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; DataTools.parseXML(xml, new OMEHandler()); xmlFragments.add(currentFragment); out.writeBytes((String) xmlFragments.get(0)); initialized = true; } boolean littleEndian=!retrieve.getPixelsBigEndian(series, 0).booleanValue(); BufferedImage buffImage=AWTImageTools.makeBuffered(image); int width = buffImage.getWidth(); int height = buffImage.getHeight(); byte[][] pix = AWTImageTools.getPixelBytes(buffImage,littleEndian); buffImage=null; //TODO: Write decompress to use LittleEndian option Object[] options= {Boolean.TRUE,Boolean.TRUE};//{Boolean.TRUE, Boolean(littleEndian); for (int i = 0; i < pix.length; i++) { //TODO: Create a Method compress to take into account all compression methods int bytes = pix[i].length / (width * height); int[] dims = new int[] { 1, bytes }; // one channels compressed at a time if (compression.equals("J2K")) { pix[i] = new JPEG2000Codec().compress(pix[i], width, height, dims, options); } else if (compression.equals("JPEG")) { pix[i] = new JPEGCodec().compress(pix[i], width, height, dims, options); } else if (compression.equals("zlib")) { pix[i] = new ZlibCodec().compress(pix[i], 0, 0, null, null); } byte[] encodedPix = new Base64Codec().compress(pix[i], 0, 0, null, null); StringBuffer plane = new StringBuffer("\n<Bin:BinData Length=\""); plane.append(encodedPix.length); plane.append("\""); if (compression != null && !compression.equals("none")) { plane.append(" Compression=\""); plane.append(compression); plane.append("\""); } plane.append(">"); plane.append(new String(encodedPix)); plane.append("</Bin:BinData>"); out.writeBytes(plane.toString()); } if (lastInSeries) { out.writeBytes((String) xmlFragments.get(series + 1)); close(); } } public boolean canDoStacks() { return true; } // -- Helper class -- class OMEHandler extends DefaultHandler { public void characters(char[] ch, int start, int length) { currentFragment += new String(ch, start, length); } public void startElement(String uri, String localName, String qName, Attributes attributes) { StringBuffer toAppend = new StringBuffer("\n<"); toAppend.append(qName); for (int i=0; i<attributes.getLength(); i++) { toAppend.append(" "); toAppend.append(attributes.getQName(i)); toAppend.append("=\""); toAppend.append(attributes.getValue(i)); toAppend.append("\""); } toAppend.append(">"); currentFragment += toAppend.toString(); if (qName.equals("Pixels")) { xmlFragments.add(currentFragment); currentFragment = ""; } } public void endElement(String uri, String localName, String qName) { currentFragment += "</" + qName + ">"; } } }
// CanvasHelper.java package imagej.data.display; import imagej.ImageJ; import imagej.data.display.event.ZoomEvent; import imagej.event.EventService; import imagej.util.IntCoords; import imagej.util.Log; import imagej.util.RealCoords; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * A collection of helper methods for {@link ImageCanvas} objects, particularly * panning and zooming. * * @author Curtis Rueden * @author Barry DeZonia */ public class CanvasHelper implements Pannable, Zoomable { private static final int MIN_ALLOWED_VIEW_SIZE = 25; private static double[] defaultZooms; static { List<Double> midLevelZooms = new ArrayList<Double>(); midLevelZooms.add(1 / 32d); midLevelZooms.add(1 / 24d); midLevelZooms.add(1 / 16d); midLevelZooms.add(1 / 12d); midLevelZooms.add(1 / 8d); midLevelZooms.add(1 / 6d); midLevelZooms.add(1 / 4d); midLevelZooms.add(1 / 3d); midLevelZooms.add(1 / 2d); midLevelZooms.add(3 / 4d); midLevelZooms.add(1d); midLevelZooms.add(1.5d); midLevelZooms.add(2d); midLevelZooms.add(3d); midLevelZooms.add(4d); midLevelZooms.add(6d); midLevelZooms.add(8d); midLevelZooms.add(12d); midLevelZooms.add(16d); midLevelZooms.add(24d); midLevelZooms.add(32d); final int EXTRA_ZOOMS = 25; List<Double> loZooms = new ArrayList<Double>(); double prevDenom = 1 / midLevelZooms.get(0); for (int i = 0; i < EXTRA_ZOOMS; i++) { double newDenom = prevDenom + 16; loZooms.add(1 / newDenom); prevDenom = newDenom; } Collections.reverse(loZooms); List<Double> hiZooms = new ArrayList<Double>(); double prevNumer = midLevelZooms.get(midLevelZooms.size()-1); for (int i = 0; i < EXTRA_ZOOMS; i++) { double newNumer = prevNumer + 16; hiZooms.add(newNumer / 1); prevNumer = newNumer; } List<Double> combinedZoomLevels = new ArrayList<Double>(); combinedZoomLevels.addAll(loZooms); combinedZoomLevels.addAll(midLevelZooms); combinedZoomLevels.addAll(hiZooms); defaultZooms = new double[combinedZoomLevels.size()]; for (int i = 0; i < defaultZooms.length; i++) defaultZooms[i] = combinedZoomLevels.get(i); } /** The {@link ImageCanvas} on which this helper operates. */ private final ImageCanvas canvas; /** The standard zoom levels for the canvas */ private final double[] zoomLevels; /** Scale factor, for zooming. */ private double scale = 1; /** Initial scale factor, for resetting zoom. */ private double initialScale = 1; /** Offset from top left, in panel coordinates (pixels). */ private final IntCoords offset = new IntCoords(0, 0); private final EventService eventService; // -- constructors -- public CanvasHelper(final ImageCanvas canvas) { this(canvas, defaultZoomLevels()); } public CanvasHelper(final ImageCanvas canvas, final double[] zoomLevels) { eventService = ImageJ.get(EventService.class); this.canvas = canvas; this.zoomLevels = validatedZoomLevels(zoomLevels); } // -- CanvasHelper methods -- public static double[] defaultZoomLevels() { return defaultZooms; } public boolean isInImage(final IntCoords point) { final RealCoords imageCoords = panelToImageCoords(point); final int x = imageCoords.getIntX(); final int y = imageCoords.getIntY(); return x >= 0 && x < canvas.getCanvasWidth() && y >= 0 && y < canvas.getCanvasHeight(); } public RealCoords panelToImageCoords(final IntCoords panelCoords) { final double imageX = (panelCoords.x + offset.x) / scale; final double imageY = (panelCoords.y + offset.y) / scale; return new RealCoords(imageX, imageY); } public IntCoords imageToPanelCoords(final RealCoords imageCoords) { final int panelX = (int) Math.round(scale * imageCoords.x - offset.x); final int panelY = (int) Math.round(scale * imageCoords.y - offset.y); return new IntCoords(panelX, panelY); } // -- Pannable methods -- @Override public void pan(final IntCoords delta) { offset.x += delta.x; offset.y += delta.y; } @Override public void setPan(final IntCoords origin) { offset.x = origin.x; offset.y = origin.y; } @Override public void panReset() { canvas.setPan(new IntCoords(0, 0)); } @Override public IntCoords getPanOrigin() { return new IntCoords(offset.x, offset.y); } // -- Zoomable methods -- @Override public void setZoom(final double factor) { canvas.setZoom(factor, getDefaultZoomCenter()); } @Override public void setZoom(final double factor, final IntCoords center) { double desiredScale = factor; if (factor == 0) desiredScale = initialScale; if (scaleOutOfBounds(desiredScale)) return; // We know: // imageCenter.x = (center.x + offset.x) / scale // (and only offset and scale change) // Hence: // (center.x + newOffset.x) / desiredScale = (center.x + offset.x) / scale // newOffset.x = -center.x + (center.x + offset.x) * desiredScale / scale offset.x = (int) (-center.x + (center.x + offset.x) * desiredScale / scale); offset.y = (int) (-center.y + (center.y + offset.y) * desiredScale / scale); scale = desiredScale; eventService.publish(new ZoomEvent(canvas, getZoomFactor(), center.x, center.y)); } @Override public void zoomIn() { canvas.zoomIn(getDefaultZoomCenter()); } @Override public void zoomIn(final IntCoords center) { final double newScale = nextLargerZoom(zoomLevels,scale); if (newScale != scale) canvas.setZoom(newScale, center); } @Override public void zoomOut() { canvas.zoomOut(getDefaultZoomCenter()); } @Override public void zoomOut(final IntCoords center) { final double newScale = nextSmallerZoom(zoomLevels,scale); if (newScale != scale) canvas.setZoom(newScale, center); } @Override public void zoomToFit(final IntCoords topLeft, final IntCoords bottomRight) { final int width = bottomRight.x - topLeft.x; final int height = bottomRight.y - topLeft.y; final double imageSizeX = width / scale; final double imageSizeY = height / scale; final double xZoom = canvas.getViewportWidth() / imageSizeX; final double yZoom = canvas.getViewportHeight() / imageSizeY; final double factor = Math.min(xZoom, yZoom); final int centerX = topLeft.x + width / 2; final int centerY = topLeft.y + height / 2; canvas.setZoom(factor, new IntCoords(centerX, centerY)); } @Override public double getZoomFactor() { return scale; } public void setInitialScale(final double value) { if (value <= 0) { throw new IllegalArgumentException("Initial scale must be > 0"); } this.initialScale = value; } public double getInitialScale() { return initialScale; } public static double getBestZoomLevel(double fractionalScale) { double[] levels = defaultZoomLevels(); double zoom = lookupZoom(levels, fractionalScale); if (zoom > 0) return zoom; return nextSmallerZoom(levels, fractionalScale); } // -- Helper methods -- /** Gets the zoom center to use when none is specified. */ private IntCoords getDefaultZoomCenter() { final int w = canvas.getViewportWidth(); final int h = canvas.getViewportHeight(); return new IntCoords(w / 2, h / 2); } private boolean scaleOutOfBounds(final double desiredScale) { if (desiredScale <= 0) { Log.warn("*********** BAD SCALE in CanvasHelper *******************"); return true; } // check if trying to zoom in too close if (desiredScale > scale) { final int maxDimension = Math.max(canvas.getCanvasWidth(), canvas.getCanvasHeight()); // if zooming the image would show less than one pixel of image data if (maxDimension / desiredScale < 1) return true; } // check if trying to zoom out too far if (desiredScale < scale) { // get boundaries of image in panel coords final RealCoords nearCornerImage = new RealCoords(0, 0); final RealCoords farCornerImage = new RealCoords(canvas.getCanvasWidth(), canvas.getCanvasHeight()); final IntCoords nearCornerPanel = imageToPanelCoords(nearCornerImage); final IntCoords farCornerPanel = imageToPanelCoords(farCornerImage); // if boundaries take up less than min allowed pixels in either dimension if (farCornerPanel.x - nearCornerPanel.x < MIN_ALLOWED_VIEW_SIZE || farCornerPanel.y - nearCornerPanel.y < MIN_ALLOWED_VIEW_SIZE) { return true; } } return false; } private static double nextSmallerZoom(double[] zoomLevels, double currScale) { final int index = Arrays.binarySearch(zoomLevels, currScale); int nextIndex; if (index >= 0) nextIndex = index - 1; else nextIndex = -(index + 1) - 1; if (nextIndex < 0) return zoomLevels[0]; if (nextIndex > zoomLevels.length - 1) { return zoomLevels[zoomLevels.length - 1]; } return zoomLevels[nextIndex]; } private static double nextLargerZoom(double[] zoomLevels, double currScale) { final int index = Arrays.binarySearch(zoomLevels, currScale); int nextIndex; if (index >= 0) nextIndex = index + 1; else nextIndex = -(index + 1); if (nextIndex < 0) return zoomLevels[0]; if (nextIndex > zoomLevels.length - 1) { return zoomLevels[zoomLevels.length - 1]; } return zoomLevels[nextIndex]; } private static double[] validatedZoomLevels(final double[] levels) { final double[] validatedLevels = levels.clone(); Arrays.sort(validatedLevels); if (validatedLevels.length == 0) { throw new IllegalArgumentException("given zoom level array is empty"); } double prevEntry = validatedLevels[0]; if (prevEntry <= 0) { throw new IllegalArgumentException( "zoom level array contains nonpositive entries"); } for (int i = 1; i < validatedLevels.length; i++) { final double currEntry = validatedLevels[i]; if (currEntry == prevEntry) { throw new IllegalArgumentException( "zoom level array contains duplicate entries"); } prevEntry = currEntry; } return validatedLevels; } // unfortunately can't rely on Java's binary search since we're using // doubles and rounding errors could cause problems. write our own that // searches zooms avoiding rounding problems. private static double lookupZoom(double[] levels, double requestedZoom) { int lo = 0; int hi = levels.length - 1; do { int mid = (lo + hi) / 2; double possibleZoom = levels[mid]; if (Math.abs(requestedZoom - possibleZoom) < 0.00001) return requestedZoom; if (requestedZoom < possibleZoom) hi = mid - 1; else lo = mid + 1; } while (hi >= lo); return -1; } }
package bisq.core.btc.wallet; import bisq.core.btc.exceptions.AddressEntryException; import bisq.core.btc.exceptions.InsufficientFundsException; import bisq.core.btc.exceptions.TransactionVerificationException; import bisq.core.btc.exceptions.WalletException; import bisq.core.btc.model.AddressEntry; import bisq.core.btc.model.AddressEntryList; import bisq.core.btc.setup.WalletsSetup; import bisq.core.provider.fee.FeeService; import bisq.core.user.Preferences; import bisq.common.handlers.ErrorMessageHandler; import org.bitcoinj.core.Address; import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.Coin; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.InsufficientMoneyException; import org.bitcoinj.core.LegacyAddress; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionConfidence; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutPoint; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.crypto.DeterministicKey; import org.bitcoinj.crypto.KeyCrypterScrypt; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptBuilder; import org.bitcoinj.wallet.SendRequest; import org.bitcoinj.wallet.Wallet; import javax.inject.Inject; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.MoreExecutors; import org.bouncycastle.crypto.params.KeyParameter; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.jetbrains.annotations.NotNull; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; public class BtcWalletService extends WalletService { private static final Logger log = LoggerFactory.getLogger(BtcWalletService.class); private final AddressEntryList addressEntryList; // Constructor @Inject public BtcWalletService(WalletsSetup walletsSetup, AddressEntryList addressEntryList, Preferences preferences, FeeService feeService) { super(walletsSetup, preferences, feeService); this.addressEntryList = addressEntryList; walletsSetup.addSetupCompletedHandler(() -> { wallet = walletsSetup.getBtcWallet(); wallet.addCoinsReceivedEventListener(walletEventListener); wallet.addCoinsSentEventListener(walletEventListener); wallet.addReorganizeEventListener(walletEventListener); wallet.addTransactionConfidenceEventListener(walletEventListener); walletsSetup.getChain().addNewBestBlockListener(block -> chainHeightProperty.set(block.getHeight())); chainHeightProperty.set(walletsSetup.getChain().getBestChainHeight()); }); } // Overridden Methods @Override void decryptWallet(@NotNull KeyParameter key) { super.decryptWallet(key); addressEntryList.getAddressEntriesAsListImmutable().forEach(e -> { DeterministicKey keyPair = e.getKeyPair(); if (keyPair.isEncrypted()) e.setDeterministicKey(keyPair.decrypt(key)); }); addressEntryList.requestPersistence(); } @Override void encryptWallet(KeyCrypterScrypt keyCrypterScrypt, KeyParameter key) { super.encryptWallet(keyCrypterScrypt, key); addressEntryList.getAddressEntriesAsListImmutable().forEach(e -> { DeterministicKey keyPair = e.getKeyPair(); if (keyPair.isEncrypted()) e.setDeterministicKey(keyPair.encrypt(keyCrypterScrypt, key)); }); addressEntryList.requestPersistence(); } @Override String getWalletAsString(boolean includePrivKeys) { StringBuilder sb = new StringBuilder(); getAddressEntryListAsImmutableList().forEach(e -> sb.append(e.toString()).append("\n")); return "Address entry list:\n" + sb.toString() + "\n\n" + wallet.toString(true, includePrivKeys, null, true, true, walletsSetup.getChain()) + "\n\n" + "All pubKeys as hex:\n" + wallet.printAllPubKeysAsHex(); } // Public Methods // Burn BSQ txs (some proposal txs, asset listing fee tx, proof of burn tx) public Transaction completePreparedBurnBsqTx(Transaction preparedBurnFeeTx, byte[] opReturnData) throws WalletException, InsufficientMoneyException, TransactionVerificationException { return completePreparedProposalTx(preparedBurnFeeTx, opReturnData, null, null); } // Proposal txs public Transaction completePreparedReimbursementRequestTx(Coin issuanceAmount, Address issuanceAddress, Transaction feeTx, byte[] opReturnData) throws TransactionVerificationException, WalletException, InsufficientMoneyException { return completePreparedProposalTx(feeTx, opReturnData, issuanceAmount, issuanceAddress); } public Transaction completePreparedCompensationRequestTx(Coin issuanceAmount, Address issuanceAddress, Transaction feeTx, byte[] opReturnData) throws TransactionVerificationException, WalletException, InsufficientMoneyException { return completePreparedProposalTx(feeTx, opReturnData, issuanceAmount, issuanceAddress); } private Transaction completePreparedProposalTx(Transaction feeTx, byte[] opReturnData, @Nullable Coin issuanceAmount, @Nullable Address issuanceAddress) throws TransactionVerificationException, WalletException, InsufficientMoneyException { // (BsqFee)tx has following structure: // inputs [1-n] BSQ inputs (fee) // outputs [0-1] BSQ request fee change output (>= 546 Satoshi) // preparedCompensationRequestTx has following structure: // inputs [1-n] BSQ inputs for request fee // inputs [1-n] BTC inputs for BSQ issuance and miner fee // outputs [1] Mandatory BSQ request fee change output (>= 546 Satoshi) // outputs [1] Potentially BSQ issuance output (>= 546 Satoshi) - in case of a issuance tx, otherwise that output does not exist // outputs [0-1] BTC change output from issuance and miner fee inputs (>= 546 Satoshi) // outputs [1] OP_RETURN with opReturnData and amount 0 // mining fee: BTC mining fee + burned BSQ fee Transaction preparedTx = new Transaction(params); // Copy inputs from BSQ fee tx feeTx.getInputs().forEach(preparedTx::addInput); int indexOfBtcFirstInput = feeTx.getInputs().size(); // Need to be first because issuance is not guaranteed to be valid and would otherwise burn change output! // BSQ change outputs from BSQ fee inputs. feeTx.getOutputs().forEach(preparedTx::addOutput); // For generic proposals there is no issuance output, for compensation and reimburse requests there is if (issuanceAmount != null && issuanceAddress != null) { // BSQ issuance output preparedTx.addOutput(issuanceAmount, issuanceAddress); } // safety check counter to avoid endless loops int counter = 0; // estimated size of input sig int sigSizePerInput = 106; // typical size for a tx with 3 inputs int txSizeWithUnsignedInputs = 300; Coin txFeePerByte = feeService.getTxFeePerByte(); Address changeAddress = getFreshAddressEntry().getAddress(); checkNotNull(changeAddress, "changeAddress must not be null"); BtcCoinSelector coinSelector = new BtcCoinSelector(walletsSetup.getAddressesByContext(AddressEntry.Context.AVAILABLE), preferences.getIgnoreDustThreshold()); List<TransactionInput> preparedBsqTxInputs = preparedTx.getInputs(); List<TransactionOutput> preparedBsqTxOutputs = preparedTx.getOutputs(); int numInputs = preparedBsqTxInputs.size(); Transaction resultTx = null; boolean isFeeOutsideTolerance; do { counter++; if (counter >= 10) { checkNotNull(resultTx, "resultTx must not be null"); log.error("Could not calculate the fee. Tx=" + resultTx); break; } Transaction tx = new Transaction(params); preparedBsqTxInputs.forEach(tx::addInput); preparedBsqTxOutputs.forEach(tx::addOutput); SendRequest sendRequest = SendRequest.forTx(tx); sendRequest.shuffleOutputs = false; sendRequest.aesKey = aesKey; // signInputs needs to be false as it would try to sign all inputs (BSQ inputs are not in this wallet) sendRequest.signInputs = false; sendRequest.fee = txFeePerByte.multiply(txSizeWithUnsignedInputs + sigSizePerInput * numInputs); sendRequest.feePerKb = Coin.ZERO; sendRequest.ensureMinRequiredFee = false; sendRequest.coinSelector = coinSelector; sendRequest.changeAddress = changeAddress; wallet.completeTx(sendRequest); resultTx = sendRequest.tx; // add OP_RETURN output resultTx.addOutput(new TransactionOutput(params, resultTx, Coin.ZERO, ScriptBuilder.createOpReturnScript(opReturnData).getProgram())); numInputs = resultTx.getInputs().size(); txSizeWithUnsignedInputs = resultTx.bitcoinSerialize().length; long estimatedFeeAsLong = txFeePerByte.multiply(txSizeWithUnsignedInputs + sigSizePerInput * numInputs).value; // calculated fee must be inside of a tolerance range with tx fee isFeeOutsideTolerance = Math.abs(resultTx.getFee().value - estimatedFeeAsLong) > 1000; } while (isFeeOutsideTolerance); // Sign all BTC inputs signAllBtcInputs(indexOfBtcFirstInput, resultTx); checkWalletConsistency(wallet); verifyTransaction(resultTx); // printTx("BTC wallet: Signed tx", resultTx); return resultTx; } // Blind vote tx // We add BTC inputs to pay miner fees and sign the BTC tx inputs // (BsqFee)tx has following structure: // inputs [1-n] BSQ inputs (fee + stake) // outputs [1] BSQ stake // outputs [0-1] BSQ change output (>= 546 Satoshi) // preparedVoteTx has following structure: // inputs [1-n] BSQ inputs (fee + stake) // inputs [1-n] BTC inputs for miner fee // outputs [1] BSQ stake // outputs [0-1] BSQ change output (>= 546 Satoshi) // outputs [0-1] BTC change output from miner fee inputs (>= 546 Satoshi) // outputs [1] OP_RETURN with opReturnData and amount 0 // mining fee: BTC mining fee + burned BSQ fee public Transaction completePreparedBlindVoteTx(Transaction preparedTx, byte[] opReturnData) throws TransactionVerificationException, WalletException, InsufficientMoneyException { // First input index for btc inputs (they get added after bsq inputs) return completePreparedBsqTxWithBtcFee(preparedTx, opReturnData); } private Transaction completePreparedBsqTxWithBtcFee(Transaction preparedTx, byte[] opReturnData) throws InsufficientMoneyException, TransactionVerificationException, WalletException { // Remember index for first BTC input int indexOfBtcFirstInput = preparedTx.getInputs().size(); Transaction tx = addInputsForMinerFee(preparedTx, opReturnData); signAllBtcInputs(indexOfBtcFirstInput, tx); checkWalletConsistency(wallet); verifyTransaction(tx); // printTx("BTC wallet: Signed tx", tx); return tx; } private Transaction addInputsForMinerFee(Transaction preparedTx, byte[] opReturnData) throws InsufficientMoneyException { // safety check counter to avoid endless loops int counter = 0; // estimated size of input sig int sigSizePerInput = 106; // typical size for a tx with 3 inputs int txSizeWithUnsignedInputs = 300; Coin txFeePerByte = feeService.getTxFeePerByte(); Address changeAddress = getFreshAddressEntry().getAddress(); checkNotNull(changeAddress, "changeAddress must not be null"); BtcCoinSelector coinSelector = new BtcCoinSelector(walletsSetup.getAddressesByContext(AddressEntry.Context.AVAILABLE), preferences.getIgnoreDustThreshold()); List<TransactionInput> preparedBsqTxInputs = preparedTx.getInputs(); List<TransactionOutput> preparedBsqTxOutputs = preparedTx.getOutputs(); int numInputs = preparedBsqTxInputs.size(); Transaction resultTx = null; boolean isFeeOutsideTolerance; do { counter++; if (counter >= 10) { checkNotNull(resultTx, "resultTx must not be null"); log.error("Could not calculate the fee. Tx=" + resultTx); break; } Transaction tx = new Transaction(params); preparedBsqTxInputs.forEach(tx::addInput); preparedBsqTxOutputs.forEach(tx::addOutput); SendRequest sendRequest = SendRequest.forTx(tx); sendRequest.shuffleOutputs = false; sendRequest.aesKey = aesKey; // signInputs needs to be false as it would try to sign all inputs (BSQ inputs are not in this wallet) sendRequest.signInputs = false; sendRequest.fee = txFeePerByte.multiply(txSizeWithUnsignedInputs + sigSizePerInput * numInputs); sendRequest.feePerKb = Coin.ZERO; sendRequest.ensureMinRequiredFee = false; sendRequest.coinSelector = coinSelector; sendRequest.changeAddress = changeAddress; wallet.completeTx(sendRequest); resultTx = sendRequest.tx; // add OP_RETURN output resultTx.addOutput(new TransactionOutput(params, resultTx, Coin.ZERO, ScriptBuilder.createOpReturnScript(opReturnData).getProgram())); numInputs = resultTx.getInputs().size(); txSizeWithUnsignedInputs = resultTx.bitcoinSerialize().length; final long estimatedFeeAsLong = txFeePerByte.multiply(txSizeWithUnsignedInputs + sigSizePerInput * numInputs).value; // calculated fee must be inside of a tolerance range with tx fee isFeeOutsideTolerance = Math.abs(resultTx.getFee().value - estimatedFeeAsLong) > 1000; } while (isFeeOutsideTolerance); return resultTx; } private void signAllBtcInputs(int indexOfBtcFirstInput, Transaction tx) throws TransactionVerificationException { for (int i = indexOfBtcFirstInput; i < tx.getInputs().size(); i++) { TransactionInput input = tx.getInputs().get(i); checkArgument(input.getConnectedOutput() != null && input.getConnectedOutput().isMine(wallet), "input.getConnectedOutput() is not in our wallet. That must not happen."); signTransactionInput(wallet, aesKey, tx, input, i); checkScriptSig(tx, input, i); } } // Vote reveal tx // We add BTC fees to the prepared reveal tx // (BsqFee)tx has following structure: // inputs [1] BSQ input (stake) // output [1] BSQ unlocked stake // preparedVoteTx has following structure: // inputs [1] BSQ inputs (stake) // inputs [1-n] BTC inputs for miner fee // outputs [1] BSQ unlocked stake // outputs [0-1] BTC change output from miner fee inputs (>= 546 Satoshi) // outputs [1] OP_RETURN with opReturnData and amount 0 // mining fee: BTC mining fee + burned BSQ fee public Transaction completePreparedVoteRevealTx(Transaction preparedTx, byte[] opReturnData) throws TransactionVerificationException, WalletException, InsufficientMoneyException { return completePreparedBsqTxWithBtcFee(preparedTx, opReturnData); } // Add fee input to prepared BSQ send tx public Transaction completePreparedSendBsqTx(Transaction preparedBsqTx, boolean isSendTx) throws TransactionVerificationException, WalletException, InsufficientMoneyException { // preparedBsqTx has following structure: // inputs [1-n] BSQ inputs // outputs [1] BSQ receiver's output // outputs [0-1] BSQ change output // We add BTC mining fee. Result tx looks like: // inputs [1-n] BSQ inputs // inputs [1-n] BTC inputs // outputs [1] BSQ receiver's output // outputs [0-1] BSQ change output // outputs [0-1] BTC change output // mining fee: BTC mining fee return completePreparedBsqTx(preparedBsqTx, isSendTx, null); } public Transaction completePreparedBsqTx(Transaction preparedBsqTx, boolean useCustomTxFee, @Nullable byte[] opReturnData) throws TransactionVerificationException, WalletException, InsufficientMoneyException { // preparedBsqTx has following structure: // inputs [1-n] BSQ inputs // outputs [1] BSQ receiver's output // outputs [0-1] BSQ change output // mining fee: optional burned BSQ fee (only if opReturnData != null) // We add BTC mining fee. Result tx looks like: // inputs [1-n] BSQ inputs // inputs [1-n] BTC inputs // outputs [0-1] BSQ receiver's output // outputs [0-1] BSQ change output // outputs [0-1] BTC change output // outputs [0-1] OP_RETURN with opReturnData (only if opReturnData != null) // mining fee: BTC mining fee + optional burned BSQ fee (only if opReturnData != null) // In case of txs for burned BSQ fees we have no receiver output and it might be that there is no change outputs // We need to guarantee that min. 1 valid output is added (OP_RETURN does not count). So we use a higher input // for BTC to force an additional change output. // safety check counter to avoid endless loops int counter = 0; // estimated size of input sig int sigSizePerInput = 106; // typical size for a tx with 2 inputs int txSizeWithUnsignedInputs = 203; // If useCustomTxFee we allow overriding the estimated fee from preferences Coin txFeePerByte = useCustomTxFee ? getTxFeeForWithdrawalPerByte() : feeService.getTxFeePerByte(); // In case there are no change outputs we force a change by adding min dust to the BTC input Coin forcedChangeValue = Coin.ZERO; Address changeAddress = getFreshAddressEntry().getAddress(); checkNotNull(changeAddress, "changeAddress must not be null"); BtcCoinSelector coinSelector = new BtcCoinSelector(walletsSetup.getAddressesByContext(AddressEntry.Context.AVAILABLE), preferences.getIgnoreDustThreshold()); List<TransactionInput> preparedBsqTxInputs = preparedBsqTx.getInputs(); List<TransactionOutput> preparedBsqTxOutputs = preparedBsqTx.getOutputs(); int numInputs = preparedBsqTxInputs.size() + 1; // We add 1 for the BTC fee input Transaction resultTx = null; boolean isFeeOutsideTolerance; boolean opReturnIsOnlyOutput; do { counter++; if (counter >= 10) { checkNotNull(resultTx, "resultTx must not be null"); log.error("Could not calculate the fee. Tx=" + resultTx); break; } Transaction tx = new Transaction(params); preparedBsqTxInputs.stream().forEach(tx::addInput); if (forcedChangeValue.isZero()) { preparedBsqTxOutputs.stream().forEach(tx::addOutput); } else { //TODO test that case checkArgument(preparedBsqTxOutputs.size() == 0, "preparedBsqTxOutputs.size must be null in that code branch"); tx.addOutput(forcedChangeValue, changeAddress); } SendRequest sendRequest = SendRequest.forTx(tx); sendRequest.shuffleOutputs = false; sendRequest.aesKey = aesKey; // signInputs needs to be false as it would try to sign all inputs (BSQ inputs are not in this wallet) sendRequest.signInputs = false; sendRequest.fee = txFeePerByte.multiply(txSizeWithUnsignedInputs + sigSizePerInput * numInputs); sendRequest.feePerKb = Coin.ZERO; sendRequest.ensureMinRequiredFee = false; sendRequest.coinSelector = coinSelector; sendRequest.changeAddress = changeAddress; wallet.completeTx(sendRequest); resultTx = sendRequest.tx; // We might have the rare case that both inputs matched the required fees, so both did not require // a change output. // In such cases we need to add artificially a change output (OP_RETURN is not allowed as only output) opReturnIsOnlyOutput = resultTx.getOutputs().size() == 0; forcedChangeValue = opReturnIsOnlyOutput ? Restrictions.getMinNonDustOutput() : Coin.ZERO; // add OP_RETURN output if (opReturnData != null) resultTx.addOutput(new TransactionOutput(params, resultTx, Coin.ZERO, ScriptBuilder.createOpReturnScript(opReturnData).getProgram())); numInputs = resultTx.getInputs().size(); txSizeWithUnsignedInputs = resultTx.bitcoinSerialize().length; final long estimatedFeeAsLong = txFeePerByte.multiply(txSizeWithUnsignedInputs + sigSizePerInput * numInputs).value; // calculated fee must be inside of a tolerance range with tx fee isFeeOutsideTolerance = Math.abs(resultTx.getFee().value - estimatedFeeAsLong) > 1000; } while (opReturnIsOnlyOutput || isFeeOutsideTolerance || resultTx.getFee().value < txFeePerByte.multiply(resultTx.bitcoinSerialize().length).value); // Sign all BTC inputs signAllBtcInputs(preparedBsqTxInputs.size(), resultTx); checkWalletConsistency(wallet); verifyTransaction(resultTx); printTx("BTC wallet: Signed tx", resultTx); return resultTx; } // Commit tx public void commitTx(Transaction tx) { wallet.commitTx(tx); // printTx("BTC commit Tx", tx); } // AddressEntry public Optional<AddressEntry> getAddressEntry(String offerId, @SuppressWarnings("SameParameterValue") AddressEntry.Context context) { return getAddressEntryListAsImmutableList().stream() .filter(e -> offerId.equals(e.getOfferId())) .filter(e -> context == e.getContext()) .findAny(); } public AddressEntry getOrCreateAddressEntry(String offerId, AddressEntry.Context context) { Optional<AddressEntry> addressEntry = getAddressEntryListAsImmutableList().stream() .filter(e -> offerId.equals(e.getOfferId())) .filter(e -> context == e.getContext()) .findAny(); if (addressEntry.isPresent()) { return addressEntry.get(); } else { // We still use non-segwit addresses for the trade protocol. // We try to use available and not yet used entries Optional<AddressEntry> emptyAvailableAddressEntry = getAddressEntryListAsImmutableList().stream() .filter(e -> AddressEntry.Context.AVAILABLE == e.getContext()) .filter(e -> isAddressUnused(e.getAddress())) .filter(e -> Script.ScriptType.P2PKH.equals(e.getAddress().getOutputScriptType())) .findAny(); if (emptyAvailableAddressEntry.isPresent()) { return addressEntryList.swapAvailableToAddressEntryWithOfferId(emptyAvailableAddressEntry.get(), context, offerId); } else { DeterministicKey key = (DeterministicKey) wallet.findKeyFromAddress(wallet.freshReceiveAddress(Script.ScriptType.P2PKH)); AddressEntry entry = new AddressEntry(key, context, offerId, false); addressEntryList.addAddressEntry(entry); return entry; } } } public AddressEntry getArbitratorAddressEntry() { AddressEntry.Context context = AddressEntry.Context.ARBITRATOR; Optional<AddressEntry> addressEntry = getAddressEntryListAsImmutableList().stream() .filter(e -> context == e.getContext()) .findAny(); return getOrCreateAddressEntry(context, addressEntry, false); } public AddressEntry getFreshAddressEntry() { return getFreshAddressEntry(true); } public AddressEntry getFreshAddressEntry(boolean segwit) { AddressEntry.Context context = AddressEntry.Context.AVAILABLE; Optional<AddressEntry> addressEntry = getAddressEntryListAsImmutableList().stream() .filter(e -> context == e.getContext()) .filter(e -> isAddressUnused(e.getAddress())) .filter(e -> { boolean isSegwitOutputScriptType = Script.ScriptType.P2WPKH.equals(e.getAddress().getOutputScriptType()); // We need to ensure that we take only addressEntries which matches our segWit flag boolean isMatchingOutputScriptType = isSegwitOutputScriptType == segwit; return isMatchingOutputScriptType; }) .findAny(); return getOrCreateAddressEntry(context, addressEntry, segwit); } public void recoverAddressEntry(String offerId, String address, AddressEntry.Context context) { findAddressEntry(address, AddressEntry.Context.AVAILABLE).ifPresent(addressEntry -> addressEntryList.swapAvailableToAddressEntryWithOfferId(addressEntry, context, offerId)); } private AddressEntry getOrCreateAddressEntry(AddressEntry.Context context, Optional<AddressEntry> addressEntry, boolean segwit) { if (addressEntry.isPresent()) { return addressEntry.get(); } else { DeterministicKey key; if (segwit) { key = (DeterministicKey) wallet.findKeyFromAddress(wallet.freshReceiveAddress(Script.ScriptType.P2WPKH)); } else { key = (DeterministicKey) wallet.findKeyFromAddress(wallet.freshReceiveAddress(Script.ScriptType.P2PKH)); } AddressEntry entry = new AddressEntry(key, context, segwit); addressEntryList.addAddressEntry(entry); return entry; } } private Optional<AddressEntry> findAddressEntry(String address, AddressEntry.Context context) { return getAddressEntryListAsImmutableList().stream() .filter(e -> address.equals(e.getAddressString())) .filter(e -> context == e.getContext()) .findAny(); } public List<AddressEntry> getAvailableAddressEntries() { return getAddressEntryListAsImmutableList().stream() .filter(addressEntry -> AddressEntry.Context.AVAILABLE == addressEntry.getContext()) .collect(Collectors.toList()); } public List<AddressEntry> getAddressEntriesForOpenOffer() { return getAddressEntryListAsImmutableList().stream() .filter(addressEntry -> AddressEntry.Context.OFFER_FUNDING == addressEntry.getContext() || AddressEntry.Context.RESERVED_FOR_TRADE == addressEntry.getContext()) .collect(Collectors.toList()); } public List<AddressEntry> getAddressEntriesForTrade() { return getAddressEntryListAsImmutableList().stream() .filter(addressEntry -> AddressEntry.Context.MULTI_SIG == addressEntry.getContext() || AddressEntry.Context.TRADE_PAYOUT == addressEntry.getContext()) .collect(Collectors.toList()); } public List<AddressEntry> getAddressEntries(AddressEntry.Context context) { return getAddressEntryListAsImmutableList().stream() .filter(addressEntry -> context == addressEntry.getContext()) .collect(Collectors.toList()); } public List<AddressEntry> getFundedAvailableAddressEntries() { return getAvailableAddressEntries().stream() .filter(addressEntry -> getBalanceForAddress(addressEntry.getAddress()).isPositive()) .collect(Collectors.toList()); } public List<AddressEntry> getAddressEntryListAsImmutableList() { return addressEntryList.getAddressEntriesAsListImmutable(); } public void swapTradeEntryToAvailableEntry(String offerId, AddressEntry.Context context) { getAddressEntryListAsImmutableList().stream() .filter(e -> offerId.equals(e.getOfferId())) .filter(e -> context == e.getContext()) .forEach(e -> { log.info("swap addressEntry with address {} and offerId {} from context {} to available", e.getAddressString(), e.getOfferId(), context); addressEntryList.swapToAvailable(e); }); } public void resetAddressEntriesForOpenOffer(String offerId) { log.info("resetAddressEntriesForOpenOffer offerId={}", offerId); swapTradeEntryToAvailableEntry(offerId, AddressEntry.Context.OFFER_FUNDING); swapTradeEntryToAvailableEntry(offerId, AddressEntry.Context.RESERVED_FOR_TRADE); } public void resetAddressEntriesForPendingTrade(String offerId) { swapTradeEntryToAvailableEntry(offerId, AddressEntry.Context.MULTI_SIG); // We swap also TRADE_PAYOUT to be sure all is cleaned up. There might be cases where a user cannot send the funds // to an external wallet directly in the last step of the trade, but the funds are in the Bisq wallet anyway and // the dealing with the external wallet is pure UI thing. The user can move the funds to the wallet and then // send out the funds to the external wallet. As this cleanup is a rare situation and most users do not use // the feature to send out the funds we prefer that strategy (if we keep the address entry it might cause // complications in some edge cases after a SPV resync). swapTradeEntryToAvailableEntry(offerId, AddressEntry.Context.TRADE_PAYOUT); } public void swapAnyTradeEntryContextToAvailableEntry(String offerId) { resetAddressEntriesForOpenOffer(offerId); resetAddressEntriesForPendingTrade(offerId); } public void saveAddressEntryList() { addressEntryList.requestPersistence(); } public DeterministicKey getMultiSigKeyPair(String tradeId, byte[] pubKey) { Optional<AddressEntry> multiSigAddressEntryOptional = getAddressEntry(tradeId, AddressEntry.Context.MULTI_SIG); DeterministicKey multiSigKeyPair; if (multiSigAddressEntryOptional.isPresent()) { AddressEntry multiSigAddressEntry = multiSigAddressEntryOptional.get(); multiSigKeyPair = multiSigAddressEntry.getKeyPair(); if (!Arrays.equals(pubKey, multiSigAddressEntry.getPubKey())) { log.error("Pub Key from AddressEntry does not match key pair from trade data. Trade ID={}\n" + "We try to find the keypair in the wallet with the pubKey we found in the trade data.", tradeId); multiSigKeyPair = findKeyFromPubKey(pubKey); } } else { log.error("multiSigAddressEntry not found for trade ID={}.\n" + "We try to find the keypair in the wallet with the pubKey we found in the trade data.", tradeId); multiSigKeyPair = findKeyFromPubKey(pubKey); } return multiSigKeyPair; } // Balance public Coin getSavingWalletBalance() { return Coin.valueOf(getFundedAvailableAddressEntries().stream() .mapToLong(addressEntry -> getBalanceForAddress(addressEntry.getAddress()).value) .sum()); } public Stream<AddressEntry> getAddressEntriesForAvailableBalanceStream() { Stream<AddressEntry> availableAndPayout = Stream.concat(getAddressEntries(AddressEntry.Context.TRADE_PAYOUT) .stream(), getFundedAvailableAddressEntries().stream()); Stream<AddressEntry> available = Stream.concat(availableAndPayout, getAddressEntries(AddressEntry.Context.ARBITRATOR).stream()); available = Stream.concat(available, getAddressEntries(AddressEntry.Context.OFFER_FUNDING).stream()); return available.filter(addressEntry -> getBalanceForAddress(addressEntry.getAddress()).isPositive()); } // Double spend unconfirmed transaction (unlock in case we got into a tx with a too low mining fee) public void doubleSpendTransaction(String txId, Runnable resultHandler, ErrorMessageHandler errorMessageHandler) throws InsufficientFundsException { AddressEntry addressEntry = getFreshAddressEntry(); checkNotNull(addressEntry.getAddress(), "addressEntry.getAddress() must not be null"); Optional<Transaction> transactionOptional = wallet.getTransactions(true).stream() .filter(t -> t.getTxId().toString().equals(txId)) .findAny(); if (transactionOptional.isPresent()) { Transaction txToDoubleSpend = transactionOptional.get(); Address toAddress = addressEntry.getAddress(); final TransactionConfidence.ConfidenceType confidenceType = txToDoubleSpend.getConfidence().getConfidenceType(); if (confidenceType == TransactionConfidence.ConfidenceType.PENDING) { log.debug("txToDoubleSpend no. of inputs " + txToDoubleSpend.getInputs().size()); Transaction newTransaction = new Transaction(params); txToDoubleSpend.getInputs().stream().forEach(input -> { final TransactionOutput connectedOutput = input.getConnectedOutput(); if (connectedOutput != null && connectedOutput.isMine(wallet) && connectedOutput.getParentTransaction() != null && connectedOutput.getParentTransaction().getConfidence() != null && input.getValue() != null) { //if (connectedOutput.getParentTransaction().getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING) { newTransaction.addInput(new TransactionInput(params, newTransaction, new byte[]{}, new TransactionOutPoint(params, input.getOutpoint().getIndex(), new Transaction(params, connectedOutput.getParentTransaction().bitcoinSerialize())), Coin.valueOf(input.getValue().value))); /* } else { log.warn("Confidence of parent tx is not of type BUILDING: ConfidenceType=" + connectedOutput.getParentTransaction().getConfidence().getConfidenceType()); }*/ } } ); log.info("newTransaction no. of inputs " + newTransaction.getInputs().size()); log.info("newTransaction size in kB " + newTransaction.bitcoinSerialize().length / 1024); if (!newTransaction.getInputs().isEmpty()) { Coin amount = Coin.valueOf(newTransaction.getInputs().stream() .mapToLong(input -> input.getValue() != null ? input.getValue().value : 0) .sum()); newTransaction.addOutput(amount, toAddress); try { Coin fee; int counter = 0; int txSize = 0; Transaction tx; SendRequest sendRequest; Coin txFeeForWithdrawalPerByte = getTxFeeForWithdrawalPerByte(); do { counter++; fee = txFeeForWithdrawalPerByte.multiply(txSize); newTransaction.clearOutputs(); newTransaction.addOutput(amount.subtract(fee), toAddress); sendRequest = SendRequest.forTx(newTransaction); sendRequest.fee = fee; sendRequest.feePerKb = Coin.ZERO; sendRequest.ensureMinRequiredFee = false; sendRequest.aesKey = aesKey; sendRequest.coinSelector = new BtcCoinSelector(toAddress, preferences.getIgnoreDustThreshold()); sendRequest.changeAddress = toAddress; wallet.completeTx(sendRequest); tx = sendRequest.tx; txSize = tx.bitcoinSerialize().length; printTx("FeeEstimationTransaction", tx); sendRequest.tx.getOutputs().forEach(o -> log.debug("Output value " + o.getValue().toFriendlyString())); } while (feeEstimationNotSatisfied(counter, tx)); if (counter == 10) log.error("Could not calculate the fee. Tx=" + tx); Wallet.SendResult sendResult = null; try { sendRequest = SendRequest.forTx(newTransaction); sendRequest.fee = fee; sendRequest.feePerKb = Coin.ZERO; sendRequest.ensureMinRequiredFee = false; sendRequest.aesKey = aesKey; sendRequest.coinSelector = new BtcCoinSelector(toAddress, preferences.getIgnoreDustThreshold()); sendRequest.changeAddress = toAddress; sendResult = wallet.sendCoins(sendRequest); } catch (InsufficientMoneyException e) { // in some cases getFee did not calculate correctly and we still get an InsufficientMoneyException log.warn("We still have a missing fee " + (e.missing != null ? e.missing.toFriendlyString() : "")); amount = amount.subtract(e.missing); newTransaction.clearOutputs(); newTransaction.addOutput(amount, toAddress); sendRequest = SendRequest.forTx(newTransaction); sendRequest.fee = fee; sendRequest.feePerKb = Coin.ZERO; sendRequest.ensureMinRequiredFee = false; sendRequest.aesKey = aesKey; sendRequest.coinSelector = new BtcCoinSelector(toAddress, preferences.getIgnoreDustThreshold(), false); sendRequest.changeAddress = toAddress; try { sendResult = wallet.sendCoins(sendRequest); printTx("FeeEstimationTransaction", newTransaction); } catch (InsufficientMoneyException e2) { errorMessageHandler.handleErrorMessage("We did not get the correct fee calculated. " + (e2.missing != null ? e2.missing.toFriendlyString() : "")); } } if (sendResult != null) { log.info("Broadcasting double spending transaction. " + sendResult.tx); Futures.addCallback(sendResult.broadcastComplete, new FutureCallback<Transaction>() { @Override public void onSuccess(Transaction result) { log.info("Double spending transaction published. " + result); resultHandler.run(); } @Override public void onFailure(@NotNull Throwable t) { log.error("Broadcasting double spending transaction failed. " + t.getMessage()); errorMessageHandler.handleErrorMessage(t.getMessage()); } }, MoreExecutors.directExecutor()); } } catch (InsufficientMoneyException e) { throw new InsufficientFundsException("The fees for that transaction exceed the available funds " + "or the resulting output value is below the min. dust value:\n" + "Missing " + (e.missing != null ? e.missing.toFriendlyString() : "null")); } } else { String errorMessage = "We could not find inputs we control in the transaction we want to double spend."; log.warn(errorMessage); errorMessageHandler.handleErrorMessage(errorMessage); } } else if (confidenceType == TransactionConfidence.ConfidenceType.BUILDING) { errorMessageHandler.handleErrorMessage("That transaction is already in the blockchain so we cannot double spend it."); } else if (confidenceType == TransactionConfidence.ConfidenceType.DEAD) { errorMessageHandler.handleErrorMessage("One of the inputs of that transaction has been already double spent."); } } } // Withdrawal Fee calculation public Transaction getFeeEstimationTransaction(String fromAddress, String toAddress, Coin amount, AddressEntry.Context context) throws AddressFormatException, AddressEntryException, InsufficientFundsException { Optional<AddressEntry> addressEntry = findAddressEntry(fromAddress, context); if (!addressEntry.isPresent()) throw new AddressEntryException("WithdrawFromAddress is not found in our wallet."); checkNotNull(addressEntry.get().getAddress(), "addressEntry.get().getAddress() must nto be null"); try { Coin fee; int counter = 0; int txSize = 0; Transaction tx; Coin txFeeForWithdrawalPerByte = getTxFeeForWithdrawalPerByte(); do { counter++; fee = txFeeForWithdrawalPerByte.multiply(txSize); SendRequest sendRequest = getSendRequest(fromAddress, toAddress, amount, fee, aesKey, context); wallet.completeTx(sendRequest); tx = sendRequest.tx; txSize = tx.bitcoinSerialize().length; printTx("FeeEstimationTransaction", tx); } while (feeEstimationNotSatisfied(counter, tx)); if (counter == 10) log.error("Could not calculate the fee. Tx=" + tx); return tx; } catch (InsufficientMoneyException e) { throw new InsufficientFundsException("The fees for that transaction exceed the available funds " + "or the resulting output value is below the min. dust value:\n" + "Missing " + (e.missing != null ? e.missing.toFriendlyString() : "null")); } } public Transaction getFeeEstimationTransactionForMultipleAddresses(Set<String> fromAddresses, Coin amount) throws AddressFormatException, AddressEntryException, InsufficientFundsException { Set<AddressEntry> addressEntries = fromAddresses.stream() .map(address -> { Optional<AddressEntry> addressEntryOptional = findAddressEntry(address, AddressEntry.Context.AVAILABLE); if (!addressEntryOptional.isPresent()) addressEntryOptional = findAddressEntry(address, AddressEntry.Context.OFFER_FUNDING); if (!addressEntryOptional.isPresent()) addressEntryOptional = findAddressEntry(address, AddressEntry.Context.TRADE_PAYOUT); if (!addressEntryOptional.isPresent()) addressEntryOptional = findAddressEntry(address, AddressEntry.Context.ARBITRATOR); return addressEntryOptional; }) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toSet()); if (addressEntries.isEmpty()) throw new AddressEntryException("No Addresses for withdraw found in our wallet"); try { Coin fee; int counter = 0; int txSize = 0; Transaction tx; Coin txFeeForWithdrawalPerByte = getTxFeeForWithdrawalPerByte(); do { counter++; fee = txFeeForWithdrawalPerByte.multiply(txSize); // We use a dummy address for the output final String dummyReceiver = LegacyAddress.fromKey(params, new ECKey()).toBase58(); SendRequest sendRequest = getSendRequestForMultipleAddresses(fromAddresses, dummyReceiver, amount, fee, null, aesKey); wallet.completeTx(sendRequest); tx = sendRequest.tx; txSize = tx.bitcoinSerialize().length; printTx("FeeEstimationTransactionForMultipleAddresses", tx); } while (feeEstimationNotSatisfied(counter, tx)); if (counter == 10) log.error("Could not calculate the fee. Tx=" + tx); return tx; } catch (InsufficientMoneyException e) { throw new InsufficientFundsException("The fees for that transaction exceed the available funds " + "or the resulting output value is below the min. dust value:\n" + "Missing " + (e.missing != null ? e.missing.toFriendlyString() : "null")); } } private boolean feeEstimationNotSatisfied(int counter, Transaction tx) { long targetFee = getTxFeeForWithdrawalPerByte().multiply(tx.bitcoinSerialize().length).value; return counter < 10 && (tx.getFee().value < targetFee || tx.getFee().value - targetFee > 1000); } public int getEstimatedFeeTxSize(List<Coin> outputValues, Coin txFee) throws InsufficientMoneyException, AddressFormatException { Transaction transaction = new Transaction(params); Address dummyAddress = LegacyAddress.fromKey(params, new ECKey()); outputValues.forEach(outputValue -> transaction.addOutput(outputValue, dummyAddress)); SendRequest sendRequest = SendRequest.forTx(transaction); sendRequest.shuffleOutputs = false; sendRequest.aesKey = aesKey; sendRequest.coinSelector = new BtcCoinSelector(walletsSetup.getAddressesByContext(AddressEntry.Context.AVAILABLE), preferences.getIgnoreDustThreshold()); sendRequest.fee = txFee; sendRequest.feePerKb = Coin.ZERO; sendRequest.ensureMinRequiredFee = false; sendRequest.changeAddress = dummyAddress; wallet.completeTx(sendRequest); return transaction.bitcoinSerialize().length; } // Withdrawal Send public String sendFunds(String fromAddress, String toAddress, Coin receiverAmount, Coin fee, @Nullable KeyParameter aesKey, @SuppressWarnings("SameParameterValue") AddressEntry.Context context, FutureCallback<Transaction> callback) throws AddressFormatException, AddressEntryException, InsufficientMoneyException { SendRequest sendRequest = getSendRequest(fromAddress, toAddress, receiverAmount, fee, aesKey, context); Wallet.SendResult sendResult = wallet.sendCoins(sendRequest); Futures.addCallback(sendResult.broadcastComplete, callback, MoreExecutors.directExecutor()); printTx("sendFunds", sendResult.tx); return sendResult.tx.getTxId().toString(); } public String sendFundsForMultipleAddresses(Set<String> fromAddresses, String toAddress, Coin receiverAmount, Coin fee, @Nullable String changeAddress, @Nullable KeyParameter aesKey, FutureCallback<Transaction> callback) throws AddressFormatException, AddressEntryException, InsufficientMoneyException { SendRequest request = getSendRequestForMultipleAddresses(fromAddresses, toAddress, receiverAmount, fee, changeAddress, aesKey); Wallet.SendResult sendResult = wallet.sendCoins(request); Futures.addCallback(sendResult.broadcastComplete, callback, MoreExecutors.directExecutor()); printTx("sendFunds", sendResult.tx); return sendResult.tx.getTxId().toString(); } private SendRequest getSendRequest(String fromAddress, String toAddress, Coin amount, Coin fee, @Nullable KeyParameter aesKey, AddressEntry.Context context) throws AddressFormatException, AddressEntryException { Transaction tx = new Transaction(params); final Coin receiverAmount = amount.subtract(fee); Preconditions.checkArgument(Restrictions.isAboveDust(receiverAmount), "The amount is too low (dust limit)."); tx.addOutput(receiverAmount, Address.fromString(params, toAddress)); SendRequest sendRequest = SendRequest.forTx(tx); sendRequest.fee = fee; sendRequest.feePerKb = Coin.ZERO; sendRequest.ensureMinRequiredFee = false; sendRequest.aesKey = aesKey; sendRequest.shuffleOutputs = false; Optional<AddressEntry> addressEntry = findAddressEntry(fromAddress, context); if (!addressEntry.isPresent()) throw new AddressEntryException("WithdrawFromAddress is not found in our wallet."); checkNotNull(addressEntry.get(), "addressEntry.get() must not be null"); checkNotNull(addressEntry.get().getAddress(), "addressEntry.get().getAddress() must not be null"); sendRequest.coinSelector = new BtcCoinSelector(addressEntry.get().getAddress(), preferences.getIgnoreDustThreshold()); sendRequest.changeAddress = addressEntry.get().getAddress(); return sendRequest; } private SendRequest getSendRequestForMultipleAddresses(Set<String> fromAddresses, String toAddress, Coin amount, Coin fee, @Nullable String changeAddress, @Nullable KeyParameter aesKey) throws AddressFormatException, AddressEntryException, InsufficientMoneyException { Transaction tx = new Transaction(params); final Coin netValue = amount.subtract(fee); checkArgument(Restrictions.isAboveDust(netValue), "The amount is too low (dust limit)."); tx.addOutput(netValue, Address.fromString(params, toAddress)); SendRequest sendRequest = SendRequest.forTx(tx); sendRequest.fee = fee; sendRequest.feePerKb = Coin.ZERO; sendRequest.ensureMinRequiredFee = false; sendRequest.aesKey = aesKey; sendRequest.shuffleOutputs = false; Set<AddressEntry> addressEntries = fromAddresses.stream() .map(address -> { Optional<AddressEntry> addressEntryOptional = findAddressEntry(address, AddressEntry.Context.AVAILABLE); if (!addressEntryOptional.isPresent()) addressEntryOptional = findAddressEntry(address, AddressEntry.Context.OFFER_FUNDING); if (!addressEntryOptional.isPresent()) addressEntryOptional = findAddressEntry(address, AddressEntry.Context.TRADE_PAYOUT); if (!addressEntryOptional.isPresent()) addressEntryOptional = findAddressEntry(address, AddressEntry.Context.ARBITRATOR); return addressEntryOptional; }) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toSet()); if (addressEntries.isEmpty()) throw new AddressEntryException("No Addresses for withdraw found in our wallet"); sendRequest.coinSelector = new BtcCoinSelector(walletsSetup.getAddressesFromAddressEntries(addressEntries), preferences.getIgnoreDustThreshold()); Optional<AddressEntry> addressEntryOptional = Optional.<AddressEntry>empty(); AddressEntry changeAddressAddressEntry = null; if (changeAddress != null) addressEntryOptional = findAddressEntry(changeAddress, AddressEntry.Context.AVAILABLE); changeAddressAddressEntry = addressEntryOptional.orElseGet(() -> getFreshAddressEntry()); checkNotNull(changeAddressAddressEntry, "change address must not be null"); sendRequest.changeAddress = changeAddressAddressEntry.getAddress(); return sendRequest; } // We ignore utxos which are considered dust attacks for spying on users' wallets. // The ignoreDustThreshold value is set in the preferences. If not set we use default non dust // value of 546 sat. @Override protected boolean isDustAttackUtxo(TransactionOutput output) { return output.getValue().value < preferences.getIgnoreDustThreshold(); } // Refund payoutTx public Transaction createRefundPayoutTx(Coin buyerAmount, Coin sellerAmount, Coin fee, String buyerAddressString, String sellerAddressString) throws AddressFormatException, InsufficientMoneyException, WalletException, TransactionVerificationException { Transaction tx = new Transaction(params); Preconditions.checkArgument(buyerAmount.add(sellerAmount).isPositive(), "The sellerAmount + buyerAmount must be positive."); // buyerAmount can be 0 if (buyerAmount.isPositive()) { Preconditions.checkArgument(Restrictions.isAboveDust(buyerAmount), "The buyerAmount is too low (dust limit)."); tx.addOutput(buyerAmount, Address.fromString(params, buyerAddressString)); } // sellerAmount can be 0 if (sellerAmount.isPositive()) { Preconditions.checkArgument(Restrictions.isAboveDust(sellerAmount), "The sellerAmount is too low (dust limit)."); tx.addOutput(sellerAmount, Address.fromString(params, sellerAddressString)); } SendRequest sendRequest = SendRequest.forTx(tx); sendRequest.fee = fee; sendRequest.feePerKb = Coin.ZERO; sendRequest.ensureMinRequiredFee = false; sendRequest.aesKey = aesKey; sendRequest.shuffleOutputs = false; sendRequest.coinSelector = new BtcCoinSelector(walletsSetup.getAddressesByContext(AddressEntry.Context.AVAILABLE), preferences.getIgnoreDustThreshold()); sendRequest.changeAddress = getFreshAddressEntry().getAddress(); checkNotNull(wallet); wallet.completeTx(sendRequest); Transaction resultTx = sendRequest.tx; checkWalletConsistency(wallet); verifyTransaction(resultTx); WalletService.printTx("createRefundPayoutTx", resultTx); return resultTx; } }
package org.zstack.core.ansible; import org.apache.commons.io.FileUtils; import org.springframework.beans.factory.annotation.Autowire; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.zstack.core.Platform; import org.zstack.core.cloudbus.CloudBus; import org.zstack.core.cloudbus.CloudBusCallBack; import org.zstack.core.defer.Defer; import org.zstack.core.defer.Deferred; import org.zstack.header.core.Completion; import org.zstack.header.exception.CloudRuntimeException; import org.zstack.header.message.MessageReply; import org.zstack.utils.ShellUtils; import org.zstack.utils.Utils; import org.zstack.utils.logging.CLogger; import org.zstack.utils.network.NetworkUtils; import org.zstack.utils.path.PathUtil; import org.zstack.utils.ssh.SshResult; import org.zstack.utils.ssh.SshShell; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.zstack.utils.CollectionDSL.e; import static org.zstack.utils.CollectionDSL.map; import static org.zstack.utils.StringDSL.ln; @Configurable(preConstruction = true, autowire = Autowire.BY_TYPE) public class AnsibleRunner { private static final CLogger logger = Utils.getLogger(AnsibleRunner.class); @Autowired private AnsibleFacade asf; @Autowired private CloudBus bus; private static String privKeyFile; private List<AnsibleChecker> checkers = new ArrayList<AnsibleChecker>(); static { privKeyFile = PathUtil.findFileOnClassPath(AnsibleConstant.RSA_PRIVATE_KEY).getAbsolutePath(); } { fullDeploy = AnsibleGlobalProperty.FULL_DEPLOY; } private String targetIp; private String username; private String password; private String privateKey; private int sshPort = 22; private String playBookName; private String playBookPath; private Map<String, Object> arguments = new HashMap<String, Object>(); private int agentPort; private boolean fullDeploy; private boolean localPublicKey; private boolean runOnLocal; private AnsibleNeedRun ansibleNeedRun; private String ansibleExecutable; public String getAnsibleExecutable() { return ansibleExecutable; } public void setAnsibleExecutable(String ansibleExecutable) { this.ansibleExecutable = ansibleExecutable; } public String getPlayBookPath() { return playBookPath; } public void setPlayBookPath(String playBookPath) { this.playBookPath = playBookPath; } public AnsibleNeedRun getAnsibleNeedRun() { return ansibleNeedRun; } public void setAnsibleNeedRun(AnsibleNeedRun ansibleNeedRun) { this.ansibleNeedRun = ansibleNeedRun; } public boolean isRunOnLocal() { return runOnLocal; } public void setRunOnLocal(boolean runOnLocal) { this.runOnLocal = runOnLocal; } public boolean isLocalPublicKey() { return localPublicKey; } public void setLocalPublicKey(boolean localPublicKey) { this.localPublicKey = localPublicKey; } public void putArgument(String key, Object value) { arguments.put(key, value); } public String getTargetIp() { return targetIp; } public void setTargetIp(String targetIp) { this.targetIp = targetIp; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPrivateKey() { return privateKey; } public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } public int getSshPort() { return sshPort; } public void setSshPort(int sshPort) { this.sshPort = sshPort; } public String getPlayBookName() { return playBookName; } public void setPlayBookName(String playBookName) { this.playBookName = playBookName; } public Map<String, Object> getArguments() { return arguments; } public void setArguments(Map<String, Object> arguments) { this.arguments = arguments; } public int getAgentPort() { return agentPort; } public void setAgentPort(int agentPort) { this.agentPort = agentPort; } public boolean isFullDeploy() { return fullDeploy; } public void setFullDeploy(boolean fullDeploy) { this.fullDeploy = fullDeploy; } private void setupPublicKey() throws IOException { File pubKeyFile = PathUtil.findFileOnClassPath(AnsibleConstant.RSA_PUBLIC_KEY); String script = PathUtil.findFileOnClassPath(AnsibleConstant.IMPORT_PUBLIC_KEY_SCRIPT_PATH, true).getAbsolutePath(); if (localPublicKey) { ShellUtils.run(String.format("sh %s %s", script, pubKeyFile.getAbsolutePath())); } else { setupPublicKeyOnRemote(); } } @Deferred private void setupPublicKeyOnRemote() { String script = ln( "#!/bin/sh", "if [ ! -d ~/.ssh ]; then", "mkdir -p ~/.ssh", "chmod 700 ~/.ssh", "fi", "if [ ! -f ~/.ssh/authorized_keys ]; then", "touch ~/.ssh/authorized_keys", "chmod 600 ~/.ssh/authorized_keys", "fi", "pub_key='{pubkey}'", "grep \"$pub_key\" ~/.ssh/authorized_keys > /dev/null", "if [ $? -eq 1 ]; then", "echo \"$pub_key\" >> ~/.ssh/authorized_keys", "fi", "if [ -x /sbin/restorecon ]; then", "/sbin/restorecon ~/.ssh ~/.ssh/authorized_keys", "fi", "exit 0" ).formatByMap(map( e("pubkey", asf.getPublicKey()) )); SshShell ssh = new SshShell(); ssh.setHostname(targetIp); ssh.setPassword(password); ssh.setPort(sshPort); ssh.setUsername(username); if (privateKey != null) { try { final File tempKeyFile = File.createTempFile("zstack", "tmp"); FileUtils.writeStringToFile(tempKeyFile, privateKey); Defer.defer(new Runnable() { @Override public void run() { //tempKeyFile.delete(); } }); ssh.setPrivateKeyFile(tempKeyFile.getAbsolutePath()); } catch (IOException e) { throw new CloudRuntimeException(e); } } SshResult res = ssh.runScript(script); res.raiseExceptionIfFailed(); } private void callAnsible(final Completion completion) { RunAnsibleMsg msg = new RunAnsibleMsg(); msg.setTargetIp(targetIp); msg.setPrivateKeyFile(privKeyFile); msg.setArguments(arguments); msg.setAnsibleExecutable(ansibleExecutable); if (playBookPath != null) { msg.setPlayBookPath(playBookPath); } else { msg.setPlayBookPath(PathUtil.join(AnsibleConstant.ROOT_DIR, playBookName)); } if (runOnLocal) { bus.makeLocalServiceId(msg, AnsibleConstant.SERVICE_ID); } else { bus.makeTargetServiceIdByResourceUuid(msg, AnsibleConstant.SERVICE_ID, targetIp); } bus.send(msg, new CloudBusCallBack(completion) { @Override public void run(MessageReply reply) { if (reply.isSuccess()) { completion.success(); } else { cleanup(); completion.fail(reply.getError()); } } }); } private boolean runChecker() { for (AnsibleChecker checker : checkers) { if (checker.needDeploy()) { logger.debug(String.format("checker[%s] reports deploy is needed", checker.getClass())); return true; } } return false; } private boolean isNeedRun() { if (isFullDeploy()) { logger.debug("Ansible.fullDeploy is set, run ansible anyway"); return true; } if (ansibleNeedRun != null) { return ansibleNeedRun.isRunNeed(); } boolean changed = asf.isModuleChanged(playBookName); if (changed) { logger.debug(String.format("ansible module[%s] changed, run ansible", playBookName)); return true; } if (agentPort != 0) { boolean opened = NetworkUtils.isRemotePortOpen(targetIp, agentPort, (int) TimeUnit.SECONDS.toMillis(5)); if (!opened) { logger.debug(String.format("agent port[%s] on target ip[%s] is not opened, run ansible[%s]", agentPort, targetIp, playBookName)); return true; } if (runChecker()) { return true; } logger.debug(String.format("agent port[%s] on target ip[%s] is opened, ansible module[%s] is not changed, skip to run ansible", agentPort, targetIp, playBookName)); return false; } logger.debug("agent port is not set, run ansible anyway"); return true; } private void cleanup() { // deleting source files. Then next time ansible is called, AnsibleChecker returns false that lets ansible run for (AnsibleChecker checker : checkers) { checker.deleteDestFile(); } } public void run(Completion completion) { try { if (!isNeedRun()) { completion.success(); return; } putArgument("pip_url", String.format("http://%s:8080/zstack/static/pypi/simple", Platform.getManagementServerIp())); putArgument("trusted_host", Platform.getManagementServerIp()); putArgument("yum_server", String.format("%s:8080", Platform.getManagementServerIp())); putArgument("remote_user", getUsername()); putArgument("remote_pass", getPassword()); putArgument("remote_port", getSshPort()); logger.debug(String.format("starts to run ansbile[%s]", playBookPath == null ? playBookName : playBookPath)); new PrepareAnsible().setTargetIp(targetIp).prepare(); setupPublicKey(); callAnsible(completion); } catch (Exception e) { throw new CloudRuntimeException(e); } } public List<AnsibleChecker> getCheckers() { return checkers; } public void installChecker(AnsibleChecker checker) { checkers.add(checker); } }
/* * Class DebuggerUtilsEx * @author Jeka */ package com.intellij.debugger.impl; import com.intellij.debugger.DebuggerBundle; import com.intellij.debugger.engine.DebuggerManagerThreadImpl; import com.intellij.debugger.engine.DebuggerUtils; import com.intellij.debugger.engine.SuspendContextImpl; import com.intellij.debugger.engine.evaluation.*; import com.intellij.debugger.engine.evaluation.expression.EvaluatorBuilder; import com.intellij.debugger.jdi.VirtualMachineProxyImpl; import com.intellij.debugger.requests.Requestor; import com.intellij.debugger.ui.CompletionEditor; import com.intellij.debugger.ui.breakpoints.Breakpoint; import com.intellij.debugger.ui.tree.DebuggerTreeNode; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.*; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.ui.classFilter.ClassFilter; import com.sun.jdi.*; import com.sun.jdi.event.Event; import org.jdom.Attribute; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import java.util.*; import java.util.regex.PatternSyntaxException; public abstract class DebuggerUtilsEx extends DebuggerUtils { private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.impl.DebuggerUtilsEx"); public static final int MAX_LABEL_SIZE = 255; public static Runnable DO_NOTHING = EmptyRunnable.getInstance(); /** * @param context * @return all CodeFragmentFactoryProviders that provide code fragment factories sutable in the context given */ public static List<CodeFragmentFactory> getCodeFragmentFactories(PsiElement context) { final DefaultCodeFragmentFactory defaultFactry = DefaultCodeFragmentFactory.getInstance(); final CodeFragmentFactory[] providers = ApplicationManager.getApplication().getComponents(CodeFragmentFactory.class); final List<CodeFragmentFactory> suitableFactories = new ArrayList<CodeFragmentFactory>(providers.length); if (providers.length > 0) { for (CodeFragmentFactory factory : providers) { if (factory != defaultFactry && factory.isContextAccepted(context)) { suitableFactories.add(factory); } } } suitableFactories.add(defaultFactry); // let default factory be the last one return suitableFactories; } public static PsiMethod findPsiMethod(PsiFile file, int offset) { PsiElement element = null; while(offset >= 0) { element = file.findElementAt(offset); if(element != null) break; offset } for (; element != null; element = element.getParent()) { if (element instanceof PsiClass) return null; if (element instanceof PsiMethod) return (PsiMethod)element; } return null; } public static boolean isAssignableFrom(final String baseQualifiedName, ReferenceType checkedType) { return getSuperClass(baseQualifiedName, checkedType) != null; } public static ReferenceType getSuperClass(final String baseQualifiedName, ReferenceType checkedType) { if (baseQualifiedName.equals(checkedType.name())) { return checkedType; } if (checkedType instanceof ClassType) { ClassType classType = (ClassType)checkedType; ClassType superClassType = classType.superclass(); if (superClassType != null) { ReferenceType superClass = getSuperClass(baseQualifiedName, superClassType); if (superClass != null) { return superClass; } } List<InterfaceType> ifaces = classType.allInterfaces(); for (Iterator<InterfaceType> it = ifaces.iterator(); it.hasNext();) { InterfaceType iface = it.next(); ReferenceType superClass = getSuperClass(baseQualifiedName, iface); if (superClass != null) { return superClass; } } } if (checkedType instanceof InterfaceType) { List<InterfaceType> list = ((InterfaceType)checkedType).superinterfaces(); for (Iterator<InterfaceType> it = list.iterator(); it.hasNext();) { InterfaceType superInterface = it.next(); ReferenceType superClass = getSuperClass(baseQualifiedName, superInterface); if (superClass != null) { return superClass; } } } return null; } public static boolean valuesEqual(Value val1, Value val2) { if (val1 == null) { return val2 == null; } if (val2 == null) { return false; } if (val1 instanceof StringReference && val2 instanceof StringReference) { return ((StringReference)val1).value().equals(((StringReference)val2).value()); } return val1.equals(val2); } public static String getValueOrErrorAsString(final EvaluationContext evaluationContext, Value value) { try { return getValueAsString(evaluationContext, value); } catch (EvaluateException e) { return e.getMessage(); } } public static boolean isCharOrInteger(Value value) { return value instanceof CharValue || isInteger(value); } private static Set<String> myCharOrIntegers; @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isCharOrIntegerArray(Value value) { if (value == null) return false; if (myCharOrIntegers == null) { myCharOrIntegers = new HashSet<String>(); myCharOrIntegers.add("C"); myCharOrIntegers.add("B"); myCharOrIntegers.add("S"); myCharOrIntegers.add("I"); myCharOrIntegers.add("J"); } String signature = value.type().signature(); int i; for (i = 0; signature.charAt(i) == '['; i++) ; if (i == 0) return false; signature = signature.substring(i, signature.length()); return myCharOrIntegers.contains(signature); } public static ClassFilter create(Element element) throws InvalidDataException { ClassFilter filter = new ClassFilter(); filter.readExternal(element); return filter; } private static boolean isFiltered(ClassFilter classFilter, String qName) { if (!classFilter.isEnabled()) { return false; } try { if (classFilter.matches(qName)) { return true; } } catch (PatternSyntaxException e) { LOG.debug(e); } return false; } public static boolean isFiltered(String qName, ClassFilter[] classFilters) { if(qName.indexOf('[') != -1) { return false; //is array } for (ClassFilter filter : classFilters) { if (isFiltered(filter, qName)) { return true; } } return false; } public static ClassFilter[] readFilters(List children) throws InvalidDataException { if (children == null || children.size() == 0) { return ClassFilter.EMPTY_ARRAY; } List<ClassFilter> classFiltersList = new ArrayList<ClassFilter>(children.size()); for (Iterator i = children.iterator(); i.hasNext();) { final ClassFilter classFilter = new ClassFilter(); classFilter.readExternal((Element)i.next()); classFiltersList.add(classFilter); } return classFiltersList.toArray(new ClassFilter[classFiltersList.size()]); } public static void writeFilters(Element parentNode, @NonNls String tagName, ClassFilter[] filters) throws WriteExternalException { for (ClassFilter filter : filters) { Element element = new Element(tagName); parentNode.addContent(element); filter.writeExternal(element); } } public static boolean filterEquals(ClassFilter[] filters1, ClassFilter[] filters2) { if (filters1.length != filters2.length) { return false; } Set<ClassFilter> f1 = new HashSet<ClassFilter>(); Set<ClassFilter> f2 = new HashSet<ClassFilter>(); for (int idx = 0; idx < filters1.length; idx++) { f1.add(filters1[idx]); } for (int idx = 0; idx < filters2.length; idx++) { f2.add(filters2[idx]); } return f2.equals(f1); } private static boolean elementListsEqual(List<Element> l1, List<Element> l2) { if(l1 == null) return l2 == null; if(l2 == null) return false; if(l1.size() != l2.size()) return false; Iterator<Element> i1 = l1.iterator(); Iterator<Element> i2 = l2.iterator(); while (i2.hasNext()) { Element elem1 = i1.next(); Element elem2 = i2.next(); if(!elementsEqual(elem1, elem2)) return false; } return true; } private static boolean attributeListsEqual(List<Attribute> l1, List<Attribute> l2) { if(l1 == null) return l2 == null; if(l2 == null) return false; if(l1.size() != l2.size()) return false; Iterator<Attribute> i1 = l1.iterator(); Iterator<Attribute> i2 = l2.iterator(); while (i2.hasNext()) { Attribute attr1 = i1.next(); Attribute attr2 = i2.next(); if (!Comparing.equal(attr1.getName(), attr2.getName()) || !Comparing.equal(attr1.getValue(), attr2.getValue())) { return false; } } return true; } private static boolean elementsEqual(Element e1, Element e2) { if(e1 == null) return e2 == null; return Comparing.equal(e1.getName(), e2.getName()) && elementListsEqual ((List<Element> )e1.getChildren (), (List<Element> )e2.getChildren ()) && attributeListsEqual((List<Attribute>)e1.getAttributes(), (List<Attribute>)e2.getAttributes()); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean externalizableEqual(JDOMExternalizable e1, JDOMExternalizable e2) { Element root1 = new Element("root"); Element root2 = new Element("root"); try { e1.writeExternal(root1); } catch (WriteExternalException e) { LOG.debug(e); } try { e2.writeExternal(root2); } catch (WriteExternalException e) { LOG.debug(e); } return elementsEqual(root1, root2); } public static List<Pair<Breakpoint, Event>> getEventDescriptors(SuspendContextImpl suspendContext) { DebuggerManagerThreadImpl.assertIsManagerThread(); if(suspendContext == null || suspendContext.getEventSet() == null) { return Collections.emptyList(); } final List<Pair<Breakpoint, Event>> eventDescriptors = new ArrayList<Pair<Breakpoint, Event>>(); for (Iterator<Event> iterator = suspendContext.getEventSet().iterator(); iterator.hasNext();) { Event event = iterator.next(); Requestor requestor = suspendContext.getDebugProcess().getRequestsManager().findRequestor(event.request()); if(requestor instanceof Breakpoint) { eventDescriptors.add(new Pair<Breakpoint, Event>((Breakpoint)requestor, event)); } } return eventDescriptors; } private static PsiElement findExpression(PsiElement element) { if (!(element instanceof PsiIdentifier || element instanceof PsiKeyword)) { return null; } PsiElement parent = element.getParent(); if (parent instanceof PsiVariable) { return element; } if (parent instanceof PsiReferenceExpression) { if (parent.getParent() instanceof PsiCallExpression) return parent.getParent(); return parent; } if (parent instanceof PsiThisExpression) { return parent; } return null; } public static TextWithImports getEditorText(final Editor editor) { if(editor == null) { return null; } final Project project = editor.getProject(); String defaultExpression = editor.getSelectionModel().getSelectedText(); if (defaultExpression == null) { int offset = editor.getCaretModel().getOffset(); PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (psiFile != null) { PsiElement elementAtCursor = psiFile.findElementAt(offset); if (elementAtCursor != null) { PsiElement element = findExpression(elementAtCursor); if (element != null) { defaultExpression = element.getText(); } } } } if(defaultExpression != null) { return new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, defaultExpression); } else { return null; } } public abstract DebuggerTreeNode getSelectedNode (DataContext context); public abstract EvaluatorBuilder getEvaluatorBuilder(); public abstract CompletionEditor createEditor(Project project, PsiElement context, @NonNls String recentsId); private static class SigReader { final String buffer; int pos = 0; SigReader(String s) { buffer = s; } int get() { return buffer.charAt(pos++); } int peek() { return buffer.charAt(pos); } boolean eof() { return buffer.length() <= pos; } @NonNls String getSignature() { if (eof()) return ""; switch (get()) { case 'Z': return "boolean"; case 'B': return "byte"; case 'C': return "char"; case 'S': return "short"; case 'I': return "int"; case 'J': return "long"; case 'F': return "float"; case 'D': return "double"; case 'V': return "void"; case 'L': int start = pos; pos = buffer.indexOf(';', start) + 1; LOG.assertTrue(pos > 0); return buffer.substring(start, pos - 1).replace('/', '.'); case '[': return getSignature() + "[]"; case '(': StringBuffer result = new StringBuffer("("); String separator = ""; while (peek() != ')') { result.append(separator); result.append(getSignature()); separator = ", "; } get(); result.append(")"); return getSignature() + " " + getClassName() + "." + getMethodName() + " " + result; default: // LOG.assertTrue(false, "unknown signature " + buffer); return null; } } String getMethodName() { return ""; } String getClassName() { return ""; } } public static String methodName(final Method m) { return methodName(signatureToName(m.declaringType().signature()), m.name(), m.signature()); } public static String methodName(final String className, final String methodName, final String signature) { try { return new SigReader(signature) { String getMethodName() { return methodName; } String getClassName() { return className; } }.getSignature(); } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("Internal error : unknown signature" + signature); } return className + "." + methodName; } } public static String signatureToName(String s) { return new SigReader(s).getSignature(); } public static Value createValue(VirtualMachineProxyImpl vm, String expectedType, double value) { if (PsiType.DOUBLE.getPresentableText().equals(expectedType)) { return vm.mirrorOf(value); } if (PsiType.FLOAT.getPresentableText().equals(expectedType)) { return vm.mirrorOf((float)value); } return createValue(vm, expectedType, (long)value); } public static Value createValue(VirtualMachineProxyImpl vm, String expectedType, long value) { if (PsiType.LONG.getPresentableText().equals(expectedType)) { return vm.mirrorOf(value); } if (PsiType.INT.getPresentableText().equals(expectedType)) { return vm.mirrorOf((int)value); } if (PsiType.SHORT.getPresentableText().equals(expectedType)) { return vm.mirrorOf((short)value); } if (PsiType.BYTE.getPresentableText().equals(expectedType)) { return vm.mirrorOf((byte)value); } if (PsiType.CHAR.getPresentableText().equals(expectedType)) { return vm.mirrorOf((char)value); } return null; } public static Value createValue(VirtualMachineProxyImpl vm, String expectedType, boolean value) { if (PsiType.BOOLEAN.getPresentableText().equals(expectedType)) { return vm.mirrorOf(value); } return null; } public static Value createValue(VirtualMachineProxyImpl vm, String expectedType, char value) { if (PsiType.CHAR.getPresentableText().equals(expectedType)) { return vm.mirrorOf(value); } if (PsiType.LONG.getPresentableText().equals(expectedType)) { return vm.mirrorOf((long)value); } if (PsiType.INT.getPresentableText().equals(expectedType)) { return vm.mirrorOf((int)value); } if (PsiType.SHORT.getPresentableText().equals(expectedType)) { return vm.mirrorOf((short)value); } if (PsiType.BYTE.getPresentableText().equals(expectedType)) { return vm.mirrorOf((byte)value); } return null; } public static String truncateString(final String str) { if (str.length() > MAX_LABEL_SIZE) { return str.substring(0, MAX_LABEL_SIZE) + "..."; } return str; } public static String getThreadStatusText(int statusId) { switch (statusId) { case ThreadReference.THREAD_STATUS_MONITOR: return DebuggerBundle.message("status.thread.monitor"); case ThreadReference.THREAD_STATUS_NOT_STARTED: return DebuggerBundle.message("status.thread.not.started"); case ThreadReference.THREAD_STATUS_RUNNING: return DebuggerBundle.message("status.thread.running"); case ThreadReference.THREAD_STATUS_SLEEPING: return DebuggerBundle.message("status.thread.sleeping"); case ThreadReference.THREAD_STATUS_UNKNOWN: return DebuggerBundle.message("status.thread.unknown"); case ThreadReference.THREAD_STATUS_WAIT: return DebuggerBundle.message("status.thread.wait"); case ThreadReference.THREAD_STATUS_ZOMBIE: return DebuggerBundle.message("status.thread.zombie"); default: return DebuggerBundle.message("status.thread.undefined"); } } //ToDo:[lex] find common implementation public static void findAllSupertypes(final Type type, final Collection<ReferenceType> typeNames) { if (type instanceof ClassType) { ClassType classType = (ClassType)type; ClassType superclassType = classType.superclass(); if (superclassType != null) { typeNames.add(superclassType); findAllSupertypes(superclassType, typeNames); } List<InterfaceType> ifaces = classType.allInterfaces(); for (Iterator<InterfaceType> it = ifaces.iterator(); it.hasNext();) { InterfaceType iface = it.next(); typeNames.add(iface); findAllSupertypes(iface, typeNames); } } if (type instanceof InterfaceType) { List<InterfaceType> ifaces = ((InterfaceType)type).superinterfaces(); for (Iterator<InterfaceType> it = ifaces.iterator(); it.hasNext();) { InterfaceType iface = it.next(); typeNames.add(iface); findAllSupertypes(iface, typeNames); } } } public static interface ElementVisitor { boolean acceptElement(PsiElement element); } public static void iterateLine(Project project, Document document, int line, ElementVisitor visitor) { PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document); int lineStart; int lineEnd; try { lineStart = document.getLineStartOffset(line); lineEnd = document.getLineEndOffset(line); } catch (IndexOutOfBoundsException e) { return; } PsiElement element; for (int off = lineStart; off < lineEnd;) { element = file.findElementAt(off); if (element != null) { if (visitor.acceptElement(element)) { return; } else { off = element.getTextRange().getEndOffset(); } } else { off++; } } } public static String getQualifiedClassName(final String jdiName, final Project project) { final String name= ApplicationManager.getApplication().runReadAction(new Computable<String>() { public String compute() { String name = jdiName; int startFrom = 0; final PsiManager psiManager = PsiManager.getInstance(project); while (true) { final int separator = name.indexOf('$', startFrom); if(separator < 0) { break; } final String qualifiedName = name.substring(0, separator); final PsiClass psiClass = psiManager.findClass(qualifiedName, GlobalSearchScope.allScope(project)); if(psiClass != null) { int tail = separator + 1; while(tail < name.length() && Character.isDigit(name.charAt(tail))) tail ++; name = qualifiedName + "." + name.substring(tail); } startFrom = separator + 1; } return name; } }); if(jdiName.equals(name)) { return jdiName.replace('$', '.'); } return name; } }
package com.yahoo.vespa.defaults; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.InetAddress; import java.nio.charset.StandardCharsets; import java.util.logging.Logger; import java.util.Optional; /** * The defaults of basic Vespa configuration variables. * Use Defaults.getDefaults() to access the defaults of this runtime environment. * * @author arnej27959 * @author bratseth */ public class Defaults { private static final Logger log = Logger.getLogger(Defaults.class.getName()); private static final Defaults defaults = new Defaults(); private final String vespaHome; private final String vespaUser; private final String vespaHost; private final int vespaWebServicePort; private final int vespaPortBase; private final int vespaPortConfigServerRpc; private final int vespaPortConfigServerHttp; private final int vespaPortConfigProxyRpc; private Defaults() { vespaHome = findVespaHome(); vespaUser = findVespaUser(); vespaHost = findVespaHostname(); vespaWebServicePort = findWebServicePort(8080); vespaPortBase = findVespaPortBase(19000); vespaPortConfigServerRpc = findConfigServerPort(vespaPortBase + 70); vespaPortConfigServerHttp = vespaPortConfigServerRpc + 1; vespaPortConfigProxyRpc = findConfigProxyPort(vespaPortBase + 90); } static private String findVespaHome() { Optional<String> vespaHomeEnv = Optional.ofNullable(System.getenv("VESPA_HOME")); if ( ! vespaHomeEnv.isPresent() || vespaHomeEnv.get().trim().isEmpty()) { log.info("VESPA_HOME not set, using /opt/vespa"); return "/opt/vespa"; } String vespaHome = vespaHomeEnv.get().trim(); if (vespaHome.endsWith("/")) { int sz = vespaHome.length() - 1; vespaHome = vespaHome.substring(0, sz); } return vespaHome; } static private String findVespaHostname() { Optional<String> vespaHostEnv = Optional.ofNullable(System.getenv("VESPA_HOSTNAME")); if (vespaHostEnv.isPresent() && ! vespaHostEnv.get().trim().isEmpty()) { return vespaHostEnv.get().trim(); } return "localhost"; } static private String findVespaUser() { Optional<String> vespaUserEnv = Optional.ofNullable(System.getenv("VESPA_USER")); if (! vespaUserEnv.isPresent()) { log.fine("VESPA_USER not set, using vespa"); return "vespa"; } return vespaUserEnv.get().trim(); } static private int findPort(String varName, int defaultPort) { Optional<String> port = Optional.ofNullable(System.getenv(varName)); if ( ! port.isPresent() || port.get().trim().isEmpty()) { log.fine("" + varName + " not set, using " + defaultPort); return defaultPort; } try { return Integer.parseInt(port.get()); } catch (NumberFormatException e) { throw new IllegalArgumentException("must be an integer, was '" + port.get() + "'"); } } static private int findVespaPortBase(int defaultPort) { return findPort("VESPA_PORT_BASE", defaultPort); } static private int findConfigServerPort(int defaultPort) { return findPort("port_configserver_rpc", defaultPort); } static private int findConfigProxyPort(int defaultPort) { return findPort("port_configproxy_rpc", defaultPort); } static private int findWebServicePort(int defaultPort) { return findPort("VESPA_WEB_SERVICE_PORT", defaultPort); } /** * Get the username to own directories, files and processes * @return the vespa user name **/ public String vespaUser() { return vespaUser; } /** * Compute the host name that identifies myself. * Detection of the hostname is now done before starting any Vespa * programs and provided in the environment variable VESPA_HOSTNAME; * if that variable isn't set a default of "localhost" is always returned. * @return the vespa host name **/ public String vespaHostname() { return vespaHost; } /** * Returns the path to the root under which Vespa should read and write files. * Will not end with a "/". * @return the vespa home directory */ public String vespaHome() { return vespaHome; } /** * Returns an absolute path produced by prepending vespaHome to the argument if it is relative. * If the path starts by "/" (absolute) or "./" (explicitly relative - useful for tests), * it is returned as-is. * * @param path the path to prepend vespaHome to unless it is absolute * @return the given path string with the root path given from * vespaHome() prepended, unless the given path is absolute, in which * case it is be returned as-is */ public String underVespaHome(String path) { if (path.startsWith("/")) return path; if (path.startsWith("./")) return path; return vespaHome() + "/" + path; } /** * Returns the port number where Vespa web services should be available. * * @return the vespa webservice port */ public int vespaWebServicePort() { return vespaWebServicePort; } /** * Returns the base for port numbers where the Vespa services should listen. * * @return the vespa base number for ports */ public int vespaPortBase() { return vespaPortBase; } /** @return port number used by cloud config server (for its RPC protocol) */ public int vespaConfigServerRpcPort() { return vespaPortConfigServerRpc; } /** @return port number used by cloud config server (REST api on HTTP) */ public int vespaConfigServerHttpPort() { return vespaPortConfigServerHttp; } /** @return port number used by config proxy server (RPC protocol) */ public int vespaConfigProxyRpcPort() { return vespaPortConfigProxyRpc; } /** Returns the defaults of this runtime environment */ public static Defaults getDefaults() { return defaults; } }
package nl.mpi.kinnate.export; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileFilter; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JTextArea; import nl.mpi.arbil.ui.ArbilWindowManager; import nl.mpi.arbil.userstorage.ArbilSessionStorage; import nl.mpi.arbil.util.ApplicationVersionManager; import nl.mpi.arbil.util.MessageDialogHandler; import nl.mpi.kinnate.KinOathVersion; import nl.mpi.kinnate.entityindexer.EntityCollection; import nl.mpi.kinnate.userstorage.KinSessionStorage; import org.basex.core.BaseXException; import org.basex.core.Context; public class GedcomExport { private ArbilWindowManager arbilWindowManager; private KinSessionStorage kinSessionStorage; private EntityCollection entityCollection; private Context context = null; public GedcomExport(ArbilWindowManager arbilWindowManager, KinSessionStorage kinSessionStorage, EntityCollection entityCollection) { this.arbilWindowManager = arbilWindowManager; this.kinSessionStorage = kinSessionStorage; this.entityCollection = entityCollection; } private String getHeader() { return "let $headerString := \"0 HEAD\n" + "1 SOUR Reunion\n" + "2 VERS V8.0\n" + "2 CORP Leister Productions\n" + "1 DEST Reunion\n" + "1 DATE 11 FEB 2006\n" + "1 FILE test\n" + "1 GEDC\n" + "2 VERS 5.5\n" + "1 CHAR MACINTOSH\n\""; } private String getIndividual() { return "string(\"0 @\")," return "let $colNames := distinct-values(collection('nl-mpi-kinnate')/*:Kinnate/*:CustomData/*//local-name())\n" // todo: get the xpath not the node name File[] importDirectoryArray = arbilWindowManager.showFileSelectBox("Select Import Directory", true, false, null, MessageDialogHandler.DialogueType.open, null/* formatSelect */);
package nl.mpi.kinnate.kindata; import java.awt.Rectangle; import java.util.ArrayList; import java.util.HashMap; import javax.xml.bind.annotation.XmlElement; import nl.mpi.kinnate.svg.GraphPanel; import nl.mpi.kinnate.svg.GraphPanelSize; public class GraphSorter { @XmlElement(name = "Entity", namespace = "http://mpi.nl/tla/kin") private EntityData[] graphDataNodeArray = new EntityData[]{}; HashMap<String, SortingEntity> knownSortingEntities; // todo: should these padding vars be stored in the svg, currently they are stored public int xPadding = 100; // todo sort out one place for this var public int yPadding = 100; // todo sort out one place for this var // private boolean requiresRedraw = false; // , int hSpacing, int vSpacing public void setPadding(GraphPanelSize graphPanelSize) { xPadding = graphPanelSize.getHorizontalSpacing(); yPadding = graphPanelSize.getVerticalSpacing(); } private class SortingEntity { String selfEntityId; ArrayList<SortingEntity> mustBeBelow; ArrayList<SortingEntity> mustBeAbove; ArrayList<SortingEntity> mustBeNextTo; ArrayList<SortingEntity> couldBeNextTo; EntityRelation[] visiblyRelateNodes; float[] calculatedPosition = null; public SortingEntity(EntityData entityData) { selfEntityId = entityData.getUniqueIdentifier(); visiblyRelateNodes = entityData.getVisiblyRelateNodes(); mustBeBelow = new ArrayList<SortingEntity>(); mustBeAbove = new ArrayList<SortingEntity>(); mustBeNextTo = new ArrayList<SortingEntity>(); couldBeNextTo = new ArrayList<SortingEntity>(); } public void calculateRelations(HashMap<String, SortingEntity> knownSortingEntities) { for (EntityRelation entityRelation : visiblyRelateNodes) { switch (entityRelation.relationType) { case ancestor: mustBeBelow.add(knownSortingEntities.get(entityRelation.alterUniqueIdentifier)); break; case descendant: mustBeAbove.add(knownSortingEntities.get(entityRelation.alterUniqueIdentifier)); break; case union: mustBeNextTo.add(knownSortingEntities.get(entityRelation.alterUniqueIdentifier)); // no break here is deliberate: those that mustBeNextTo to need also to be in couldBeNextTo case sibling: couldBeNextTo.add(knownSortingEntities.get(entityRelation.alterUniqueIdentifier)); break; } } } private boolean positionIsFree(String currentIdentifier, float[] targetPosition, HashMap<String, float[]> entityPositions) { int useCount = 0; for (float[] currentPosition : entityPositions.values()) { if (currentPosition[0] == targetPosition[0] && currentPosition[1] == targetPosition[1]) { useCount++; } } if (useCount == 0) { return true; } if (useCount == 1) { float[] entityPosition = entityPositions.get(currentIdentifier); if (entityPosition != null) { // todo: change this to compare distance not exact location if (entityPosition[0] == targetPosition[0] && entityPosition[1] == targetPosition[1]) { // if there is one entity already in this position then check if it is the current entity, in which case it is free return true; } } } return false; } protected float[] getPosition(HashMap<String, float[]> entityPositions, float[] defaultPosition) { System.out.println("getPosition: " + selfEntityId); calculatedPosition = entityPositions.get(selfEntityId); if (calculatedPosition == null) { for (SortingEntity sortingEntity : mustBeBelow) { // note that this get position also sets the position and the result will not be null float[] nextAbovePos = sortingEntity.getPosition(entityPositions, defaultPosition); if (calculatedPosition == null) { calculatedPosition = new float[]{nextAbovePos[0], nextAbovePos[1]}; } if (nextAbovePos[1] > calculatedPosition[1] - yPadding) { calculatedPosition[1] = nextAbovePos[1] + yPadding; // calculatedPosition[0] = nextAbovePos[0]; System.out.println("move down: " + selfEntityId); } } if (calculatedPosition == null) { for (SortingEntity sortingEntity : couldBeNextTo) { // note that this does not set the position and the result can be null float[] nextToPos = entityPositions.get(sortingEntity.selfEntityId); if (calculatedPosition == null && nextToPos != null) { calculatedPosition = new float[]{nextToPos[0], nextToPos[1]}; } } } if (calculatedPosition == null) { for (SortingEntity sortingEntity : mustBeAbove) { // note that this does not set the position and the result can be null float[] nextBelowPos = entityPositions.get(sortingEntity.selfEntityId); if (nextBelowPos != null) { if (calculatedPosition == null) { calculatedPosition = new float[]{nextBelowPos[0], nextBelowPos[1]}; } if (nextBelowPos[1] < calculatedPosition[1] + yPadding) { calculatedPosition[1] = nextBelowPos[1] - yPadding; // calculatedPosition[0] = nextAbovePos[0]; System.out.println("move up: " + selfEntityId); } } } } if (calculatedPosition == null) { calculatedPosition = new float[]{0, defaultPosition[1]}; } // make sure any spouses are in the same row // todo: this should probably be moved into a separate action and when a move is made then move in sequence the entities that are below and to the right for (SortingEntity sortingEntity : mustBeNextTo) { float[] nextToPos = entityPositions.get(sortingEntity.selfEntityId); if (nextToPos != null) { if (nextToPos[1] > calculatedPosition[1]) { calculatedPosition = new float[]{nextToPos[0], nextToPos[1]}; } // } else { // // prepopulate the spouse position // float[] spousePosition = new float[]{calculatedPosition[0], calculatedPosition[1]}; // while (!positionIsFree(sortingEntity.selfEntityId, spousePosition, entityPositions)) { // // todo: this should be checking min distance not free // spousePosition[0] = spousePosition[0] + xPadding; // System.out.println("move spouse right: " + selfEntityId); // entityPositions.put(sortingEntity.selfEntityId, spousePosition); } } while (!positionIsFree(selfEntityId, calculatedPosition, entityPositions)) { // todo: this should be checking min distance not free calculatedPosition[0] = calculatedPosition[0] + xPadding; System.out.println("move right: " + selfEntityId); } // System.out.println("Insert: " + selfEntityId + " : " + calculatedPosition[0] + " : " + calculatedPosition[1]); entityPositions.put(selfEntityId, calculatedPosition); } System.out.println("Position: " + selfEntityId + " : " + calculatedPosition[0] + " : " + calculatedPosition[1]); // float[] debugArray = entityPositions.get("Charles II of Spain"); // if (debugArray != null) { // System.out.println("Charles II of Spain: " + debugArray[0] + " : " + debugArray[1]); return calculatedPosition; } protected void getRelatedPositions(HashMap<String, float[]> entityPositions) { ArrayList<SortingEntity> allRelations = new ArrayList<SortingEntity>(); allRelations.addAll(mustBeAbove); allRelations.addAll(mustBeBelow); // allRelations.addAll(mustBeNextTo); // those that are in mustBeNextTo are also in couldBeNextTo allRelations.addAll(couldBeNextTo); for (SortingEntity sortingEntity : allRelations) { if (sortingEntity.calculatedPosition == null) { Rectangle rectangle = getGraphSize(entityPositions); float[] defaultPosition = new float[]{rectangle.width, rectangle.height}; sortingEntity.getPosition(entityPositions, defaultPosition); sortingEntity.getRelatedPositions(entityPositions); } } } } public void setEntitys(EntityData[] graphDataNodeArrayLocal) { graphDataNodeArray = graphDataNodeArrayLocal; // this section need only be done when the nodes are added to this graphsorter knownSortingEntities = new HashMap<String, SortingEntity>(); for (EntityData currentNode : graphDataNodeArrayLocal) { if (currentNode.isVisible) { // only create sorting entities for visible entities knownSortingEntities.put(currentNode.getUniqueIdentifier(), new SortingEntity(currentNode)); } } for (SortingEntity currentSorter : knownSortingEntities.values()) { currentSorter.calculateRelations(knownSortingEntities); } // sanguineSort(); //printLocations(); // todo: remove this and maybe add a label of x,y post for each node to better see the sorting } // public boolean isResizeRequired() { // boolean returnBool = requiresRedraw; // requiresRedraw = false; // return returnBool; // private void placeRelatives(EntityData currentNode, ArrayList<EntityData> intendedSortOrder, HashMap<String, Float[]> entityPositions) { // for (EntityRelation entityRelation : currentNode.getVisiblyRelateNodes()) { // EntityData relatedEntity = entityRelation.getAlterNode(); public Rectangle getGraphSize(HashMap<String, float[]> entityPositions) { // get min positions // this should also take into account any graphics such as labels, although the border provided should be adequate, in other situations the page size could be set, in which case maybe an align option would be helpful int[] minPostion = null; int[] maxPostion = null; for (float[] currentPosition : entityPositions.values()) { if (minPostion == null) { minPostion = new int[]{Math.round(currentPosition[0]), Math.round(currentPosition[1])}; maxPostion = new int[]{Math.round(currentPosition[0]), Math.round(currentPosition[1])}; } else { minPostion[0] = Math.min(minPostion[0], Math.round(currentPosition[0])); minPostion[1] = Math.min(minPostion[1], Math.round(currentPosition[1])); maxPostion[0] = Math.max(maxPostion[0], Math.round(currentPosition[0])); maxPostion[1] = Math.max(maxPostion[1], Math.round(currentPosition[1])); } } if (minPostion == null) { // when there are no entities this could be null and must be corrected here minPostion = new int[]{0, 0}; maxPostion = new int[]{0, 0}; } int xOffset = minPostion[0] - xPadding; int yOffset = minPostion[1] - yPadding; int graphWidth = maxPostion[0] + xPadding; int graphHeight = maxPostion[1] + yPadding; return new Rectangle(xOffset, yOffset, graphWidth, graphHeight); } public void placeAllNodes(GraphPanel graphPanel, HashMap<String, float[]> entityPositions) { // make a has table of all entites // find the first ego node // place it and all its immediate relatives onto the graph, each time checking that the space is free // contine to the next nearest relatives // when all done search for any unrelated nodes and do it all again // make sure that invisible nodes are ignored for (EntityData currentNode : graphDataNodeArray) { if (!currentNode.isVisible) { entityPositions.remove(currentNode.getUniqueIdentifier()); } } for (SortingEntity currentSorter : knownSortingEntities.values()) { Rectangle rectangle = getGraphSize(entityPositions); float[] defaultPosition = new float[]{rectangle.width, rectangle.height}; currentSorter.getPosition(entityPositions, defaultPosition); currentSorter.getRelatedPositions(entityPositions); } // requiresRedraw = (yOffset != 0 || xOffset != 0); // todo: use a transalte rather than moving the nodes because the label position is important // if (yOffset < 0 || xOffset < 0) { // todo: use a transalte rather than moving the nodes because the label position is important // for (float[] currentPosition : entityPositions.values()) { // currentPosition[0] = currentPosition[0] + xOffset; // currentPosition[1] = currentPosition[1] + yOffset; // ArrayList<EntityData> intendedSortOrder = new ArrayList<EntityData>(); //// ArrayList<EntityData> placedEntities = new ArrayList<EntityData>(); // for (EntityData currentNode : allEntitys) { // if (currentNode.isVisible && entityPositions.containsKey(currentNode.getUniqueIdentifier())) { // // add all the placed entities first in the list // intendedSortOrder.add(currentNode); // boolean nodesNeedPlacement = false; // for (EntityData currentNode : allEntitys) { // if (currentNode.isVisible && !intendedSortOrder.contains(currentNode)) { // intendedSortOrder.add(currentNode); // nodesNeedPlacement = true; // if (!nodesNeedPlacement) { // return; // // store the max and min X Y so that the diagram size can be correctly specified // while (!intendedSortOrder.isEmpty()) { // EntityData currentNode = intendedSortOrder.remove(0); //// placedEntities.add(currentNode); // if (currentNode.isVisible) { // // loop through the filled locations and move to the right or left if not empty required //// // todo: check the related nodes and average their positions then check to see if it is free and insert the node there // boolean positionFree = false; // float preferedX = 0; // String currentIdentifier = currentNode.getUniqueIdentifier(); // Float[] storedPosition = entityPositions.get(currentIdentifier); //// if (storedPosition == null) { //// storedPosition = new Float[]{preferedX, 0.0f}; // while (!positionFree) { //// storedPosition = new Float[]{preferedX * hSpacing + hSpacing - symbolSize / 2.0f, //// currentNode.getyPos() * vSpacing + vSpacing - symbolSize / 2.0f}; //// if (entityPositions.isEmpty()) { //// break; // if (storedPosition != null) { // positionFree = true; // for (String comparedIdentifier : entityPositions.keySet()) { // if (!comparedIdentifier.equals(currentIdentifier)) { // Float[] currentPosition = entityPositions.get(comparedIdentifier); // positionFree = !currentPosition[0].equals(storedPosition[0]) || !currentPosition[1].equals(storedPosition[1]); // if (!positionFree) { // break; // preferedX++; // if (!positionFree) { // storedPosition = new Float[]{preferedX, 0.0f}; // entityPositions.put(currentIdentifier, storedPosition); } //// public int[] getEntityLocation(String entityId) { //// for (EntityData entityData : graphDataNodeArray) { //// if (entityData.getUniqueIdentifier().equals(entityId)) { //// return new int[]{entityData.xPos, entityData.yPos}; //// return null; //// public void setEntityLocation(String entityId, int xPos, int yPos) { //// for (EntityData entityData : graphDataNodeArray) { //// if (entityData.getUniqueIdentifier().equals(entityId)) { //// entityData.xPos = xPos; //// entityData.yPos = yPos; //// return; // // todo: and http://books.google.nl/books?id=diqHjRjMhW0C&pg=PA138&lpg=PA138&dq=SVGDOMImplementation+add+namespace&source=bl&ots=IuqzAz7dsz&sig=e5FW_B1bQbhnth6i2rifalv2LuQ&hl=nl&ei=zYpnTYD3E4KVOuPF2YoL&sa=X&oi=book_result&ct=result&resnum=3&ved=0CC0Q6AEwAg#v=onepage&q&f=false // // page 139 shows jgraph layout usage // // todo: lookinto: //// layouts.put("Hierarchical", new JGraphHierarchicalLayout()); //// layouts.put("Compound", new JGraphCompoundLayout()); //// layouts.put("CompactTree", new JGraphCompactTreeLayout()); //// layouts.put("Tree", new JGraphTreeLayout()); //// layouts.put("RadialTree", new JGraphRadialTreeLayout()); //// layouts.put("Organic", new JGraphOrganicLayout()); //// layouts.put("FastOrganic", new JGraphFastOrganicLayout()); //// layouts.put("SelfOrganizingOrganic", new JGraphSelfOrganizingOrganicLayout()); //// layouts.put("SimpleCircle", new JGraphSimpleLayout(JGraphSimpleLayout.TYPE_CIRCLE)); //// layouts.put("SimpleTilt", new JGraphSimpleLayout(JGraphSimpleLayout.TYPE_TILT)); //// layouts.put("SimpleRandom", new JGraphSimpleLayout(JGraphSimpleLayout.TYPE_RANDOM)); //// layouts.put("Spring", new JGraphSpringLayout()); //// layouts.put("Grid", new SimpleGridLayout()); // private void sanguineSubnodeSort(ArrayList<HashSet<EntityData>> generationRows, HashSet<EntityData> currentColumns, ArrayList<EntityData> inputNodes, EntityData currentNode) { // int currentRowIndex = generationRows.indexOf(currentColumns); // HashSet<EntityData> ancestorColumns; // HashSet<EntityData> descendentColumns; // if (currentRowIndex < generationRows.size() - 1) { // descendentColumns = generationRows.get(currentRowIndex + 1); // } else { // descendentColumns = new HashSet<EntityData>(); // generationRows.add(currentRowIndex + 1, descendentColumns); // if (currentRowIndex > 0) { // ancestorColumns = generationRows.get(currentRowIndex - 1); // } else { // ancestorColumns = new HashSet<EntityData>(); // generationRows.add(currentRowIndex, ancestorColumns); // for (EntityRelation relatedNode : currentNode.getVisiblyRelateNodes()) { // todo: here we are soriting only visible nodes, sorting invisible nodes as well might cause issues or might help the layout and this must be tested // // todo: what happens here if there are multiple relations specified? // if (/*relatedNode.getAlterNode().isVisible &&*/inputNodes.contains(relatedNode.getAlterNode())) { // HashSet<EntityData> targetColumns; // switch (relatedNode.relationType) { // case ancestor: // targetColumns = ancestorColumns; // break; // case sibling: // targetColumns = currentColumns; // break; // case descendant: // targetColumns = descendentColumns; // break; // case union: // targetColumns = currentColumns; // break; // case none: // // this would be a kin term or other so skip when sorting // targetColumns = null; // break; // default: // targetColumns = null; // if (targetColumns != null) { // inputNodes.remove(relatedNode.getAlterNode()); // targetColumns.add(relatedNode.getAlterNode()); //// System.out.println("sorted: " + relatedNode.getAlterNode().getLabel() + " : " + relatedNode.relationType + " of " + currentNode.getLabel()); // sanguineSubnodeSort(generationRows, targetColumns, inputNodes, relatedNode.getAlterNode()); // protected void sanguineSort() { // // todo: improve this sorting by adding a secondary row sort // System.out.println("calculateLocations"); // // create an array of rows // ArrayList<HashSet<EntityData>> generationRows = new ArrayList<HashSet<EntityData>>(); // ArrayList<EntityData> inputNodes = new ArrayList<EntityData>(); // inputNodes.addAll(Arrays.asList(graphDataNodeArray)); // // put an array of columns into the current row // HashSet<EntityData> currentColumns = new HashSet<EntityData>(); // generationRows.add(currentColumns); // while (inputNodes.size() > 0) { // this loop checks all nodes provided for display, but the sanguineSubnodeSort will remove any related nodes before we return to this loop, so this loop would only run once if all nodes are related // EntityData currentNode = inputNodes.remove(0); //// System.out.println("add as root node: " + currentNode.getLabel()); //// if (currentNode.isVisible) { // currentColumns.add(currentNode); // sanguineSubnodeSort(generationRows, currentColumns, inputNodes, currentNode); // gridWidth = 0; // int yPos = 0; // for (HashSet<EntityData> currentRow : generationRows) { // System.out.println("row: : " + yPos); // if (currentRow.isEmpty()) { // System.out.println("Skipping empty row"); // } else { // int xPos = 0; // if (gridWidth < currentRow.size()) { // gridWidth = currentRow.size(); // for (EntityData graphDataNode : currentRow) { //// System.out.println("updating: " + xPos + " : " + yPos + " : " + graphDataNode.getLabel()); // graphDataNode.yPos = yPos; // graphDataNode.xPos = xPos; // //graphDataNode.appendTempLabel("X:" + xPos + " Y:" + yPos); // xPos++; // yPos++; // gridHeight = yPos; // int maxRowWidth = 0; // // correct the grid width // for (HashSet<EntityData> currentRow : generationRows) { // if (maxRowWidth < currentRow.size()) { // maxRowWidth = currentRow.size(); // gridWidth = maxRowWidth; // System.out.println("gridWidth: " + gridWidth); //// sortRowsByAncestor(generationRows); // sortByLinkDistance(); // sortByLinkDistance(); // private void sortRowsByAncestor(ArrayList<HashSet<EntityData>> generationRows) { // // todo: handle reverse generations also // ArrayList<EntityData> sortedRow = new ArrayList<EntityData>(); // int startRow = 0; // while (generationRows.get(startRow).isEmpty()) { // startRow++; // HashSet<EntityData> firstRow = generationRows.get(startRow); // for (EntityData currentEntity : firstRow) { // if (!sortedRow.contains(currentEntity)) { // if the entity has been added then do not look into any further // sortedRow.add(currentEntity); // // if this node has children in common with any other on this row then place them next to each other // // todo: add sort by DOB // for (EntityData contemporariesEntity : findContemporariesWithCommonDescendant(currentEntity, 2)) { // if (!sortedRow.contains(contemporariesEntity)) { // sortedRow.add(contemporariesEntity); // while (sortedRow.size() > 0) { // assignRowOrder(sortedRow); // ArrayList<EntityData> nextRow = new ArrayList<EntityData>(); // for (EntityData currentEntity : sortedRow) { // for (EntityRelation childRelation : currentEntity.getDistinctRelateNodes()) { // if (childRelation.getAlterNode().yPos == currentEntity.yPos + 1) { // if (!nextRow.contains(childRelation.getAlterNode())) { // nextRow.add(childRelation.getAlterNode()); // sortedRow = nextRow; // private void assignRowOrder(ArrayList<EntityData> sortedRow) { // int columnCount = 0; // for (EntityData currentEntity : sortedRow) { // // todo: space the nodes // currentEntity.xPos = columnCount; // columnCount++; // System.out.println("sorted: " + currentEntity.getLabel()[0] + " : " + currentEntity.xPos + "," + currentEntity.yPos); // private HashSet<EntityData> findContemporariesWithCommonDescendant(EntityData currentEntity, int depth) { // HashSet<EntityData> foundContemporaries = new HashSet<EntityData>(); // for (EntityRelation childRelation : currentEntity.getDistinctRelateNodes()) { // if (childRelation.getAlterNode().yPos == currentEntity.yPos) { // foundContemporaries.add(childRelation.getAlterNode()); // } else { // depth--; // if (depth > 0) { // foundContemporaries.addAll(findContemporariesWithCommonDescendant(currentEntity, depth)); // return foundContemporaries; // private void sortByLinkDistance() { // // todo: correct the grid width, // // start at the top row and count the childeren of each parent and space accordingly // EntityData[][] graphGrid = new EntityData[gridHeight][gridWidth]; // for (EntityData graphDataNode : graphDataNodeArray) { // graphGrid[graphDataNode.yPos][graphDataNode.xPos] = graphDataNode; // for (EntityData graphDataNode : graphDataNodeArray) { // int relationCounter = 0; // int totalPositionCounter = 0; // for (EntityRelation graphLinkNode : graphDataNode.getVisiblyRelateNodes()) { // relationCounter++; // totalPositionCounter += graphLinkNode.getAlterNode().xPos; // //totalPositionCounter += Math.abs(graphLinkNode.linkedNode.xPos - graphLinkNode.sourceNode.xPos); //// totalPositionCounter += Math.abs(graphLinkNode.linkedNode.xPos - graphLinkNode.sourceNode.xPos); // System.out.println("link: " + graphLinkNode.getAlterNode().xPos + ":" + graphLinkNode.getAlterNode().xPos); // System.out.println("totalPositionCounter: " + totalPositionCounter); // if (relationCounter > 0) { // int averagePosition = totalPositionCounter / relationCounter; // while (averagePosition < gridWidth - 1 && graphGrid[graphDataNode.yPos][averagePosition] != null) { // averagePosition++; // while (averagePosition > 0 && graphGrid[graphDataNode.yPos][averagePosition] != null) { // averagePosition--; // if (graphGrid[graphDataNode.yPos][averagePosition] == null) { // graphGrid[graphDataNode.yPos][graphDataNode.xPos] = null; // graphDataNode.xPos = averagePosition; // todo: swap what ever is aready there // graphGrid[graphDataNode.yPos][graphDataNode.xPos] = graphDataNode; // System.out.println("averagePosition: " + averagePosition); public EntityData[] getDataNodes() { return graphDataNodeArray; } // private void printLocations() { // System.out.println("printLocations"); // for (EntityData graphDataNode : graphDataNodeArray) { // System.out.println("node: " + graphDataNode.xPos + ":" + graphDataNode.yPos); // for (EntityRelation graphLinkNode : graphDataNode.getVisiblyRelateNodes()) { // System.out.println("link: " + graphLinkNode.getAlterNode().xPos + ":" + graphLinkNode.getAlterNode().yPos); }
package io.quarkus.maven; import java.text.MessageFormat; import java.util.Collections; import java.util.Map; import java.util.function.Supplier; import org.apache.maven.plugin.logging.Log; import org.apache.maven.shared.utils.logging.MessageBuilder; import org.apache.maven.shared.utils.logging.MessageUtils; import org.jboss.logging.Logger; import org.jboss.logging.LoggerProvider; import org.wildfly.common.Assert; public class MojoLogger implements LoggerProvider { static final Object[] NO_PARAMS = new Object[0]; public static volatile Supplier<Log> logSupplier; @Override public Logger getLogger(final String name) { return new Logger(name) { @Override protected void doLog(final Level level, final String loggerClassName, final Object message, final Object[] parameters, final Throwable thrown) { final Supplier<Log> logSupplier = MojoLogger.logSupplier; if (logSupplier != null) { Log log = logSupplier.get(); String text; if (parameters == null || parameters.length == 0) { text = String.valueOf(message); } else { try { text = MessageFormat.format(String.valueOf(message), parameters); } catch (Exception e) { text = invalidFormat(String.valueOf(message), parameters); } } synchronized (MojoLogger.class) { doActualLog(log, level, text, thrown); } } } @Override protected void doLogf(final Level level, final String loggerClassName, final String format, final Object[] parameters, final Throwable thrown) { final Supplier<Log> logSupplier = MojoLogger.logSupplier; if (logSupplier != null) { Log log = logSupplier.get(); String text; if (parameters == null) { try { //noinspection RedundantStringFormatCall text = String.format(format); } catch (Exception e) { text = invalidFormat(format, NO_PARAMS); } } else { try { text = String.format(format, (Object[]) parameters); } catch (Exception e) { text = invalidFormat(format, parameters); } } synchronized (MojoLogger.class) { doActualLog(log, level, text, thrown); } } } @Override public boolean isEnabled(final Level level) { final Supplier<Log> logSupplier = MojoLogger.logSupplier; if (logSupplier == null) return false; Log log = logSupplier.get(); switch (level) { case FATAL: case ERROR: return log.isErrorEnabled(); case WARN: return log.isWarnEnabled(); case INFO: return log.isInfoEnabled(); default: return log.isDebugEnabled(); } } void doActualLog(final Log log, final Level level, final String message, final Throwable thrown) { final MessageBuilder buffer = MessageUtils.buffer(); // style options are limited unless we crack into jansi ourselves buffer.strong("[").project(name).strong("]").a(" ").a(message); if (thrown != null) { switch (level) { case FATAL: case ERROR: log.error(buffer.toString(), thrown); break; case WARN: log.warn(buffer.toString(), thrown); break; case INFO: log.info(buffer.toString(), thrown); break; default: log.debug(buffer.toString(), thrown); break; } } else { switch (level) { case FATAL: case ERROR: log.error(buffer.toString()); break; case WARN: log.warn(buffer.toString()); break; case INFO: log.info(buffer.toString()); break; default: log.debug(buffer.toString()); break; } } } }; } String invalidFormat(final String format, final Object[] parameters) { final StringBuilder b = new StringBuilder("** invalid format \'" + format + "\'"); if (parameters != null && parameters.length > 0) { b.append(" [").append(parameters[0]); for (int i = 1; i < parameters.length; i++) { b.append(',').append(parameters[i]); } b.append("]"); } return b.toString(); } @Override public void clearMdc() { } @Override public Object putMdc(final String key, final Object value) { //throw Assert.unsupported(); return null; } @Override public Object getMdc(final String key) { return null; } @Override public void removeMdc(final String key) { } @Override public Map<String, Object> getMdcMap() { return Collections.emptyMap(); } @Override public void clearNdc() { } @Override public String getNdc() { return ""; } @Override public int getNdcDepth() { return 0; } @Override public String popNdc() { return ""; } @Override public String peekNdc() { return ""; } @Override public void pushNdc(final String message) { throw Assert.unsupported(); } @Override public void setNdcMaxDepth(final int maxDepth) { } }
package com.jme3.scene.plugins; import com.jme3.asset.*; import com.jme3.material.Material; import com.jme3.material.MaterialList; import com.jme3.util.*; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.renderer.queue.RenderQueue.Bucket; import com.jme3.scene.Geometry; import com.jme3.scene.Mesh; import com.jme3.scene.Mesh.Mode; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.jme3.scene.VertexBuffer; import com.jme3.scene.VertexBuffer.Type; import com.jme3.scene.mesh.IndexBuffer; import com.jme3.scene.mesh.IndexIntBuffer; import com.jme3.scene.mesh.IndexShortBuffer; import java.io.IOException; import java.io.InputStream; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; import java.util.Map.Entry; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; /** * Reads OBJ format models. */ public final class OBJLoader implements AssetLoader { private static final Logger logger = Logger.getLogger(OBJLoader.class.getName()); protected final ArrayList<Vector3f> verts = new ArrayList<Vector3f>(); protected final ArrayList<Vector2f> texCoords = new ArrayList<Vector2f>(); protected final ArrayList<Vector3f> norms = new ArrayList<Vector3f>(); protected final ArrayList<Face> faces = new ArrayList<Face>(); protected final HashMap<String, ArrayList<Face>> matFaces = new HashMap<String, ArrayList<Face>>(); protected String currentMatName; protected String currentObjectName; protected final HashMap<Vertex, Integer> vertIndexMap = new HashMap<Vertex, Integer>(100); protected final IntMap<Vertex> indexVertMap = new IntMap<Vertex>(100); protected int curIndex = 0; protected int objectIndex = 0; protected int geomIndex = 0; protected Scanner scan; protected ModelKey key; protected AssetManager assetManager; protected MaterialList matList; protected String objName; protected Node objNode; protected static class Vertex { Vector3f v; Vector2f vt; Vector3f vn; int index; @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Vertex other = (Vertex) obj; if (this.v != other.v && (this.v == null || !this.v.equals(other.v))) { return false; } if (this.vt != other.vt && (this.vt == null || !this.vt.equals(other.vt))) { return false; } if (this.vn != other.vn && (this.vn == null || !this.vn.equals(other.vn))) { return false; } return true; } @Override public int hashCode() { int hash = 5; hash = 53 * hash + (this.v != null ? this.v.hashCode() : 0); hash = 53 * hash + (this.vt != null ? this.vt.hashCode() : 0); hash = 53 * hash + (this.vn != null ? this.vn.hashCode() : 0); return hash; } } protected static class Face { Vertex[] verticies; } protected class ObjectGroup { final String objectName; public ObjectGroup(String objectName){ this.objectName = objectName; } public Spatial createGeometry(){ Node groupNode = new Node(objectName); // if (matFaces.size() > 0){ // for (Entry<String, ArrayList<Face>> entry : matFaces.entrySet()){ // ArrayList<Face> materialFaces = entry.getValue(); // if (materialFaces.size() > 0){ // Geometry geom = createGeometry(materialFaces, entry.getKey()); // objNode.attachChild(geom); // }else if (faces.size() > 0){ // // generate final geometry // Geometry geom = createGeometry(faces, null); // objNode.attachChild(geom); return groupNode; } } public void reset(){ verts.clear(); texCoords.clear(); norms.clear(); faces.clear(); matFaces.clear(); vertIndexMap.clear(); indexVertMap.clear(); currentMatName = null; curIndex = 0; geomIndex = 0; scan = null; } protected void findVertexIndex(Vertex vert){ Integer index = vertIndexMap.get(vert); if (index != null){ vert.index = index.intValue(); }else{ vert.index = curIndex++; vertIndexMap.put(vert, vert.index); indexVertMap.put(vert.index, vert); } } protected Face[] quadToTriangle(Face f){ assert f.verticies.length == 4; Face[] t = new Face[]{ new Face(), new Face() }; t[0].verticies = new Vertex[3]; t[1].verticies = new Vertex[3]; Vertex v0 = f.verticies[0]; Vertex v1 = f.verticies[1]; Vertex v2 = f.verticies[2]; Vertex v3 = f.verticies[3]; // find the pair of verticies that is closest to each over // v0 and v2 // v1 and v3 float d1 = v0.v.distanceSquared(v2.v); float d2 = v1.v.distanceSquared(v3.v); if (d1 < d2){ // put an edge in v0, v2 t[0].verticies[0] = v0; t[0].verticies[1] = v1; t[0].verticies[2] = v3; t[1].verticies[0] = v1; t[1].verticies[1] = v2; t[1].verticies[2] = v3; }else{ // put an edge in v1, v3 t[0].verticies[0] = v0; t[0].verticies[1] = v1; t[0].verticies[2] = v2; t[1].verticies[0] = v0; t[1].verticies[1] = v2; t[1].verticies[2] = v3; } return t; } private ArrayList<Vertex> vertList = new ArrayList<Vertex>(); protected void readFace(){ Face f = new Face(); vertList.clear(); String line = scan.nextLine().trim(); String[] verticies = line.split(" "); for (String vertex : verticies){ int v = 0; int vt = 0; int vn = 0; String[] split = vertex.split("/"); if (split.length == 1){ v = Integer.parseInt(split[0]); }else if (split.length == 2){ v = Integer.parseInt(split[0]); vt = Integer.parseInt(split[1]); }else if (split.length == 3 && !split[1].equals("")){ v = Integer.parseInt(split[0]); vt = Integer.parseInt(split[1]); vn = Integer.parseInt(split[2]); }else if (split.length == 3){ v = Integer.parseInt(split[0]); vn = Integer.parseInt(split[2]); } Vertex vx = new Vertex(); vx.v = verts.get(v - 1); if (vt > 0) vx.vt = texCoords.get(vt - 1); if (vn > 0) vx.vn = norms.get(vn - 1); vertList.add(vx); } if (vertList.size() > 4 || vertList.size() <= 2) logger.warning("Edge or polygon detected in OBJ. Ignored."); f.verticies = new Vertex[vertList.size()]; for (int i = 0; i < vertList.size(); i++){ f.verticies[i] = vertList.get(i); } if (matList != null && matFaces.containsKey(currentMatName)){ matFaces.get(currentMatName).add(f); }else{ faces.add(f); // faces that belong to the default material } } protected Vector3f readVector3(){ Vector3f v = new Vector3f(); v.set(Float.parseFloat(scan.next()), Float.parseFloat(scan.next()), Float.parseFloat(scan.next())); return v; } protected Vector2f readVector2(){ Vector2f v = new Vector2f(); String line = scan.nextLine().trim(); String[] split = line.split(" "); v.setX( Float.parseFloat(split[0]) ); v.setY( Float.parseFloat(split[1]) ); // v.setX(scan.nextFloat()); // if (scan.hasNextFloat()){ // v.setY(scan.nextFloat()); // if (scan.hasNextFloat()){ // scan.nextFloat(); // ignore return v; } protected void loadMtlLib(String name) throws IOException{ if (!name.toLowerCase().endsWith(".mtl")) throw new IOException("Expected .mtl file! Got: " + name); matList = (MaterialList) assetManager.loadAsset(key.getFolder() + name); if (matList != null){ // create face lists for every material for (String matName : matList.keySet()){ matFaces.put(matName, new ArrayList<Face>()); } }else{ logger.log(Level.WARNING, "Can't find MTL file. " + "Using default material for OBJ."); } } private static final Pattern nl = Pattern.compile("\n"); private static final Pattern ws = Pattern.compile("\\p{javaWhitespace}+"); protected void nextStatement(){ scan.useDelimiter(nl); scan.next(); scan.useDelimiter(ws); } protected boolean readLine() throws IOException{ if (!scan.hasNext()){ return false; } String cmd = scan.next(); if (cmd.startsWith(" // skip entire comment until next line nextStatement(); }else if (cmd.equals("v")){ // vertex position verts.add(readVector3()); }else if (cmd.equals("vn")){ // vertex normal norms.add(readVector3()); }else if (cmd.equals("vt")){ // texture coordinate texCoords.add(readVector2()); }else if (cmd.equals("f")){ // face, can be triangle, quad, or polygon (unsupported) readFace(); }else if (cmd.equals("usemtl")){ // use material from MTL lib for the following faces currentMatName = scan.next(); // if (!matList.containsKey(currentMatName)) // throw new IOException("Cannot locate material " + currentMatName + " in MTL file!"); }else if (cmd.equals("mtllib")){ // specify MTL lib to use for this OBJ file String mtllib = scan.nextLine().trim(); loadMtlLib(mtllib); }else if (cmd.equals("s") || cmd.equals("g")){ nextStatement(); }else{ // skip entire command until next line System.out.println("Unknown statement in OBJ! "+cmd); nextStatement(); } return true; } protected Geometry createGeometry(ArrayList<Face> faceList, String matName) throws IOException{ if (faceList.isEmpty()) throw new IOException("No geometry data to generate mesh"); // Create mesh from the faces Mesh mesh = constructMesh(faceList); Geometry geom = new Geometry(objName + "-geom-" + (geomIndex++), mesh); Material material = null; if (matName != null && matList != null){ // Get material from material list material = matList.get(matName); } if (material == null){ // create default material material = new Material(assetManager, "Common/MatDefs/Light/Lighting.j3md"); material.setFloat("Shininess", 64); } geom.setMaterial(material); if (material.isTransparent()) geom.setQueueBucket(Bucket.Transparent); else geom.setQueueBucket(Bucket.Opaque); if (material.getMaterialDef().getName().contains("Lighting") || mesh.getFloatBuffer(Type.Normal) == null){ logger.log(Level.WARNING, "OBJ mesh {0} doesn't contain normals! " + "It might not display correctly", geom.getName()); } return geom; } protected Mesh constructMesh(ArrayList<Face> faceList){ Mesh m = new Mesh(); m.setMode(Mode.Triangles); boolean hasTexCoord = false; boolean hasNormals = false; ArrayList<Face> newFaces = new ArrayList<Face>(faceList.size()); for (int i = 0; i < faceList.size(); i++){ Face f = faceList.get(i); for (Vertex v : f.verticies){ findVertexIndex(v); if (!hasTexCoord && v.vt != null) hasTexCoord = true; if (!hasNormals && v.vn != null) hasNormals = true; } if (f.verticies.length == 4){ Face[] t = quadToTriangle(f); newFaces.add(t[0]); newFaces.add(t[1]); }else{ newFaces.add(f); } } FloatBuffer posBuf = BufferUtils.createFloatBuffer(vertIndexMap.size() * 3); FloatBuffer normBuf = null; FloatBuffer tcBuf = null; if (hasNormals){ normBuf = BufferUtils.createFloatBuffer(vertIndexMap.size() * 3); } if (hasTexCoord){ tcBuf = BufferUtils.createFloatBuffer(vertIndexMap.size() * 2); } IndexBuffer indexBuf = null; if (vertIndexMap.size() >= 65536){ // too many verticies: use intbuffer instead of shortbuffer IntBuffer ib = BufferUtils.createIntBuffer(newFaces.size() * 3); m.setBuffer(VertexBuffer.Type.Index, 3, ib); indexBuf = new IndexIntBuffer(ib); }else{ ShortBuffer sb = BufferUtils.createShortBuffer(newFaces.size() * 3); m.setBuffer(VertexBuffer.Type.Index, 3, sb); indexBuf = new IndexShortBuffer(sb); } int numFaces = newFaces.size(); for (int i = 0; i < numFaces; i++){ Face f = newFaces.get(i); if (f.verticies.length != 3) continue; Vertex v0 = f.verticies[0]; Vertex v1 = f.verticies[1]; Vertex v2 = f.verticies[2]; posBuf.position(v0.index * 3); posBuf.put(v0.v.x).put(v0.v.y).put(v0.v.z); posBuf.position(v1.index * 3); posBuf.put(v1.v.x).put(v1.v.y).put(v1.v.z); posBuf.position(v2.index * 3); posBuf.put(v2.v.x).put(v2.v.y).put(v2.v.z); if (normBuf != null){ if (v0.vn != null){ normBuf.position(v0.index * 3); normBuf.put(v0.vn.x).put(v0.vn.y).put(v0.vn.z); normBuf.position(v1.index * 3); normBuf.put(v1.vn.x).put(v1.vn.y).put(v1.vn.z); normBuf.position(v2.index * 3); normBuf.put(v2.vn.x).put(v2.vn.y).put(v2.vn.z); } } if (tcBuf != null){ if (v0.vt != null){ tcBuf.position(v0.index * 2); tcBuf.put(v0.vt.x).put(v0.vt.y); tcBuf.position(v1.index * 2); tcBuf.put(v1.vt.x).put(v1.vt.y); tcBuf.position(v2.index * 2); tcBuf.put(v2.vt.x).put(v2.vt.y); } } int index = i * 3; // current face * 3 = current index indexBuf.put(index, v0.index); indexBuf.put(index+1, v1.index); indexBuf.put(index+2, v2.index); } m.setBuffer(VertexBuffer.Type.Position, 3, posBuf); m.setBuffer(VertexBuffer.Type.Normal, 3, normBuf); m.setBuffer(VertexBuffer.Type.TexCoord, 2, tcBuf); // index buffer was set on creation m.setStatic(); m.updateBound(); m.updateCounts(); //m.setInterleaved(); // clear data generated face statements // to prepare for next mesh vertIndexMap.clear(); indexVertMap.clear(); curIndex = 0; return m; } @SuppressWarnings("empty-statement") public Object load(AssetInfo info) throws IOException{ key = (ModelKey) info.getKey(); assetManager = info.getManager(); if (!(info.getKey() instanceof ModelKey)) throw new IllegalArgumentException("Model assets must be loaded using a ModelKey"); InputStream in = info.openStream(); scan = new Scanner(in); scan.useLocale(Locale.US); objName = key.getName(); String folderName = key.getFolder(); String ext = key.getExtension(); objName = objName.substring(0, objName.length() - ext.length() - 1); if (folderName != null && folderName.length() > 0){ objName = objName.substring(folderName.length()); } objNode = new Node(objName + "-objnode"); while (readLine()); if (matFaces.size() > 0){ for (Entry<String, ArrayList<Face>> entry : matFaces.entrySet()){ ArrayList<Face> materialFaces = entry.getValue(); if (materialFaces.size() > 0){ Geometry geom = createGeometry(materialFaces, entry.getKey()); objNode.attachChild(geom); } } }else if (faces.size() > 0){ // generate final geometry Geometry geom = createGeometry(faces, null); objNode.attachChild(geom); } reset(); try{ in.close(); }catch (IOException ex){ } if (objNode.getQuantity() == 1) // only 1 geometry, so no need to send node return objNode.getChild(0); else return objNode; } }
package org.neo4j.kernel.impl.ha; public interface Broker { Master getMaster(); SlaveContext getSlaveContext(); void setLastCommittedTxId( long txId ); boolean thisIsMaster(); }
package com.sims.topaz; import java.util.ArrayList; import java.util.Date; import java.util.List; import android.app.Activity; import android.content.Intent; import android.graphics.drawable.Drawable; import android.graphics.drawable.TransitionDrawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.format.DateFormat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.EditText; import android.widget.HeaderViewListAdapter; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.sims.topaz.AsyncTask.LoadPictureTask; import com.sims.topaz.AsyncTask.LoadPictureTask.LoadPictureTaskInterface; import com.sims.topaz.adapter.CommentAdapter; import com.sims.topaz.interfaces.OnShowUserProfile; import com.sims.topaz.modele.CommentItem; import com.sims.topaz.network.NetworkRestModule; import com.sims.topaz.network.interfaces.CommentDelegate; import com.sims.topaz.network.interfaces.ErreurDelegate; import com.sims.topaz.network.interfaces.LikeStatusDelegate; import com.sims.topaz.network.interfaces.MessageDelegate; import com.sims.topaz.network.modele.ApiError; import com.sims.topaz.network.modele.Comment; import com.sims.topaz.network.modele.Message; import com.sims.topaz.network.modele.Preview; import com.sims.topaz.utils.AuthUtils; import com.sims.topaz.utils.DebugUtils; import com.sims.topaz.utils.MyPreferencesUtilsSingleton; import com.sims.topaz.utils.MyTypefaceSingleton; import com.sims.topaz.utils.SimsContext; public class CommentFragment extends Fragment implements MessageDelegate,CommentDelegate,LoadPictureTaskInterface,LikeStatusDelegate,ErreurDelegate { private TextView mFirstComment; private TextView mFirstCommentNameUser; private TextView mFirstCommentTimestamp; private ImageView mFirstCommentPicture; private EditText mNewComment; private ListView mListComments; private ImageButton mShareButton; private ImageButton mLikeButton; private ImageButton mDislikeButton; private ImageButton mSendCommentButton; private ProgressBar mProgressBar; // The main message private Message mMessage=null; //intelligence private NetworkRestModule restModule = new NetworkRestModule(this); OnShowUserProfile mCallback; @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mCallback = (OnShowUserProfile) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnShowUserProfile"); } } @Override public void onDetach() { super.onDetach(); mCallback = null; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_comment, container, false); //setClickable(true) prevents from touching the view behind v.setClickable(true); //mSendCommentButton = (ImageButton)v.findViewById(R.id.send_comment_button); mNewComment = (EditText)v.findViewById(R.id.write_comment_text); mNewComment.setTypeface(MyTypefaceSingleton.getInstance().getTypeFace()); mListComments = (ListView)v.findViewById(R.id.comment_list); mProgressBar = (ProgressBar)v.findViewById(R.id.progressBar); mProgressBar.setVisibility(View.VISIBLE); //Set Like, Dislike and Share Buttons setButtons(v); View v2 = inflater.inflate(R.layout.fragment_comment_message_item, null); mFirstComment = (TextView) v2.findViewById(R.id.comment_first_comment_text); mFirstComment.setTypeface(MyTypefaceSingleton.getInstance().getTypeFace()); mFirstCommentNameUser = (TextView) v2.findViewById(R.id.comment_person_name); mFirstCommentNameUser.setTypeface(MyTypefaceSingleton.getInstance().getTypeFace()); mFirstCommentTimestamp = (TextView) v2.findViewById(R.id.comment_time); mFirstCommentTimestamp.setTypeface(MyTypefaceSingleton.getInstance().getTypeFace()); mFirstCommentPicture = (ImageView) v2.findViewById(R.id.comment_first_picture_view); mFirstCommentPicture.setVisibility(View.GONE); mShareButton = (ImageButton)v2.findViewById(R.id.comment_share); mLikeButton = (ImageButton)v2.findViewById(R.id.comment_like); mDislikeButton = (ImageButton)v2.findViewById(R.id.comment_dislike); v2.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.MATCH_PARENT, ListView.LayoutParams.WRAP_CONTENT)); mListComments.addHeaderView(v2); mShareButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {shareMessage();} }); mShareButton.setClickable(false); mShareButton.setEnabled(false); mLikeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {likeMessage();} }); mLikeButton.setClickable(false); mLikeButton.setEnabled(false); mDislikeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {dislikeMessage();} }); mDislikeButton.setClickable(false); mDislikeButton.setEnabled(false); //get the main message from the preview id loadMessage(); return v; } private void displayComments() { List<CommentItem> lci = new ArrayList<CommentItem>(); for (Comment co : mMessage.getComments()) { lci.add(new CommentItem(co)); } mListComments.setAdapter(new CommentAdapter(SimsContext.getContext(), R.layout.fragment_comment_item, lci)); mListComments.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view,int position, long arg3) { mCallback.OnShowUserProfileFragment(mMessage.getComments().get(position).getUserId()); } }); mSendCommentButton.setEnabled(true); mSendCommentButton.setClickable(true); } //Set Like, Dislike and Share Buttons private void setButtons(View v) { mSendCommentButton = (ImageButton)v.findViewById(R.id.send_comment_button); mSendCommentButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {sendComment();} }); mSendCommentButton.setClickable(false); mSendCommentButton.setEnabled(false); } protected void likeMessage() { if(mMessage!=null) { switch(mMessage.likeStatus) { case LIKED: mMessage.unlike(); ((TransitionDrawable) mLikeButton.getDrawable()) .reverseTransition(0); break; case NONE: mMessage.like(); ((TransitionDrawable) mLikeButton.getDrawable()) .startTransition(0); break; case DISLIKED: mMessage.undislike();mMessage.like(); ((TransitionDrawable) mDislikeButton.getDrawable()) .reverseTransition(0); ((TransitionDrawable) mLikeButton.getDrawable()) .startTransition(0); break; } //REST method call restModule.postLikeStatus(mMessage); //Update view updateLikes(); } } protected void dislikeMessage() { if(mMessage!=null) { switch(mMessage.likeStatus) { case LIKED: mMessage.unlike(); mMessage.dislike(); ((TransitionDrawable) mLikeButton.getDrawable()) .reverseTransition(0); ((TransitionDrawable) mDislikeButton.getDrawable()) .startTransition(0); break; case NONE: mMessage.dislike(); ((TransitionDrawable) mDislikeButton.getDrawable()) .startTransition(0); break; case DISLIKED: mMessage.undislike(); ((TransitionDrawable) mDislikeButton.getDrawable()) .reverseTransition(0); break; } // REST method call restModule.postLikeStatus(mMessage); //update view updateLikes(); } } private void initShareButton() { mShareButton.setEnabled(true); mShareButton.setClickable(true); } private void initLikeButtons() { if(mMessage==null) return; mLikeButton.setEnabled(true); mLikeButton.setClickable(true); mDislikeButton.setEnabled(true); mDislikeButton.setClickable(true); switch(mMessage.likeStatus) { case NONE: //nothing break; case LIKED: ((TransitionDrawable) mLikeButton.getDrawable()) .startTransition(0); break; case DISLIKED: ((TransitionDrawable) mDislikeButton.getDrawable()) .startTransition(0); break; } } protected void updateLikes() { if(mMessage!=null) { TextView likes = (TextView) getView().findViewById(R.id.textViewLikes); likes.setText(Integer.toString(mMessage.getLikes())); TextView dislikes = (TextView) getView().findViewById(R.id.textViewDislikes); dislikes.setText(Integer.toString(mMessage.getDislikes())); } } public void shareMessage(){ Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_TEXT, mFirstComment.getText()); shareIntent.setType("text/plain"); startActivity(Intent.createChooser(shareIntent, "Share Comment")); } protected void sendComment() { if(mMessage==null) return; String comm = mNewComment.getText().toString(); mNewComment.setEnabled(false); mSendCommentButton.setEnabled(false); Comment comment = new Comment(); comment.setText(comm); comment.setUserName(AuthUtils.getSessionStringValue (MyPreferencesUtilsSingleton.SHARED_PREFERENCES_AUTH_USERNAME)); restModule.postComment(comment, mMessage); } private void loadMessage() { //get the main message from the preview id if(getArguments()!=null && getArguments().containsKey("id_preview")){ Long id = getArguments().getLong("id_preview"); restModule.getMessage(id); } } // public void onDoneButton(){ // getFragmentManager().beginTransaction().remove(this).commit(); @Override public void afterPostMessage(Message message) {} @Override public void afterGetMessage(Message message) { if(message!=null) { mMessage=message; mFirstCommentNameUser.setText(message.getUserName()); mFirstComment.setText(message.getText()); mFirstCommentTimestamp.setText(DateFormat.format (getString(R.string.date_format), new Date( message.getTimestamp() ) ) ); if(message.getPictureUrl() != null && !message.getPictureUrl().isEmpty()) { LoadPictureTask setImageTask = new LoadPictureTask(this); setImageTask.execute(NetworkRestModule.SERVER_IMG_BASEURL + message.getPictureUrl()); DebugUtils.log(NetworkRestModule.SERVER_IMG_BASEURL + message.getPictureUrl()); } initLikeButtons(); initShareButton(); updateLikes(); displayComments(); mProgressBar.setVisibility(View.GONE); } } @Override public void afterGetPreviews(List<Preview> list) {} @Override public void networkError() { Toast.makeText(SimsContext.getContext(),SimsContext.getString(R.string.network_error), Toast.LENGTH_SHORT).show(); mNewComment.setEnabled(true); mSendCommentButton.setEnabled(true); } @Override public void apiError(ApiError error) { Toast.makeText(SimsContext.getContext(),SimsContext.getString(R.string.network_error), Toast.LENGTH_SHORT).show(); } public void clearMessage(){ mNewComment.setText(""); } @Override public void afterPostComment(Comment comment) { CommentItem ci = new CommentItem(comment); HeaderViewListAdapter headerAdapter = (HeaderViewListAdapter)mListComments.getAdapter(); CommentAdapter ca = (CommentAdapter)headerAdapter.getWrappedAdapter(); ca.addItem(ci); mNewComment.setText(""); mNewComment.setEnabled(true); mSendCommentButton.setEnabled(true); } @Override public void afterPostLikeStatus(Message message) { if(message != null && mMessage != null) { if(message.getLikeStatus()==mMessage.getLikeStatus()) { //Rafraichir les informations //Le nombre de like a pu changer mMessage = message; mFirstComment.setText(message.getText()); mFirstCommentTimestamp.setText(DateFormat.format(getString(R.string.date_format), new Date( message.getTimestamp() ) ) ); updateLikes(); } } } @Override public void loadPictureTaskOnPostExecute(Drawable image) { mFirstCommentPicture.setImageDrawable(image); mFirstCommentPicture.setVisibility(View.VISIBLE); } }
package it.innove; import android.annotation.TargetApi; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothManager; import android.bluetooth.le.ScanCallback; import android.bluetooth.le.ScanFilter; import android.bluetooth.le.ScanResult; import android.bluetooth.le.ScanSettings; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Build; import android.os.Bundle; import android.os.ParcelUuid; import android.support.annotation.Nullable; import android.util.Base64; import android.util.Log; import com.facebook.react.bridge.*; import com.facebook.react.modules.core.RCTNativeAppEventEmitter; import org.json.JSONException; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import static android.app.Activity.RESULT_OK; import static android.os.Build.VERSION_CODES.LOLLIPOP; import static com.facebook.react.bridge.UiThreadUtil.runOnUiThread; class BleManager extends ReactContextBaseJavaModule implements ActivityEventListener { private static final String LOG_TAG = "logs"; static final int ENABLE_REQUEST = 1; private BluetoothAdapter bluetoothAdapter; private Context context; private ReactContext reactContext; private Callback enableBluetoothCallback; // key is the MAC Address private Map<String, Peripheral> peripherals = new LinkedHashMap<>(); // scan session id private AtomicInteger scanSessionId = new AtomicInteger(); public BleManager(ReactApplicationContext reactContext) { super(reactContext); context = reactContext; this.reactContext = reactContext; reactContext.addActivityEventListener(this); Log.d(LOG_TAG, "BleManager created"); } @Override public String getName() { return "BleManager"; } private BluetoothAdapter getBluetoothAdapter() { if (bluetoothAdapter == null) { BluetoothManager manager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); bluetoothAdapter = manager.getAdapter(); } return bluetoothAdapter; } private void sendEvent(String eventName, @Nullable WritableMap params) { getReactApplicationContext() .getJSModule(RCTNativeAppEventEmitter.class) .emit(eventName, params); } @ReactMethod public void start(ReadableMap options, Callback callback) { Log.d(LOG_TAG, "start"); if (getBluetoothAdapter() == null) { Log.d(LOG_TAG, "No bluetooth support"); callback.invoke("No bluetooth support"); return; } IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); context.registerReceiver(mReceiver, filter); callback.invoke(); Log.d(LOG_TAG, "BleManager initialized"); } @ReactMethod public void enableBluetooth(Callback callback) { if (getBluetoothAdapter() == null) { Log.d(LOG_TAG, "No bluetooth support"); callback.invoke("No bluetooth support"); return; } if (!getBluetoothAdapter().isEnabled()) { enableBluetoothCallback = callback; Intent intentEnable = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); if (getCurrentActivity() == null) callback.invoke("Current activity not available"); else getCurrentActivity().startActivityForResult(intentEnable, ENABLE_REQUEST); } else callback.invoke(); } @ReactMethod public void scan(ReadableArray serviceUUIDs, final int scanSeconds, boolean allowDuplicates, Callback callback) { Log.d(LOG_TAG, "scan"); if (getBluetoothAdapter() == null) { Log.d(LOG_TAG, "No bluetooth support"); callback.invoke("No bluetooth support"); return; } if (!getBluetoothAdapter().isEnabled()) return; for (Iterator<Map.Entry<String, Peripheral>> iterator = peripherals.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<String, Peripheral> entry = iterator.next(); if (!entry.getValue().isConnected()) { iterator.remove(); } } if (Build.VERSION.SDK_INT >= LOLLIPOP) { scan21(serviceUUIDs, scanSeconds, callback); } else { scan19(serviceUUIDs, scanSeconds, callback); } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void scan21(ReadableArray serviceUUIDs, final int scanSeconds, Callback callback) { ScanSettings settings = new ScanSettings.Builder().build(); List<ScanFilter> filters = new ArrayList<>(); if (serviceUUIDs.size() > 0) { for(int i = 0; i < serviceUUIDs.size(); i++){ ScanFilter.Builder builder = new ScanFilter.Builder(); builder.setServiceUuid(new ParcelUuid(UUIDHelper.uuidFromString(serviceUUIDs.getString(i)))); filters.add(builder.build()); Log.d(LOG_TAG, "Filter service: " + serviceUUIDs.getString(i)); } } final ScanCallback mScanCallback = new ScanCallback() { @Override public void onScanResult(final int callbackType, final ScanResult result) { runOnUiThread(new Runnable() { @Override public void run() { Log.i(LOG_TAG, "DiscoverPeripheral: " + result.getDevice().getName()); String address = result.getDevice().getAddress(); if (!peripherals.containsKey(address)) { Peripheral peripheral = new Peripheral(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes(), reactContext); peripherals.put(address, peripheral); BundleJSONConverter bjc = new BundleJSONConverter(); try { Bundle bundle = bjc.convertToBundle(peripheral.asJSONObject()); WritableMap map = Arguments.fromBundle(bundle); sendEvent("BleManagerDiscoverPeripheral", map); } catch (JSONException ignored) { } } else { // this isn't necessary Peripheral peripheral = peripherals.get(address); peripheral.updateRssi(result.getRssi()); } } }); } @Override public void onBatchScanResults(final List<ScanResult> results) { } @Override public void onScanFailed(final int errorCode) { } }; getBluetoothAdapter().getBluetoothLeScanner().startScan(filters, settings, mScanCallback); if (scanSeconds > 0) { Thread thread = new Thread() { private int currentScanSession = scanSessionId.incrementAndGet(); @Override public void run() { try { Thread.sleep(scanSeconds * 1000); } catch (InterruptedException ignored) { } runOnUiThread(new Runnable() { @Override public void run() { // check current scan session was not stopped if (scanSessionId.intValue() == currentScanSession) { getBluetoothAdapter().getBluetoothLeScanner().stopScan(mScanCallback); WritableMap map = Arguments.createMap(); sendEvent("BleManagerStopScan", map); } } }); } }; thread.start(); } callback.invoke(); } private void scan19(ReadableArray serviceUUIDs, final int scanSeconds, Callback callback) { getBluetoothAdapter().startLeScan(mLeScanCallback); if (scanSeconds > 0) { Thread thread = new Thread() { private int currentScanSession = scanSessionId.incrementAndGet(); @Override public void run() { try { Thread.sleep(scanSeconds * 1000); } catch (InterruptedException ignored) { } runOnUiThread(new Runnable() { @Override public void run() { // check current scan session was not stopped if (scanSessionId.intValue() == currentScanSession) { getBluetoothAdapter().stopLeScan(mLeScanCallback); WritableMap map = Arguments.createMap(); sendEvent("BleManagerStopScan", map); } } }); } }; thread.start(); } callback.invoke(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void stopScan21(Callback callback) { final ScanCallback mScanCallback = new ScanCallback() { @Override public void onScanResult(final int callbackType, final ScanResult result) { } }; getBluetoothAdapter().getBluetoothLeScanner().stopScan(mScanCallback); callback.invoke(); } private void stopScan19(Callback callback) { getBluetoothAdapter().stopLeScan(mLeScanCallback); callback.invoke(); } @ReactMethod public void stopScan(Callback callback) { Log.d(LOG_TAG, "Stop scan"); if (getBluetoothAdapter() == null) { Log.d(LOG_TAG, "No bluetooth support"); callback.invoke("No bluetooth support"); return; } if (!getBluetoothAdapter().isEnabled()) { callback.invoke("Bluetooth not enabled"); return; } // update scanSessionId to prevent stopping next scan by running timeout thread scanSessionId.incrementAndGet(); if (Build.VERSION.SDK_INT >= LOLLIPOP) { stopScan21(callback); } else { stopScan19(callback); } } @ReactMethod public void connect(String peripheralUUID, Callback callback) { Log.d(LOG_TAG, "Connect to: " + peripheralUUID ); Peripheral peripheral = peripherals.get(peripheralUUID); if (peripheral == null) { if (peripheralUUID != null) { peripheralUUID = peripheralUUID.toUpperCase(); } if (bluetoothAdapter.checkBluetoothAddress(peripheralUUID)) { BluetoothDevice device = bluetoothAdapter.getRemoteDevice(peripheralUUID); peripheral = new Peripheral(device, reactContext); peripherals.put(peripheralUUID, peripheral); } else { callback.invoke("Invalid peripheral uuid"); return; } } peripheral.connect(callback, getCurrentActivity()); } @ReactMethod public void disconnect(String peripheralUUID, Callback callback) { Log.d(LOG_TAG, "Disconnect from: " + peripheralUUID); Peripheral peripheral = peripherals.get(peripheralUUID); if (peripheral != null){ peripheral.disconnect(); callback.invoke(); } else callback.invoke("Peripheral not found"); } @ReactMethod public void startNotification(String deviceUUID, String serviceUUID, String characteristicUUID, Callback callback) { Log.d(LOG_TAG, "startNotification"); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null){ peripheral.registerNotify(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), callback); } else callback.invoke("Peripheral not found"); } @ReactMethod public void stopNotification(String deviceUUID, String serviceUUID, String characteristicUUID, Callback callback) { Log.d(LOG_TAG, "stopNotification"); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null){ peripheral.removeNotify(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), callback); } else callback.invoke("Peripheral not found"); } @ReactMethod public void write(String deviceUUID, String serviceUUID, String characteristicUUID, String message, Integer maxByteSize, Callback callback) { Log.d(LOG_TAG, "Write to: " + deviceUUID); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null){ byte[] decoded = Base64.decode(message.getBytes(), Base64.DEFAULT); Log.d(LOG_TAG, "Message(" + decoded.length + "): " + bytesToHex(decoded)); peripheral.write(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), decoded, maxByteSize, null, callback, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT); } else callback.invoke("Peripheral not found"); } @ReactMethod public void writeWithoutResponse(String deviceUUID, String serviceUUID, String characteristicUUID, String message, Integer maxByteSize, Integer queueSleepTime, Callback callback) { Log.d(LOG_TAG, "Write without response to: " + deviceUUID); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null){ byte[] decoded = Base64.decode(message.getBytes(), Base64.DEFAULT); Log.d(LOG_TAG, "Message(" + decoded.length + "): " + bytesToHex(decoded)); peripheral.write(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), decoded, maxByteSize, queueSleepTime, callback, BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE); } else callback.invoke("Peripheral not found"); } @ReactMethod public void read(String deviceUUID, String serviceUUID, String characteristicUUID, Callback callback) { Log.d(LOG_TAG, "Read from: " + deviceUUID); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null){ peripheral.read(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), callback); } else callback.invoke("Peripheral not found", null); } @ReactMethod public void readRSSI(String deviceUUID, Callback callback) { Log.d(LOG_TAG, "Read RSSI from: " + deviceUUID); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null){ peripheral.readRSSI(callback); } else callback.invoke("Peripheral not found", null); } private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) { runOnUiThread(new Runnable() { @Override public void run() { Log.i(LOG_TAG, "DiscoverPeripheral: " + device.getName()); String address = device.getAddress(); if (!peripherals.containsKey(address)) { Peripheral peripheral = new Peripheral(device, rssi, scanRecord, reactContext); peripherals.put(device.getAddress(), peripheral); BundleJSONConverter bjc = new BundleJSONConverter(); try { Bundle bundle = bjc.convertToBundle(peripheral.asJSONObject()); WritableMap map = Arguments.fromBundle(bundle); sendEvent("BleManagerDiscoverPeripheral", map); } catch (JSONException ignored) { } } else { // this isn't necessary Peripheral peripheral = peripherals.get(address); peripheral.updateRssi(rssi); } } }); } }; @ReactMethod public void checkState(){ Log.d(LOG_TAG, "checkState"); BluetoothAdapter adapter = getBluetoothAdapter(); String state = "off"; if (adapter != null) { switch (adapter.getState()){ case BluetoothAdapter.STATE_ON: state = "on"; break; case BluetoothAdapter.STATE_OFF: state = "off"; } } WritableMap map = Arguments.createMap(); map.putString("state", state); Log.d(LOG_TAG, "state:" + state); sendEvent("BleManagerDidUpdateState", map); } private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(LOG_TAG, "onReceive"); final String action = intent.getAction(); String stringState = ""; if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); switch (state) { case BluetoothAdapter.STATE_OFF: stringState = "off"; break; case BluetoothAdapter.STATE_TURNING_OFF: stringState = "turning_off"; break; case BluetoothAdapter.STATE_ON: stringState = "on"; break; case BluetoothAdapter.STATE_TURNING_ON: stringState = "turning_on"; break; } } WritableMap map = Arguments.createMap(); map.putString("state", stringState); Log.d(LOG_TAG, "state: " + stringState); sendEvent("BleManagerDidUpdateState", map); } }; @ReactMethod public void getDiscoveredPeripherals(Callback callback) { Log.d(LOG_TAG, "Get discovered peripherals"); WritableArray map = Arguments.createArray(); BundleJSONConverter bjc = new BundleJSONConverter(); for (Iterator<Map.Entry<String, Peripheral>> iterator = peripherals.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<String, Peripheral> entry = iterator.next(); Peripheral peripheral = entry.getValue(); try { Bundle bundle = bjc.convertToBundle(peripheral.asJSONObject()); WritableMap jsonBundle = Arguments.fromBundle(bundle); map.pushMap(jsonBundle); } catch (JSONException ignored) { callback.invoke("Peripheral json conversion error", null); } } callback.invoke(null, map); } @ReactMethod public void getConnectedPeripherals(ReadableArray serviceUUIDs, Callback callback) { Log.d(LOG_TAG, "Get connected peripherals"); WritableArray map = Arguments.createArray(); BundleJSONConverter bjc = new BundleJSONConverter(); for (Iterator<Map.Entry<String, Peripheral>> iterator = peripherals.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<String, Peripheral> entry = iterator.next(); Peripheral peripheral = entry.getValue(); Boolean accept = false; if (serviceUUIDs != null && serviceUUIDs.size() > 0) { for (int i = 0; i < serviceUUIDs.size(); i++) { accept = peripheral.hasService(UUIDHelper.uuidFromString(serviceUUIDs.getString(i))); } } else { accept = true; } if (peripheral.isConnected() && accept) { try { Bundle bundle = bjc.convertToBundle(peripheral.asJSONObject()); WritableMap jsonBundle = Arguments.fromBundle(bundle); map.pushMap(jsonBundle); } catch (JSONException ignored) { callback.invoke("Peripheral json conversion error", null); } } } callback.invoke(null, map); } private final static char[] hexArray = "0123456789ABCDEF".toCharArray(); public static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } @Override public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) { Log.d(LOG_TAG, "onActivityResult"); if (requestCode == ENABLE_REQUEST && enableBluetoothCallback != null) { if (resultCode == RESULT_OK) { enableBluetoothCallback.invoke(); } else { enableBluetoothCallback.invoke("User refused to enable"); } enableBluetoothCallback = null; } } @Override public void onNewIntent(Intent intent) { } }
package com.breadwallet; import android.annotation.TargetApi; import android.app.Activity; import android.app.Application; import android.content.Context; import android.graphics.Point; import android.hardware.fingerprint.FingerprintManager; import android.os.Build; import android.util.Log; import android.view.Display; import android.view.WindowManager; import com.breadwallet.presenter.activities.util.BRActivity; import com.breadwallet.tools.listeners.SyncReceiver; import com.breadwallet.tools.util.Utils; import com.google.firebase.crash.FirebaseCrash; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicInteger; import static com.platform.APIClient.BREAD_POINT; public class BreadApp extends Application { private static final String TAG = BreadApp.class.getName(); public static int DISPLAY_HEIGHT_PX; FingerprintManager mFingerprintManager; // host is the server(s) on which the API is hosted public static String HOST = "api.breadwallet.com"; private static List<OnAppBackgrounded> listeners; private static Timer isBackgroundChecker; public static AtomicInteger activityCounter = new AtomicInteger(); public static long backgroundedTime; public static boolean appInBackground; public static final boolean IS_ALPHA = false; public static final Map<String, String> mHeaders = new HashMap<>(); private static Activity currentActivity; @Override public void onCreate() { super.onCreate(); if (Utils.isEmulatorOrDebug(this)) { // BRKeyStore.putFailCount(0, this); HOST = "stage2.breadwallet.com"; FirebaseCrash.setCrashCollectionEnabled(false); // FirebaseCrash.report(new RuntimeException("test with new json file")); } if (!Utils.isEmulatorOrDebug(this) && IS_ALPHA) throw new RuntimeException("can't be alpha for release"); boolean isTestVersion = BREAD_POINT.contains("staging") || BREAD_POINT.contains("stage"); boolean isTestNet = BuildConfig.BITCOIN_TESTNET; String lang = getCurrentLocale(this); mHeaders.put("X-Is-Internal", IS_ALPHA ? "true" : "false"); mHeaders.put("X-Testflight", isTestVersion ? "true" : "false"); mHeaders.put("X-Bitcoin-Testnet", isTestNet ? "true" : "false"); mHeaders.put("Accept-Language", lang); WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); Point size = new Point(); display.getSize(size); int DISPLAY_WIDTH_PX = size.x; DISPLAY_HEIGHT_PX = size.y; mFingerprintManager = (FingerprintManager) getSystemService(Context.FINGERPRINT_SERVICE); // addOnBackgroundedListener(new OnAppBackgrounded() { // @Override // public void onBackgrounded() { } @TargetApi(Build.VERSION_CODES.N) public String getCurrentLocale(Context ctx) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return ctx.getResources().getConfiguration().getLocales().get(0).getLanguage(); } else { //noinspection deprecation return ctx.getResources().getConfiguration().locale.getLanguage(); } } public static Map<String, String> getBreadHeaders() { return mHeaders; } public static Context getBreadContext() { return currentActivity == null ? SyncReceiver.app : currentActivity; } public static void setBreadContext(Activity app) { currentActivity = app; } public static void fireListeners() { if (listeners == null) return; for (OnAppBackgrounded lis : listeners) lis.onBackgrounded(); } public static void addOnBackgroundedListener(OnAppBackgrounded listener) { if (listeners == null) listeners = new ArrayList<>(); if (!listeners.contains(listener)) listeners.add(listener); } public static boolean isAppInBackground(final Context context) { return context == null || activityCounter.get() <= 0; } //call onStop on evert activity so public static void onStop(final BRActivity app) { if (isBackgroundChecker != null) isBackgroundChecker.cancel(); isBackgroundChecker = new Timer(); TimerTask backgroundCheck = new TimerTask() { @Override public void run() { if (isAppInBackground(app)) { backgroundedTime = System.currentTimeMillis(); Log.e(TAG, "App went in background!"); // APP in background, do something isBackgroundChecker.cancel(); fireListeners(); } // APP in foreground, do something else } }; isBackgroundChecker.schedule(backgroundCheck, 500, 500); } public interface OnAppBackgrounded { void onBackgrounded(); } }
// AbstractDatasetView.java package imagej.display; import imagej.data.Dataset; import imagej.data.Position; import imagej.data.event.DatasetRGBChangedEvent; import imagej.data.event.DatasetTypeChangedEvent; import imagej.data.event.DatasetUpdatedEvent; import imagej.event.EventSubscriber; import imagej.event.Events; import java.util.ArrayList; import java.util.Collections; import java.util.List; import net.imglib2.display.ARGBScreenImage; import net.imglib2.display.ColorTable8; import net.imglib2.display.CompositeXYProjector; import net.imglib2.display.RealLUTConverter; import net.imglib2.img.Axes; import net.imglib2.img.ImgPlus; import net.imglib2.type.numeric.ARGBType; import net.imglib2.type.numeric.RealType; /** * A view into a {@link Dataset}, for use with a {@link Display}. * * @author Grant Harris * @author Curtis Rueden */ public abstract class AbstractDatasetView extends AbstractDisplayView implements DatasetView { private final Dataset dataset; /** The dimensional index representing channels, for compositing. */ private int channelDimIndex; /** * Default color tables, one per channel, used when the {@link Dataset} * doesn't have one for a particular plane. */ private ArrayList<ColorTable8> defaultLUTs; private ARGBScreenImage screenImage; private CompositeXYProjector<? extends RealType<?>, ARGBType> projector; private final ArrayList<RealLUTConverter<? extends RealType<?>>> converters = new ArrayList<RealLUTConverter<? extends RealType<?>>>(); private ArrayList<EventSubscriber<?>> subscribers; public AbstractDatasetView(final Display display, final Dataset dataset) { super(display, dataset); this.dataset = dataset; subscribeToEvents(); } // -- DatasetView methods -- @Override public ARGBScreenImage getScreenImage() { return screenImage; } @Override public int getCompositeDimIndex() { return channelDimIndex; } @Override public ImgPlus<? extends RealType<?>> getImgPlus() { return dataset.getImgPlus(); } @Override public CompositeXYProjector<? extends RealType<?>, ARGBType> getProjector() { return projector; } @Override public List<RealLUTConverter<? extends RealType<?>>> getConverters() { return Collections.unmodifiableList(converters); } @Override public void setComposite(final boolean composite) { projector.setComposite(composite); } @Override public List<ColorTable8> getColorTables() { return Collections.unmodifiableList(defaultLUTs); } @Override public void setColorTable(final ColorTable8 colorTable, final int channel) { defaultLUTs.set(channel, colorTable); updateLUTs(); } @Override public void resetColorTables(final boolean grayscale) { final int channelCount = (int) getChannelCount(); defaultLUTs.clear(); defaultLUTs.ensureCapacity(channelCount); if (grayscale || channelCount == 1) { for (int i = 0; i < channelCount; i++) { defaultLUTs.add(ColorTables.GRAYS); } } else { for (int c = 0; c < channelCount; c++) { defaultLUTs.add(ColorTables.getDefaultColorTable(c)); } } updateLUTs(); } @Override public ColorMode getColorMode() { final boolean composite = projector.isComposite(); if (composite) { return ColorMode.COMPOSITE; } final List<ColorTable8> colorTables = getColorTables(); for (final ColorTable8 colorTable : colorTables) { if (colorTable != ColorTables.GRAYS) { return ColorMode.COLOR; } } return ColorMode.GRAYSCALE; } @Override public void setColorMode(final ColorMode colorMode) { resetColorTables(colorMode == ColorMode.GRAYSCALE); projector.setComposite(colorMode == ColorMode.COMPOSITE); projector.map(); } // -- DisplayView methods -- @Override public Dataset getDataObject() { return dataset; } @Override public long getPosition(final int dim) { if ((dim == Axes.X.ordinal()) || (dim == Axes.Y.ordinal())) return 0; return projector.getLongPosition(dim); } @Override public void setPosition(final long value, final int dim) { if ((dim == Axes.X.ordinal()) || (dim == Axes.Y.ordinal())) return; final long currentValue = projector.getLongPosition(dim); if (value == currentValue) { return; // no change } projector.setPosition(value, dim); // update color tables if (dim != channelDimIndex) { updateLUTs(); } projector.map(); super.setPosition(value, dim); } @Override public void rebuild() { channelDimIndex = getChannelDimIndex(); final ImgPlus<? extends RealType<?>> img = dataset.getImgPlus(); long[] dims = new long[img.numDimensions()]; img.dimensions(dims); setDimensions(dims); if (defaultLUTs == null || defaultLUTs.size() != getChannelCount()) { defaultLUTs = new ArrayList<ColorTable8>(); resetColorTables(false); } final int width = (int) img.dimension(0); final int height = (int) img.dimension(1); screenImage = new ARGBScreenImage(width, height); final boolean composite = isComposite(); projector = createProjector(composite); projector.map(); } // -- Helper methods -- private boolean isComposite() { return dataset.getCompositeChannelCount() > 1 || dataset.isRGBMerged(); } private int getChannelDimIndex() { return dataset.getAxisIndex(Axes.CHANNEL); } @SuppressWarnings({ "rawtypes", "unchecked" }) private CompositeXYProjector<? extends RealType<?>, ARGBType> createProjector(final boolean composite) { converters.clear(); final long channelCount = getChannelCount(); for (int c = 0; c < channelCount; c++) { autoscale(c); converters .add(new RealLUTConverter(dataset.getImgPlus().getChannelMinimum(c), dataset.getImgPlus().getChannelMaximum(c), null)); } final CompositeXYProjector proj = new CompositeXYProjector(dataset.getImgPlus(), screenImage, converters, channelDimIndex); proj.setComposite(composite); updateLUTs(); return proj; } @SuppressWarnings({"rawtypes","unchecked"}) public void autoscale(final int c) { // Get min/max from metadata double min = dataset.getImgPlus().getChannelMinimum(c); double max = dataset.getImgPlus().getChannelMaximum(c); if (Double.isNaN(max) || Double.isNaN(min)) { // not provided in metadata, so calculate the min/max // TODO: this currently applies the global min/max to all channels... // need to change GetImgMinMax to find min/max per channel final GetImgMinMax<? extends RealType<?>> cmm = new GetImgMinMax(dataset.getImgPlus().getImg()); cmm.process(); min = cmm.getMin().getRealDouble(); max = cmm.getMax().getRealDouble(); dataset.getImgPlus().setChannelMinimum(c, min); dataset.getImgPlus().setChannelMaximum(c, max); } if (min == max) { // if all black or all white, use range for type final RealType<?> type = dataset.getType(); dataset.getImgPlus().setChannelMinimum(c, type.getMinValue()); dataset.getImgPlus().setChannelMaximum(c, type.getMaxValue()); } } private void updateLUTs() { if (converters.size() == 0) { return; // converters not yet initialized } final long channelCount = getChannelCount(); for (int c = 0; c < channelCount; c++) { final ColorTable8 lut = getCurrentLUT(c); converters.get(c).setLUT(lut); } } private ColorTable8 getCurrentLUT(final int cPos) { Position pos = getPlanePosition(); if (channelDimIndex >= 0) { pos = new Position(pos); pos.setPosition(cPos, channelDimIndex-2); } final int no = (int) pos.getIndex(); final ColorTable8 lut = dataset.getColorTable8(no); if (lut != null) { return lut; // return dataset-specific LUT } return defaultLUTs.get(cPos); // return default channel LUT } private long getChannelCount() { return channelDimIndex < 0 ? 1 : dataset.getExtents().dimension(channelDimIndex); } @SuppressWarnings("synthetic-access") private void subscribeToEvents() { subscribers = new ArrayList<EventSubscriber<?>>(); final EventSubscriber<DatasetTypeChangedEvent> typeChangeSubscriber = new EventSubscriber<DatasetTypeChangedEvent>() { @Override public void onEvent(final DatasetTypeChangedEvent event) { if (dataset == event.getObject()) { rebuild(); } } }; subscribers.add(typeChangeSubscriber); Events.subscribe(DatasetTypeChangedEvent.class, typeChangeSubscriber); final EventSubscriber<DatasetRGBChangedEvent> rgbChangeSubscriber = new EventSubscriber<DatasetRGBChangedEvent>() { @Override public void onEvent(final DatasetRGBChangedEvent event) { if (dataset == event.getObject()) { rebuild(); } } }; subscribers.add(rgbChangeSubscriber); Events.subscribe(DatasetRGBChangedEvent.class, rgbChangeSubscriber); final EventSubscriber<DatasetUpdatedEvent> updateSubscriber = new EventSubscriber<DatasetUpdatedEvent>() { @Override public void onEvent(final DatasetUpdatedEvent event) { if (event instanceof DatasetTypeChangedEvent) { return; } if (event instanceof DatasetRGBChangedEvent) { return; } if (dataset == event.getObject()) { projector.map(); } } }; subscribers.add(updateSubscriber); Events.subscribe(DatasetUpdatedEvent.class, updateSubscriber); } }
package de.danoeh.antennapod.core.storage; import android.database.Cursor; import android.support.v4.util.ArrayMap; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Map; import de.danoeh.antennapod.core.feed.Chapter; import de.danoeh.antennapod.core.feed.Feed; import de.danoeh.antennapod.core.feed.FeedItem; import de.danoeh.antennapod.core.feed.FeedMedia; import de.danoeh.antennapod.core.feed.FeedPreferences; import de.danoeh.antennapod.core.preferences.UserPreferences; import de.danoeh.antennapod.core.service.download.DownloadStatus; import de.danoeh.antennapod.core.util.LongIntMap; import de.danoeh.antennapod.core.util.LongList; import de.danoeh.antennapod.core.util.comparator.DownloadStatusComparator; import de.danoeh.antennapod.core.util.comparator.FeedItemPubdateComparator; import de.danoeh.antennapod.core.util.comparator.PlaybackCompletionDateComparator; import de.danoeh.antennapod.core.util.flattr.FlattrThing; /** * Provides methods for reading data from the AntennaPod database. * In general, all database calls in DBReader-methods are executed on the caller's thread. * This means that the caller should make sure that DBReader-methods are not executed on the GUI-thread. * This class will use the {@link de.danoeh.antennapod.core.feed.EventDistributor} to notify listeners about changes in the database. */ public final class DBReader { private static final String TAG = "DBReader"; /** * Maximum size of the list returned by {@link #getPlaybackHistory()}. */ public static final int PLAYBACK_HISTORY_SIZE = 50; /** * Maximum size of the list returned by {@link #getDownloadLog()}. */ private static final int DOWNLOAD_LOG_SIZE = 200; private DBReader() { } /** * Returns a list of Feeds, sorted alphabetically by their title. * * @return A list of Feeds, sorted alphabetically by their title. A Feed-object * of the returned list does NOT have its list of FeedItems yet. The FeedItem-list * can be loaded separately with {@link #getFeedItemList(Feed)}. */ public static List<Feed> getFeedList() { Log.d(TAG, "Extracting Feedlist"); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); try { return getFeedList(adapter); } finally { adapter.close(); } } private static List<Feed> getFeedList(PodDBAdapter adapter) { Cursor cursor = null; try { cursor = adapter.getAllFeedsCursor(); List<Feed> feeds = new ArrayList<>(cursor.getCount()); while (cursor.moveToNext()) { Feed feed = extractFeedFromCursorRow(adapter, cursor); feeds.add(feed); } return feeds; } finally { if (cursor != null) { cursor.close(); } } } /** * Returns a list with the download URLs of all feeds. * * @return A list of Strings with the download URLs of all feeds. */ public static List<String> getFeedListDownloadUrls() { PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); Cursor cursor = null; try { cursor = adapter.getFeedCursorDownloadUrls(); List<String> result = new ArrayList<>(cursor.getCount()); while (cursor.moveToNext()) { result.add(cursor.getString(1)); } return result; } finally { if (cursor != null) { cursor.close(); } adapter.close(); } } /** * Loads additional data in to the feed items from other database queries * * @param items the FeedItems who should have other data loaded */ public static void loadAdditionalFeedItemListData(List<FeedItem> items) { loadTagsOfFeedItemList(items); loadFeedDataOfFeedItemList(items); } private static void loadTagsOfFeedItemList(List<FeedItem> items) { LongList favoriteIds = getFavoriteIDList(); LongList queueIds = getQueueIDList(); for (FeedItem item : items) { if (favoriteIds.contains(item.getId())) { item.addTag(FeedItem.TAG_FAVORITE); } if (queueIds.contains(item.getId())) { item.addTag(FeedItem.TAG_QUEUE); } } } /** * Takes a list of FeedItems and loads their corresponding Feed-objects from the database. * The feedID-attribute of a FeedItem must be set to the ID of its feed or the method will * not find the correct feed of an item. * * @param items The FeedItems whose Feed-objects should be loaded. */ private static void loadFeedDataOfFeedItemList(List<FeedItem> items) { List<Feed> feeds = getFeedList(); Map<Long, Feed> feedIndex = new ArrayMap<>(feeds.size()); for (Feed feed : feeds) { feedIndex.put(feed.getId(), feed); } for (FeedItem item : items) { Feed feed = feedIndex.get(item.getFeedId()); if (feed == null) { Log.w(TAG, "No match found for item with ID " + item.getId() + ". Feed ID was " + item.getFeedId()); } item.setFeed(feed); } } /** * Loads the list of FeedItems for a certain Feed-object. This method should NOT be used if the FeedItems are not * used. In order to get information ABOUT the list of FeedItems, consider using {@link #getFeedStatisticsList()} instead. * * @param feed The Feed whose items should be loaded * @return A list with the FeedItems of the Feed. The Feed-attribute of the FeedItems will already be set correctly. * The method does NOT change the items-attribute of the feed. */ public static List<FeedItem> getFeedItemList(final Feed feed) { Log.d(TAG, "getFeedItemList() called with: " + "feed = [" + feed + "]"); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); Cursor cursor = null; try { cursor = adapter.getAllItemsOfFeedCursor(feed); List<FeedItem> items = extractItemlistFromCursor(adapter, cursor); Collections.sort(items, new FeedItemPubdateComparator()); for (FeedItem item : items) { item.setFeed(feed); } return items; } finally { if (cursor != null) { cursor.close(); } adapter.close(); } } public static List<FeedItem> extractItemlistFromCursor(Cursor itemlistCursor) { Log.d(TAG, "extractItemlistFromCursor() called with: " + "itemlistCursor = [" + itemlistCursor + "]"); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); try { return extractItemlistFromCursor(adapter, itemlistCursor); } finally { adapter.close(); } } private static List<FeedItem> extractItemlistFromCursor(PodDBAdapter adapter, Cursor cursor) { List<FeedItem> result = new ArrayList<>(cursor.getCount()); LongList itemIds = new LongList(cursor.getCount()); if (cursor.moveToFirst()) { do { FeedItem item = FeedItem.fromCursor(cursor); result.add(item); itemIds.add(item.getId()); } while (cursor.moveToNext()); Map<Long, FeedMedia> medias = getFeedMedia(adapter, itemIds); for (FeedItem item : result) { FeedMedia media = medias.get(item.getId()); item.setMedia(media); if (media != null) { media.setItem(item); } } } return result; } private static Map<Long, FeedMedia> getFeedMedia(PodDBAdapter adapter, LongList itemIds) { List<String> ids = new ArrayList<>(itemIds.size()); for (long item : itemIds.toArray()) { ids.add(String.valueOf(item)); } Map<Long, FeedMedia> result = new ArrayMap<>(itemIds.size()); Cursor cursor = adapter.getFeedMediaCursor(ids.toArray(new String[0])); try { if (cursor.moveToFirst()) { do { int index = cursor.getColumnIndex(PodDBAdapter.KEY_FEEDITEM); long itemId = cursor.getLong(index); FeedMedia media = FeedMedia.fromCursor(cursor); result.put(itemId, media); } while (cursor.moveToNext()); } } finally { cursor.close(); } return result; } private static Feed extractFeedFromCursorRow(PodDBAdapter adapter, Cursor cursor) { Feed feed = Feed.fromCursor(cursor); FeedPreferences preferences = FeedPreferences.fromCursor(cursor); feed.setPreferences(preferences); return feed; } static List<FeedItem> getQueue(PodDBAdapter adapter) { Log.d(TAG, "getQueue()"); Cursor cursor = null; try { cursor = adapter.getQueueCursor(); List<FeedItem> items = extractItemlistFromCursor(adapter, cursor); loadAdditionalFeedItemListData(items); return items; } finally { if (cursor != null) { cursor.close(); } } } /** * Loads the IDs of the FeedItems in the queue. This method should be preferred over * {@link #getQueue()} if the FeedItems of the queue are not needed. * * @return A list of IDs sorted by the same order as the queue. The caller can wrap the returned * list in a {@link de.danoeh.antennapod.core.util.QueueAccess} object for easier access to the queue's properties. */ public static LongList getQueueIDList() { Log.d(TAG, "getQueueIDList() called"); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); try { return getQueueIDList(adapter); } finally { adapter.close(); } } private static LongList getQueueIDList(PodDBAdapter adapter) { Cursor cursor = null; try { cursor = adapter.getQueueIDCursor(); LongList queueIds = new LongList(cursor.getCount()); while (cursor.moveToNext()) { queueIds.add(cursor.getLong(0)); } return queueIds; } finally { if (cursor != null) { cursor.close(); } } } /** * Loads a list of the FeedItems in the queue. If the FeedItems of the queue are not used directly, consider using * {@link #getQueueIDList()} instead. * * @return A list of FeedItems sorted by the same order as the queue. The caller can wrap the returned * list in a {@link de.danoeh.antennapod.core.util.QueueAccess} object for easier access to the queue's properties. */ public static List<FeedItem> getQueue() { Log.d(TAG, "getQueue() called"); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); try { return getQueue(adapter); } finally { adapter.close(); } } /** * Loads a list of FeedItems whose episode has been downloaded. * * @return A list of FeedItems whose episdoe has been downloaded. */ public static List<FeedItem> getDownloadedItems() { Log.d(TAG, "getDownloadedItems() called"); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); Cursor cursor = null; try { cursor = adapter.getDownloadedItemsCursor(); List<FeedItem> items = extractItemlistFromCursor(adapter, cursor); loadAdditionalFeedItemListData(items); Collections.sort(items, new FeedItemPubdateComparator()); return items; } finally { if (cursor != null) { cursor.close(); } adapter.close(); } } /** * Loads a list of FeedItems that are considered new. * Excludes items from feeds that do not have keep updated enabled. * * @return A list of FeedItems that are considered new. */ public static List<FeedItem> getNewItemsList() { Log.d(TAG, "getNewItemsList() called"); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); Cursor cursor = null; try { cursor = adapter.getNewItemsCursor(); List<FeedItem> items = extractItemlistFromCursor(adapter, cursor); loadAdditionalFeedItemListData(items); return items; } finally { if (cursor != null) { cursor.close(); } adapter.close(); } } public static List<FeedItem> getFavoriteItemsList() { Log.d(TAG, "getFavoriteItemsList() called"); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); Cursor cursor = null; try { cursor = adapter.getFavoritesCursor(); List<FeedItem> items = extractItemlistFromCursor(adapter, cursor); loadAdditionalFeedItemListData(items); return items; } finally { if (cursor != null) { cursor.close(); } adapter.close(); } } private static LongList getFavoriteIDList() { Log.d(TAG, "getFavoriteIDList() called"); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); Cursor cursor = null; try { cursor = adapter.getFavoritesCursor(); LongList favoriteIDs = new LongList(cursor.getCount()); while (cursor.moveToNext()) { favoriteIDs.add(cursor.getLong(0)); } return favoriteIDs; } finally { if (cursor != null) { cursor.close(); } adapter.close(); } } /** * Loads a list of FeedItems sorted by pubDate in descending order. * * @param limit The maximum number of episodes that should be loaded. */ public static List<FeedItem> getRecentlyPublishedEpisodes(int limit) { Log.d(TAG, "getRecentlyPublishedEpisodes() called with: " + "limit = [" + limit + "]"); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); Cursor cursor = null; try { cursor = adapter.getRecentlyPublishedItemsCursor(limit); List<FeedItem> items = extractItemlistFromCursor(adapter, cursor); loadAdditionalFeedItemListData(items); return items; } finally { if (cursor != null) { cursor.close(); } adapter.close(); } } /** * Loads the playback history from the database. A FeedItem is in the playback history if playback of the correpsonding episode * has been completed at least once. * * @return The playback history. The FeedItems are sorted by their media's playbackCompletionDate in descending order. * The size of the returned list is limited by {@link #PLAYBACK_HISTORY_SIZE}. */ public static List<FeedItem> getPlaybackHistory() { Log.d(TAG, "getPlaybackHistory() called"); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); Cursor mediaCursor = null; Cursor itemCursor = null; try { mediaCursor = adapter.getCompletedMediaCursor(PLAYBACK_HISTORY_SIZE); String[] itemIds = new String[mediaCursor.getCount()]; for (int i = 0; i < itemIds.length && mediaCursor.moveToPosition(i); i++) { int index = mediaCursor.getColumnIndex(PodDBAdapter.KEY_FEEDITEM); itemIds[i] = Long.toString(mediaCursor.getLong(index)); } itemCursor = adapter.getFeedItemCursor(itemIds); List<FeedItem> items = extractItemlistFromCursor(adapter, itemCursor); loadAdditionalFeedItemListData(items); Collections.sort(items, new PlaybackCompletionDateComparator()); return items; } finally { if (mediaCursor != null) { mediaCursor.close(); } if (itemCursor != null) { itemCursor.close(); } adapter.close(); } } /** * Loads the download log from the database. * * @return A list with DownloadStatus objects that represent the download log. * The size of the returned list is limited by {@link #DOWNLOAD_LOG_SIZE}. */ public static List<DownloadStatus> getDownloadLog() { Log.d(TAG, "getDownloadLog() called"); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); Cursor cursor = null; try { cursor = adapter.getDownloadLogCursor(DOWNLOAD_LOG_SIZE); List<DownloadStatus> downloadLog = new ArrayList<>(cursor.getCount()); while (cursor.moveToNext()) { downloadLog.add(DownloadStatus.fromCursor(cursor)); } Collections.sort(downloadLog, new DownloadStatusComparator()); return downloadLog; } finally { if (cursor != null) { cursor.close(); } adapter.close(); } } /** * Loads the download log for a particular feed from the database. * * @param feed Feed for which the download log is loaded * @return A list with DownloadStatus objects that represent the feed's download log, * newest events first. */ public static List<DownloadStatus> getFeedDownloadLog(Feed feed) { Log.d(TAG, "getFeedDownloadLog() called with: " + "feed = [" + feed + "]"); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); Cursor cursor = null; try { cursor = adapter.getDownloadLog(Feed.FEEDFILETYPE_FEED, feed.getId()); List<DownloadStatus> downloadLog = new ArrayList<>(cursor.getCount()); while (cursor.moveToNext()) { downloadLog.add(DownloadStatus.fromCursor(cursor)); } Collections.sort(downloadLog, new DownloadStatusComparator()); return downloadLog; } finally { if (cursor != null) { cursor.close(); } adapter.close(); } } /** * Loads the FeedItemStatistics objects of all Feeds in the database. This method should be preferred over * {@link #getFeedItemList(Feed)} if only metadata about * the FeedItems is needed. * * @return A list of FeedItemStatistics objects sorted alphabetically by their Feed's title. */ public static List<FeedItemStatistics> getFeedStatisticsList() { Log.d(TAG, "getFeedStatisticsList() called"); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); Cursor cursor = null; try { cursor = adapter.getFeedStatisticsCursor(); List<FeedItemStatistics> result = new ArrayList<>(cursor.getCount()); while (cursor.moveToNext()) { FeedItemStatistics fis = FeedItemStatistics.fromCursor(cursor); result.add(fis); } return result; } finally { if (cursor != null) { cursor.close(); } adapter.close(); } } /** * Loads a specific Feed from the database. * * @param feedId The ID of the Feed * @return The Feed or null if the Feed could not be found. The Feeds FeedItems will also be loaded from the * database and the items-attribute will be set correctly. */ public static Feed getFeed(final long feedId) { Log.d(TAG, "getFeed() called with: " + "feedId = [" + feedId + "]"); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); try { return getFeed(feedId, adapter); } finally { adapter.close(); } } static Feed getFeed(final long feedId, PodDBAdapter adapter) { Feed feed = null; Cursor cursor = null; try { cursor = adapter.getFeedCursor(feedId); if (cursor.moveToNext()) { feed = extractFeedFromCursorRow(adapter, cursor); feed.setItems(getFeedItemList(feed)); } else { Log.e(TAG, "getFeed could not find feed with id " + feedId); } return feed; } finally { if (cursor != null) { cursor.close(); } } } private static FeedItem getFeedItem(final long itemId, PodDBAdapter adapter) { Log.d(TAG, "Loading feeditem with id " + itemId); FeedItem item = null; Cursor cursor = null; try { cursor = adapter.getFeedItemCursor(Long.toString(itemId)); if (cursor.moveToNext()) { List<FeedItem> list = extractItemlistFromCursor(adapter, cursor); if (!list.isEmpty()) { item = list.get(0); loadAdditionalFeedItemListData(list); if (item.hasChapters()) { loadChaptersOfFeedItem(adapter, item); } } } return item; } finally { if (cursor != null) { cursor.close(); } } } /** * Loads a specific FeedItem from the database. This method should not be used for loading more * than one FeedItem because this method might query the database several times for each item. * * @param itemId The ID of the FeedItem * @return The FeedItem or null if the FeedItem could not be found. All FeedComponent-attributes * as well as chapter marks of the FeedItem will also be loaded from the database. */ public static FeedItem getFeedItem(final long itemId) { Log.d(TAG, "getFeedItem() called with: " + "itemId = [" + itemId + "]"); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); try { return getFeedItem(itemId, adapter); } finally { adapter.close(); } } private static FeedItem getFeedItem(final String podcastUrl, final String episodeUrl, PodDBAdapter adapter) { Log.d(TAG, "Loading feeditem with podcast url " + podcastUrl + " and episode url " + episodeUrl); Cursor cursor = null; try { cursor = adapter.getFeedItemCursor(podcastUrl, episodeUrl); if (!cursor.moveToNext()) { return null; } List<FeedItem> list = extractItemlistFromCursor(adapter, cursor); FeedItem item = null; if (!list.isEmpty()) { item = list.get(0); loadAdditionalFeedItemListData(list); if (item.hasChapters()) { loadChaptersOfFeedItem(adapter, item); } } return item; } finally { if (cursor != null) { cursor.close(); } } } /** * Returns credentials based on image URL * * @param imageUrl The URL of the image * @return Credentials in format "<Username>:<Password>", empty String if no authorization given */ public static String getImageAuthentication(final String imageUrl) { Log.d(TAG, "getImageAuthentication() called with: " + "imageUrl = [" + imageUrl + "]"); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); try { return getImageAuthentication(imageUrl, adapter); } finally { adapter.close(); } } private static String getImageAuthentication(final String imageUrl, PodDBAdapter adapter) { String credentials = null; Cursor cursor = null; try { cursor = adapter.getImageAuthenticationCursor(imageUrl); if (cursor.moveToFirst()) { String username = cursor.getString(0); String password = cursor.getString(1); if (username != null && password != null) { credentials = username + ":" + password; } else { credentials = ""; } } else { credentials = ""; } } finally { if (cursor != null) { cursor.close(); } } return credentials; } /** * Loads a specific FeedItem from the database. * * @param podcastUrl the corresponding feed's url * @param episodeUrl the feed item's url * @return The FeedItem or null if the FeedItem could not be found. All FeedComponent-attributes * as well as chapter marks of the FeedItem will also be loaded from the database. */ public static FeedItem getFeedItem(final String podcastUrl, final String episodeUrl) { Log.d(TAG, "getFeedItem() called with: " + "podcastUrl = [" + podcastUrl + "], episodeUrl = [" + episodeUrl + "]"); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); try { return getFeedItem(podcastUrl, episodeUrl, adapter); } finally { adapter.close(); } } /** * Loads additional information about a FeedItem, e.g. shownotes * * @param item The FeedItem */ public static void loadExtraInformationOfFeedItem(final FeedItem item) { Log.d(TAG, "loadExtraInformationOfFeedItem() called with: " + "item = [" + item + "]"); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); Cursor cursor = null; try { cursor = adapter.getExtraInformationOfItem(item); if (cursor.moveToFirst()) { int indexDescription = cursor.getColumnIndex(PodDBAdapter.KEY_DESCRIPTION); String description = cursor.getString(indexDescription); int indexContentEncoded = cursor.getColumnIndex(PodDBAdapter.KEY_CONTENT_ENCODED); String contentEncoded = cursor.getString(indexContentEncoded); item.setDescription(description); item.setContentEncoded(contentEncoded); } } finally { if (cursor != null) { cursor.close(); } adapter.close(); } } /** * Loads the list of chapters that belongs to this FeedItem if available. This method overwrites * any chapters that this FeedItem has. If no chapters were found in the database, the chapters * reference of the FeedItem will be set to null. * * @param item The FeedItem */ public static void loadChaptersOfFeedItem(final FeedItem item) { Log.d(TAG, "loadChaptersOfFeedItem() called with: " + "item = [" + item + "]"); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); try { loadChaptersOfFeedItem(adapter, item); } finally { adapter.close(); } } private static void loadChaptersOfFeedItem(PodDBAdapter adapter, FeedItem item) { Cursor cursor = null; try { cursor = adapter.getSimpleChaptersOfFeedItemCursor(item); int chaptersCount = cursor.getCount(); if (chaptersCount == 0) { item.setChapters(null); return; } item.setChapters(new ArrayList<>(chaptersCount)); while (cursor.moveToNext()) { Chapter chapter = Chapter.fromCursor(cursor, item); if (chapter != null) { item.getChapters().add(chapter); } } } finally { if (cursor != null) { cursor.close(); } } } /** * Returns the number of downloaded episodes. * * @return The number of downloaded episodes. */ public static int getNumberOfDownloadedEpisodes() { Log.d(TAG, "getNumberOfDownloadedEpisodes() called with: " + ""); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); try { return adapter.getNumberOfDownloadedEpisodes(); } finally { adapter.close(); } } /** * Searches the DB for a FeedMedia of the given id. * * @param mediaId The id of the object * @return The found object */ public static FeedMedia getFeedMedia(final long mediaId) { PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); Cursor mediaCursor = null; try { mediaCursor = adapter.getSingleFeedMediaCursor(mediaId); if (!mediaCursor.moveToFirst()) { return null; } int indexFeedItem = mediaCursor.getColumnIndex(PodDBAdapter.KEY_FEEDITEM); long itemId = mediaCursor.getLong(indexFeedItem); FeedMedia media = FeedMedia.fromCursor(mediaCursor); if (media != null) { FeedItem item = getFeedItem(itemId); if (item != null) { media.setItem(item); item.setMedia(media); } } return media; } finally { if (mediaCursor != null) { mediaCursor.close(); } adapter.close(); } } /** * Searches the DB for statistics * * @param sortByCountAll If true, the statistic items will be sorted according to the * countAll calculation time * @return The StatisticsInfo object */ public static StatisticsData getStatistics(boolean sortByCountAll) { PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); long totalTimeCountAll = 0; long totalTime = 0; List<StatisticsItem> feedTime = new ArrayList<>(); List<Feed> feeds = getFeedList(); for (Feed feed : feeds) { long feedPlayedTimeCountAll = 0; long feedPlayedTime = 0; long feedTotalTime = 0; long episodes = 0; long episodesStarted = 0; long episodesStartedIncludingMarked = 0; List<FeedItem> items = getFeed(feed.getId()).getItems(); for (FeedItem item : items) { FeedMedia media = item.getMedia(); if (media == null) { continue; } // played duration used to be reset when the item is added to the playback history if (media.getPlaybackCompletionDate() != null) { feedPlayedTime += media.getDuration() / 1000; } feedPlayedTime += media.getPlayedDuration() / 1000; if (item.isPlayed()) { feedPlayedTimeCountAll += media.getDuration() / 1000; } else { feedPlayedTimeCountAll += media.getPosition() / 1000; } if (media.getPlaybackCompletionDate() != null || media.getPlayedDuration() > 0) { episodesStarted++; } if (item.isPlayed() || media.getPosition() != 0) { episodesStartedIncludingMarked++; } feedTotalTime += media.getDuration() / 1000; episodes++; } feedTime.add(new StatisticsItem( feed, feedTotalTime, feedPlayedTime, feedPlayedTimeCountAll, episodes, episodesStarted, episodesStartedIncludingMarked)); totalTime += feedPlayedTime; totalTimeCountAll += feedPlayedTimeCountAll; } if (sortByCountAll) { Collections.sort(feedTime, (item1, item2) -> compareLong(item1.timePlayedCountAll, item2.timePlayedCountAll)); } else { Collections.sort(feedTime, (item1, item2) -> compareLong(item1.timePlayed, item2.timePlayed)); } adapter.close(); return new StatisticsData(totalTime, totalTimeCountAll, feedTime); } /** * Compares two {@code long} values. Long.compare() is not available before API 19 * * @return 0 if long1 = long2, less than 0 if long1 &lt; long2, * and greater than 0 if long1 &gt; long2. */ private static int compareLong(long long1, long long2) { if (long1 > long2) { return -1; } else if (long1 < long2) { return 1; } else { return 0; } } public static class StatisticsData { /** * Simply sums up time of podcasts that are marked as played */ public final long totalTimeCountAll; /** * Respects speed, listening twice, ... */ public final long totalTime; public final List<StatisticsItem> feedTime; public StatisticsData(long totalTime, long totalTimeCountAll, List<StatisticsItem> feedTime) { this.totalTime = totalTime; this.totalTimeCountAll = totalTimeCountAll; this.feedTime = feedTime; } } public static class StatisticsItem { public final Feed feed; public final long time; /** * Respects speed, listening twice, ... */ public final long timePlayed; /** * Simply sums up time of podcasts that are marked as played */ public final long timePlayedCountAll; public final long episodes; /** * Episodes that are actually played */ public final long episodesStarted; /** * All episodes that are marked as played (or have position != 0) */ public final long episodesStartedIncludingMarked; public StatisticsItem(Feed feed, long time, long timePlayed, long timePlayedCountAll, long episodes, long episodesStarted, long episodesStartedIncludingMarked) { this.feed = feed; this.time = time; this.timePlayed = timePlayed; this.timePlayedCountAll = timePlayedCountAll; this.episodes = episodes; this.episodesStarted = episodesStarted; this.episodesStartedIncludingMarked = episodesStartedIncludingMarked; } } /** * Returns the flattr queue as a List of FlattrThings. The list consists of Feeds and FeedItems. * * @return The flattr queue as a List. */ public static List<FlattrThing> getFlattrQueue() { Log.d(TAG, "getFlattrQueue() called with: " + ""); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); List<FlattrThing> result = new ArrayList<>(); // load feeds Cursor feedCursor = adapter.getFeedsInFlattrQueueCursor(); if (feedCursor.moveToFirst()) { do { result.add(extractFeedFromCursorRow(adapter, feedCursor)); } while (feedCursor.moveToNext()); } feedCursor.close(); //load feed items Cursor feedItemCursor = adapter.getFeedItemsInFlattrQueueCursor(); result.addAll(extractItemlistFromCursor(adapter, feedItemCursor)); feedItemCursor.close(); adapter.close(); Log.d(TAG, "Returning flattrQueueIterator for queue with " + result.size() + " items."); return result; } /** * Returns data necessary for displaying the navigation drawer. This includes * the list of subscriptions, the number of items in the queue and the number of unread * items. */ public static NavDrawerData getNavDrawerData() { Log.d(TAG, "getNavDrawerData() called with: " + ""); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); List<Feed> feeds = getFeedList(adapter); long[] feedIds = new long[feeds.size()]; for (int i = 0; i < feeds.size(); i++) { feedIds[i] = feeds.get(i).getId(); } final LongIntMap feedCounters = adapter.getFeedCounters(feedIds); Comparator<Feed> comparator; int feedOrder = UserPreferences.getFeedOrder(); if (feedOrder == UserPreferences.FEED_ORDER_COUNTER) { comparator = (lhs, rhs) -> { long counterLhs = feedCounters.get(lhs.getId()); long counterRhs = feedCounters.get(rhs.getId()); if (counterLhs > counterRhs) { // reverse natural order: podcast with most unplayed episodes first return -1; } else if (counterLhs == counterRhs) { return lhs.getTitle().compareToIgnoreCase(rhs.getTitle()); } else { return 1; } }; } else if (feedOrder == UserPreferences.FEED_ORDER_ALPHABETICAL) { comparator = (lhs, rhs) -> { String t1 = lhs.getTitle(); String t2 = rhs.getTitle(); if (t1 == null) { return 1; } else if (t2 == null) { return -1; } else { return t1.compareToIgnoreCase(t2); } }; } else if (feedOrder == UserPreferences.FEED_ORDER_MOST_PLAYED) { final LongIntMap playedCounters = adapter.getPlayedEpisodesCounters(feedIds); comparator = (lhs, rhs) -> { long counterLhs = playedCounters.get(lhs.getId()); long counterRhs = playedCounters.get(rhs.getId()); if (counterLhs > counterRhs) { // podcast with most played episodes first return -1; } else if (counterLhs == counterRhs) { return lhs.getTitle().compareToIgnoreCase(rhs.getTitle()); } else { return 1; } }; } else { comparator = (lhs, rhs) -> { if (lhs.getItems() == null || lhs.getItems().size() == 0) { List<FeedItem> items = DBReader.getFeedItemList(lhs); lhs.setItems(items); } if (rhs.getItems() == null || rhs.getItems().size() == 0) { List<FeedItem> items = DBReader.getFeedItemList(rhs); rhs.setItems(items); } if (lhs.getMostRecentItem() == null) { return 1; } else if (rhs.getMostRecentItem() == null) { return -1; } else { Date d1 = lhs.getMostRecentItem().getPubDate(); Date d2 = rhs.getMostRecentItem().getPubDate(); return d2.compareTo(d1); } }; } Collections.sort(feeds, comparator); int queueSize = adapter.getQueueSize(); int numNewItems = adapter.getNumberOfNewItems(); int numDownloadedItems = adapter.getNumberOfDownloadedEpisodes(); NavDrawerData result = new NavDrawerData(feeds, queueSize, numNewItems, numDownloadedItems, feedCounters, UserPreferences.getEpisodeCleanupAlgorithm().getReclaimableItems()); adapter.close(); return result; } public static class NavDrawerData { public final List<Feed> feeds; public final int queueSize; public final int numNewItems; public final int numDownloadedItems; public final LongIntMap feedCounters; public final int reclaimableSpace; public NavDrawerData(List<Feed> feeds, int queueSize, int numNewItems, int numDownloadedItems, LongIntMap feedIndicatorValues, int reclaimableSpace) { this.feeds = feeds; this.queueSize = queueSize; this.numNewItems = numNewItems; this.numDownloadedItems = numDownloadedItems; this.feedCounters = feedIndicatorValues; this.reclaimableSpace = reclaimableSpace; } } }
package de.danoeh.antennapod.core.storage; import android.app.backup.BackupManager; import android.content.Context; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import org.greenrobot.eventbus.EventBus; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import de.danoeh.antennapod.core.ClientConfig; import de.danoeh.antennapod.core.R; import de.danoeh.antennapod.core.event.DownloadLogEvent; import de.danoeh.antennapod.core.event.FavoritesEvent; import de.danoeh.antennapod.core.event.FeedItemEvent; import de.danoeh.antennapod.core.event.FeedListUpdateEvent; import de.danoeh.antennapod.core.event.MessageEvent; import de.danoeh.antennapod.core.event.PlaybackHistoryEvent; import de.danoeh.antennapod.core.event.QueueEvent; import de.danoeh.antennapod.core.event.UnreadItemsUpdateEvent; import de.danoeh.antennapod.core.feed.Feed; import de.danoeh.antennapod.core.feed.FeedEvent; import de.danoeh.antennapod.core.feed.FeedItem; import de.danoeh.antennapod.core.feed.FeedMedia; import de.danoeh.antennapod.core.feed.FeedPreferences; import de.danoeh.antennapod.core.gpoddernet.model.GpodnetEpisodeAction; import de.danoeh.antennapod.core.preferences.GpodnetPreferences; import de.danoeh.antennapod.core.preferences.PlaybackPreferences; import de.danoeh.antennapod.core.preferences.UserPreferences; import de.danoeh.antennapod.core.service.download.DownloadStatus; import de.danoeh.antennapod.core.service.playback.PlaybackService; import de.danoeh.antennapod.core.util.FeedItemPermutors; import de.danoeh.antennapod.core.util.IntentUtils; import de.danoeh.antennapod.core.util.LongList; import de.danoeh.antennapod.core.util.Permutor; import de.danoeh.antennapod.core.util.SortOrder; import de.danoeh.antennapod.core.util.playback.Playable; /** * Provides methods for writing data to AntennaPod's database. * In general, DBWriter-methods will be executed on an internal ExecutorService. * Some methods return a Future-object which the caller can use for waiting for the method's completion. The returned Future's * will NOT contain any results. */ public class DBWriter { private static final String TAG = "DBWriter"; private static final ExecutorService dbExec; static { dbExec = Executors.newSingleThreadExecutor(r -> { Thread t = new Thread(r); t.setPriority(Thread.MIN_PRIORITY); return t; }); } private DBWriter() { } /** * Deletes a downloaded FeedMedia file from the storage device. * * @param context A context that is used for opening a database connection. * @param mediaId ID of the FeedMedia object whose downloaded file should be deleted. */ public static Future<?> deleteFeedMediaOfItem(@NonNull final Context context, final long mediaId) { return dbExec.submit(() -> { final FeedMedia media = DBReader.getFeedMedia(mediaId); if (media != null) { boolean result = deleteFeedMediaSynchronous(context, media); if (result && UserPreferences.shouldDeleteRemoveFromQueue()) { DBWriter.removeQueueItemSynchronous(context, false, media.getItem().getId()); } } }); } private static boolean deleteFeedMediaSynchronous( @NonNull Context context, @NonNull FeedMedia media) { Log.i(TAG, String.format("Requested to delete FeedMedia [id=%d, title=%s, downloaded=%s", media.getId(), media.getEpisodeTitle(), String.valueOf(media.isDownloaded()))); if (media.isDownloaded()) { // delete downloaded media file File mediaFile = new File(media.getFile_url()); if (mediaFile.exists() && !mediaFile.delete()) { MessageEvent evt = new MessageEvent(context.getString(R.string.delete_failed)); EventBus.getDefault().post(evt); return false; } media.setDownloaded(false); media.setFile_url(null); media.setHasEmbeddedPicture(false); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setMedia(media); adapter.close(); if (media.getId() == PlaybackPreferences.getCurrentlyPlayingFeedMediaId()) { PlaybackPreferences.writeNoMediaPlaying(); IntentUtils.sendLocalBroadcast(context, PlaybackService.ACTION_SHUTDOWN_PLAYBACK_SERVICE); } // Gpodder: queue delete action for synchronization if (GpodnetPreferences.loggedIn()) { FeedItem item = media.getItem(); GpodnetEpisodeAction action = new GpodnetEpisodeAction.Builder(item, GpodnetEpisodeAction.Action.DELETE) .currentDeviceId() .currentTimestamp() .build(); GpodnetPreferences.enqueueEpisodeAction(action); } } EventBus.getDefault().post(FeedItemEvent.deletedMedia(Collections.singletonList(media.getItem()))); EventBus.getDefault().post(new UnreadItemsUpdateEvent()); return true; } /** * Deletes a Feed and all downloaded files of its components like images and downloaded episodes. * * @param context A context that is used for opening a database connection. * @param feedId ID of the Feed that should be deleted. */ public static Future<?> deleteFeed(final Context context, final long feedId) { return dbExec.submit(() -> { DownloadRequester requester = DownloadRequester.getInstance(); final Feed feed = DBReader.getFeed(feedId); if (feed != null) { // delete stored media files and mark them as read List<FeedItem> queue = DBReader.getQueue(); List<FeedItem> removed = new ArrayList<>(); if (feed.getItems() == null) { DBReader.getFeedItemList(feed); } for (FeedItem item : feed.getItems()) { if (queue.remove(item)) { removed.add(item); } if (item.getMedia() != null && item.getMedia().isDownloaded()) { deleteFeedMediaSynchronous(context, item.getMedia()); } else if (item.getMedia() != null && requester.isDownloadingFile(item.getMedia())) { requester.cancelDownload(context, item.getMedia()); } } PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); if (removed.size() > 0) { adapter.setQueue(queue); for (FeedItem item : removed) { EventBus.getDefault().post(QueueEvent.irreversibleRemoved(item)); } } adapter.removeFeed(feed); adapter.close(); if (ClientConfig.gpodnetCallbacks.gpodnetEnabled()) { GpodnetPreferences.addRemovedFeed(feed.getDownload_url()); } EventBus.getDefault().post(new FeedListUpdateEvent(feed)); // we assume we also removed download log entries for the feed or its media files. // especially important if download or refresh failed, as the user should not be able // to retry these EventBus.getDefault().post(DownloadLogEvent.listUpdated()); BackupManager backupManager = new BackupManager(context); backupManager.dataChanged(); } }); } /** * Deletes the entire playback history. */ public static Future<?> clearPlaybackHistory() { return dbExec.submit(() -> { PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.clearPlaybackHistory(); adapter.close(); EventBus.getDefault().post(PlaybackHistoryEvent.listUpdated()); }); } /** * Deletes the entire download log. */ public static Future<?> clearDownloadLog() { return dbExec.submit(() -> { PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.clearDownloadLog(); adapter.close(); EventBus.getDefault().post(DownloadLogEvent.listUpdated()); }); } /** * Adds a FeedMedia object to the playback history. A FeedMedia object is in the playback history if * its playback completion date is set to a non-null value. This method will set the playback completion date to the * current date regardless of the current value. * * @param media FeedMedia that should be added to the playback history. */ public static Future<?> addItemToPlaybackHistory(final FeedMedia media) { return dbExec.submit(() -> { Log.d(TAG, "Adding new item to playback history"); media.setPlaybackCompletionDate(new Date()); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setFeedMediaPlaybackCompletionDate(media); adapter.close(); EventBus.getDefault().post(PlaybackHistoryEvent.listUpdated()); }); } /** * Adds a Download status object to the download log. * * @param status The DownloadStatus object. */ public static Future<?> addDownloadStatus(final DownloadStatus status) { return dbExec.submit(() -> { PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setDownloadStatus(status); adapter.close(); EventBus.getDefault().post(DownloadLogEvent.listUpdated()); }); } /** * Inserts a FeedItem in the queue at the specified index. The 'read'-attribute of the FeedItem will be set to * true. If the FeedItem is already in the queue, the queue will not be modified. * * @param context A context that is used for opening a database connection. * @param itemId ID of the FeedItem that should be added to the queue. * @param index Destination index. Must be in range 0..queue.size() * @param performAutoDownload True if an auto-download process should be started after the operation * @throws IndexOutOfBoundsException if index < 0 || index >= queue.size() */ public static Future<?> addQueueItemAt(final Context context, final long itemId, final int index, final boolean performAutoDownload) { return dbExec.submit(() -> { final PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); final List<FeedItem> queue = DBReader.getQueue(adapter); FeedItem item; if (queue != null) { if (!itemListContains(queue, itemId)) { item = DBReader.getFeedItem(itemId); if (item != null) { queue.add(index, item); adapter.setQueue(queue); item.addTag(FeedItem.TAG_QUEUE); EventBus.getDefault().post(QueueEvent.added(item, index)); EventBus.getDefault().post(FeedItemEvent.updated(item)); if (item.isNew()) { DBWriter.markItemPlayed(FeedItem.UNPLAYED, item.getId()); } } } } adapter.close(); if (performAutoDownload) { DBTasks.autodownloadUndownloadedItems(context); } }); } public static Future<?> addQueueItem(final Context context, final FeedItem... items) { LongList itemIds = new LongList(items.length); for (FeedItem item : items) { itemIds.add(item.getId()); item.addTag(FeedItem.TAG_QUEUE); } return addQueueItem(context, false, itemIds.toArray()); } /** * Appends FeedItem objects to the end of the queue. The 'read'-attribute of all items will be set to true. * If a FeedItem is already in the queue, the FeedItem will not change its position in the queue. * * @param context A context that is used for opening a database connection. * @param performAutoDownload true if an auto-download process should be started after the operation. * @param itemIds IDs of the FeedItem objects that should be added to the queue. */ public static Future<?> addQueueItem(final Context context, final boolean performAutoDownload, final long... itemIds) { return dbExec.submit(() -> { if (itemIds.length < 1) { return; } final PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); final List<FeedItem> queue = DBReader.getQueue(adapter); boolean queueModified = false; LongList markAsUnplayedIds = new LongList(); List<QueueEvent> events = new ArrayList<>(); List<FeedItem> updatedItems = new ArrayList<>(); ItemEnqueuePositionCalculator positionCalculator = new ItemEnqueuePositionCalculator(UserPreferences.getEnqueueLocation()); Playable currentlyPlaying = Playable.PlayableUtils.createInstanceFromPreferences(context); int insertPosition = positionCalculator.calcPosition(queue, currentlyPlaying); for (long itemId : itemIds) { if (!itemListContains(queue, itemId)) { final FeedItem item = DBReader.getFeedItem(itemId); if (item != null) { queue.add(insertPosition, item); events.add(QueueEvent.added(item, insertPosition)); item.addTag(FeedItem.TAG_QUEUE); updatedItems.add(item); queueModified = true; if (item.isNew()) { markAsUnplayedIds.add(item.getId()); } insertPosition++; } } } if (queueModified) { applySortOrder(queue, events); adapter.setQueue(queue); for (QueueEvent event : events) { EventBus.getDefault().post(event); } EventBus.getDefault().post(FeedItemEvent.updated(updatedItems)); if (markAsUnplayedIds.size() > 0) { DBWriter.markItemPlayed(FeedItem.UNPLAYED, markAsUnplayedIds.toArray()); } } adapter.close(); if (performAutoDownload) { DBTasks.autodownloadUndownloadedItems(context); } }); } /** * Sorts the queue depending on the configured sort order. * If the queue is not in keep sorted mode, nothing happens. * * @param queue The queue to be sorted. * @param events Replaces the events by a single SORT event if the list has to be sorted automatically. */ private static void applySortOrder(List<FeedItem> queue, List<QueueEvent> events) { if (!UserPreferences.isQueueKeepSorted()) { // queue is not in keep sorted mode, there's nothing to do return; } // Sort queue by configured sort order SortOrder sortOrder = UserPreferences.getQueueKeepSortedOrder(); if (sortOrder == SortOrder.RANDOM) { // do not shuffle the list on every change return; } Permutor<FeedItem> permutor = FeedItemPermutors.getPermutor(sortOrder); permutor.reorder(queue); // Replace ADDED events by a single SORTED event events.clear(); events.add(QueueEvent.sorted(queue)); } /** * Removes all FeedItem objects from the queue. */ public static Future<?> clearQueue() { return dbExec.submit(() -> { PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.clearQueue(); adapter.close(); EventBus.getDefault().post(QueueEvent.cleared()); }); } /** * Removes a FeedItem object from the queue. * * @param context A context that is used for opening a database connection. * @param performAutoDownload true if an auto-download process should be started after the operation. * @param item FeedItem that should be removed. */ public static Future<?> removeQueueItem(final Context context, final boolean performAutoDownload, final FeedItem item) { return dbExec.submit(() -> removeQueueItemSynchronous(context, performAutoDownload, item.getId())); } public static Future<?> removeQueueItem(final Context context, final boolean performAutoDownload, final long... itemIds) { return dbExec.submit(() -> removeQueueItemSynchronous(context, performAutoDownload, itemIds)); } private static void removeQueueItemSynchronous(final Context context, final boolean performAutoDownload, final long... itemIds) { if (itemIds.length < 1) { return; } final PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); final List<FeedItem> queue = DBReader.getQueue(adapter); if (queue != null) { boolean queueModified = false; List<QueueEvent> events = new ArrayList<>(); List<FeedItem> updatedItems = new ArrayList<>(); for (long itemId : itemIds) { int position = indexInItemList(queue, itemId); if (position >= 0) { final FeedItem item = DBReader.getFeedItem(itemId); if (item == null) { Log.e(TAG, "removeQueueItem - item in queue but somehow cannot be loaded." + " Item ignored. It should never happen. id:" + itemId); continue; } queue.remove(position); item.removeTag(FeedItem.TAG_QUEUE); events.add(QueueEvent.removed(item)); updatedItems.add(item); queueModified = true; } else { Log.v(TAG, "removeQueueItem - item not in queue:" + itemId); } } if (queueModified) { adapter.setQueue(queue); for (QueueEvent event : events) { EventBus.getDefault().post(event); } EventBus.getDefault().post(FeedItemEvent.updated(updatedItems)); } else { Log.w(TAG, "Queue was not modified by call to removeQueueItem"); } } else { Log.e(TAG, "removeQueueItem: Could not load queue"); } adapter.close(); if (performAutoDownload) { DBTasks.autodownloadUndownloadedItems(context); } } public static Future<?> addFavoriteItem(final FeedItem item) { return dbExec.submit(() -> { final PodDBAdapter adapter = PodDBAdapter.getInstance().open(); adapter.addFavoriteItem(item); adapter.close(); item.addTag(FeedItem.TAG_FAVORITE); EventBus.getDefault().post(FavoritesEvent.added(item)); EventBus.getDefault().post(FeedItemEvent.updated(item)); }); } public static Future<?> removeFavoriteItem(final FeedItem item) { return dbExec.submit(() -> { final PodDBAdapter adapter = PodDBAdapter.getInstance().open(); adapter.removeFavoriteItem(item); adapter.close(); item.removeTag(FeedItem.TAG_FAVORITE); EventBus.getDefault().post(FavoritesEvent.removed(item)); EventBus.getDefault().post(FeedItemEvent.updated(item)); }); } /** * Moves the specified item to the top of the queue. * * @param itemId The item to move to the top of the queue * @param broadcastUpdate true if this operation should trigger a QueueUpdateBroadcast. This option should be set to */ public static Future<?> moveQueueItemToTop(final long itemId, final boolean broadcastUpdate) { return dbExec.submit(() -> { LongList queueIdList = DBReader.getQueueIDList(); int index = queueIdList.indexOf(itemId); if (index >= 0) { moveQueueItemHelper(index, 0, broadcastUpdate); } else { Log.e(TAG, "moveQueueItemToTop: item not found"); } }); } /** * Moves the specified item to the bottom of the queue. * * @param itemId The item to move to the bottom of the queue * @param broadcastUpdate true if this operation should trigger a QueueUpdateBroadcast. This option should be set to */ public static Future<?> moveQueueItemToBottom(final long itemId, final boolean broadcastUpdate) { return dbExec.submit(() -> { LongList queueIdList = DBReader.getQueueIDList(); int index = queueIdList.indexOf(itemId); if (index >= 0) { moveQueueItemHelper(index, queueIdList.size() - 1, broadcastUpdate); } else { Log.e(TAG, "moveQueueItemToBottom: item not found"); } }); } /** * Changes the position of a FeedItem in the queue. * * @param from Source index. Must be in range 0..queue.size()-1. * @param to Destination index. Must be in range 0..queue.size()-1. * @param broadcastUpdate true if this operation should trigger a QueueUpdateBroadcast. This option should be set to * false if the caller wants to avoid unexpected updates of the GUI. * @throws IndexOutOfBoundsException if (to < 0 || to >= queue.size()) || (from < 0 || from >= queue.size()) */ public static Future<?> moveQueueItem(final int from, final int to, final boolean broadcastUpdate) { return dbExec.submit(() -> moveQueueItemHelper(from, to, broadcastUpdate)); } /** * Changes the position of a FeedItem in the queue. * <p/> * This function must be run using the ExecutorService (dbExec). * * @param from Source index. Must be in range 0..queue.size()-1. * @param to Destination index. Must be in range 0..queue.size()-1. * @param broadcastUpdate true if this operation should trigger a QueueUpdateBroadcast. This option should be set to * false if the caller wants to avoid unexpected updates of the GUI. * @throws IndexOutOfBoundsException if (to < 0 || to >= queue.size()) || (from < 0 || from >= queue.size()) */ private static void moveQueueItemHelper(final int from, final int to, final boolean broadcastUpdate) { final PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); final List<FeedItem> queue = DBReader.getQueue(adapter); if (queue != null) { if (from >= 0 && from < queue.size() && to >= 0 && to < queue.size()) { final FeedItem item = queue.remove(from); queue.add(to, item); adapter.setQueue(queue); if (broadcastUpdate) { EventBus.getDefault().post(QueueEvent.moved(item, to)); } } } else { Log.e(TAG, "moveQueueItemHelper: Could not load queue"); } adapter.close(); } /* * Sets the 'read'-attribute of all specified FeedItems * * @param played New value of the 'read'-attribute, one of FeedItem.PLAYED, FeedItem.NEW, * FeedItem.UNPLAYED * @param itemIds IDs of the FeedItems. */ public static Future<?> markItemPlayed(final int played, final long... itemIds) { return markItemPlayed(played, true, itemIds); } /* * Sets the 'read'-attribute of all specified FeedItems * * @param played New value of the 'read'-attribute, one of FeedItem.PLAYED, FeedItem.NEW, * FeedItem.UNPLAYED * @param broadcastUpdate true if this operation should trigger a UnreadItemsUpdate broadcast. * This option is usually set to true * @param itemIds IDs of the FeedItems. */ public static Future<?> markItemPlayed(final int played, final boolean broadcastUpdate, final long... itemIds) { return dbExec.submit(() -> { final PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setFeedItemRead(played, itemIds); adapter.close(); if (broadcastUpdate) { EventBus.getDefault().post(new UnreadItemsUpdateEvent()); } }); } /** * Sets the 'read'-attribute of a FeedItem to the specified value. * * @param item The FeedItem object * @param played New value of the 'read'-attribute one of FeedItem.PLAYED, * FeedItem.NEW, FeedItem.UNPLAYED * @param resetMediaPosition true if this method should also reset the position of the FeedItem's FeedMedia object. */ @NonNull public static Future<?> markItemPlayed(FeedItem item, int played, boolean resetMediaPosition) { long mediaId = (item.hasMedia()) ? item.getMedia().getId() : 0; return markItemPlayed(item.getId(), played, mediaId, resetMediaPosition); } @NonNull private static Future<?> markItemPlayed(final long itemId, final int played, final long mediaId, final boolean resetMediaPosition) { return dbExec.submit(() -> { final PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setFeedItemRead(played, itemId, mediaId, resetMediaPosition); adapter.close(); EventBus.getDefault().post(new UnreadItemsUpdateEvent()); }); } /** * Sets the 'read'-attribute of all NEW FeedItems of a specific Feed to UNPLAYED. * * @param feedId ID of the Feed. */ public static Future<?> removeFeedNewFlag(final long feedId) { return dbExec.submit(() -> { final PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setFeedItems(FeedItem.NEW, FeedItem.UNPLAYED, feedId); adapter.close(); EventBus.getDefault().post(new UnreadItemsUpdateEvent()); }); } /** * Sets the 'read'-attribute of all FeedItems of a specific Feed to PLAYED. * * @param feedId ID of the Feed. */ public static Future<?> markFeedRead(final long feedId) { return dbExec.submit(() -> { final PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setFeedItems(FeedItem.PLAYED, feedId); adapter.close(); EventBus.getDefault().post(new UnreadItemsUpdateEvent()); }); } /** * Sets the 'read'-attribute of all FeedItems to PLAYED. */ public static Future<?> markAllItemsRead() { return dbExec.submit(() -> { final PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setFeedItems(FeedItem.PLAYED); adapter.close(); EventBus.getDefault().post(new UnreadItemsUpdateEvent()); }); } /** * Sets the 'read'-attribute of all NEW FeedItems to UNPLAYED. */ public static Future<?> removeAllNewFlags() { return dbExec.submit(() -> { final PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setFeedItems(FeedItem.NEW, FeedItem.UNPLAYED); adapter.close(); EventBus.getDefault().post(new UnreadItemsUpdateEvent()); }); } static Future<?> addNewFeed(final Context context, final Feed... feeds) { return dbExec.submit(() -> { final PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setCompleteFeed(feeds); adapter.close(); if (ClientConfig.gpodnetCallbacks.gpodnetEnabled()) { for (Feed feed : feeds) { GpodnetPreferences.addAddedFeed(feed.getDownload_url()); } } BackupManager backupManager = new BackupManager(context); backupManager.dataChanged(); }); } static Future<?> setCompleteFeed(final Feed... feeds) { return dbExec.submit(() -> { PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setCompleteFeed(feeds); adapter.close(); }); } /** * Saves a FeedMedia object in the database. This method will save all attributes of the FeedMedia object. The * contents of FeedComponent-attributes (e.g. the FeedMedia's 'item'-attribute) will not be saved. * * @param media The FeedMedia object. */ public static Future<?> setFeedMedia(final FeedMedia media) { return dbExec.submit(() -> { PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setMedia(media); adapter.close(); }); } /** * Saves the 'position', 'duration' and 'last played time' attributes of a FeedMedia object * * @param media The FeedMedia object. */ public static Future<?> setFeedMediaPlaybackInformation(final FeedMedia media) { return dbExec.submit(() -> { PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setFeedMediaPlaybackInformation(media); adapter.close(); }); } /** * Saves a FeedItem object in the database. This method will save all attributes of the FeedItem object including * the content of FeedComponent-attributes. * * @param item The FeedItem object. */ public static Future<?> setFeedItem(final FeedItem item) { return dbExec.submit(() -> { PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setSingleFeedItem(item); adapter.close(); EventBus.getDefault().post(FeedItemEvent.updated(item)); }); } /** * Updates download URL of a feed */ public static Future<?> updateFeedDownloadURL(final String original, final String updated) { Log.d(TAG, "updateFeedDownloadURL(original: " + original + ", updated: " + updated + ")"); return dbExec.submit(() -> { PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setFeedDownloadUrl(original, updated); adapter.close(); }); } /** * Saves a FeedPreferences object in the database. The Feed ID of the FeedPreferences-object MUST NOT be 0. * * @param preferences The FeedPreferences object. */ public static Future<?> setFeedPreferences(final FeedPreferences preferences) { return dbExec.submit(() -> { PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setFeedPreferences(preferences); adapter.close(); EventBus.getDefault().post(new FeedListUpdateEvent(preferences.getFeedID())); }); } private static boolean itemListContains(List<FeedItem> items, long itemId) { return indexInItemList(items, itemId) >= 0; } private static int indexInItemList(List<FeedItem> items, long itemId) { for (int i = 0; i < items.size(); i++) { FeedItem item = items.get(i); if (item.getId() == itemId) { return i; } } return -1; } /** * Saves if a feed's last update failed * * @param lastUpdateFailed true if last update failed */ public static Future<?> setFeedLastUpdateFailed(final long feedId, final boolean lastUpdateFailed) { return dbExec.submit(() -> { PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setFeedLastUpdateFailed(feedId, lastUpdateFailed); adapter.close(); }); } public static Future<?> setFeedCustomTitle(Feed feed) { return dbExec.submit(() -> { PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setFeedCustomTitle(feed.getId(), feed.getCustomTitle()); adapter.close(); EventBus.getDefault().post(new FeedListUpdateEvent(feed)); }); } /** * Sort the FeedItems in the queue with the given the named sort order. * * @param broadcastUpdate <code>true</code> if this operation should trigger a * QueueUpdateBroadcast. This option should be set to <code>false</code> * if the caller wants to avoid unexpected updates of the GUI. */ public static Future<?> reorderQueue(@Nullable SortOrder sortOrder, final boolean broadcastUpdate) { if (sortOrder == null) { Log.w(TAG, "reorderQueue() - sortOrder is null. Do nothing."); return dbExec.submit(() -> { }); } final Permutor<FeedItem> permutor = FeedItemPermutors.getPermutor(sortOrder); return dbExec.submit(() -> { final PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); final List<FeedItem> queue = DBReader.getQueue(adapter); if (queue != null) { permutor.reorder(queue); adapter.setQueue(queue); if (broadcastUpdate) { EventBus.getDefault().post(QueueEvent.sorted(queue)); } } else { Log.e(TAG, "reorderQueue: Could not load queue"); } adapter.close(); }); } /** * Sets the 'auto_download'-attribute of specific FeedItem. * * @param feedItem FeedItem. * @param autoDownload true enables auto download, false disables it */ public static Future<?> setFeedItemAutoDownload(final FeedItem feedItem, final boolean autoDownload) { return dbExec.submit(() -> { final PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setFeedItemAutoDownload(feedItem, autoDownload ? 1 : 0); adapter.close(); EventBus.getDefault().post(new UnreadItemsUpdateEvent()); }); } public static Future<?> saveFeedItemAutoDownloadFailed(final FeedItem feedItem) { return dbExec.submit(() -> { int failedAttempts = feedItem.getFailedAutoDownloadAttempts() + 1; long autoDownload; if (!feedItem.getAutoDownload() || failedAttempts >= 10) { autoDownload = 0; // giving up, disable auto download feedItem.setAutoDownload(false); } else { long now = System.currentTimeMillis(); autoDownload = (now / 10) * 10 + failedAttempts; } final PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setFeedItemAutoDownload(feedItem, autoDownload); adapter.close(); EventBus.getDefault().post(new UnreadItemsUpdateEvent()); }); } /** * Sets the 'auto_download'-attribute of specific FeedItem. * * @param feed This feed's episodes will be processed. * @param autoDownload If true, auto download will be enabled for the feed's episodes. Else, */ public static Future<?> setFeedsItemsAutoDownload(final Feed feed, final boolean autoDownload) { Log.d(TAG, (autoDownload ? "Enabling" : "Disabling") + " auto download for items of feed " + feed.getId()); return dbExec.submit(() -> { final PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setFeedsItemsAutoDownload(feed, autoDownload); adapter.close(); EventBus.getDefault().post(new UnreadItemsUpdateEvent()); }); } /** * Set filter of the feed * * @param feedId The feed's ID * @param filterValues Values that represent properties to filter by */ public static Future<?> setFeedItemsFilter(final long feedId, final Set<String> filterValues) { Log.d(TAG, "setFeedItemsFilter() called with: " + "feedId = [" + feedId + "], filterValues = [" + filterValues + "]"); return dbExec.submit(() -> { PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setFeedItemFilter(feedId, filterValues); adapter.close(); EventBus.getDefault().post(new FeedEvent(FeedEvent.Action.FILTER_CHANGED, feedId)); }); } /** * Set item sort order of the feed * */ public static Future<?> setFeedItemSortOrder(long feedId, @Nullable SortOrder sortOrder) { return dbExec.submit(() -> { PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setFeedItemSortOrder(feedId, sortOrder); adapter.close(); EventBus.getDefault().post(new FeedEvent(FeedEvent.Action.SORT_ORDER_CHANGED, feedId)); }); } /** * Reset the statistics in DB */ @NonNull public static Future<?> resetStatistics() { return dbExec.submit(() -> { PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.resetAllMediaPlayedDuration(); adapter.close(); }); } }
package me.prettyprint.hector.api.factory; import java.util.HashMap; import java.util.List; import java.util.Map; import me.prettyprint.cassandra.model.ExecutingKeyspace; import me.prettyprint.cassandra.model.ExecutingVirtualKeyspace; import me.prettyprint.cassandra.model.HColumnImpl; import me.prettyprint.cassandra.model.HSuperColumnImpl; import me.prettyprint.cassandra.model.IndexedSlicesQuery; import me.prettyprint.cassandra.model.MutatorImpl; import me.prettyprint.cassandra.model.QuorumAllConsistencyLevelPolicy; import me.prettyprint.cassandra.model.thrift.ThriftColumnQuery; import me.prettyprint.cassandra.model.thrift.ThriftCountQuery; import me.prettyprint.cassandra.model.thrift.ThriftMultigetSliceQuery; import me.prettyprint.cassandra.model.thrift.ThriftMultigetSubSliceQuery; import me.prettyprint.cassandra.model.thrift.ThriftMultigetSuperSliceQuery; import me.prettyprint.cassandra.model.thrift.ThriftRangeSlicesQuery; import me.prettyprint.cassandra.model.thrift.ThriftRangeSubSlicesQuery; import me.prettyprint.cassandra.model.thrift.ThriftRangeSuperSlicesQuery; import me.prettyprint.cassandra.model.thrift.ThriftSliceQuery; import me.prettyprint.cassandra.model.thrift.ThriftSubColumnQuery; import me.prettyprint.cassandra.model.thrift.ThriftSubCountQuery; import me.prettyprint.cassandra.model.thrift.ThriftSubSliceQuery; import me.prettyprint.cassandra.model.thrift.ThriftSuperColumnQuery; import me.prettyprint.cassandra.model.thrift.ThriftSuperCountQuery; import me.prettyprint.cassandra.model.thrift.ThriftSuperSliceQuery; import me.prettyprint.cassandra.serializers.StringSerializer; import me.prettyprint.cassandra.service.CassandraHostConfigurator; import me.prettyprint.cassandra.service.FailoverPolicy; import me.prettyprint.cassandra.service.ThriftCfDef; import me.prettyprint.cassandra.service.ThriftCluster; import me.prettyprint.cassandra.service.ThriftKsDef; import me.prettyprint.cassandra.service.clock.MicrosecondsClockResolution; import me.prettyprint.cassandra.service.clock.MicrosecondsSyncClockResolution; import me.prettyprint.cassandra.service.clock.MillisecondsClockResolution; import me.prettyprint.cassandra.service.clock.SecondsClockResolution; import me.prettyprint.hector.api.ClockResolution; import me.prettyprint.hector.api.Cluster; import me.prettyprint.hector.api.ConsistencyLevelPolicy; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.beans.HSuperColumn; import me.prettyprint.hector.api.ddl.ColumnDefinition; import me.prettyprint.hector.api.ddl.ColumnFamilyDefinition; import me.prettyprint.hector.api.ddl.ComparatorType; import me.prettyprint.hector.api.ddl.KeyspaceDefinition; import me.prettyprint.hector.api.mutation.Mutator; import me.prettyprint.hector.api.query.ColumnQuery; import me.prettyprint.hector.api.query.CountQuery; import me.prettyprint.hector.api.query.MultigetSliceQuery; import me.prettyprint.hector.api.query.MultigetSubSliceQuery; import me.prettyprint.hector.api.query.MultigetSuperSliceQuery; import me.prettyprint.hector.api.query.RangeSlicesQuery; import me.prettyprint.hector.api.query.RangeSubSlicesQuery; import me.prettyprint.hector.api.query.RangeSuperSlicesQuery; import me.prettyprint.hector.api.query.SliceQuery; import me.prettyprint.hector.api.query.SubColumnQuery; import me.prettyprint.hector.api.query.SubCountQuery; import me.prettyprint.hector.api.query.SubSliceQuery; import me.prettyprint.hector.api.query.SuperColumnQuery; import me.prettyprint.hector.api.query.SuperCountQuery; import me.prettyprint.hector.api.query.SuperSliceQuery; /** * A convenience class with bunch of factory static methods to help create a * mutator, queries etc. * * @author Ran * @author zznate */ public final class HFactory { private static final Map<String, Cluster> clusters = new HashMap<String, Cluster>(); private static final ConsistencyLevelPolicy DEFAULT_CONSISTENCY_LEVEL_POLICY = new QuorumAllConsistencyLevelPolicy(); public static Cluster getCluster(String clusterName) { synchronized (clusters) { return clusters.get(clusterName); } } public static Cluster getOrCreateCluster(String clusterName, String hostIp) { return getOrCreateCluster(clusterName, new CassandraHostConfigurator(hostIp)); } public static Cluster getOrCreateCluster(String clusterName, CassandraHostConfigurator cassandraHostConfigurator) { synchronized (clusters) { Cluster c = clusters.get(clusterName); if (c == null) { c = createCluster(clusterName, cassandraHostConfigurator); clusters.put(clusterName, c); } return c; } } public static Cluster createCluster(String clusterName, CassandraHostConfigurator cassandraHostConfigurator) { synchronized (clusters) { return clusters.get(clusterName) == null ? new ThriftCluster(clusterName, cassandraHostConfigurator) : clusters.get(clusterName); } } public static Cluster createCluster(String clusterName, CassandraHostConfigurator cassandraHostConfigurator, Map<String, String> credentials) { synchronized (clusters) { return clusters.get(clusterName) == null ? new ThriftCluster(clusterName, cassandraHostConfigurator, credentials) : clusters.get(clusterName); } } /** * Shutdown this cluster, removing it from the Map. This operation is * extremely expensive and should not be done lightly. * @param cluster */ public static void shutdownCluster(Cluster cluster) { synchronized (clusters) { String clusterName = cluster.getName(); if (clusters.get(clusterName) != null ) { cluster.getConnectionManager().shutdown(); clusters.remove(clusterName); } } } /** * Creates a Keyspace with the default consistency level policy. * * Example usage. * * String clusterName = "Test Cluster"; * String host = "localhost:9160"; * Cluster cluster = HFactory.getOrCreateCluster(clusterName, host); * String keyspaceName = "testKeyspace"; * Keyspace myKeyspace = HFactory.createKeyspace(keyspaceName, cluster); * * @param keyspace * @param cluster * @return */ public static Keyspace createKeyspace(String keyspace, Cluster cluster) { return createKeyspace(keyspace, cluster, createDefaultConsistencyLevelPolicy(), FailoverPolicy.ON_FAIL_TRY_ALL_AVAILABLE); } public static Keyspace createKeyspace(String keyspace, Cluster cluster, ConsistencyLevelPolicy consistencyLevelPolicy) { return createKeyspace(keyspace, cluster, consistencyLevelPolicy, FailoverPolicy.ON_FAIL_TRY_ALL_AVAILABLE); } public static Keyspace createKeyspace(String keyspace, Cluster cluster, ConsistencyLevelPolicy consistencyLevelPolicy, FailoverPolicy failoverPolicy) { return new ExecutingKeyspace(keyspace, cluster.getConnectionManager(), consistencyLevelPolicy, failoverPolicy, cluster.getCredentials()); } public static Keyspace createKeyspace(String keyspace, Cluster cluster, ConsistencyLevelPolicy consistencyLevelPolicy, FailoverPolicy failoverPolicy, Map<String, String> credentials) { return new ExecutingKeyspace(keyspace, cluster.getConnectionManager(), consistencyLevelPolicy, failoverPolicy, credentials); } public static <E> Keyspace createVirtualKeyspace(String keyspace, E keyPrefix, Serializer<E> keyPrefixSerializer, Cluster cluster) { return createVirtualKeyspace(keyspace, keyPrefix, keyPrefixSerializer, cluster, createDefaultConsistencyLevelPolicy(), FailoverPolicy.ON_FAIL_TRY_ALL_AVAILABLE); } public static <E> Keyspace createVirtualKeyspace(String keyspace, E keyPrefix, Serializer<E> keyPrefixSerializer, Cluster cluster, ConsistencyLevelPolicy consistencyLevelPolicy) { return createVirtualKeyspace(keyspace, keyPrefix, keyPrefixSerializer, cluster, consistencyLevelPolicy, FailoverPolicy.ON_FAIL_TRY_ALL_AVAILABLE); } public static <E> Keyspace createVirtualKeyspace(String keyspace, E keyPrefix, Serializer<E> keyPrefixSerializer, Cluster cluster, ConsistencyLevelPolicy consistencyLevelPolicy, FailoverPolicy failoverPolicy) { return new ExecutingVirtualKeyspace<E>(keyspace, keyPrefix, keyPrefixSerializer, cluster.getConnectionManager(), consistencyLevelPolicy, failoverPolicy, cluster.getCredentials()); } public static <E> Keyspace createVirtualKeyspace(String keyspace, E keyPrefix, Serializer<E> keyPrefixSerializer, Cluster cluster, ConsistencyLevelPolicy consistencyLevelPolicy, FailoverPolicy failoverPolicy, Map<String, String> credentials) { return new ExecutingVirtualKeyspace<E>(keyspace, keyPrefix, keyPrefixSerializer, cluster.getConnectionManager(), consistencyLevelPolicy, failoverPolicy, credentials); } public static ConsistencyLevelPolicy createDefaultConsistencyLevelPolicy() { return DEFAULT_CONSISTENCY_LEVEL_POLICY; } /** * Creates a mutator for updating records in a keyspace. * * @param keyspace * @param keySerializer */ public static <K, N, V> Mutator<K> createMutator(Keyspace keyspace, Serializer<K> keySerializer) { return new MutatorImpl<K>(keyspace, keySerializer); } public static <K, N, V> ColumnQuery<K, N, V> createColumnQuery( Keyspace keyspace, Serializer<K> keySerializer, Serializer<N> nameSerializer, Serializer<V> valueSerializer) { return new ThriftColumnQuery<K, N, V>(keyspace, keySerializer, nameSerializer, valueSerializer); } public static <K, N> CountQuery<K, N> createCountQuery(Keyspace keyspace, Serializer<K> keySerializer, Serializer<N> nameSerializer) { return new ThriftCountQuery<K, N>(keyspace, keySerializer, nameSerializer); } public static <K, SN> SuperCountQuery<K, SN> createSuperCountQuery( Keyspace keyspace, Serializer<K> keySerializer, Serializer<SN> superNameSerializer) { return new ThriftSuperCountQuery<K, SN>(keyspace, keySerializer, superNameSerializer); } public static <K, SN, N> SubCountQuery<K, SN, N> createSubCountQuery( Keyspace keyspace, Serializer<K> keySerializer, Serializer<SN> superNameSerializer, Serializer<N> nameSerializer) { return new ThriftSubCountQuery<K, SN, N>(keyspace, keySerializer, superNameSerializer, nameSerializer); } public static ColumnQuery<String, String, String> createStringColumnQuery( Keyspace keyspace) { StringSerializer se = StringSerializer.get(); return createColumnQuery(keyspace, se, se, se); } public static <K, SN, N, V> SuperColumnQuery<K, SN, N, V> createSuperColumnQuery( Keyspace keyspace, Serializer<K> keySerializer, Serializer<SN> sNameSerializer, Serializer<N> nameSerializer, Serializer<V> valueSerializer) { return new ThriftSuperColumnQuery<K, SN, N, V>(keyspace, keySerializer, sNameSerializer, nameSerializer, valueSerializer); } public static <K, N, V> MultigetSliceQuery<K, N, V> createMultigetSliceQuery( Keyspace keyspace, Serializer<K> keySerializer, Serializer<N> nameSerializer, Serializer<V> valueSerializer) { return new ThriftMultigetSliceQuery<K, N, V>(keyspace, keySerializer, nameSerializer, valueSerializer); } public static <K, SN, N, V> SubColumnQuery<K, SN, N, V> createSubColumnQuery( Keyspace keyspace, Serializer<K> keySerializer, Serializer<SN> sNameSerializer, Serializer<N> nameSerializer, Serializer<V> valueSerializer) { return new ThriftSubColumnQuery<K, SN, N, V>(keyspace, keySerializer, sNameSerializer, nameSerializer, valueSerializer); } public static <K, SN, N, V> MultigetSuperSliceQuery<K, SN, N, V> createMultigetSuperSliceQuery( Keyspace keyspace, Serializer<K> keySerializer, Serializer<SN> sNameSerializer, Serializer<N> nameSerializer, Serializer<V> valueSerializer) { return new ThriftMultigetSuperSliceQuery<K, SN, N, V>(keyspace, keySerializer, sNameSerializer, nameSerializer, valueSerializer); } public static <K, SN, N, V> MultigetSubSliceQuery<K, SN, N, V> createMultigetSubSliceQuery( Keyspace keyspace, Serializer<K> keySerializer, Serializer<SN> sNameSerializer, Serializer<N> nameSerializer, Serializer<V> valueSerializer) { return new ThriftMultigetSubSliceQuery<K, SN, N, V>(keyspace, keySerializer, sNameSerializer, nameSerializer, valueSerializer); } public static <K, N, V> RangeSlicesQuery<K, N, V> createRangeSlicesQuery( Keyspace keyspace, Serializer<K> keySerializer, Serializer<N> nameSerializer, Serializer<V> valueSerializer) { return new ThriftRangeSlicesQuery<K, N, V>(keyspace, keySerializer, nameSerializer, valueSerializer); } public static <K, SN, N, V> RangeSuperSlicesQuery<K, SN, N, V> createRangeSuperSlicesQuery( Keyspace keyspace, Serializer<K> keySerializer, Serializer<SN> sNameSerializer, Serializer<N> nameSerializer, Serializer<V> valueSerializer) { return new ThriftRangeSuperSlicesQuery<K, SN, N, V>(keyspace, keySerializer, sNameSerializer, nameSerializer, valueSerializer); } public static <K, N, V> IndexedSlicesQuery<K, N, V> createIndexedSlicesQuery( Keyspace keyspace, Serializer<K> keySerializer, Serializer<N> nameSerializer, Serializer<V> valueSerializer) { return new IndexedSlicesQuery<K, N, V>(keyspace, keySerializer, nameSerializer, valueSerializer); } public static <K, SN, N, V> RangeSubSlicesQuery<K, SN, N, V> createRangeSubSlicesQuery( Keyspace keyspace, Serializer<K> keySerializer, Serializer<SN> sNameSerializer, Serializer<N> nameSerializer, Serializer<V> valueSerializer) { return new ThriftRangeSubSlicesQuery<K, SN, N, V>(keyspace, keySerializer, sNameSerializer, nameSerializer, valueSerializer); } public static <K, N, V> SliceQuery<K, N, V> createSliceQuery( Keyspace keyspace, Serializer<K> keySerializer, Serializer<N> nameSerializer, Serializer<V> valueSerializer) { return new ThriftSliceQuery<K, N, V>(keyspace, keySerializer, nameSerializer, valueSerializer); } public static <K, SN, N, V> SubSliceQuery<K, SN, N, V> createSubSliceQuery( Keyspace keyspace, Serializer<K> keySerializer, Serializer<SN> sNameSerializer, Serializer<N> nameSerializer, Serializer<V> valueSerializer) { return new ThriftSubSliceQuery<K, SN, N, V>(keyspace, keySerializer, sNameSerializer, nameSerializer, valueSerializer); } public static <K, SN, N, V> SuperSliceQuery<K, SN, N, V> createSuperSliceQuery( Keyspace keyspace, Serializer<K> keySerializer, Serializer<SN> sNameSerializer, Serializer<N> nameSerializer, Serializer<V> valueSerializer) { return new ThriftSuperSliceQuery<K, SN, N, V>(keyspace, keySerializer, sNameSerializer, nameSerializer, valueSerializer); } /** * createSuperColumn accepts a variable number of column arguments * * @param name * supercolumn name * @param columns * @param superNameSerializer * @param nameSerializer * @param valueSerializer * @return */ public static <SN, N, V> HSuperColumn<SN, N, V> createSuperColumn(SN name, List<HColumn<N, V>> columns, Serializer<SN> superNameSerializer, Serializer<N> nameSerializer, Serializer<V> valueSerializer) { return new HSuperColumnImpl<SN, N, V>(name, columns, createClock(), superNameSerializer, nameSerializer, valueSerializer); } public static <SN, N, V> HSuperColumn<SN, N, V> createSuperColumn(SN name, List<HColumn<N, V>> columns, long clock, Serializer<SN> superNameSerializer, Serializer<N> nameSerializer, Serializer<V> valueSerializer) { return new HSuperColumnImpl<SN, N, V>(name, columns, clock, superNameSerializer, nameSerializer, valueSerializer); } public static <N, V> HColumn<N, V> createColumn(N name, V value, long clock, Serializer<N> nameSerializer, Serializer<V> valueSerializer) { return new HColumnImpl<N, V>(name, value, clock, nameSerializer, valueSerializer); } /** * Creates a column with the clock of now. */ public static <N, V> HColumn<N, V> createColumn(N name, V value, Serializer<N> nameSerializer, Serializer<V> valueSerializer) { return new HColumnImpl<N, V>(name, value, createClock(), nameSerializer, valueSerializer); } /** * Convienience method for creating a column with a String name and String * value */ public static HColumn<String, String> createStringColumn(String name, String value) { StringSerializer se = StringSerializer.get(); return createColumn(name, value, se, se); } /** * Creates a clock of now with the default clock resolution (micorosec) as * defined in {@link CassandraHostConfigurator}. Notice that this is a * convenient method. Be aware that there might be multiple * {@link CassandraHostConfigurator} each of them with different clock * resolutions, in which case the result of {@link HFactory.createClock} will * not be consistent. {@link Keyspace.createClock()} should be used instead. */ public static long createClock() { return CassandraHostConfigurator.DEF_CLOCK_RESOLUTION.createClock(); } /** * Use createKeyspaceDefinition to add a new Keyspace to cluster. Example: * * String testKeyspace = "testKeyspace"; KeyspaceDefinition newKeyspace = * HFactory.createKeyspaceDefinition(testKeyspace); * cluster.addKeyspace(newKeyspace); * * @param keyspace */ public static KeyspaceDefinition createKeyspaceDefinition(String keyspace) { return new ThriftKsDef(keyspace); } public static KeyspaceDefinition createKeyspaceDefinition( String keyspaceName, String strategyClass, int replicationFactor, List<ColumnFamilyDefinition> cfDefs) { return new ThriftKsDef(keyspaceName, strategyClass, replicationFactor, cfDefs); } /** * Create a column family for a given keyspace without comparator type. * Example: String keyspace = "testKeyspace"; String column1 = "testcolumn"; * ColumnFamilyDefinition columnFamily1 = * HFactory.createColumnFamilyDefinition(keyspace, column1); * List<ColumnFamilyDefinition> columns = new * ArrayList<ColumnFamilyDefinition>(); columns.add(columnFamily1); * KeyspaceDefinition testKeyspace = * HFactory.createKeyspaceDefinition(keyspace, * org.apache.cassandra.locator.SimpleStrategy.class.getName(), 1, columns); * cluster.addKeyspace(testKeyspace); * * @param keyspace * @param columnFamilyName */ public static ColumnFamilyDefinition createColumnFamilyDefinition( String keyspace, String cfName) { return new ThriftCfDef(keyspace, cfName); } /** * Create a column family for a given keyspace without comparator type. * Example: String keyspace = "testKeyspace"; String column1 = "testcolumn"; * ColumnFamilyDefinition columnFamily1 = * HFactory.createColumnFamilyDefinition(keyspace, column1, * ComparatorType.UTF8TYPE); List<ColumnFamilyDefinition> columns = new * ArrayList<ColumnFamilyDefinition>(); columns.add(columnFamily1); * KeyspaceDefinition testKeyspace = * HFactory.createKeyspaceDefinition(keyspace, * org.apache.cassandra.locator.SimpleStrategy.class.getName(), 1, columns); * cluster.addKeyspace(testKeyspace); * * @param keyspace * @param columnFamilyName * @param comparatorType */ public static ColumnFamilyDefinition createColumnFamilyDefinition( String keyspace, String cfName, ComparatorType comparatorType) { return new ThriftCfDef(keyspace, cfName, comparatorType); } public static ColumnFamilyDefinition createColumnFamilyDefinition( String keyspace, String cfName, ComparatorType comparatorType, List<ColumnDefinition> columnMetadata) { return new ThriftCfDef(keyspace, cfName, comparatorType, columnMetadata); } /** * Create a clock resolution based on <code>clockResolutionName</code> which * has to match any of the constants defined at {@link ClockResolution} * * @param clockResolutionName * type of clock resolution to create * @return a ClockResolution */ public static ClockResolution createClockResolution(String clockResolutionName) { if (clockResolutionName.equals(ClockResolution.SECONDS)) { return new SecondsClockResolution(); } else if (clockResolutionName.equals(ClockResolution.MILLISECONDS)) { return new MillisecondsClockResolution(); } else if (clockResolutionName.equals(ClockResolution.MICROSECONDS)) { return new MicrosecondsClockResolution(); } else if (clockResolutionName.equals(ClockResolution.MICROSECONDS_SYNC)) { return new MicrosecondsSyncClockResolution(); } throw new RuntimeException(String.format( "Unsupported clock resolution: %s", clockResolutionName)); } }
package org.jasig.cas.web.flow; import javax.servlet.http.HttpServletRequest; import org.jasig.cas.web.flow.util.ContextUtils; import org.jasig.cas.web.support.WebConstants; import org.jasig.cas.web.util.SecureCookieGenerator; import org.jasig.cas.web.util.WebUtils; import org.springframework.util.Assert; import org.springframework.webflow.Event; import org.springframework.webflow.RequestContext; import org.springframework.webflow.action.AbstractAction; /** * Abstract class to retrieve common attributes from request and expose them so * that implementing classes do not need to replicate same behavior. * * @author Scott Battaglia * @version $Revision$ $Date$ * @since 3.0.4 */ public abstract class AbstractLoginAction extends AbstractAction { private static final String EVENT_AUTHENTICATION_REQUIRED = "authenticationRequired"; private static final String EVENT_AUTHENTICATED_BUT_NO_SERVICE = "authenticatedButNoService"; private static final String EVENT_GATEWAY = "gateway"; private static final String EVENT_HAS_SERVICE = "hasService"; private static final String EVENT_REDIRECT = "redirect"; protected static final String REQUEST_PARAM_GATEWAY = "gateway"; protected static final String REQUEST_ATTRIBUTE_TICKET_GRANTING_TICKET = "ticketGrantingTicketId"; private SecureCookieGenerator ticketGrantingTicketCookieGenerator; private SecureCookieGenerator warnCookieGenerator; protected final Event doExecute(final RequestContext context) throws Exception { final HttpServletRequest request = ContextUtils .getHttpServletRequest(context); final String ticketGrantingTicketId = this.ticketGrantingTicketCookieGenerator .getCookieValue(request); final String service = WebUtils.getRequestParameterAsString(request, WebConstants.SERVICE); final boolean gateway = WebUtils.getRequestParameterAsBoolean(request, REQUEST_PARAM_GATEWAY); final boolean renew = WebUtils.getRequestParameterAsBoolean(request, WebConstants.RENEW); final boolean warn = Boolean.valueOf( this.warnCookieGenerator.getCookieValue(request)).booleanValue(); return doExecuteInternal(context, ticketGrantingTicketId, service, gateway, renew, warn); } protected final Event authenticationRequired() { return result(EVENT_AUTHENTICATION_REQUIRED); } protected final Event authenticatedButNoService() { return result(EVENT_AUTHENTICATED_BUT_NO_SERVICE); } protected final Event gateway() { return result(EVENT_GATEWAY); } protected final Event hasService() { return result(EVENT_HAS_SERVICE); } protected final Event redirect() { return result(EVENT_REDIRECT); } protected abstract Event doExecuteInternal(final RequestContext context, final String ticketGrantingTicketId, final String service, final boolean gateway, final boolean renew, final boolean warn); protected final void initAction() { Assert.notNull(this.ticketGrantingTicketCookieGenerator); Assert.notNull(this.warnCookieGenerator); initActionInternal(); } public final void setTicketGrantingTicketCookieGenerator( final SecureCookieGenerator ticketGrantingTicketCookieGenerator) { this.ticketGrantingTicketCookieGenerator = ticketGrantingTicketCookieGenerator; } public final void setWarnCookieGenerator( final SecureCookieGenerator warnCookieGenerator) { this.warnCookieGenerator = warnCookieGenerator; } protected final SecureCookieGenerator getTicketGrantingTicketCookieGenerator() { return this.ticketGrantingTicketCookieGenerator; } protected final SecureCookieGenerator getWarnCookieGenerator() { return this.warnCookieGenerator; } protected void initActionInternal() { // to be overwritten as needed } }
package com.google.mu.util.graph; import static com.google.common.truth.Truth8.assertThat; import static java.util.Arrays.asList; import java.util.Collection; import java.util.Map; import java.util.stream.Stream; import org.junit.Test; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Multimap; import com.google.common.graph.ElementOrder; import com.google.common.graph.Graph; import com.google.common.graph.GraphBuilder; import com.google.common.graph.MutableGraph; import com.google.common.testing.ClassSanityTester; import com.google.common.testing.NullPointerTester; import com.google.mu.util.stream.BiStream; public class CycleDetectorTest { @Test public void detectCycle_noChildren() { assertThat(CycleDetector.forGraph(n -> null).detectCycleFrom("root")).isEmpty(); } @Test public void detectCycle_trivialCycle() { assertThat(CycleDetector.forGraph(Stream::of).detectCycleFrom("root")) .containsExactly("root", "root"); } @Test public void detectCycle_oneUndirectedEdge() { Stream<String> cycle = detectCycle(toUndirectedGraph(ImmutableListMultimap.of("foo", "bar")), "foo"); assertThat(cycle).containsExactly("foo", "bar", "foo").inOrder(); } @Test public void detectCycle_oneDirectedEdge() { assertThat(detectCycle(toDirectedGraph(ImmutableListMultimap.of("foo", "bar")), "foo")) .isEmpty(); } @Test public void detectCycle_twoDirectedEdges_noCycle() { assertThat(detectCycle(toDirectedGraph( ImmutableListMultimap.of("foo", "bar", "bar", "baz")), "foo")) .isEmpty(); } @Test public void detectCycle_threeDirectedEdges_withCycle() { Graph<String> graph = toDirectedGraph(ImmutableListMultimap.of("foo", "bar", "bar", "baz", "baz", "foo")); Stream<String> cycle = detectCycle(graph, "foo"); assertThat(cycle).containsExactly("foo", "bar", "baz", "foo").inOrder(); } @Test public void detectCycle_innerDirectedEdges_withCycle() { Graph<String> graph = toDirectedGraph( ImmutableListMultimap.of("foo", "bar", "bar", "baz", "baz", "zoo", "zoo", "bar")); Stream<String> cycle = detectCycle(graph, "foo"); assertThat(cycle).containsExactly("foo", "bar", "baz", "zoo", "bar").inOrder(); } @Test public void detectCycle_dag_noCycle() { Graph<String> graph = toDirectedGraph(ImmutableListMultimap.of( "foo", "bar", "bar", "baz", "baz", "zoo", "bar", "tea", "tea", "zoo")); assertThat(detectCycle(graph, "foo")).isEmpty(); } @Test public void detectCycle_diamondCycle() { Graph<String> graph = toDirectedGraph(ImmutableMap.of( "foo", asList("bar"), "bar", asList("baz", "tea"), "baz", asList("zoo"), "tea", asList("zoo"), "zoo", asList("foo"))); Stream<String> cycle = detectCycle(graph, "bar"); assertThat(cycle).containsExactly("bar", "baz", "zoo", "foo", "bar").inOrder(); } @Test public void detectCycle_noStartingNodes() { assertThat(detectCycle(toUndirectedGraph(ImmutableListMultimap.of("foo", "bar")))) .isEmpty(); } @Test public void detectCycle_multipleStartingNodes() { Graph<String> graph = toDirectedGraph( ImmutableListMultimap.of("a", "b", "foo", "bar", "bar", "baz", "baz", "foo")); assertThat(detectCycle(graph, "a", "foo")).containsExactly("foo", "bar", "baz", "foo") .inOrder(); assertThat(detectCycle(graph, "foo", "a")).containsExactly("foo", "bar", "baz", "foo") .inOrder(); } @Test public void staticMethods_nullCheck() throws Exception { new NullPointerTester().testAllPublicStaticMethods(CycleDetector.class); new ClassSanityTester().forAllPublicStaticMethods(CycleDetector.class).testNulls(); } @Test public void instanceMethods_nullCheck() throws Exception { new NullPointerTester().testAllPublicInstanceMethods(CycleDetector.forGraph(n -> null)); } private static <N> Stream<N> detectCycle(Graph<N> graph, N... startNodes) { return CycleDetector.forGraph((N n) -> graph.successors(n).stream()) .detectCycleFrom(startNodes); } private static <N> Graph<N> toUndirectedGraph(Multimap<N, N> edges) { MutableGraph<N> graph = GraphBuilder.undirected().<N>build(); BiStream.from(edges.asMap()).flatMapValues(Collection::stream).forEach(graph::putEdge); return graph; } private static <N> Graph<N> toDirectedGraph(Multimap<N, N> edges) { MutableGraph<N> graph = GraphBuilder.directed().incidentEdgeOrder(ElementOrder.stable()).<N>build(); BiStream.from(edges.asMap()).flatMapValues(Collection::stream).forEach(graph::putEdge); return graph; } private static <N> Graph<N> toDirectedGraph(Map<N, ? extends Collection<? extends N>> edges) { return toDirectedGraph(toMultimap(edges)); } private static <N> ImmutableListMultimap<N, N> toMultimap( Map<N, ? extends Collection<? extends N>> map) { return BiStream.from(map) .flatMapValues(Collection::stream) .collect(ImmutableListMultimap::toImmutableListMultimap); } }
package com.oneandone.typedrest; import com.github.tomakehurst.wiremock.client.WireMock; import static com.github.tomakehurst.wiremock.client.WireMock.*; import java.net.URI; import java.util.HashMap; import java.util.Map; import static org.apache.http.HttpStatus.*; import static org.apache.http.HttpHeaders.*; import org.apache.http.client.fluent.Request; import org.apache.http.message.BasicHeader; import static org.hamcrest.CoreMatchers.equalTo; import org.junit.*; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import org.hamcrest.core.StringContains; import org.junit.rules.ExpectedException; public class CustomEndpointTest extends AbstractEndpointTest { private CustomEndpoint endpoint; @Before @Override public void before() { super.before(); endpoint = new CustomEndpoint(entryEndpoint, "endpoint"); } @Test public void testDefaultHeader() throws Exception { stubFor(get(urlEqualTo("/endpoint")) .withHeader("X-Mock", WireMock.equalTo("mock")) .willReturn(aResponse() .withStatus(SC_NO_CONTENT) .withHeader(LINK, "<a>; rel=target1-template"))); endpoint.get(); } @Test public void testAllowHeader() throws Exception { stubFor(get(urlEqualTo("/endpoint")) .willReturn(aResponse() .withStatus(SC_OK) .withHeader("Allow", "PUT, POST"))); endpoint.get(); assertThat(endpoint.isVerbAllowed("PUT").get(), is(true)); assertThat(endpoint.isVerbAllowed("POST").get(), is(true)); assertThat(endpoint.isVerbAllowed("DELETE").get(), is(false)); } @Test public void testLink() throws Exception { stubFor(get(urlEqualTo("/endpoint")) .willReturn(aResponse() .withStatus(SC_NO_CONTENT) .withHeader(LINK, "<a>; rel=target1, <b>; rel=target2"))); endpoint.get(); assertThat(endpoint.link("target1"), is(equalTo(endpoint.getUri().resolve("a")))); assertThat(endpoint.link("target2"), is(equalTo(endpoint.getUri().resolve("b")))); } @Test public void testLinkLazy() throws Exception { stubFor(head(urlEqualTo("/endpoint")) .willReturn(aResponse() .withStatus(SC_NO_CONTENT) .withHeader(LINK, "<a>; rel=target1, <b>; rel=target2"))); assertThat(endpoint.link("target1"), is(equalTo(endpoint.getUri().resolve("a")))); assertThat(endpoint.link("target2"), is(equalTo(endpoint.getUri().resolve("b")))); } @Test public void testLinkAbsolute() throws Exception { stubFor(get(urlEqualTo("/endpoint")) .willReturn(aResponse() .withStatus(SC_NO_CONTENT) .withHeader(LINK, "<http://localhost/b>; rel=target1"))); endpoint.get(); assertThat(endpoint.link("target1"), is(equalTo(URI.create("http://localhost/b")))); } @Test(expected = RuntimeException.class) public void testLinkException() throws Exception { stubFor(head(urlEqualTo("/endpoint")) .willReturn(aResponse() .withStatus(SC_NO_CONTENT) .withHeader(LINK, "<a>; rel=target1"))); endpoint.link("target2"); } @Test public void testGetLinks() throws Exception { stubFor(get(urlEqualTo("/endpoint")) .willReturn(aResponse() .withStatus(SC_NO_CONTENT) .withHeader(LINK, "<target1>; rel=notify, <target2>; rel=notify") .withHeader(LINK, "<target3>; rel=notify"))); endpoint.get(); assertThat(endpoint.getLinks("notify"), containsInAnyOrder( endpoint.getUri().resolve("target1"), endpoint.getUri().resolve("target2"), endpoint.getUri().resolve("target3"))); } @Test public void testGetLinksWithTitles() throws Exception { stubFor(get(urlEqualTo("/endpoint")) .willReturn(aResponse() .withStatus(SC_NO_CONTENT) .withHeader(LINK, "<target1>; rel=child; title=\"Title 1\"") .withHeader(LINK, "<target2>; rel=child"))); endpoint.get(); Map<URI, String> expected = new HashMap<>(); expected.put(endpoint.getUri().resolve("target1"), "Title 1"); expected.put(endpoint.getUri().resolve("target2"), null); assertThat(endpoint.getLinksWithTitles("child").entrySet(), equalTo( expected.entrySet())); } @Test public void testGetLinksWithTitlesEscaping() throws Exception { stubFor(get(urlEqualTo("/endpoint")) .willReturn(aResponse() .withStatus(SC_NO_CONTENT) .withHeader(LINK, "<target1>; rel=child; title=\"Title,1\", <target2>; rel=child"))); endpoint.get(); Map<URI, String> expected = new HashMap<>(); expected.put(endpoint.getUri().resolve("target1"), "Title,1"); expected.put(endpoint.getUri().resolve("target2"), null); assertThat(endpoint.getLinksWithTitles("child").entrySet(), equalTo( expected.entrySet())); } @Test public void testDefaultLink() throws Exception { endpoint.addDefaultLink("target1", "child", "Title 1"); endpoint.addDefaultLink("target2", "child"); Map<URI, String> expected = new HashMap<>(); expected.put(endpoint.getUri().resolve("target1"), "Title 1"); expected.put(endpoint.getUri().resolve("target2"), null); assertThat(endpoint.getLinksWithTitles("child").entrySet(), equalTo( expected.entrySet())); } @Test public void testLinkTemplate() throws Exception { stubFor(get(urlEqualTo("/endpoint")) .willReturn(aResponse() .withStatus(SC_NO_CONTENT) .withHeader(LINK, "<a{?x}>; rel=child; templated=true"))); endpoint.get(); assertThat(endpoint.linkTemplate("child").getTemplate(), is(equalTo("a{?x}"))); } @Test public void testLinkTemplateResolve() throws Exception { stubFor(get(urlEqualTo("/endpoint")) .willReturn(aResponse() .withStatus(SC_NO_CONTENT) .withHeader(LINK, "<a{?x}>; rel=child; templated=true"))); endpoint.get(); assertThat(endpoint.linkTemplate("child", "x", 1), is(equalTo(endpoint.getUri().resolve("a?x=1")))); } @Test public void testLinkTemplateResolveAbsolute() throws Exception { stubFor(get(urlEqualTo("/endpoint")) .willReturn(aResponse() .withStatus(SC_NO_CONTENT) .withHeader(LINK, "<http://localhost/b{?x}>; rel=child; templated=true"))); endpoint.get(); assertThat(endpoint.linkTemplate("child", "x", 1), is(equalTo(URI.create("http://localhost/b?x=1")))); } @Test(expected = RuntimeException.class) public void testLinkTemplateException() throws Exception { stubFor(head(urlEqualTo("/endpoint")) .willReturn(aResponse() .withStatus(SC_NO_CONTENT) .withHeader(LINK, "<a>; rel=child; templated=true"))); endpoint.linkTemplate("child2"); } @Test public void testDefaultLinkTemplate() throws Exception { endpoint.addDefaultLinkTemplate("a", "child"); assertThat(endpoint.linkTemplate("child").getTemplate(), is(equalTo("a"))); } @Test public void testLinkBody() throws Exception { stubFor(get(urlEqualTo("/endpoint")) .willReturn(aResponse() .withStatus(SC_OK) .withHeader(CONTENT_TYPE, JSON_MIME) .withBody("{\"links\": {" + " \"single\": {\"href\": \"a\"}," + " \"collection\": [{\"href\": \"b\", \"title\": \"Title 1\"},{\"href\": \"c\"},true,{\"something\":false}]," + " \"template\": {\"href\": \"{id}\",\"templated\": true}" + "}}"))); endpoint.get(); assertThat(endpoint.link("single"), is(equalTo(endpoint.getUri().resolve("a")))); assertThat(endpoint.getLinks("collection"), containsInAnyOrder( endpoint.getUri().resolve("b"), endpoint.getUri().resolve("c"))); assertThat(endpoint.linkTemplate("template").getTemplate(), is(equalTo("{id}"))); Map<URI, String> expected = new HashMap<>(); expected.put(endpoint.getUri().resolve("b"), "Title 1"); expected.put(endpoint.getUri().resolve("c"), null); assertThat(endpoint.getLinksWithTitles("collection").entrySet(), equalTo( expected.entrySet())); } @Rule public final ExpectedException exception = ExpectedException.none(); @Test public void testErrorHandling() throws Exception { stubFor(get(urlEqualTo("/endpoint")) .willReturn(aResponse() .withStatus(SC_CONFLICT))); exception.expectMessage(new StringContains(" responded with 409 Conflict")); endpoint.get(); } private class CustomEndpoint extends AbstractEndpoint { public CustomEndpoint(Endpoint parent, String relativeUri) { super(parent, relativeUri); defaultHeaders.add(new BasicHeader("X-Mock", "mock")); } public void get() throws Exception { executeAndHandle(Request.Get(uri)); } } }
package io.paradoxical.cassieq.unittests; import categories.BuildVerification; import categories.VerySlowTests; import com.godaddy.logging.Logger; import com.squareup.okhttp.ResponseBody; import io.paradoxical.cassieq.api.client.CassieqApi; import io.paradoxical.cassieq.api.client.CassieqCredentials; import io.paradoxical.cassieq.model.GetMessageResponse; import io.paradoxical.cassieq.model.QueryAuthUrlResult; import io.paradoxical.cassieq.model.QueueCreateOptions; import io.paradoxical.cassieq.model.QueueName; import io.paradoxical.cassieq.model.UpdateMessageRequest; import io.paradoxical.cassieq.model.UpdateMessageResponse; import io.paradoxical.cassieq.model.accounts.AccountDefinition; import io.paradoxical.cassieq.model.accounts.AccountName; import io.paradoxical.cassieq.model.accounts.GetAuthQueryParamsRequest; import io.paradoxical.cassieq.model.accounts.KeyName; import io.paradoxical.cassieq.model.accounts.WellKnownKeyNames; import io.paradoxical.cassieq.model.auth.AuthorizationLevel; import io.paradoxical.cassieq.unittests.modules.HazelcastTestModule; import io.paradoxical.cassieq.unittests.modules.InMemorySessionProvider; import io.paradoxical.cassieq.unittests.server.AdminClient; import io.paradoxical.cassieq.unittests.server.SelfHostServer; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.Period; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import retrofit.Response; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Collections; import java.util.Optional; import static com.godaddy.logging.LoggerFactory.getLogger; import static org.assertj.core.api.Assertions.assertThat; @Category(BuildVerification.class) public class ApiTester extends DbTestBase { private static final Logger logger = getLogger(ApiTester.class); private static SelfHostServer server; private static CassieqApi client; public ApiTester() throws NoSuchAlgorithmException, InvalidKeyException { } @BeforeClass public static void setup() throws InterruptedException, NoSuchAlgorithmException, InvalidKeyException { server = new SelfHostServer(new InMemorySessionProvider(session), new HazelcastTestModule("api-tester")); server.start(); server.getService().waitForRun(); client = CassieqApi.createClient(server.getBaseUri().toString(), getTestAccountCredentials(server.getService().getGuiceBundleProvider().getInjector())); } @AfterClass public static void cleanup() { server.stop(); } @Test public void put_into_deleted_queue_fails() throws IOException { final QueueName queueName = QueueName.valueOf("put_into_deleted_queue_fails"); client.createQueue(testAccountName, new QueueCreateOptions(queueName)).execute(); client.deleteQueue(testAccountName, queueName).execute(); final Response<ResponseBody> result = client.addMessage(testAccountName, queueName, "foo").execute(); assertThat(result.isSuccess()).isFalse(); } @Test public void create_queue_with_invalid_name_fails() throws IOException { final QueueName queueName = QueueName.valueOf("invalid!"); final Response<ResponseBody> execute = client.createQueue(testAccountName, new QueueCreateOptions(queueName)).execute(); assertThat(execute.isSuccess()).isFalse(); } @Test public void create_queue_with_dots_works() throws IOException { final QueueName queueName = QueueName.valueOf("create.queue.with.dots.works"); final Response<ResponseBody> execute = client.createQueue(testAccountName, new QueueCreateOptions(queueName)).execute(); assertThat(execute.isSuccess()).isTrue(); } @Test public void create_account_with_dots_works() throws IOException { final AccountName accountName = AccountName.valueOf("create.account.with.dots.works"); final AdminClient adminClient = AdminClient.createClient(server.getAdminuri().toString()); final Response<AccountDefinition> execute = adminClient.createAccount(accountName).execute(); assertThat(execute.isSuccess()).isTrue(); } @Test public void test_client_can_create_put_and_ack() throws Exception { final QueueName queueName = QueueName.valueOf("test_client_can_create_put_and_ack"); client.createQueue(testAccountName, new QueueCreateOptions(queueName)).execute(); client.addMessage(testAccountName, queueName, "hi").execute(); getTestClock().tick(); final Response<GetMessageResponse> message = client.getMessage(testAccountName, queueName).execute(); final GetMessageResponse body = message.body(); assertThat(body).isNotNull(); final String popReceipt = body.getPopReceipt(); assertThat(popReceipt).isNotNull(); final Response<ResponseBody> ackResponse = client.ackMessage(testAccountName, queueName, popReceipt).execute(); assertThat(ackResponse.isSuccess()).isTrue(); } @Test public void test_query_auth_authorizes() throws InvalidKeyException, NoSuchAlgorithmException, IOException { final AdminClient adminClient = AdminClient.createClient(server.getAdminuri().toString()); final AccountName accountName = AccountName.valueOf("test_query_auth_authorizes"); final Response<AccountDefinition> createAccountResponse = adminClient.createAccount(accountName).execute(); assertThat(createAccountResponse.isSuccess()).isTrue(); final GetAuthQueryParamsRequest getAuthQueryParamsRequest = new GetAuthQueryParamsRequest(accountName, KeyName.valueOf(WellKnownKeyNames.Primary.getKeyName()), Collections.singletonList(AuthorizationLevel.CreateQueue), Optional.empty(), Optional.empty()); final QueryAuthUrlResult result = adminClient.createPermissions(getAuthQueryParamsRequest).execute().body(); final String queryParam = result.getQueryParam(); final CassieqApi client = CassieqApi.createClient(server.getBaseUri().toString(), CassieqCredentials.signedQueryString(queryParam)); final Response<ResponseBody> authAuthorizes = client.createQueue(accountName, new QueueCreateOptions(QueueName.valueOf("test_query_auth_authorizes"))) .execute(); assertThat(authAuthorizes.isSuccess()).isTrue(); } @Test public void test_query_auth_authenticates() throws IOException, InvalidKeyException, NoSuchAlgorithmException { final AdminClient adminClient = AdminClient.createClient(server.getAdminuri().toString()); final AccountName accountName = AccountName.valueOf("test_query_auth_authenticates"); adminClient.createAccount(accountName).execute(); final GetAuthQueryParamsRequest getAuthQueryParamsRequest = new GetAuthQueryParamsRequest(accountName, KeyName.valueOf(WellKnownKeyNames.Primary.getKeyName()), Collections.singletonList(AuthorizationLevel.ReadMessage), Optional.empty(), Optional.empty()); final QueryAuthUrlResult result = adminClient.createPermissions(getAuthQueryParamsRequest).execute().body(); final String queryParam = result.getQueryParam(); final CassieqApi client = CassieqApi.createClient(server.getBaseUri().toString(), CassieqCredentials.signedQueryString(queryParam)); final Response<ResponseBody> authAuthorizes = client.createQueue(accountName, new QueueCreateOptions(QueueName.valueOf("test_query_auth_authenticates"))) .execute(); assertThat(authAuthorizes.isSuccess()).isFalse(); // unauthorized assertThat(authAuthorizes.code()).isEqualTo(403); } @Test public void test_query_auth_authenticates_with_end_time() throws IOException, InvalidKeyException, NoSuchAlgorithmException { final AdminClient adminClient = AdminClient.createClient(server.getAdminuri().toString()); final AccountName accountName = AccountName.valueOf("test_query_auth_authenticates_with_end_time"); adminClient.createAccount(accountName).execute(); final GetAuthQueryParamsRequest getAuthQueryParamsRequest = new GetAuthQueryParamsRequest(accountName, KeyName.valueOf(WellKnownKeyNames.Primary.getKeyName()), Collections.singletonList(AuthorizationLevel.CreateQueue), Optional.empty(), Optional.of(DateTime.now(DateTimeZone.UTC).plus(Period.days(5)))); final QueryAuthUrlResult result = adminClient.createPermissions(getAuthQueryParamsRequest).execute().body(); final String queryParam = result.getQueryParam(); final CassieqApi client = CassieqApi.createClient(server.getBaseUri().toString(), CassieqCredentials.signedQueryString(queryParam)); final Response<ResponseBody> authAuthorizes = client.createQueue(accountName, new QueueCreateOptions(QueueName.valueOf("test_query_auth_authenticates"))) .execute(); assertThat(authAuthorizes.isSuccess()).isTrue(); } @Test public void test_invalid_key_name_fails() throws IOException, InvalidKeyException, NoSuchAlgorithmException { final AdminClient adminClient = AdminClient.createClient(server.getAdminuri().toString()); final AccountName accountName = AccountName.valueOf("test_invalid_key_name_fails"); adminClient.createAccount(accountName).execute(); final GetAuthQueryParamsRequest getAuthQueryParamsRequest = new GetAuthQueryParamsRequest(accountName, KeyName.valueOf("invalid!"), Collections.singletonList(AuthorizationLevel.CreateQueue), Optional.empty(), Optional.of(DateTime.now(DateTimeZone.UTC).plus(Period.days(5)))); final Boolean result = adminClient.createPermissions(getAuthQueryParamsRequest).execute().isSuccess(); assertThat(result).isFalse(); } @Test public void test_query_auth_expires_with_end_time() throws IOException, InvalidKeyException, NoSuchAlgorithmException { final AdminClient adminClient = AdminClient.createClient(server.getAdminuri().toString()); final AccountName accountName = AccountName.valueOf("test_query_auth_expires_with_end_time"); adminClient.createAccount(accountName).execute(); final GetAuthQueryParamsRequest getAuthQueryParamsRequest = new GetAuthQueryParamsRequest(accountName, KeyName.valueOf(WellKnownKeyNames.Primary.getKeyName()), Collections.singletonList(AuthorizationLevel.CreateQueue), Optional.empty(), Optional.of(DateTime.now(DateTimeZone.UTC).minus(Period.seconds(3)))); final QueryAuthUrlResult result = adminClient.createPermissions(getAuthQueryParamsRequest).execute().body(); final String queryParam = result.getQueryParam(); final CassieqApi client = CassieqApi.createClient(server.getBaseUri().toString(), CassieqCredentials.signedQueryString(queryParam)); final Response<ResponseBody> authAuthorizes = client.createQueue(accountName, new QueueCreateOptions(QueueName.valueOf("test_query_auth_authenticates"))) .execute(); assertThat(authAuthorizes.isSuccess()).isFalse(); assertThat(authAuthorizes.code()).isEqualTo(401); } /** * Invalid signature * * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws IOException */ @Test public void test_query_auth_prevents_invalid_authentiation() throws InvalidKeyException, NoSuchAlgorithmException, IOException { final AdminClient adminClient = AdminClient.createClient(server.getAdminuri().toString()); final AccountName accountName = AccountName.valueOf("test_query_auth_prevents_invalid_authentiation"); adminClient.createAccount(accountName).execute(); final GetAuthQueryParamsRequest getAuthQueryParamsRequest = new GetAuthQueryParamsRequest(accountName, KeyName.valueOf(WellKnownKeyNames.Primary.getKeyName()), Collections.singletonList(AuthorizationLevel.CreateQueue), Optional.empty(), Optional.empty()); final QueryAuthUrlResult result = adminClient.createPermissions(getAuthQueryParamsRequest).execute().body(); final String queryParam = result.getQueryParam(); final CassieqApi client = CassieqApi.createClient(server.getBaseUri().toString(), CassieqCredentials.signedQueryString(queryParam + "fail")); final Response<ResponseBody> authAuthorizes = client.createQueue(accountName, new QueueCreateOptions(QueueName.valueOf("test_query_auth_prevents_invalid_authentiation"))) .execute(); assertThat(authAuthorizes.isSuccess()).isFalse(); // unauthenticated assertThat(authAuthorizes.code()).isEqualTo(401); } @Test public void test_revoked_key_prevents_authentiation() throws InvalidKeyException, NoSuchAlgorithmException, IOException { final AdminClient adminClient = AdminClient.createClient(server.getAdminuri().toString()); final AccountName accountName = AccountName.valueOf("test_revoked_key_prevents_authentiation"); adminClient.createAccount(accountName).execute(); final GetAuthQueryParamsRequest getAuthQueryParamsRequest = new GetAuthQueryParamsRequest(accountName, KeyName.valueOf(WellKnownKeyNames.Primary.getKeyName()), Collections.singletonList(AuthorizationLevel.CreateQueue), Optional.empty(), Optional.empty()); final QueryAuthUrlResult result = adminClient.createPermissions(getAuthQueryParamsRequest).execute().body(); final String queryParam = result.getQueryParam(); final CassieqApi client = CassieqApi.createClient(server.getBaseUri().toString(), CassieqCredentials.signedQueryString(queryParam)); final Response<ResponseBody> authAuthorizes = client.createQueue(accountName, new QueueCreateOptions(QueueName.valueOf("test_revoked_key_prevents_authentiation"))) .execute(); assertThat(authAuthorizes.isSuccess()).isTrue(); adminClient.deleteAccountKey(accountName, WellKnownKeyNames.Primary.getKeyName()).execute(); final Response<ResponseBody> usingOldCreds = client.createQueue(accountName, new QueueCreateOptions(QueueName.valueOf("test_revoked_key_prevents_authentiation_failure"))) .execute(); // unauthenticated since key was revoked assertThat(usingOldCreds.code()).isEqualTo(401); } @Test public void demo_invis_client() throws Exception { final QueueName queueName = QueueName.valueOf("demo_invis_client"); client.createQueue(testAccountName, new QueueCreateOptions(queueName)).execute(); int count = 21; for (int i = 0; i < count; i++) { client.addMessage(testAccountName, queueName, Integer.valueOf(i).toString()).execute(); } int c = -1; while (true) { c++; final Response<GetMessageResponse> message = client.getMessage(testAccountName, queueName, 1L).execute(); final GetMessageResponse body = message.body(); if (body == null) { break; } assertThat(body).isNotNull(); final String popReceipt = body.getPopReceipt(); System.out.println(String.format("Message id: %s, Delivery count %s", body.getMessage(), body.getDeliveryCount())); if (c == 0 || c == 10) { // message times out System.out.println("WAIT"); Thread.sleep(2000); continue; } else { assertThat(popReceipt).isNotNull(); final Response<ResponseBody> ackResponse = client.ackMessage(testAccountName, queueName, popReceipt).execute(); System.out.println("ACK"); assertThat(ackResponse.isSuccess()).isTrue(); } } } @Test public void delete_queue() throws IOException { final QueueName delete_queue = QueueName.valueOf("delete_queue"); client.createQueue(testAccountName, new QueueCreateOptions(delete_queue)).execute(); assertThat(client.deleteQueue(testAccountName, delete_queue).execute().isSuccess()).isTrue(); assertThat(client.getMessage(testAccountName, delete_queue).execute().isSuccess()).isFalse(); } @Test public void update_message() throws Exception { final QueueName delete_queue = QueueName.valueOf("update_message"); client.createQueue(testAccountName, new QueueCreateOptions(delete_queue)).execute(); client.addMessage(testAccountName, delete_queue, "foo").execute(); final GetMessageResponse body = client.getMessage(testAccountName, delete_queue).execute().body(); final UpdateMessageResponse updateResponse = client.updateMessage( testAccountName, delete_queue, body.getPopReceipt(), new UpdateMessageRequest("foo2", 10L)).execute() .body(); client.ackMessage(testAccountName, delete_queue, updateResponse.getPopReceipt()).execute(); assertThat(client.getMessage(testAccountName, delete_queue).execute().code()).isEqualTo(javax.ws.rs.core.Response.Status.NO_CONTENT.getStatusCode()); } @Test(timeout = 30000) @Category(VerySlowTests.class) public void test_invis_like_crazy() throws Exception { final QueueName queueName = QueueName.valueOf("test"); client.createQueue(testAccountName, new QueueCreateOptions(queueName)).execute(); int count = 100; for (int i = 0; i < count; i++) { client.addMessage(testAccountName, queueName, Integer.valueOf(i).toString()).execute(); } GetMessageResponse body; int i = 0; while ((body = getMessage(client, queueName)) != null && count > 0) { final String popReceipt = body.getPopReceipt(); System.out.println(String.format("Message id: %s, Delivery count %s", body.getMessage(), body.getDeliveryCount())); if (i++ % 20 == 0 && body.getDeliveryCount() < 4) { // message times out Thread.sleep(3000); } else { assertThat(popReceipt).isNotNull(); final Response<ResponseBody> ackResponse = client.ackMessage(testAccountName, queueName, popReceipt).execute(); assertThat(ackResponse.isSuccess()).isTrue(); count } } } private GetMessageResponse getMessage(final CassieqApi client, final QueueName queueName) throws java.io.IOException { final Response<GetMessageResponse> message = client.getMessage(testAccountName, queueName, 3L).execute(); return message.body(); } }
package org.realityforge.arez.test; import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nonnull; import org.realityforge.arez.AbstractArezTest; import org.realityforge.arez.ArezContext; import org.realityforge.arez.ComputedValue; import org.realityforge.arez.Observable; import org.realityforge.arez.Observer; import org.realityforge.arez.ObserverErrorHandler; import org.realityforge.arez.Procedure; import org.realityforge.guiceyloops.shared.ValueUtil; import org.testng.annotations.Test; import static org.testng.Assert.*; /** * This class tests all the public API of Arez and identifies all * the elements that should be visible outside package. */ public class ExternalApiTest extends AbstractArezTest { @Test public void areNamesEnabled() throws Exception { final ArezContext context = new ArezContext(); assertTrue( context.areNamesEnabled() ); } @Test public void createComputedValue() throws Exception { final ArezContext context = new ArezContext(); final String name = ValueUtil.randomString(); final ComputedValue<String> computedValue = context.createComputedValue( name, () -> "", Objects::equals ); context.procedure( ValueUtil.randomString(), false, () -> { assertEquals( computedValue.getName(), name ); assertEquals( computedValue.get(), "" ); computedValue.dispose(); assertThrows( computedValue::get ); } ); } @Test public void createReactionObserver() throws Exception { final ArezContext context = new ArezContext(); final AtomicInteger callCount = new AtomicInteger(); final String name = ValueUtil.randomString(); final Observer observer = context.autorun( name, false, callCount::incrementAndGet, true ); assertEquals( observer.getName(), name ); assertEquals( observer.isActive(), true ); assertEquals( callCount.get(), 1 ); observer.dispose(); assertEquals( observer.isActive(), false ); } @Test public void observerErrorHandler() throws Exception { final ArezContext context = new ArezContext(); final AtomicInteger callCount = new AtomicInteger(); final ObserverErrorHandler handler = ( observer, error, throwable ) -> callCount.incrementAndGet(); context.addObserverErrorHandler( handler ); final Procedure reaction = () -> { throw new RuntimeException(); }; // This will run immediately and generate an exception context.autorun( ValueUtil.randomString(), false, reaction, true ); assertEquals( callCount.get(), 1 ); context.removeObserverErrorHandler( handler ); // This will run immediately and generate an exception context.autorun( ValueUtil.randomString(), false, reaction, true ); assertEquals( callCount.get(), 1 ); } @Test public void interactionWithSingleObservable() throws Exception { final ArezContext context = new ArezContext(); final Observable observable = context.createObservable( ValueUtil.randomString() ); final AtomicInteger reactionCount = new AtomicInteger(); final Observer observer = context.autorun( ValueUtil.randomString(), false, () -> { observable.reportObserved(); reactionCount.incrementAndGet(); }, true ); assertEquals( reactionCount.get(), 1 ); assertEquals( observer.isActive(), true ); // Run an "action" context.procedure( ValueUtil.randomString(), true, observable::reportChanged ); assertEquals( reactionCount.get(), 2 ); assertEquals( observer.isActive(), true ); } @Test public void interactionWithMultipleObservable() throws Exception { final ArezContext context = new ArezContext(); final Observable observable1 = context.createObservable( ValueUtil.randomString() ); final Observable observable2 = context.createObservable( ValueUtil.randomString() ); final Observable observable3 = context.createObservable( ValueUtil.randomString() ); final Observable observable4 = context.createObservable( ValueUtil.randomString() ); final AtomicInteger reactionCount = new AtomicInteger(); final Observer observer = context.autorun( ValueUtil.randomString(), false, () -> { observable1.reportObserved(); observable2.reportObserved(); observable3.reportObserved(); reactionCount.incrementAndGet(); }, true ); assertEquals( reactionCount.get(), 1 ); assertEquals( observer.isActive(), true ); // Run an "action" context.procedure( ValueUtil.randomString(), true, observable1::reportChanged ); assertEquals( reactionCount.get(), 2 ); assertEquals( observer.isActive(), true ); // Update observer1+observer2 in transaction context.procedure( ValueUtil.randomString(), true, () -> { observable1.reportChanged(); observable2.reportChanged(); } ); assertEquals( reactionCount.get(), 3 ); assertEquals( observer.isActive(), true ); context.procedure( ValueUtil.randomString(), true, () -> { observable3.reportChanged(); observable4.reportChanged(); } ); assertEquals( reactionCount.get(), 4 ); assertEquals( observer.isActive(), true ); // observable4 should not cause a reaction as not observed context.procedure( ValueUtil.randomString(), true, observable4::reportChanged ); assertEquals( reactionCount.get(), 4 ); assertEquals( observer.isActive(), true ); } @Test public void function() throws Exception { final ArezContext context = new ArezContext(); final Observable observable = context.createObservable( ValueUtil.randomString() ); assertNotInTransaction( observable ); final String expectedValue = ValueUtil.randomString(); final String v0 = context.function( ValueUtil.randomString(), false, () -> { assertInTransaction( observable ); return expectedValue; } ); assertNotInTransaction( observable ); assertEquals( v0, expectedValue ); } @Test public void safeFunction() throws Exception { final ArezContext context = new ArezContext(); final Observable observable = context.createObservable( ValueUtil.randomString() ); assertNotInTransaction( observable ); final String expectedValue = ValueUtil.randomString(); final String v0 = context.safeFunction( ValueUtil.randomString(), false, () -> { assertInTransaction( observable ); return expectedValue; } ); assertNotInTransaction( observable ); assertEquals( v0, expectedValue ); } @Test public void proceduresCanBeNested() throws Exception { final ArezContext context = new ArezContext(); final Observable observable = context.createObservable( ValueUtil.randomString() ); assertNotInTransaction( observable ); context.procedure( ValueUtil.randomString(), false, () -> { assertInTransaction( observable ); //First nested exception context.procedure( ValueUtil.randomString(), false, () -> { assertInTransaction( observable ); //Second nested exception context.procedure( ValueUtil.randomString(), false, () -> assertInTransaction( observable ) ); assertInTransaction( observable ); } ); assertInTransaction( observable ); } ); assertNotInTransaction( observable ); } @Test public void nestedFunctions() throws Exception { final ArezContext context = new ArezContext(); final Observable observable = context.createObservable( ValueUtil.randomString() ); assertNotInTransaction( observable ); final String expectedValue = ValueUtil.randomString(); final String v0 = context.function( ValueUtil.randomString(), false, () -> { assertInTransaction( observable ); //First nested exception final String v1 = context.function( ValueUtil.randomString(), false, () -> { assertInTransaction( observable ); //Second nested exception final String v2 = context.function( ValueUtil.randomString(), false, () -> { assertInTransaction( observable ); return expectedValue; } ); assertInTransaction( observable ); return v2; } ); assertInTransaction( observable ); return v1; } ); assertNotInTransaction( observable ); assertEquals( v0, expectedValue ); } /** * Test we are in a transaction by trying to observe an observable. */ private void assertInTransaction( @Nonnull final Observable observable ) { observable.reportObserved(); } /** * Test we are not in a transaction by trying to observe an observable. */ private void assertNotInTransaction( @Nonnull final Observable observable ) { assertThrows( observable::reportObserved ); } }
package nl.mpi.kinnate.gedcomimport; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import javax.swing.JTextArea; import nl.mpi.arbil.util.ArbilBugCatcher; import nl.mpi.kinnate.kindata.DataTypes.RelationType; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; public class CsvImporter extends EntityImporter implements GenericImporter { public CsvImporter(boolean overwriteExistingLocal) { super(overwriteExistingLocal); } @Override public boolean canImport(String inputFileString) { return (inputFileString.toLowerCase().endsWith(".csv")); } private String cleanCsvString(String valueString) { valueString = valueString.replaceAll("^\"", ""); valueString = valueString.replaceAll("\"$", ""); valueString = valueString.replaceAll("\"\"", ""); return valueString; } @Override public URI[] importFile(JTextArea importTextArea, InputStreamReader inputStreamReader) { ArrayList<URI> createdNodes = new ArrayList<URI>(); HashMap<String, EntityDocument> createdDocuments = new HashMap<String, EntityDocument>(); createdNodeIds = new HashMap<String, ArrayList<UniqueIdentifier>>(); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); File destinationDirectory = super.getDestinationDirectory(); String inputLine; try { int maxImportCount = 10; // "ID","Gender","Name1","Name2","Name3","Name4","Name5","Name6","Date of Birth","Date of Death","sub_group","Parents1-ID","Parents1-Gender","Parents1-Name1","Parents1-Name2","Parents1-Name3","Parents1-Name4","Parents1-Name5","Parents1-Name6","Parents1-Date of Birth","Parents1-Date of Death","Parents1-sub_group","Parents2-ID","Parents2-Gender","Parents2-Name1","Parents2-Name2","Parents2-Name3","Parents2-Name4","Parents2-Name5","Parents2-Name6","Parents2-Date of Birth","Parents2-Date of Death","Parents2-sub_group","Spouses1-ID","Spouses1-Gender","Spouses1-Name1","Spouses1-Name2","Spouses1-Name3","Spouses1-Name4","Spouses1-Name5","Spouses1-Name6","Spouses1-Date of Birth","Spouses1-Date of Death","Spouses1-sub_group","Spouses2-ID","Spouses2-Gender","Spouses2-Name1","Spouses2-Name2","Spouses2-Name3","Spouses2-Name4","Spouses2-Name5","Spouses2-Name6","Spouses2-Date of Birth","Spouses2-Date of Death","Spouses2-sub_group","Spouses3-ID","Spouses3-Gender","Spouses3-Name1","Spouses3-Name2","Spouses3-Name3","Spouses3-Name4","Spouses3-Name5","Spouses3-Name6","Spouses3-Date of Birth","Spouses3-Date of Death","Spouses3-sub_group","Spouses4-ID","Spouses4-Gender","Spouses4-Name1","Spouses4-Name2","Spouses4-Name3","Spouses4-Name4","Spouses4-Name5","Spouses4-Name6","Spouses4-Date of Birth","Spouses4-Date of Death","Spouses4-sub_group","Spouses5-ID","Spouses5-Gender","Spouses5-Name1","Spouses5-Name2","Spouses5-Name3","Spouses5-Name4","Spouses5-Name5","Spouses5-Name6","Spouses5-Date of Birth","Spouses5-Date of Death","Spouses5-sub_group","Spouses6-ID","Spouses6-Gender","Spouses6-Name1","Spouses6-Name2","Spouses6-Name3","Spouses6-Name4","Spouses6-Name5","Spouses6-Name6","Spouses6-Date of Birth","Spouses6-Date of Death","Spouses6-sub_group","Children1-ID","Children1-Gender","Children1-Name1","Children1-Name2","Children1-Name3","Children1-Name4","Children1-Name5","Children1-Name6","Children1-Date of Birth","Children1-Date of Death","Children1-sub_group","Children2-ID","Children2-Gender","Children2-Name1","Children2-Name2","Children2-Name3","Children2-Name4","Children2-Name5","Children2-Name6","Children2-Date of Birth","Children2-Date of Death","Children2-sub_group","Children3-ID","Children3-Gender","Children3-Name1","Children3-Name2","Children3-Name3","Children3-Name4","Children3-Name5","Children3-Name6","Children3-Date of Birth","Children3-Date of Death","Children3-sub_group","Children4-ID","Children4-Gender","Children4-Name1","Children4-Name2","Children4-Name3","Children4-Name4","Children4-Name5","Children4-Name6","Children4-Date of Birth","Children4-Date of Death","Children4-sub_group","Children5-ID","Children5-Gender","Children5-Name1","Children5-Name2","Children5-Name3","Children5-Name4","Children5-Name5","Children5-Name6","Children5-Date of Birth","Children5-Date of Death","Children5-sub_group","Children6-ID","Children6-Gender","Children6-Name1","Children6-Name2","Children6-Name3","Children6-Name4","Children6-Name5","Children6-Name6","Children6-Date of Birth","Children6-Date of Death","Children6-sub_group","Children7-ID","Children7-Gender","Children7-Name1","Children7-Name2","Children7-Name3","Children7-Name4","Children7-Name5","Children7-Name6","Children7-Date of Birth","Children7-Date of Death","Children7-sub_group","Children8-ID","Children8-Gender","Children8-Name1","Children8-Name2","Children8-Name3","Children8-Name4","Children8-Name5","Children8-Name6","Children8-Date of Birth","Children8-Date of Death","Children8-sub_group","Children9-ID","Children9-Gender","Children9-Name1","Children9-Name2","Children9-Name3","Children9-Name4","Children9-Name5","Children9-Name6","Children9-Date of Birth","Children9-Date of Death","Children9-sub_group","Children10-ID","Children10-Gender","Children10-Name1","Children10-Name2","Children10-Name3","Children10-Name4","Children10-Name5","Children10-Name6","Children10-Date of Birth","Children10-Date of Death","Children10-sub_group","Children11-ID","Children11-Gender","Children11-Name1","Children11-Name2","Children11-Name3","Children11-Name4","Children11-Name5","Children11-Name6","Children11-Date of Birth","Children11-Date of Death","Children11-sub_group","Children12-ID","Children12-Gender","Children12-Name1","Children12-Name2","Children12-Name3","Children12-Name4","Children12-Name5","Children12-Name6","Children12-Date of Birth","Children12-Date of Death","Children12-sub_group","Children13-ID","Children13-Gender","Children13-Name1","Children13-Name2","Children13-Name3","Children13-Name4","Children13-Name5","Children13-Name6","Children13-Date of Birth","Children13-Date of Death","Children13-sub_group","Children14-ID","Children14-Gender","Children14-Name1","Children14-Name2","Children14-Name3","Children14-Name4","Children14-Name5","Children14-Name6","Children14-Date of Birth","Children14-Date of Death","Children14-sub_group","Children15-ID","Children15-Gender","Children15-Name1","Children15-Name2","Children15-Name3","Children15-Name4","Children15-Name5","Children15-Name6","Children15-Date of Birth","Children15-Date of Death","Children15-sub_group","Children16-ID","Children16-Gender","Children16-Name1","Children16-Name2","Children16-Name3","Children16-Name4","Children16-Name5","Children16-Name6","Children16-Date of Birth","Children16-Date of Death","Children16-sub_group","Children17-ID","Children17-Gender","Children17-Name1","Children17-Name2","Children17-Name3","Children17-Name4","Children17-Name5","Children17-Name6","Children17-Date of Birth","Children17-Date of Death","Children17-sub_group","Children18-ID","Children18-Gender","Children18-Name1","Children18-Name2","Children18-Name3","Children18-Name4","Children18-Name5","Children18-Name6","Children18-Date of Birth","Children18-Date of Death","Children18-sub_group","Children19-ID","Children19-Gender","Children19-Name1","Children19-Name2","Children19-Name3","Children19-Name4","Children19-Name5","Children19-Name6","Children19-Date of Birth","Children19-Date of Death","Children19-sub_group","Children20-ID","Children20-Gender","Children20-Name1","Children20-Name2","Children20-Name3","Children20-Name4","Children20-Name5","Children20-Name6","Children20-Date of Birth","Children20-Date of Death","Children20-sub_group" String headingLine = bufferedReader.readLine(); if (headingLine != null) { ArrayList<String> allHeadings = new ArrayList<String>(); for (String headingString : headingLine.split(",")) { String cleanHeading = cleanCsvString(headingString); allHeadings.add(cleanHeading); // appendToTaskOutput(importTextArea, "Heading: " + cleanHeading); } try { while ((inputLine = bufferedReader.readLine()) != null) { EntityDocument currentEntity = null; EntityDocument relatedEntity = null; String relatedEntityPrefix = null; int valueCount = 0; for (String entityLineString : inputLine.split(",")) { String cleanValue = cleanCsvString(entityLineString); String headingString = allHeadings.get(valueCount); if (currentEntity == null) { currentEntity = getEntityDocument(importTextArea, destinationDirectory, createdDocuments, createdNodes, cleanValue); } else if (cleanValue.length() > 0) { if (headingString.matches("Spouses[\\d]*-ID")) { relatedEntity = getEntityDocument(importTextArea, destinationDirectory, createdDocuments, createdNodes, cleanValue); currentEntity.insertRelation(relatedEntity.entityData, RelationType.union, relatedEntity.getFileName()); relatedEntityPrefix = headingString.substring(0, headingString.length() - "ID".length()); } else if (headingString.matches("Parents[\\d]*-ID")) { relatedEntity = getEntityDocument(importTextArea, destinationDirectory, createdDocuments, createdNodes, cleanValue); currentEntity.insertRelation(relatedEntity.entityData, RelationType.ancestor, relatedEntity.getFileName()); relatedEntityPrefix = headingString.substring(0, headingString.length() - "ID".length()); } else if (headingString.matches("Children[\\d]*-ID")) { relatedEntity = getEntityDocument(importTextArea, destinationDirectory, createdDocuments, createdNodes, cleanValue); currentEntity.insertRelation(relatedEntity.entityData, RelationType.descendant, relatedEntity.getFileName()); relatedEntityPrefix = headingString.substring(0, headingString.length() - "ID".length()); } else if (relatedEntityPrefix != null && headingString.startsWith(relatedEntityPrefix)) { relatedEntity.insertValue(headingString.substring(relatedEntityPrefix.length()), cleanValue); appendToTaskOutput(importTextArea, "Setting value in related entity: " + allHeadings.get(valueCount) + " : " + cleanValue); // appendToTaskOutput(importTextArea, "Ignoring: " + allHeadings.get(valueCount) + " : " + cleanValue); } else if (headingString.equals("Gender")) { String genderString = cleanValue; if ("0".equals(cleanValue)) { genderString = "female"; // currentEntity.entityData.setSymbolType(SymbolType.circle); } else if ("1".equals(cleanValue)) { genderString = "male"; // currentEntity.entityData.setSymbolType(SymbolType.triangle); } else { throw new ImportException("Unknown gender type: " + genderString); } currentEntity.insertValue(headingString, genderString); appendToTaskOutput(importTextArea, "Setting value: " + allHeadings.get(valueCount) + " : " + cleanValue); } else { currentEntity.insertValue(headingString, cleanValue); appendToTaskOutput(importTextArea, "Setting value: " + allHeadings.get(valueCount) + " : " + cleanValue); } } valueCount++; } // if (maxImportCount-- < 0) { // appendToTaskOutput(importTextArea, "Aborting import due to max testing limit"); // break; } } catch (ImportException exception) { appendToTaskOutput(importTextArea, exception.getMessage()); } } appendToTaskOutput(importTextArea, "Saving all documents"); for (EntityDocument currentDocument : createdDocuments.values()) { // todo: add progress for this try { currentDocument.saveDocument(); } catch (ImportException exception) { new ArbilBugCatcher().logError(exception); appendToTaskOutput(importTextArea, "Error saving file: " + exception.getMessage()); } // appendToTaskOutput(importTextArea, "saved: " + currentDocument.getFilePath()); } } catch (IOException exception) { new ArbilBugCatcher().logError(exception); appendToTaskOutput(importTextArea, "Error: " + exception.getMessage()); } return createdNodes.toArray(new URI[]{}); } }
package nl.mpi.kinnate.gedcomimport; import nl.mpi.kinnate.kindocument.EntityDocument; import nl.mpi.kinnate.kindocument.ImportTranslator; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.util.ArrayList; import javax.swing.JProgressBar; import javax.swing.JTextArea; import nl.mpi.arbil.userstorage.SessionStorage; import nl.mpi.arbil.util.ArbilBugCatcher; import nl.mpi.kinnate.kindata.DataTypes.RelationLineType; import nl.mpi.kinnate.kindata.DataTypes.RelationType; public class CsvImporter extends EntityImporter implements GenericImporter { public CsvImporter(JProgressBar progressBarLocal, JTextArea importTextAreaLocal, boolean overwriteExistingLocal, SessionStorage sessionStorage) { super(progressBarLocal, importTextAreaLocal, overwriteExistingLocal, sessionStorage); } @Override public boolean canImport(String inputFileString) { return (inputFileString.toLowerCase().endsWith(".csv")); } @Deprecated private String cleanCsvString(String valueString) { valueString = valueString.replaceAll("^\"", ""); valueString = valueString.replaceAll("\"$", ""); valueString = valueString.replaceAll("\"\"", ""); return valueString; } // private char detectFieldDelimiter(BufferedReader bufferedReader) throws IOException { // int tabCounter = 0; // int commaCounter = 0; // outerLoop: // for (int charCount = 0; charCount < 1000; charCount++) { // try { // switch (bufferedReader.read()) { // case -1: // case '\n': // case '\r': // break outerLoop; // case ',': // commaCounter++; // break; // case '\t': // tabCounter++; // break; // } catch (IOException exception) { // appendToTaskOutput("Failed to test the file type"); // throw exception; // char fieldSeparator; // if (commaCounter > tabCounter) { // fieldSeparator = ','; // appendToTaskOutput("Comma separated file detected"); // } else { // fieldSeparator = '\t'; // appendToTaskOutput("Tab separated file detected"); // return fieldSeparator; private ArrayList<String> getFieldForLine(BufferedReader bufferedReader /*, char fieldSeparator*/) throws IOException { ArrayList<String> lineFields = new ArrayList<String>(); StringBuilder stringBuilder = new StringBuilder(); try { int readChar = bufferedReader.read(); while (readChar != -1) { switch (readChar) { case -1: case '\n': case '\r': return lineFields; case '"': boolean insideQuotes = true; int quotedCharsCount = 0; while (insideQuotes) { // ignore all the chars between quotes final int readQuoted = bufferedReader.read(); if (readQuoted == -1) { appendToTaskOutput("Warning: file ended within a quoted section"); return lineFields; } quotedCharsCount++; insideQuotes = readQuoted != '"'; } if (quotedCharsCount < 1) { // todo: test that escaped quotes pass into the output correctly // allow "" excaped quotes to pass as a single quote into the output stringBuilder.append((char) readChar); } break; case ',': case '\t': lineFields.add(stringBuilder.toString()); stringBuilder = new StringBuilder(); break; default: stringBuilder.append((char) readChar); } // if (readChar == fieldSeparator) { // lineFields.add(stringBuilder.toString()); // } else { // stringBuilder.append(readChar); readChar = bufferedReader.read(); } } catch (IOException exception) { appendToTaskOutput("Failed to read lines of input file"); throw exception; } return lineFields; } @Override public URI[] importFile(InputStreamReader inputStreamReader) { ArrayList<URI> createdNodes = new ArrayList<URI>(); try { BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // char fieldSeparator = detectFieldDelimiter(bufferedReader); // restart at the begining of the file bufferedReader = new BufferedReader(inputStreamReader); // create the import translator ImportTranslator importTranslator = new ImportTranslator(true); importTranslator.addTranslationEntry("Gender", "0", "Gender", "female"); importTranslator.addTranslationEntry("Gender", "1", "Gender", "male"); importTranslator.addTranslationEntry("Gender", "f", "Gender", "female"); importTranslator.addTranslationEntry("Gender", "m", "Gender", "male"); ArrayList<String> allHeadings = getFieldForLine(bufferedReader /*, fieldSeparator */); super.incrementLineProgress(); // int maxImportCount = 10; // "ID","Gender","Name1","Name2","Name3","Name4","Name5","Name6","Date of Birth","Date of Death","sub_group","Parents1-ID","Parents1-Gender","Parents1-Name1","Parents1-Name2","Parents1-Name3","Parents1-Name4","Parents1-Name5","Parents1-Name6","Parents1-Date of Birth","Parents1-Date of Death","Parents1-sub_group","Parents2-ID","Parents2-Gender","Parents2-Name1","Parents2-Name2","Parents2-Name3","Parents2-Name4","Parents2-Name5","Parents2-Name6","Parents2-Date of Birth","Parents2-Date of Death","Parents2-sub_group","Spouses1-ID","Spouses1-Gender","Spouses1-Name1","Spouses1-Name2","Spouses1-Name3","Spouses1-Name4","Spouses1-Name5","Spouses1-Name6","Spouses1-Date of Birth","Spouses1-Date of Death","Spouses1-sub_group","Spouses2-ID","Spouses2-Gender","Spouses2-Name1","Spouses2-Name2","Spouses2-Name3","Spouses2-Name4","Spouses2-Name5","Spouses2-Name6","Spouses2-Date of Birth","Spouses2-Date of Death","Spouses2-sub_group","Spouses3-ID","Spouses3-Gender","Spouses3-Name1","Spouses3-Name2","Spouses3-Name3","Spouses3-Name4","Spouses3-Name5","Spouses3-Name6","Spouses3-Date of Birth","Spouses3-Date of Death","Spouses3-sub_group","Spouses4-ID","Spouses4-Gender","Spouses4-Name1","Spouses4-Name2","Spouses4-Name3","Spouses4-Name4","Spouses4-Name5","Spouses4-Name6","Spouses4-Date of Birth","Spouses4-Date of Death","Spouses4-sub_group","Spouses5-ID","Spouses5-Gender","Spouses5-Name1","Spouses5-Name2","Spouses5-Name3","Spouses5-Name4","Spouses5-Name5","Spouses5-Name6","Spouses5-Date of Birth","Spouses5-Date of Death","Spouses5-sub_group","Spouses6-ID","Spouses6-Gender","Spouses6-Name1","Spouses6-Name2","Spouses6-Name3","Spouses6-Name4","Spouses6-Name5","Spouses6-Name6","Spouses6-Date of Birth","Spouses6-Date of Death","Spouses6-sub_group","Children1-ID","Children1-Gender","Children1-Name1","Children1-Name2","Children1-Name3","Children1-Name4","Children1-Name5","Children1-Name6","Children1-Date of Birth","Children1-Date of Death","Children1-sub_group","Children2-ID","Children2-Gender","Children2-Name1","Children2-Name2","Children2-Name3","Children2-Name4","Children2-Name5","Children2-Name6","Children2-Date of Birth","Children2-Date of Death","Children2-sub_group","Children3-ID","Children3-Gender","Children3-Name1","Children3-Name2","Children3-Name3","Children3-Name4","Children3-Name5","Children3-Name6","Children3-Date of Birth","Children3-Date of Death","Children3-sub_group","Children4-ID","Children4-Gender","Children4-Name1","Children4-Name2","Children4-Name3","Children4-Name4","Children4-Name5","Children4-Name6","Children4-Date of Birth","Children4-Date of Death","Children4-sub_group","Children5-ID","Children5-Gender","Children5-Name1","Children5-Name2","Children5-Name3","Children5-Name4","Children5-Name5","Children5-Name6","Children5-Date of Birth","Children5-Date of Death","Children5-sub_group","Children6-ID","Children6-Gender","Children6-Name1","Children6-Name2","Children6-Name3","Children6-Name4","Children6-Name5","Children6-Name6","Children6-Date of Birth","Children6-Date of Death","Children6-sub_group","Children7-ID","Children7-Gender","Children7-Name1","Children7-Name2","Children7-Name3","Children7-Name4","Children7-Name5","Children7-Name6","Children7-Date of Birth","Children7-Date of Death","Children7-sub_group","Children8-ID","Children8-Gender","Children8-Name1","Children8-Name2","Children8-Name3","Children8-Name4","Children8-Name5","Children8-Name6","Children8-Date of Birth","Children8-Date of Death","Children8-sub_group","Children9-ID","Children9-Gender","Children9-Name1","Children9-Name2","Children9-Name3","Children9-Name4","Children9-Name5","Children9-Name6","Children9-Date of Birth","Children9-Date of Death","Children9-sub_group","Children10-ID","Children10-Gender","Children10-Name1","Children10-Name2","Children10-Name3","Children10-Name4","Children10-Name5","Children10-Name6","Children10-Date of Birth","Children10-Date of Death","Children10-sub_group","Children11-ID","Children11-Gender","Children11-Name1","Children11-Name2","Children11-Name3","Children11-Name4","Children11-Name5","Children11-Name6","Children11-Date of Birth","Children11-Date of Death","Children11-sub_group","Children12-ID","Children12-Gender","Children12-Name1","Children12-Name2","Children12-Name3","Children12-Name4","Children12-Name5","Children12-Name6","Children12-Date of Birth","Children12-Date of Death","Children12-sub_group","Children13-ID","Children13-Gender","Children13-Name1","Children13-Name2","Children13-Name3","Children13-Name4","Children13-Name5","Children13-Name6","Children13-Date of Birth","Children13-Date of Death","Children13-sub_group","Children14-ID","Children14-Gender","Children14-Name1","Children14-Name2","Children14-Name3","Children14-Name4","Children14-Name5","Children14-Name6","Children14-Date of Birth","Children14-Date of Death","Children14-sub_group","Children15-ID","Children15-Gender","Children15-Name1","Children15-Name2","Children15-Name3","Children15-Name4","Children15-Name5","Children15-Name6","Children15-Date of Birth","Children15-Date of Death","Children15-sub_group","Children16-ID","Children16-Gender","Children16-Name1","Children16-Name2","Children16-Name3","Children16-Name4","Children16-Name5","Children16-Name6","Children16-Date of Birth","Children16-Date of Death","Children16-sub_group","Children17-ID","Children17-Gender","Children17-Name1","Children17-Name2","Children17-Name3","Children17-Name4","Children17-Name5","Children17-Name6","Children17-Date of Birth","Children17-Date of Death","Children17-sub_group","Children18-ID","Children18-Gender","Children18-Name1","Children18-Name2","Children18-Name3","Children18-Name4","Children18-Name5","Children18-Name6","Children18-Date of Birth","Children18-Date of Death","Children18-sub_group","Children19-ID","Children19-Gender","Children19-Name1","Children19-Name2","Children19-Name3","Children19-Name4","Children19-Name5","Children19-Name6","Children19-Date of Birth","Children19-Date of Death","Children19-sub_group","Children20-ID","Children20-Gender","Children20-Name1","Children20-Name2","Children20-Name3","Children20-Name4","Children20-Name5","Children20-Name6","Children20-Date of Birth","Children20-Date of Death","Children20-sub_group" // String headingLine = bufferedReader.readLine(); try { boolean continueReading = true; while (continueReading) { ArrayList<String> lineFields = getFieldForLine(bufferedReader); continueReading = lineFields.size() > 0; EntityDocument currentEntity = null; EntityDocument relatedEntity = null; String relatedEntityPrefix = null; int valueCount = 0; for (String entityField : lineFields) { // String cleanValue = cleanCsvString(entityLineString); String headingString; if (allHeadings.size() > valueCount) { headingString = allHeadings.get(valueCount); } else { headingString = "-unnamed-field-"; appendToTaskOutput("Warning " + headingString + " for value: " + entityField); } if (currentEntity == null) { currentEntity = getEntityDocument(createdNodes, "Entity", entityField, importTranslator); } else if (entityField.length() > 0) { if (headingString.matches("Spouses[\\d]*-ID")) { relatedEntity = getEntityDocument(createdNodes, "Entity", entityField, importTranslator); currentEntity.entityData.addRelatedNode(relatedEntity.entityData, RelationType.union, RelationLineType.sanguineLine, null, null); relatedEntityPrefix = headingString.substring(0, headingString.length() - "ID".length()); } else if (headingString.matches("Parents[\\d]*-ID")) { relatedEntity = getEntityDocument(createdNodes, "Entity", entityField, importTranslator); currentEntity.entityData.addRelatedNode(relatedEntity.entityData, RelationType.ancestor, RelationLineType.sanguineLine, null, null); relatedEntityPrefix = headingString.substring(0, headingString.length() - "ID".length()); } else if (headingString.matches("Children[\\d]*-ID")) { relatedEntity = getEntityDocument(createdNodes, "Entity", entityField, importTranslator); currentEntity.entityData.addRelatedNode(relatedEntity.entityData, RelationType.descendant, RelationLineType.sanguineLine, null, null); relatedEntityPrefix = headingString.substring(0, headingString.length() - "ID".length()); } else if (relatedEntityPrefix != null && headingString.startsWith(relatedEntityPrefix)) { relatedEntity.insertValue(headingString.substring(relatedEntityPrefix.length()), entityField); // appendToTaskOutput("Setting value in related entity: " + allHeadings.get(valueCount) + " : " + cleanValue); // appendToTaskOutput(importTextArea, "Ignoring: " + allHeadings.get(valueCount) + " : " + cleanValue); } else { currentEntity.insertValue(headingString, entityField); // appendToTaskOutput("Setting value: " + allHeadings.get(valueCount) + " : " + cleanValue); } } valueCount++; } // if (maxImportCount-- < 0) { // appendToTaskOutput(importTextArea, "Aborting import due to max testing limit"); // break; super.incrementLineProgress(); } } catch (ImportException exception) { appendToTaskOutput(exception.getMessage()); } saveAllDocuments(); } catch (IOException exception) { new ArbilBugCatcher().logError(exception); appendToTaskOutput("Error: " + exception.getMessage()); } return createdNodes.toArray(new URI[]{}); } }
package org.drools.agent; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.StringReader; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.drools.KnowledgeBase; import org.drools.SystemEventListenerFactory; import org.drools.agent.impl.PrintStreamSystemEventListener; import org.drools.definition.process.Process; import org.drools.event.knowledgeagent.AfterChangeSetAppliedEvent; import org.drools.event.knowledgeagent.AfterChangeSetProcessedEvent; import org.drools.event.knowledgeagent.AfterResourceProcessedEvent; import org.drools.event.knowledgeagent.BeforeChangeSetAppliedEvent; import org.drools.event.knowledgeagent.BeforeChangeSetProcessedEvent; import org.drools.event.knowledgeagent.BeforeResourceProcessedEvent; import org.drools.event.knowledgeagent.KnowledgeAgentEventListener; import org.drools.event.knowledgeagent.KnowledgeBaseUpdatedEvent; import org.drools.event.knowledgeagent.ResourceCompilationFailedEvent; import org.drools.io.ResourceChangeScannerConfiguration; import org.drools.io.ResourceFactory; import org.drools.rule.Package; import org.junit.After; import org.junit.Test; public class KnowledgeAgentTest { private static final String CHANGE_SET = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> " + "<change-set xmlns=\"http://drools.org/drools-5.0/change-set\" " + "xmlns:xs=\"http: "xs:schemaLocation=\"http: "<add> " + "<resource source=\"{0}\" type=\"PKG\"/> " + "</add>" + "</change-set>"; @Test public void testRemoveRuleFlow() throws Exception { File tempDir = RuleBaseAssemblerTest.getTempDirectory(); String location = tempDir.getAbsolutePath() +File.separator + "p1.pkg"; Package p1 = new Package("dummy"); Process process1 = new DummyProcess("1","name"); p1.addProcess(process1); Process process2 = new DummyProcess("2","name2"); p1.addProcess(process2); RuleBaseAssemblerTest.writePackage(p1, new File(location)); final CountDownLatch latch = new CountDownLatch(2); String changeset = CHANGE_SET.replaceFirst("\\{0\\}", "file:"+location); ResourceChangeScannerConfiguration sconf = ResourceFactory.getResourceChangeScannerService().newResourceChangeScannerConfiguration(); sconf.setProperty( "drools.resource.scanner.interval", "1" ); ResourceFactory.getResourceChangeScannerService().configure( sconf ); ResourceFactory.getResourceChangeNotifierService().start(); ResourceFactory.getResourceChangeScannerService().start(); KnowledgeAgentConfiguration aconf = KnowledgeAgentFactory.newKnowledgeAgentConfiguration(); aconf.setProperty("drools.agent.newInstance", "false"); KnowledgeAgent agent = KnowledgeAgentFactory.newKnowledgeAgent("test", aconf); agent.addEventListener(new KnowledgeAgentEventListener() { public void resourceCompilationFailed(ResourceCompilationFailedEvent event) { } public void knowledgeBaseUpdated(KnowledgeBaseUpdatedEvent event) { System.out.println("Knowledge Base updated"); latch.countDown(); } public void beforeResourceProcessed(BeforeResourceProcessedEvent event) { } public void beforeChangeSetProcessed(BeforeChangeSetProcessedEvent event) { } public void beforeChangeSetApplied(BeforeChangeSetAppliedEvent event) { } public void afterResourceProcessed(AfterResourceProcessedEvent event) { } public void afterChangeSetProcessed(AfterChangeSetProcessedEvent event) { } public void afterChangeSetApplied(AfterChangeSetAppliedEvent event) { } }); SystemEventListenerFactory.setSystemEventListener(new PrintStreamSystemEventListener()); agent.applyChangeSet(ResourceFactory.newReaderResource(new StringReader(changeset))); KnowledgeBase kbase = agent.getKnowledgeBase(); assertEquals(2, kbase.getProcesses().size()); assertEquals(2, kbase.getKnowledgePackage("dummy").getProcesses().size()); p1.getRuleFlows().remove("1"); assertEquals(1, p1.getRuleFlows().size()); RuleBaseAssemblerTest.writePackage(p1, new File(location)); latch.await(20, TimeUnit.SECONDS); kbase = agent.getKnowledgeBase(); assertEquals(1, kbase.getProcesses().size()); assertEquals(1, kbase.getKnowledgePackage("dummy").getProcesses().size()); } @After public void clearup() { RuleBaseAssemblerTest.clearTempDirectory(); } }
package erogenousbeef.bigreactors.common.multiblock; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.packet.Packet; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.ForgeDirection; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.oredict.OreDictionary; import cofh.api.energy.IEnergyHandler; import cpw.mods.fml.common.network.PacketDispatcher; import cpw.mods.fml.common.network.Player; import erogenousbeef.bigreactors.api.HeatPulse; import erogenousbeef.bigreactors.api.IRadiationPulse; import erogenousbeef.bigreactors.common.BigReactors; import erogenousbeef.bigreactors.common.block.BlockReactorPart; import erogenousbeef.bigreactors.common.tileentity.TileEntityReactorAccessPort; import erogenousbeef.bigreactors.common.tileentity.TileEntityReactorControlRod; import erogenousbeef.bigreactors.common.tileentity.TileEntityReactorPart; import erogenousbeef.bigreactors.common.tileentity.TileEntityReactorPowerTap; import erogenousbeef.bigreactors.common.tileentity.TileEntityReactorRedNetPort; import erogenousbeef.bigreactors.net.PacketWrapper; import erogenousbeef.bigreactors.net.Packets; import erogenousbeef.bigreactors.utils.StaticUtils; import erogenousbeef.core.common.CoordTriplet; import erogenousbeef.core.multiblock.IMultiblockPart; import erogenousbeef.core.multiblock.MultiblockControllerBase; public class MultiblockReactor extends MultiblockControllerBase implements IEnergyHandler { // Game stuff protected boolean active; private float latentHeat; private WasteEjectionSetting wasteEjection; private float energyStored; // UI stuff private float energyGeneratedLastTick; private int fuelConsumedLastTick; public enum WasteEjectionSetting { kAutomatic, // Full auto, always remove waste kAutomaticOnlyIfCanReplace, // Remove only if it can be replaced with fuel kManual, // Manual, only on button press } private Set<CoordTriplet> attachedPowerTaps; private Set<CoordTriplet> attachedRedNetPorts; // TODO: Convert these to sets. private LinkedList<CoordTriplet> attachedControlRods; // Highest internal Y-coordinate in the fuel column private LinkedList<CoordTriplet> attachedAccessPorts; private LinkedList<CoordTriplet> attachedControllers; private Set<EntityPlayer> updatePlayers; private int ticksSinceLastUpdate; private static final int ticksBetweenUpdates = 3; private static final int maxEnergyStored = 10000000; public MultiblockReactor(World world) { super(world); // Game stuff active = false; latentHeat = 0f; energyGeneratedLastTick = 0f; fuelConsumedLastTick = 0; wasteEjection = WasteEjectionSetting.kAutomatic; attachedPowerTaps = new HashSet<CoordTriplet>(); attachedRedNetPorts = new HashSet<CoordTriplet>(); attachedControlRods = new LinkedList<CoordTriplet>(); attachedAccessPorts = new LinkedList<CoordTriplet>(); attachedControllers = new LinkedList<CoordTriplet>(); updatePlayers = new HashSet<EntityPlayer>(); ticksSinceLastUpdate = 0; } public void beginUpdatingPlayer(EntityPlayer playerToUpdate) { updatePlayers.add(playerToUpdate); sendIndividualUpdate(playerToUpdate); } public void stopUpdatingPlayer(EntityPlayer playerToRemove) { updatePlayers.remove(playerToRemove); } @Override protected void onBlockAdded(IMultiblockPart part) { CoordTriplet coord = part.getWorldLocation(); if(part instanceof TileEntityReactorAccessPort) { if(!attachedAccessPorts.contains(coord)) { attachedAccessPorts.add(coord); } } else if(part instanceof TileEntityReactorControlRod) { if(!attachedControlRods.contains(coord)) { attachedControlRods.add(coord); } } else if(part instanceof TileEntityReactorPowerTap) { attachedPowerTaps.add(coord); } else if(part instanceof TileEntityReactorRedNetPort) { attachedRedNetPorts.add(coord); } else if(part instanceof TileEntityReactorPart) { int metadata = ((TileEntityReactorPart)part).getBlockMetadata(); if(BlockReactorPart.isController(metadata) && !attachedControllers.contains(coord)) { attachedControllers.add(coord); } } } @Override protected void onBlockRemoved(IMultiblockPart part) { CoordTriplet coord = part.getWorldLocation(); if(part instanceof TileEntityReactorAccessPort) { if(attachedAccessPorts.contains(coord)) { attachedAccessPorts.remove(coord); } } else if(part instanceof TileEntityReactorControlRod) { attachedControlRods.remove(coord); if(attachedControlRods.contains(coord)) { attachedControlRods.remove(coord); } } else if(part instanceof TileEntityReactorPowerTap) { attachedPowerTaps.remove(coord); } else if(part instanceof TileEntityReactorRedNetPort) { attachedRedNetPorts.remove(coord); } else if(part instanceof TileEntityReactorPart) { int metadata = ((TileEntityReactorPart)part).getBlockMetadata(); if(BlockReactorPart.isController(metadata) && attachedControllers.contains(coord)) { attachedControllers.remove(coord); } } } @Override protected boolean isMachineWhole() { // Ensure that there is at least one controller and control rod attached. if(attachedControlRods.size() < 1) { return false; } if(attachedControllers.size() < 1) { return false; } return super.isMachineWhole(); } // Update loop. Only called when the machine is assembled. @Override public boolean update() { if(Float.isNaN(this.getHeat())) { this.setHeat(0.0f); } float oldHeat = this.getHeat(); float oldEnergy = this.getEnergyStored(); energyGeneratedLastTick = 0f; fuelConsumedLastTick = 0; // How much waste do we have? int wasteAmt = 0; int freeFuelSpace = 0; float newHeat = 0f; IRadiationPulse radiationResult; // Look for waste and run radiation & heat simulations TileEntityReactorControlRod controlRod; for(CoordTriplet coord : attachedControlRods) { controlRod = (TileEntityReactorControlRod)worldObj.getBlockTileEntity(coord.x, coord.y, coord.z); if(controlRod == null) { continue; } // Happens due to chunk unloads if(this.isActive()) { int fuelChange = controlRod.getFuelAmount(); radiationResult = controlRod.radiate(); fuelChange -= controlRod.getFuelAmount(); if(fuelChange > 0) { fuelConsumedLastTick += fuelChange; } this.generateEnergy(radiationResult.getPowerProduced()); } HeatPulse heatPulse = controlRod.onRadiateHeat(getHeat()); if(heatPulse != null) { this.addLatentHeat(heatPulse.heatChange); } wasteAmt += controlRod.getWasteAmount(); freeFuelSpace += controlRod.getSizeOfFuelTank() - controlRod.getTotalContainedAmount(); } // If we can, poop out waste and inject new fuel. // TODO: Change so control rods are individually considered for fueling instead // of doing it in aggregate. if(freeFuelSpace >= 1000 || wasteAmt >= 1000) { // Auto/Replace: Discover amount of available fuel and peg wasteAmt to that. if(this.wasteEjection == WasteEjectionSetting.kAutomaticOnlyIfCanReplace) { int fuelIngotsAvailable = 0; for(CoordTriplet coord : attachedAccessPorts) { TileEntityReactorAccessPort port = (TileEntityReactorAccessPort)worldObj.getBlockTileEntity(coord.x, coord.y, coord.z); if(port == null) { continue; } ItemStack fuelStack = port.getStackInSlot(TileEntityReactorAccessPort.SLOT_INLET); if(fuelStack != null) { fuelIngotsAvailable += fuelStack.stackSize; } } if(wasteAmt/1000 > fuelIngotsAvailable) { wasteAmt = fuelIngotsAvailable * 1000; } // Consider any space made by distributable waste to be free space. freeFuelSpace += wasteAmt; } else if(this.wasteEjection == WasteEjectionSetting.kManual) { // Manual just means to suppress waste injection, not ignore incoming fuel. Sooo.. wasteAmt = 0; } else { // Automatic - consider waste to be spare space for fuel freeFuelSpace += wasteAmt; } if(freeFuelSpace >= 1000 || wasteAmt >= 1000) { tryEjectWaste(freeFuelSpace, wasteAmt); } } // leak 1% of heat to the environment per tick // TODO: Better equation. if(latentHeat > 0.0f) { float latentHeatLoss = Math.max(0.05f, this.latentHeat * 0.01f); if(this.latentHeat < latentHeatLoss) { latentHeatLoss = latentHeat; } this.addLatentHeat(-1 * latentHeatLoss); // Generate power based on the amount of heat lost this.generateEnergy(latentHeatLoss * BigReactors.powerPerHeat); } if(latentHeat < 0.0f) { setHeat(0.0f); } // Distribute available power int energyAvailable = (int)getEnergyStored(); int energyRemaining = energyAvailable; if(attachedPowerTaps.size() > 0 && energyRemaining > 0) { // First, try to distribute fairly int splitEnergy = energyRemaining / attachedPowerTaps.size(); for(CoordTriplet coord : attachedPowerTaps) { if(energyRemaining <= 0) { break; } TileEntityReactorPowerTap tap = (TileEntityReactorPowerTap)this.worldObj.getBlockTileEntity(coord.x, coord.y, coord.z); if(tap == null) { continue; } energyRemaining -= splitEnergy - tap.onProvidePower(splitEnergy); } // Next, just hose out whatever we can, if we have any left if(energyRemaining > 0) { for(CoordTriplet coord : attachedPowerTaps) { if(energyRemaining <= 0) { break; } TileEntityReactorPowerTap tap = (TileEntityReactorPowerTap)this.worldObj.getBlockTileEntity(coord.x, coord.y, coord.z); if(tap == null) { continue; } energyRemaining = tap.onProvidePower(energyRemaining); } } } if(energyAvailable != energyRemaining) { reduceStoredEnergy((energyAvailable - energyRemaining)); } // Send updates periodically ticksSinceLastUpdate++; if(ticksSinceLastUpdate >= ticksBetweenUpdates) { ticksSinceLastUpdate = 0; sendTickUpdate(); } // TODO: Overload/overheat // Update any connected rednet networks for(CoordTriplet coord : attachedRedNetPorts) { TileEntityReactorRedNetPort port = (TileEntityReactorRedNetPort)worldObj.getBlockTileEntity(coord.x, coord.y, coord.z); if(port == null) { continue; } port.updateRedNetNetwork(); } return (oldHeat != this.getHeat() || oldEnergy != this.getEnergyStored()); } public void setStoredEnergy(float oldEnergy) { energyStored = oldEnergy; if(energyStored < 0.0 || Float.isNaN(energyStored)) { energyStored = 0.0f; } else if(energyStored > maxEnergyStored) { energyStored = maxEnergyStored; } } /** * Generate energy, internally. Will be multiplied by the BR Setting powerProductionMultiplier * @param newEnergy Base, unmultiplied energy to generate */ protected void generateEnergy(float newEnergy) { this.energyGeneratedLastTick += newEnergy * BigReactors.powerProductionMultiplier; this.addStoredEnergy(newEnergy * BigReactors.powerProductionMultiplier); } /** * Add some energy to the internal storage buffer. * Will not increase the buffer above the maximum or reduce it below 0. * @param newEnergy */ protected void addStoredEnergy(float newEnergy) { if(Float.isNaN(newEnergy)) { return; } energyStored += newEnergy; if(energyStored > maxEnergyStored) { energyStored = maxEnergyStored; } if(-0.00001f < energyStored && energyStored < 0.00001f) { // Clamp to zero energyStored = 0f; } } /** * Remove some energy from the internal storage buffer. * Will not reduce the buffer below 0. * @param energy Amount by which the buffer should be reduced. */ protected void reduceStoredEnergy(float energy) { this.addStoredEnergy(-1f * energy); } protected void addLatentHeat(float newCasingHeat) { if(Float.isNaN(newCasingHeat)) { return; } latentHeat += newCasingHeat; // Clamp to zero to prevent floating point issues if(-0.00001f < latentHeat && latentHeat < 0.00001f) { latentHeat = 0.0f; } } public boolean isActive() { return this.active; } public void setActive(boolean act) { if(act == this.active) { return; } this.active = act; TileEntity te = null; IMultiblockPart part = null; for(CoordTriplet coord : connectedBlocks) { te = this.worldObj.getBlockTileEntity(coord.x, coord.y, coord.z); if(te instanceof IMultiblockPart) { part = (IMultiblockPart)te; if(this.active) { part.onMachineActivated(); } else { part.onMachineDeactivated(); } } } } public float getHeat() { return latentHeat; } public void setHeat(float newHeat) { if(Float.isNaN(newHeat)) { latentHeat = 0.0f; } else { latentHeat = newHeat; } } public int getFuelColumnCount() { return attachedControlRods.size(); } // Static validation helpers // Water and air. protected boolean isBlockGoodForInterior(World world, int x, int y, int z) { Material material = world.getBlockMaterial(x, y, z); if(material == net.minecraft.block.material.MaterialLiquid.water || material == net.minecraft.block.material.Material.air) { return true; } return false; } @Override public void writeToNBT(NBTTagCompound data) { data.setBoolean("reactorActive", this.active); data.setFloat("heat", this.latentHeat); data.setFloat("storedEnergy", this.energyStored); data.setInteger("wasteEjection", this.wasteEjection.ordinal()); } @Override public void readFromNBT(NBTTagCompound data) { if(data.hasKey("reactorActive")) { setActive(data.getBoolean("reactorActive")); } if(data.hasKey("heat")) { setHeat(data.getFloat("heat")); } else { setHeat(0.0f); } if(data.hasKey("storedEnergy")) { setStoredEnergy(data.getFloat("storedEnergy")); } else { setStoredEnergy(0.0f); } if(data.hasKey("wasteEjection")) { this.wasteEjection = WasteEjectionSetting.values()[data.getInteger("wasteEjection")]; } } @Override protected int getMinimumNumberOfBlocksForAssembledMachine() { // Hollow cube. return 26; } @Override public void formatDescriptionPacket(NBTTagCompound data) { data.setInteger("wasteEjection", this.wasteEjection.ordinal()); data.setFloat("energy", this.energyStored); data.setFloat("heat", this.latentHeat); data.setBoolean("isActive", this.isActive()); } @Override public void decodeDescriptionPacket(NBTTagCompound data) { if(data.hasKey("wasteEjection")) { this.wasteEjection = WasteEjectionSetting.values()[data.getInteger("wasteEjection")]; } if(data.hasKey("isActive")) { this.setActive(data.getBoolean("isActive")); } if(data.hasKey("energy")) { this.energyStored = data.getFloat("energyStored"); } if(data.hasKey("heat")) { this.latentHeat = data.getFloat("heat"); } } protected Packet getUpdatePacket() { return PacketWrapper.createPacket(BigReactors.CHANNEL, Packets.ReactorControllerFullUpdate, new Object[] { referenceCoord.x, referenceCoord.y, referenceCoord.z, this.active, this.latentHeat, energyStored, this.energyGeneratedLastTick, this.fuelConsumedLastTick}); } /** * Sends a full state update to a player. */ protected void sendIndividualUpdate(EntityPlayer player) { if(this.worldObj.isRemote) { return; } PacketDispatcher.sendPacketToPlayer(getUpdatePacket(), (Player)player); } /** * Send an update to any clients with GUIs open * @param energyGenerated */ protected void sendTickUpdate() { if(this.worldObj.isRemote) { return; } if(this.updatePlayers.size() <= 0) { return; } Packet data = getUpdatePacket(); for(EntityPlayer player : updatePlayers) { PacketDispatcher.sendPacketToPlayer(data, (Player)player); } } private void tryDistributeWaste(TileEntityReactorAccessPort port, CoordTriplet coord, ItemStack wasteToDistribute, boolean distributeToInputs) { ItemStack wasteStack = port.getStackInSlot(TileEntityReactorAccessPort.SLOT_OUTLET); int metadata = worldObj.getBlockMetadata(coord.x, coord.y, coord.z); if(metadata == BlockReactorPart.ACCESSPORT_OUTLET || (distributeToInputs || attachedAccessPorts.size() < 2)) { // Dump waste preferentially to outlets, unless we only have one access port if(wasteStack == null) { if(wasteToDistribute.stackSize > port.getInventoryStackLimit()) { ItemStack newStack = wasteToDistribute.splitStack(port.getInventoryStackLimit()); port.setInventorySlotContents(TileEntityReactorAccessPort.SLOT_OUTLET, newStack); } else { port.setInventorySlotContents(TileEntityReactorAccessPort.SLOT_OUTLET, wasteToDistribute.copy()); wasteToDistribute.stackSize = 0; } } else { ItemStack existingStack = port.getStackInSlot(TileEntityReactorAccessPort.SLOT_OUTLET); if(existingStack.isItemEqual(wasteToDistribute)) { if(existingStack.stackSize + wasteToDistribute.stackSize <= existingStack.getMaxStackSize()) { existingStack.stackSize += wasteToDistribute.stackSize; wasteToDistribute.stackSize = 0; } else { int amt = existingStack.getMaxStackSize() - existingStack.stackSize; wasteToDistribute.stackSize -= existingStack.getMaxStackSize() - existingStack.stackSize; existingStack.stackSize += amt; } } } port.onWasteReceived(); } } @Override protected void onMachineMerge(MultiblockControllerBase otherMachine) { this.attachedPowerTaps.clear(); this.attachedRedNetPorts.clear(); this.attachedAccessPorts.clear(); this.attachedControllers.clear(); this.attachedControlRods.clear(); } public float getEnergyStored() { return energyStored; } /** * Increment the waste ejection setting by 1 value. */ public void changeWasteEjection() { WasteEjectionSetting[] settings = WasteEjectionSetting.values(); int newIdx = this.wasteEjection.ordinal() + 1; if(newIdx >= settings.length) { newIdx = 0; } WasteEjectionSetting newSetting = settings[newIdx]; setWasteEjection(newSetting); } /** * Directly set the waste ejection setting. Will dispatch network updates * from server to interested clients. * @param newSetting The new waste ejection setting. */ public void setWasteEjection(WasteEjectionSetting newSetting) { if(this.wasteEjection != newSetting) { this.wasteEjection = newSetting; if(!this.worldObj.isRemote) { if(this.updatePlayers.size() > 0) { Packet updatePacket = PacketWrapper.createPacket(BigReactors.CHANNEL, Packets.ReactorWasteEjectionSettingUpdate, new Object[] { referenceCoord.x, referenceCoord.y, referenceCoord.z, this.wasteEjection.ordinal() }); for(EntityPlayer player : updatePlayers) { PacketDispatcher.sendPacketToPlayer(updatePacket, (Player)player); } } } } } public WasteEjectionSetting getWasteEjection() { return this.wasteEjection; } public void ejectWaste() { TileEntityReactorControlRod controlRod; int wasteAmt = 0; int freeFuelSpace = 0; for(CoordTriplet coord : attachedControlRods) { controlRod = (TileEntityReactorControlRod)worldObj.getBlockTileEntity(coord.x, coord.y, coord.z); if(controlRod == null) { continue; } wasteAmt += controlRod.getWasteAmount(); freeFuelSpace += controlRod.getSizeOfFuelTank() - controlRod.getFuelAmount(); } if(freeFuelSpace >= 1000 || wasteAmt >= 1000) { tryEjectWaste(freeFuelSpace, wasteAmt); } } /** * Honestly attempt to eject waste and inject fuel, up to a certain amount. * @param fuelAmt Amount of fuel to inject. * @param wasteAmt Amount of waste to eject. */ protected void tryEjectWaste(int fuelAmt, int wasteAmt) { if(fuelAmt < 1000 && wasteAmt < 1000) { return; } ItemStack wasteToDistribute = null; if(wasteAmt >= 1000) { // TODO: Make this query the existing fuel type for the right type of waste to create wasteToDistribute = OreDictionary.getOres("ingotCyanite").get(0).copy(); wasteToDistribute.stackSize = wasteAmt/1000; } int fuelIngotsToConsume = fuelAmt / 1000; int fuelIngotsConsumed = 0; // Distribute waste, slurp in ingots. for(CoordTriplet coord : attachedAccessPorts) { if(fuelIngotsToConsume <= 0 && (wasteToDistribute == null || wasteToDistribute.stackSize <= 0)) { break; } TileEntityReactorAccessPort port = (TileEntityReactorAccessPort)worldObj.getBlockTileEntity(coord.x, coord.y, coord.z); if(port == null) { continue; } ItemStack fuelStack = port.getStackInSlot(TileEntityReactorAccessPort.SLOT_INLET); if(fuelStack != null) { if(fuelStack.stackSize >= fuelIngotsToConsume) { fuelStack = StaticUtils.Inventory.consumeItem(fuelStack, fuelIngotsToConsume); fuelIngotsConsumed = fuelIngotsToConsume; fuelIngotsToConsume = 0; } else { fuelIngotsConsumed += fuelStack.stackSize; fuelIngotsToConsume -= fuelStack.stackSize; fuelStack = StaticUtils.Inventory.consumeItem(fuelStack, fuelStack.stackSize); } port.setInventorySlotContents(TileEntityReactorAccessPort.SLOT_INLET, fuelStack); } if(wasteToDistribute != null && wasteToDistribute.stackSize > 0) { tryDistributeWaste(port, coord, wasteToDistribute, false); } } // If we have waste leftover and we have multiple ports, go back over them for the // outlets. if(wasteToDistribute != null && wasteToDistribute.stackSize > 0 && attachedAccessPorts.size() > 1) { for(CoordTriplet coord : attachedAccessPorts) { if(wasteToDistribute == null || wasteToDistribute.stackSize <= 0) { break; } TileEntityReactorAccessPort port = (TileEntityReactorAccessPort)worldObj.getBlockTileEntity(coord.x, coord.y, coord.z); if(port == null) { continue; } tryDistributeWaste(port, coord, wasteToDistribute, true); } } // Okay... let's modify the fuel rods now if((wasteToDistribute != null && wasteToDistribute.stackSize != wasteAmt / 1000) || fuelIngotsConsumed > 0) { int fuelToDistribute = fuelIngotsConsumed * 1000; int wasteToConsume = 0; if(wasteToDistribute != null) { wasteToConsume = ((wasteAmt/1000) - wasteToDistribute.stackSize) * 1000; } TileEntityReactorControlRod controlRod; for(CoordTriplet coord : attachedControlRods) { if(wasteToConsume <= 0 && fuelToDistribute <= 0) { break; } controlRod = (TileEntityReactorControlRod)worldObj.getBlockTileEntity(coord.x, coord.y, coord.z); if(controlRod == null) { continue; } if(wasteToConsume > 0 && controlRod.getWasteAmount() > 0) { int amtDrained = controlRod.removeWaste(new FluidStack(controlRod.getWasteType(), wasteToConsume), wasteToConsume, true); wasteToConsume -= amtDrained; } if(fuelToDistribute > 0) { if(controlRod.getFuelType() == null) { // TODO: Discover fuel type FluidStack fuel = new FluidStack(BigReactors.fluidYellorium, fuelToDistribute); fuelToDistribute -= controlRod.addFuel(fuel, fuelToDistribute, true); } else { fuelToDistribute -= controlRod.addFuel(new FluidStack(controlRod.getFuelType(), fuelToDistribute), fuelToDistribute, true); } } } } } // End fuel/waste autotransfer @Override protected void onMachineAssembled() { } @Override protected void onMachineRestored() { } @Override protected void onMachinePaused() { } @Override protected void onMachineDisassembled() { this.active = false; } @Override protected int getMaximumXSize() { return BigReactors.maximumReactorSize; } @Override protected int getMaximumZSize() { return BigReactors.maximumReactorSize; } @Override protected int getMaximumYSize() { return BigReactors.maximumReactorHeight; } /** * Used to update the UI */ public void setEnergyGeneratedLastTick(float energyGeneratedLastTick) { this.energyGeneratedLastTick = energyGeneratedLastTick; } /** * UI Helper */ public float getEnergyGeneratedLastTick() { return this.energyGeneratedLastTick; } /** * Used to update the UI */ public void setFuelConsumedLastTick(int fuelConsumed) { this.fuelConsumedLastTick = fuelConsumed; } /** * UI Helper */ public int getFuelConsumedLastTick() { return this.fuelConsumedLastTick; } /** * UI Helper * @return Percentile fuel richness (fuel/fuel+waste), or 0 if all control rods are empty */ public float getFuelRichness() { int amtFuel, amtWaste; TileEntityReactorControlRod controlRod = null; amtFuel = amtWaste = 0; for(CoordTriplet coord : this.attachedControlRods) { controlRod = (TileEntityReactorControlRod)worldObj.getBlockTileEntity(coord.x, coord.y, coord.z); if(controlRod == null) { continue; } // Happens due to chunk unloads amtFuel += controlRod.getFuelAmount(); amtWaste += controlRod.getWasteAmount(); } if(amtFuel + amtWaste <= 0f) { return 0f; } else { return (float)amtFuel / (float)(amtFuel+amtWaste); } } /** DO NOT USE **/ @Override public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { int amtReceived = (int)Math.min(maxReceive, Math.floor(this.maxEnergyStored - this.energyStored)); if(!simulate) { this.addStoredEnergy(amtReceived); } return amtReceived; } @Override public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { int amtRemoved = (int)Math.min(maxExtract, this.energyStored); if(!simulate) { this.reduceStoredEnergy(amtRemoved); } return amtRemoved; } @Override public boolean canInterface(ForgeDirection from) { return false; } @Override public int getEnergyStored(ForgeDirection from) { return (int)energyStored; } @Override public int getMaxEnergyStored(ForgeDirection from) { return maxEnergyStored; } public int getMaxEnergyPerTick() { return this.maxEnergyStored; } // Redstone helper public void setAllControlRodInsertionValues(int newValue) { if(this.assemblyState != AssemblyState.Assembled) { return; } TileEntity te; TileEntityReactorControlRod cr; for(CoordTriplet coord : attachedControlRods) { te = this.worldObj.getBlockTileEntity(coord.x, coord.y, coord.z); if(te instanceof TileEntityReactorControlRod) { cr = (TileEntityReactorControlRod)te; cr.setControlRodInsertion((short)newValue); } } } public CoordTriplet[] getControlRodLocations() { CoordTriplet[] coords = new CoordTriplet[this.attachedControlRods.size()]; int i = 0; for(CoordTriplet coord : this.attachedControlRods) { coords[i++] = coord.copy(); } return coords; } }
package erogenousbeef.bigreactors.common.multiblock; import java.io.DataInputStream; import java.io.IOException; import java.util.HashSet; import java.util.Set; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.packet.Packet; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.ForgeDirection; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.oredict.OreDictionary; import cofh.api.energy.IEnergyHandler; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.network.PacketDispatcher; import cpw.mods.fml.common.network.Player; import erogenousbeef.bigreactors.common.BigReactors; import erogenousbeef.bigreactors.common.interfaces.IMultipleFluidHandler; import erogenousbeef.bigreactors.common.multiblock.block.BlockTurbinePart; import erogenousbeef.bigreactors.common.multiblock.block.BlockTurbineRotorPart; import erogenousbeef.bigreactors.common.multiblock.interfaces.ITickableMultiblockPart; import erogenousbeef.bigreactors.common.multiblock.tileentity.TileEntityTurbinePartBase; import erogenousbeef.bigreactors.common.multiblock.tileentity.TileEntityTurbinePowerTap; import erogenousbeef.bigreactors.gui.container.ISlotlessUpdater; import erogenousbeef.bigreactors.net.PacketWrapper; import erogenousbeef.bigreactors.net.Packets; import erogenousbeef.bigreactors.utils.StaticUtils; import erogenousbeef.core.common.CoordTriplet; import erogenousbeef.core.multiblock.IMultiblockPart; import erogenousbeef.core.multiblock.MultiblockControllerBase; import erogenousbeef.core.multiblock.MultiblockValidationException; import erogenousbeef.core.multiblock.rectangular.RectangularMultiblockControllerBase; public class MultiblockTurbine extends RectangularMultiblockControllerBase implements IEnergyHandler, IMultipleFluidHandler, ISlotlessUpdater { public enum VentStatus { VentOverflow, VentAll, DoNotVent }; // UI updates private Set<EntityPlayer> updatePlayers; private int ticksSinceLastUpdate; private static final int ticksBetweenUpdates = 3; // Fluid tanks. Input = Steam, Output = Water. public static final int TANK_INPUT = 0; public static final int TANK_OUTPUT = 1; public static final int NUM_TANKS = 2; public static final int FLUID_NONE = -1; public static final int TANK_SIZE = 2000; private FluidTank[] tanks; static final float maxEnergyStored = 1000000f; // 1 MegaRF // Persistent game data float energyStored; boolean active; float rotorSpeed; // Player settings VentStatus ventStatus; int maxIntakeRate; // Derivable game data int bladeSurfaceArea; // # of blocks that are blades int rotorMass; // 10 = 1 standard block-weight int coilSize; // number of blocks in the coils // Inductor dynamic constants - get from a table on assembly float inductorDragCoefficient = 0.01f; // Keep this small, as it gets multiplied by v^2 and dominates at high speeds. Higher = more drag from the inductor vs. aerodynamic drag = more efficient energy conversion. float inductionEnergyBonus = 1f; // Bonus to energy generation based on construction materials. 1 = plain iron. float inductionEnergyExponentBonus = 0f; // Exponential bonus to energy generation. Use this for very rare materials or special constructs. // Rotor dynamic constants - calculate on assembly float rotorDragCoefficient = 0.1f; // totally arbitrary. Allow upgrades to decrease this. This is the drag of the ROTOR. float bladeDragCoefficient = 0.04f; // From wikipedia, drag of a standard airfoil. This is the drag of the BLADES. // Penalize suboptimal shapes with worse drag (i.e. increased drag without increasing lift) // Suboptimal is defined as "not a christmas-tree shape". At worst, drag is increased 4x. // Game balance constants final static float bladeLiftCoefficient = 0.75f; // From wikipedia, lift of a standard airfoil final static float inductionEnergyCoefficient = 1.2f; // Power to raise the induced current by. This makes higher RPMs more efficient. float energyGeneratedLastTick; private Set<IMultiblockPart> attachedControllers; private Set<IMultiblockPart> attachedRotorBearings; private Set<TileEntityTurbinePowerTap> attachedPowerTaps; private Set<ITickableMultiblockPart> attachedTickables; // Data caches for validation private Set<CoordTriplet> foundCoils; private Set<CoordTriplet> foundRotors; private Set<CoordTriplet> foundBlades; private static final ForgeDirection[] RotorXBladeDirections = new ForgeDirection[] { ForgeDirection.UP, ForgeDirection.SOUTH, ForgeDirection.DOWN, ForgeDirection.NORTH }; private static final ForgeDirection[] RotorZBladeDirections = new ForgeDirection[] { ForgeDirection.UP, ForgeDirection.EAST, ForgeDirection.DOWN, ForgeDirection.WEST }; public MultiblockTurbine(World world) { super(world); updatePlayers = new HashSet<EntityPlayer>(); ticksSinceLastUpdate = 0; tanks = new FluidTank[NUM_TANKS]; for(int i = 0; i < NUM_TANKS; i++) tanks[i] = new FluidTank(TANK_SIZE); attachedControllers = new HashSet<IMultiblockPart>(); attachedRotorBearings = new HashSet<IMultiblockPart>(); attachedPowerTaps = new HashSet<TileEntityTurbinePowerTap>(); attachedTickables = new HashSet<ITickableMultiblockPart>(); energyStored = 0f; active = false; ventStatus = VentStatus.VentOverflow; rotorSpeed = 0f; maxIntakeRate = TANK_SIZE; bladeSurfaceArea = 0; rotorMass = 0; coilSize = 0; energyGeneratedLastTick = 0f; foundCoils = new HashSet<CoordTriplet>(); foundRotors = new HashSet<CoordTriplet>(); foundBlades = new HashSet<CoordTriplet>(); } /** * Sends a full state update to a player. */ protected void sendIndividualUpdate(EntityPlayer player) { if(this.worldObj.isRemote) { return; } PacketDispatcher.sendPacketToPlayer(getUpdatePacket(), (Player)player); } protected Packet getUpdatePacket() { // Capture compacted fluid data first int inputFluidID, inputFluidAmt, outputFluidID, outputFluidAmt; FluidStack inputFluid, outputFluid; inputFluid = tanks[TANK_INPUT].getFluid(); outputFluid = tanks[TANK_OUTPUT].getFluid(); if(inputFluid == null || inputFluid.amount <= 0) { inputFluidID = FLUID_NONE; inputFluidAmt = 0; } else { inputFluidID = inputFluid.getFluid().getID(); inputFluidAmt = inputFluid.amount; } if(outputFluid == null || outputFluid.amount <= 0) { outputFluidID = FLUID_NONE; outputFluidAmt = 0; } else { outputFluidID = outputFluid.getFluid().getID(); outputFluidAmt = outputFluid.amount; } CoordTriplet referenceCoord = getReferenceCoord(); return PacketWrapper.createPacket(BigReactors.CHANNEL, Packets.MultiblockTurbineFullUpdate, new Object[] { referenceCoord.x, referenceCoord.y, referenceCoord.z, inputFluidID, inputFluidAmt, outputFluidID, outputFluidAmt, energyStored, rotorSpeed, energyGeneratedLastTick, maxIntakeRate }); } /** * Parses a full-update packet. Only used on the client. * @param data The data input stream containing the update data. * @throws IOException */ public void onReceiveUpdatePacket(DataInputStream data) throws IOException { int inputFluidID = data.readInt(); int inputFluidAmt = data.readInt(); int outputFluidID = data.readInt(); int outputFluidAmt = data.readInt(); energyStored = data.readFloat(); rotorSpeed = data.readFloat(); energyGeneratedLastTick = data.readFloat(); maxIntakeRate = data.readInt(); if(inputFluidID == FLUID_NONE || inputFluidAmt <= 0) { tanks[TANK_INPUT].setFluid(null); } else { Fluid fluid = FluidRegistry.getFluid(inputFluidID); if(fluid == null) { FMLLog.warning("[CLIENT] Multiblock Turbine received an unknown fluid of type %d, setting input tank to empty", inputFluidID); tanks[TANK_INPUT].setFluid(null); } else { tanks[TANK_INPUT].setFluid(new FluidStack(fluid, inputFluidAmt)); } } if(outputFluidID == FLUID_NONE || outputFluidAmt <= 0) { tanks[TANK_OUTPUT].setFluid(null); } else { Fluid fluid = FluidRegistry.getFluid(outputFluidID); if(fluid == null) { FMLLog.warning("[CLIENT] Multiblock Turbine received an unknown fluid of type %d, setting output tank to empty", outputFluidID); tanks[TANK_OUTPUT].setFluid(null); } else { tanks[TANK_OUTPUT].setFluid(new FluidStack(fluid, outputFluidAmt)); } } } /** * Send an update to any clients with GUIs open */ protected void sendTickUpdate() { if(this.updatePlayers.size() <= 0) { return; } Packet data = getUpdatePacket(); for(EntityPlayer player : updatePlayers) { PacketDispatcher.sendPacketToPlayer(data, (Player)player); } } public void onNetworkPacket(int packetType, DataInputStream data) throws IOException { // Client->Server Packets if(packetType == Packets.MultiblockControllerButton) { Class decodeAs[] = { String.class, Boolean.class }; Object[] decodedData = PacketWrapper.readPacketData(data, decodeAs); String buttonName = (String) decodedData[0]; boolean newValue = (Boolean) decodedData[1]; if(buttonName.equals("activate")) { setActive(newValue); markReferenceCoordDirty(); } } if(packetType == Packets.MultiblockTurbineGovernorUpdate) { setMaxIntakeRate(data.readInt()); markReferenceCoordDirty(); } if(packetType == Packets.MultiblockTurbineVentUpdate) { int idx = data.readInt(); if(idx >= 0 && idx < VentStatus.values().length) { ventStatus = VentStatus.values()[idx]; markReferenceCoordDirty(); } } // Server->Client Packets if(packetType == Packets.MultiblockTurbineFullUpdate) { onReceiveUpdatePacket(data); } // Bidirectional packets } // MultiblockControllerBase overrides @Override public void onAttachedPartWithMultiblockData(IMultiblockPart part, NBTTagCompound data) { // TODO: Additional validation to only replace current data if current data is "worse" than NBT data readFromNBT(data); } @Override protected void onBlockAdded(IMultiblockPart newPart) { if(newPart instanceof TileEntityTurbinePartBase) { CoordTriplet coord = newPart.getWorldLocation(); int metadata = worldObj.getBlockMetadata(coord.x, coord.y, coord.z); if(metadata == BlockTurbinePart.METADATA_BEARING) { this.attachedRotorBearings.add(newPart); } } if(newPart instanceof TileEntityTurbinePowerTap) { attachedPowerTaps.add((TileEntityTurbinePowerTap)newPart); } if(newPart instanceof ITickableMultiblockPart) { attachedTickables.add((ITickableMultiblockPart)newPart); } } @Override protected void onBlockRemoved(IMultiblockPart oldPart) { this.attachedRotorBearings.remove(oldPart); if(oldPart instanceof TileEntityTurbinePowerTap) { attachedPowerTaps.remove((TileEntityTurbinePowerTap)oldPart); } if(oldPart instanceof ITickableMultiblockPart) { attachedTickables.remove((ITickableMultiblockPart)oldPart); } } @Override protected void onMachineAssembled() { recalculateDerivedStatistics(); } @Override protected void onMachineRestored() { recalculateDerivedStatistics(); } @Override protected void onMachinePaused() { } @Override protected void onMachineDisassembled() { rotorMass = 0; bladeSurfaceArea = 0; coilSize = 0; } // Validation code @Override protected void isMachineWhole() throws MultiblockValidationException { if(attachedRotorBearings.size() != 1) { throw new MultiblockValidationException("Turbines require exactly 1 rotor bearing"); } // Set up validation caches foundBlades.clear(); foundRotors.clear(); foundCoils.clear(); super.isMachineWhole(); // Now do additional validation based on the coils/blades/rotors that were found // Check that we have a rotor that goes all the way up the bearing TileEntityTurbinePartBase rotorPart = (TileEntityTurbinePartBase)attachedRotorBearings.iterator().next(); // Rotor bearing must calculate outwards dir, as this is normally only calculated in onMachineAssembled(). rotorPart.recalculateOutwardsDirection(getMinimumCoord(), getMaximumCoord()); // Find out which way the rotor runs. Obv, this is inwards from the bearing. ForgeDirection rotorDir = rotorPart.getOutwardsDir().getOpposite(); CoordTriplet rotorCoord = rotorPart.getWorldLocation(); CoordTriplet minRotorCoord = getMinimumCoord(); CoordTriplet maxRotorCoord = getMaximumCoord(); // Constrain min/max rotor coords to where the rotor bearing is and the block opposite it if(rotorDir.offsetX == 0) { minRotorCoord.x = maxRotorCoord.x = rotorCoord.x; } if(rotorDir.offsetY == 0) { minRotorCoord.y = maxRotorCoord.y = rotorCoord.y; } if(rotorDir.offsetZ == 0) { minRotorCoord.z = maxRotorCoord.z = rotorCoord.z; } // Figure out where the rotor ends and which directions are normal to the rotor's 4 faces (this is where blades emit from) CoordTriplet endRotorCoord = rotorCoord.equals(minRotorCoord) ? maxRotorCoord : minRotorCoord; endRotorCoord.translate(rotorDir.getOpposite()); ForgeDirection[] bladeDirections; if(rotorDir.offsetY != 0) { bladeDirections = StaticUtils.CardinalDirections; } else if(rotorDir.offsetX != 0) { bladeDirections = RotorXBladeDirections; } else { bladeDirections = RotorZBladeDirections; } // Move along the length of the rotor, 1 block at a time boolean encounteredCoils = false; while(!foundRotors.isEmpty() && !rotorCoord.equals(endRotorCoord)) { rotorCoord.translate(rotorDir); // Ensure we find a rotor block along the length of the entire rotor if(!foundRotors.remove(rotorCoord)) { throw new MultiblockValidationException(String.format("%s - This block must contain a rotor. The rotor must begin at the bearing and run the entire length of the turbine", rotorCoord)); } // Now move out in the 4 rotor normals, looking for blades and coils CoordTriplet checkCoord = rotorCoord.copy(); boolean encounteredBlades = false; for(ForgeDirection bladeDir : bladeDirections) { checkCoord.copy(rotorCoord); boolean foundABlade = false; checkCoord.translate(bladeDir); // If we find 1 blade, we can keep moving along the normal to find more blades while(foundBlades.remove(checkCoord)) { // We found a coil already?! NOT ALLOWED. if(encounteredCoils) { throw new MultiblockValidationException(String.format("%s - Rotor blades must be placed closer to the rotor bearing than all other parts inside a turbine", checkCoord)); } foundABlade = encounteredBlades = true; checkCoord.translate(bladeDir); } // If this block wasn't a blade, check to see if it was a coil if(!foundABlade) { if(foundCoils.remove(checkCoord)) { encounteredCoils = true; // We cannot have blades and coils intermix. This prevents intermixing, depending on eval order. if(encounteredBlades) { throw new MultiblockValidationException(String.format("%s - Metal blocks must by placed further from the rotor bearing than all rotor blades", checkCoord)); } // Check the two coil spots in the 'corners', which are permitted if they're connected to the main rotor coil somehow CoordTriplet coilCheck = checkCoord.copy(); coilCheck.translate(bladeDir.getRotation(rotorDir)); foundCoils.remove(coilCheck); coilCheck.copy(checkCoord); coilCheck.translate(bladeDir.getRotation(rotorDir.getOpposite())); foundCoils.remove(coilCheck); } // Else: It must have been air. } } } if(!rotorCoord.equals(endRotorCoord)) { throw new MultiblockValidationException("The rotor shaft must extend the entire length of the turbine interior."); } // Ensure that we encountered all the rotor, blade and coil blocks. If not, there's loose stuff inside the turbine. if(!foundRotors.isEmpty()) { throw new MultiblockValidationException(String.format("Found %d rotor blocks that are not attached to the main rotor. All rotor blocks must be in a column extending the entire length of the turbine, starting from the bearing.", foundRotors.size())); } if(!foundBlades.isEmpty()) { throw new MultiblockValidationException(String.format("Found %d rotor blades that are not attached to the rotor. All rotor blades must extend continuously from the rotor's shaft.", foundBlades.size())); } if(!foundCoils.isEmpty()) { throw new MultiblockValidationException(String.format("Found %d metal blocks which were not in a ring around the rotor. All metal blocks must be in rings, or partial rings, around the rotor.", foundCoils.size())); } // A-OK! } @Override protected void isBlockGoodForInterior(World world, int x, int y, int z) throws MultiblockValidationException { // We only allow air and functional parts in turbines. // Air is ok if(world.isAirBlock(x, y, z)) { return; } int blockId = world.getBlockId(x, y, z); int metadata = world.getBlockMetadata(x,y,z); // Allow rotors and stuff if(blockId == BigReactors.blockTurbineRotorPart.blockID) { if(BlockTurbineRotorPart.isRotorBlade(metadata)) { foundBlades.add(new CoordTriplet(x,y,z)); } else if(BlockTurbineRotorPart.isRotorShaft(metadata)) { foundRotors.add(new CoordTriplet(x,y,z)); } else { throw new MultiblockValidationException("%d, %d, %d - Found an unrecognized turbine rotor part. This is a bug, please report it."); } return; } // Coil windings below here: if(isBlockPartOfCoil(x, y, z, blockId, metadata)) { foundCoils.add(new CoordTriplet(x,y,z)); return; } // Everything else, gtfo throw new MultiblockValidationException(String.format("%d, %d, %d is invalid for a turbine interior. Only rotor parts, metal blocks and empty space are allowed.", x, y, z)); } @Override protected int getMinimumNumberOfBlocksForAssembledMachine() { // Hollow 5x5x4 cube (100 - 18), interior minimum is 3x3x2 return 82; } @Override protected int getMaximumXSize() { return BigReactors.maximumTurbineSize; } @Override protected int getMaximumZSize() { return BigReactors.maximumTurbineSize; } @Override protected int getMaximumYSize() { return BigReactors.maximumTurbineHeight; } @Override protected int getMinimumXSize() { return 5; } @Override protected int getMinimumYSize() { return 4; } @Override protected int getMinimumZSize() { return 5; } @Override protected void onAssimilate(MultiblockControllerBase assimilated) { } @Override protected void onAssimilated(MultiblockControllerBase assimilator) { attachedControllers.clear(); attachedRotorBearings.clear(); attachedTickables.clear(); attachedPowerTaps.clear(); } @Override protected boolean updateServer() { energyGeneratedLastTick = 0f; // Generate energy based on steam int steamIn = 0; // mB. Based on water, actually. Probably higher for steam. Measure it. float fluidEnergyDensity = 0.001f; if(isActive()) { // TODO: Lookup fluid parameters from a table fluidEnergyDensity = 0.001f; // effectively, force-units per mB. (one mB-force or mBf). Stand-in for fluid density. // Spin up via steam inputs, convert some steam back into water. // Use at most the user-configured max, or the amount in the tank, whichever is less. steamIn = Math.min(maxIntakeRate, tanks[TANK_INPUT].getFluidAmount()); if(ventStatus == VentStatus.DoNotVent) { // Cap steam used to available space, if not venting // TODO: Calculate difference from available space int availableSpace = tanks[TANK_OUTPUT].getCapacity() - tanks[TANK_OUTPUT].getFluidAmount(); steamIn = Math.max(steamIn, availableSpace); } } if(steamIn > 0 || rotorSpeed > 0) { // Induction-driven torque pulled out of my ass. float inductionTorque = (float)(Math.pow(rotorSpeed*0.1f, 1.5)*inductorDragCoefficient*coilSize); // Aerodynamic drag equation. Thanks, Mr. Euler. float aerodynamicDragTorque = (float)Math.pow(rotorSpeed, 2) * fluidEnergyDensity * bladeDragCoefficient * bladeSurfaceArea / 2f; // Frictional drag equation. Basically, a small amount of constant drag based on the size of your rotor. float frictionalDragTorque = rotorDragCoefficient * rotorMass; // Aerodynamic lift equation. Also via Herr Euler. float liftTorque = 2 * (float)Math.pow(steamIn, 2) * fluidEnergyDensity * bladeLiftCoefficient * bladeSurfaceArea; // Yay for derivation. We're assuming delta-Time is always 1, as we're always calculating for 1 tick. // TODO: When calculating rotor mass, factor in a division by two to eliminate the constant term. float deltaV = (2 * (liftTorque + -1f*inductionTorque + -1f*aerodynamicDragTorque + -1f*frictionalDragTorque)) / rotorMass; float energyToGenerate = (float)Math.pow(inductionTorque, inductionEnergyCoefficient + inductionEnergyExponentBonus) * inductionEnergyBonus * BigReactors.powerProductionMultiplier; generateEnergy(energyToGenerate); rotorSpeed += deltaV; if(rotorSpeed < 0f) { rotorSpeed = 0f; } // And create some water if(steamIn > 0) { Fluid effluent = FluidRegistry.WATER; FluidStack effluentStack = new FluidStack(effluent, steamIn); fill(TANK_OUTPUT, effluentStack, true); drain(TANK_INPUT, steamIn, true); } } int energyAvailable = (int)getEnergyStored(); int energyRemaining = energyAvailable; if(energyStored > 0 && attachedPowerTaps.size() > 0) { // First, try to distribute fairly int splitEnergy = energyRemaining / attachedPowerTaps.size(); for(TileEntityTurbinePowerTap powerTap : attachedPowerTaps) { if(energyRemaining <= 0) { break; } if(powerTap == null || !powerTap.isConnected()) { continue; } energyRemaining -= splitEnergy - powerTap.onProvidePower(splitEnergy); } // Next, just hose out whatever we can, if we have any left if(energyRemaining > 0) { for(TileEntityTurbinePowerTap powerTap : attachedPowerTaps) { if(energyRemaining <= 0) { break; } if(powerTap == null || !powerTap.isConnected()) { continue; } energyRemaining = powerTap.onProvidePower(energyRemaining); } } } if(energyAvailable != energyRemaining) { reduceStoredEnergy((energyAvailable - energyRemaining)); } for(ITickableMultiblockPart part : attachedTickables) { part.onMultiblockServerTick(); } ticksSinceLastUpdate++; if(ticksSinceLastUpdate >= ticksBetweenUpdates) { sendTickUpdate(); ticksSinceLastUpdate = 0; } // TODO: Only mark dirty when stuff changes return true; } @Override protected void updateClient() { } @Override public void writeToNBT(NBTTagCompound data) { data.setCompoundTag("inputTank", tanks[TANK_INPUT].writeToNBT(new NBTTagCompound())); data.setCompoundTag("outputTank", tanks[TANK_OUTPUT].writeToNBT(new NBTTagCompound())); data.setBoolean("active", active); data.setFloat("energy", energyStored); data.setInteger("ventStatus", ventStatus.ordinal()); data.setFloat("rotorSpeed", rotorSpeed); data.setInteger("maxIntakeRate", maxIntakeRate); } @Override public void readFromNBT(NBTTagCompound data) { if(data.hasKey("inputTank")) { tanks[TANK_INPUT].readFromNBT(data.getCompoundTag("inputTank")); } if(data.hasKey("outputTank")) { tanks[TANK_OUTPUT].readFromNBT(data.getCompoundTag("outputTank")); } if(data.hasKey("active")) { setActive(data.getBoolean("active")); } if(data.hasKey("energy")) { setEnergyStored(data.getFloat("energy")); } if(data.hasKey("ventStatus")) { ventStatus = VentStatus.values()[data.getInteger("ventStatus")]; } if(data.hasKey("rotorSpeed")) { rotorSpeed = data.getFloat("rotorSpeed"); if(Float.isNaN(rotorSpeed) || Float.isInfinite(rotorSpeed)) { rotorSpeed = 0f; } } if(data.hasKey("maxIntakeRate")) { maxIntakeRate = data.getInteger("maxIntakeRate"); } } @Override public void formatDescriptionPacket(NBTTagCompound data) { writeToNBT(data); } @Override public void decodeDescriptionPacket(NBTTagCompound data) { readFromNBT(data); } @Override public void getOrphanData(IMultiblockPart newOrphan, int oldSize, int newSize, NBTTagCompound dataContainer) { } // Nondirectional FluidHandler implementation, similar to IFluidHandler public int fill(int tank, FluidStack resource, boolean doFill) { if(!canFill(tank, resource.getFluid())) { return 0; } return tanks[tank].fill(resource, doFill); } public FluidStack drain(int tank, FluidStack resource, boolean doDrain) { if(canDrain(tank, resource.getFluid())) { return tanks[tank].drain(resource.amount, doDrain); } return null; } public FluidStack drain(int tank, int maxDrain, boolean doDrain) { if(tank < 0 || tank >= NUM_TANKS) { return null; } return tanks[tank].drain(maxDrain, doDrain); } public boolean canFill(int tank, Fluid fluid) { if(tank < 0 || tank >= NUM_TANKS) { return false; } FluidStack fluidStack = tanks[tank].getFluid(); if(fluidStack != null) { return fluidStack.getFluid().getID() == fluid.getID(); } else if(tank == TANK_INPUT) { // TODO: Input tank can only be filled with compatible fluids from a registry return fluid.getName().equals("steam"); } else { // Output tank can be filled with anything. Don't be a dumb. return true; } } public boolean canDrain(int tank, Fluid fluid) { if(tank < 0 || tank >= NUM_TANKS) { return false; } FluidStack fluidStack = tanks[tank].getFluid(); if(fluidStack == null) { return false; } return fluidStack.getFluid().getID() == fluid.getID(); } public FluidTankInfo[] getTankInfo() { FluidTankInfo[] infos = new FluidTankInfo[NUM_TANKS]; for(int i = 0; i < NUM_TANKS; i++) { infos[i] = tanks[i].getInfo(); } return infos; } public FluidTankInfo getTankInfo(int tankIdx) { return tanks[tankIdx].getInfo(); } // IEnergyHandler @Override public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { // haha no return 0; } @Override public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { int energyExtracted = Math.min((int)energyStored, maxExtract); if(!simulate) { energyStored -= energyExtracted; } return energyExtracted; } @Override public boolean canInterface(ForgeDirection from) { return true; } @Override public int getEnergyStored(ForgeDirection from) { return (int)energyStored; } @Override public int getMaxEnergyStored(ForgeDirection from) { return (int)maxEnergyStored; } private void setEnergyStored(float newEnergy) { if(Float.isInfinite(newEnergy) || Float.isNaN(newEnergy)) { return; } energyStored = Math.max(0f, Math.min(maxEnergyStored, newEnergy)); } // Energy Helpers public float getEnergyStored() { return energyStored; } /** * Remove some energy from the internal storage buffer. * Will not reduce the buffer below 0. * @param energy Amount by which the buffer should be reduced. */ protected void reduceStoredEnergy(float energy) { addStoredEnergy(-1f * energy); } /** * Add some energy to the internal storage buffer. * Will not increase the buffer above the maximum or reduce it below 0. * @param newEnergy */ protected void addStoredEnergy(float newEnergy) { if(Float.isNaN(newEnergy)) { return; } energyStored += newEnergy; if(energyStored > maxEnergyStored) { energyStored = maxEnergyStored; } if(-0.00001f < energyStored && energyStored < 0.00001f) { // Clamp to zero energyStored = 0f; } } public void setStoredEnergy(float oldEnergy) { energyStored = oldEnergy; if(energyStored < 0.0 || Float.isNaN(energyStored)) { energyStored = 0.0f; } else if(energyStored > maxEnergyStored) { energyStored = maxEnergyStored; } } /** * Generate energy, internally. Will be multiplied by the BR Setting powerProductionMultiplier * @param newEnergy Base, unmultiplied energy to generate */ protected void generateEnergy(float newEnergy) { energyGeneratedLastTick += newEnergy * BigReactors.powerProductionMultiplier; addStoredEnergy(newEnergy * BigReactors.powerProductionMultiplier); } // Activity state public boolean isActive() { return active; } public void setActive(boolean newValue) { if(newValue != active) { this.active = newValue; for(IMultiblockPart part : connectedParts) { if(this.active) { part.onMachineActivated(); } else { part.onMachineDeactivated(); } } CoordTriplet referenceCoord = getReferenceCoord(); worldObj.markBlockForUpdate(referenceCoord.x, referenceCoord.y, referenceCoord.z); if(worldObj.isRemote) { // Force controllers to re-render on client for(IMultiblockPart part : attachedControllers) { worldObj.markBlockForUpdate(part.xCoord, part.yCoord, part.zCoord); } } } } // Governor public int getMaxIntakeRate() { return maxIntakeRate; } public void setMaxIntakeRate(int newRate) { maxIntakeRate = Math.min(TANK_SIZE, Math.max(0, newRate)); } // for GUI use public int getMaxIntakeRateMax() { return TANK_SIZE; } // ISlotlessUpdater @Override public void beginUpdatingPlayer(EntityPlayer playerToUpdate) { updatePlayers.add(playerToUpdate); sendIndividualUpdate(playerToUpdate); } @Override public void stopUpdatingPlayer(EntityPlayer playerToRemove) { updatePlayers.remove(playerToRemove); } @Override public boolean isUseableByPlayer(EntityPlayer player) { // TODO DISTANCE CHECK return true; } private boolean isBlockPartOfCoil(int x, int y, int z) { return isBlockPartOfCoil(x, y, z, worldObj.getBlockId(x,y,z), worldObj.getBlockMetadata(x, y, z)); } private boolean isBlockPartOfCoil(int x, int y, int z, int blockID, int metadata) { // Allow vanilla iron and gold blocks if(blockID == Block.blockGold.blockID || blockID == Block.blockIron.blockID) { return true; } // Check the oredict to see if it's copper, or a funky kind of gold/iron block int oreId = OreDictionary.getOreID(new ItemStack(blockID, 1, metadata)); // Not oredicted? Buzz off. if(oreId < 0) { return false; } String oreName = OreDictionary.getOreName(oreId); if(oreName.equals("blockCopper") || oreName.equals("blockIron") || oreName.equals("blockGold")) { return true; } return false; } /** * Recalculate rotor and coil parameters */ private void recalculateDerivedStatistics() { CoordTriplet minInterior, maxInterior; minInterior = getMinimumCoord(); maxInterior = getMaximumCoord(); minInterior.x++; minInterior.y++; minInterior.z++; maxInterior.x++; maxInterior.y++; maxInterior.z++; rotorMass = 0; bladeSurfaceArea = 0; coilSize = 0; // Loop over interior space. Calculate mass and blade area of rotor and size of coils for(int x = minInterior.x; x <= maxInterior.x; x++) { for(int y = minInterior.y; y <= maxInterior.y; y++) { for(int z = minInterior.z; z <= maxInterior.z; z++) { int blockId = worldObj.getBlockId(x, y, z); int metadata = worldObj.getBlockMetadata(x, y, z); if(blockId == BigReactors.blockTurbineRotorPart.blockID) { rotorMass += BigReactors.blockTurbineRotorPart.getRotorMass(blockId, metadata); if(BlockTurbineRotorPart.isRotorBlade(metadata)) { bladeSurfaceArea += 1; } } if(isBlockPartOfCoil(x, y, z, blockId, metadata)) { coilSize += 1; } } // end z } // end y } // end x loop - looping over interior } public float getRotorSpeed() { return rotorSpeed; } public float getEnergyGeneratedLastTick() { return energyGeneratedLastTick; } public float getMaxRotorSpeed() { return 2000f; } private void markReferenceCoordDirty() { if(worldObj == null || worldObj.isRemote) { return; } CoordTriplet referenceCoord = getReferenceCoord(); if(referenceCoord == null) { return; } TileEntity saveTe = worldObj.getBlockTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z); worldObj.markTileEntityChunkModified(referenceCoord.x, referenceCoord.y, referenceCoord.z, saveTe); } }
package etomica.spin.heisenberg; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import etomica.action.IAction; import etomica.action.SimulationRestart; import etomica.action.activity.ActivityIntegrate; import etomica.api.IAtomType; import etomica.api.IBox; import etomica.box.Box; import etomica.box.BoxAgentManager; import etomica.chem.elements.ElementSimple; import etomica.data.AccumulatorAverage; import etomica.data.AccumulatorAverageCollapsing; import etomica.data.AccumulatorAverageCovariance; import etomica.data.AccumulatorAverageFixed; import etomica.data.DataPump; import etomica.data.IData; import etomica.data.types.DataDouble; import etomica.data.types.DataGroup; import etomica.graphics.DeviceSlider; import etomica.graphics.DisplayBox; import etomica.graphics.DisplayBoxSpin2D; import etomica.graphics.DisplayTextBox; import etomica.graphics.DisplayTextBoxesCAE; import etomica.graphics.SimulationGraphic; import etomica.integrator.IntegratorMC; import etomica.integrator.mcmove.MCMoveRotate; import etomica.listener.IntegratorListenerAction; import etomica.nbr.site.NeighborSiteManager; import etomica.nbr.site.PotentialMasterSite; import etomica.simulation.Simulation; import etomica.space.Space; import etomica.space2d.Space2D; import etomica.species.SpeciesSpheresMono; import etomica.species.SpeciesSpheresRotating; import etomica.units.systems.LJ; import etomica.util.ParameterBase; import etomica.util.ParseArgs; /** * Compute the dielectric constant of 2D Heisenberg model in conventional way and mapped averaging. * Conventional way: get the -bt*bt*<M^2> with M is the total dipole moment; * Mapped averaging: get the A_EE secondDerivative of free energy w.r.t electric field E when E is zero * Prototype for simulation of a more general magnetic system. * * @author David Kofke & Weisong Lin * */ public class Heisenberg extends Simulation { private static final String APP_NAME = "Heisenberg"; public Heisenberg(Space _space, int nCells, double temperature, double interactionS, double dipoleMagnitude) { super(_space); potentialMaster = new PotentialMasterSite(this, nCells, space); box = new Box(space); addBox(box); int numAtoms = space.powerD(nCells); spins = new SpeciesSpheresRotating(space, new ElementSimple("A")); addSpecies(spins); box.setNMolecules(spins, numAtoms); potential = new P2Spin(space,interactionS); field = new P1MagneticField(space,dipoleMagnitude); integrator = new IntegratorMC(this, potentialMaster); mcMove =new MCMoveRotate(potentialMaster, random, space); // new MCMoveSpinFlip(potentialMaster, getRandom(),space); integrator.getMoveManager().addMCMove(mcMove); integrator.setTemperature(temperature); activityIntegrate = new ActivityIntegrate(integrator); getController().addAction(activityIntegrate); IAtomType type = spins.getLeafType(); // potentialMaster.addPotential(field, new IAtomType[] {type}); potentialMaster.addPotential(potential, new IAtomType[] {type, type}); integrator.setBox(box); } private static final long serialVersionUID = 2L; public PotentialMasterSite potentialMaster; // difference betweet Pmaster pmastersite public IBox box; public SpeciesSpheresMono spins; public P2Spin potential; public P1MagneticField field; private IntegratorMC integrator; public MCMoveRotate mcMove; public final ActivityIntegrate activityIntegrate; public static void main(String[] args) { Param params = new Param(); if (args.length > 0) { ParseArgs.doParseArgs(params, args); } else { } final long startTime = System.currentTimeMillis(); DateFormat date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Calendar cal = Calendar.getInstance(); System.out.println("startTime : " + date.format(cal.getTime())); boolean isGraphic = params.isGraphic; double temperature = params.temperature; int nCells = params.nCells; int numberMolecules = nCells*nCells; boolean aEE = params.aEE; boolean mSquare = params.mSquare; int steps = params.steps; double interactionS = params.interactionS; double dipoleMagnitude = params.dipoleMagnitude; System.out.println("steps= "+steps); System.out.println("numberMolecules= "+numberMolecules); System.out.println("temperature= " + temperature); Space sp = Space2D.getInstance(); Heisenberg sim = new Heisenberg(sp, nCells,temperature,interactionS,dipoleMagnitude); MeterSpinMSquare meterMSquare = null; AccumulatorAverage dipoleSumSquaredAccumulator = null; if(isGraphic){ meterMSquare = new MeterSpinMSquare(sim.space,sim.box,dipoleMagnitude); dipoleSumSquaredAccumulator = new AccumulatorAverageCollapsing(100); DataPump dipolePump = new DataPump(meterMSquare,dipoleSumSquaredAccumulator); IntegratorListenerAction dipoleListener = new IntegratorListenerAction(dipolePump); dipoleListener.setInterval(10); sim.integrator.getEventManager().addListener(dipoleListener); SimulationGraphic simGraphic = new SimulationGraphic(sim, APP_NAME, sim.space, sim.getController()); ((SimulationRestart)simGraphic.getController().getReinitButton().getAction()).setConfiguration(null); IAction repaintAction = simGraphic.getPaintAction(sim.box); DisplayBox displayBox = simGraphic.getDisplayBox(sim.box); simGraphic.remove(displayBox); BoxAgentManager boxAgentManager = sim.potentialMaster.getCellAgentManager(); NeighborSiteManager neighborSiteManager = (NeighborSiteManager)boxAgentManager.getAgent(sim.box); displayBox.setBoxCanvas(new DisplayBoxSpin2D(displayBox,neighborSiteManager, sim.space, sim.getController())); simGraphic.add(displayBox); DeviceSlider temperatureSlider = new DeviceSlider(sim.getController(), sim.integrator,"temperature"); temperatureSlider.setMinimum(0.5); temperatureSlider.setMaximum(10.0); temperatureSlider.setShowBorder(true); LJ lj = new LJ(); temperatureSlider.setUnit(lj.temperature()); simGraphic.add(temperatureSlider); temperatureSlider.setValue(sim.integrator.getTemperature()); DeviceSlider fieldSlider = new DeviceSlider(sim.getController(), sim.field, "h"); fieldSlider.setMinimum(-5.); fieldSlider.setMaximum(+5.); fieldSlider.setNMajor(5); fieldSlider.setValue(0.0); fieldSlider.setShowBorder(true); fieldSlider.setLabel("Magnetic field"); simGraphic.add(fieldSlider); DisplayTextBoxesCAE boxes = new DisplayTextBoxesCAE(); boxes.setAccumulator(dipoleSumSquaredAccumulator); boxes.setLabel("Magnetization"); boxes.setLabelType(DisplayTextBox.LabelType.BORDER); simGraphic.add(boxes); simGraphic.getController().getReinitButton().setPostAction(repaintAction); simGraphic.makeAndDisplayFrame(APP_NAME); }//Graphics int blockNumber = 100; int sampleAtInterval = numberMolecules; int samplePerBlock = steps/sampleAtInterval/blockNumber; sim.activityIntegrate.setMaxSteps(steps/5); sim.getController().actionPerformed(); sim.getController().reset(); System.out.println("equilibration finished"); long equilibrationTime = System.currentTimeMillis(); System.out.println("equilibrationTime: " + (equilibrationTime - startTime)/(1000.0*60.0)); //mSquare if(mSquare){ meterMSquare = new MeterSpinMSquare(sim.space,sim.box,dipoleMagnitude); dipoleSumSquaredAccumulator = new AccumulatorAverageFixed(samplePerBlock); DataPump dipolePump = new DataPump(meterMSquare,dipoleSumSquaredAccumulator); IntegratorListenerAction dipoleListener = new IntegratorListenerAction(dipolePump); dipoleListener.setInterval(sampleAtInterval); sim.integrator.getEventManager().addListener(dipoleListener); } //AEE MeterMappedAveraging AEEMeter = null; AccumulatorAverageCovariance AEEAccumulator = null; if(aEE){ AEEMeter = new MeterMappedAveraging(sim.space, sim.box, sim,temperature,interactionS,dipoleMagnitude,sim.potentialMaster); AEEAccumulator = new AccumulatorAverageCovariance(samplePerBlock,true); DataPump AEEPump = new DataPump(AEEMeter,AEEAccumulator); IntegratorListenerAction AEEListener = new IntegratorListenerAction(AEEPump); AEEListener.setInterval(sampleAtInterval); sim.integrator.getEventManager().addListener(AEEListener); } sim.activityIntegrate.setMaxSteps(steps); sim.getController().actionPerformed(); public static class Param extends ParameterBase { public boolean isGraphic = false; public boolean mSquare = true; public boolean aEE = true; public double temperature = 78;// Kelvin public int nCells = 100;//number of atoms is nCells*nCells public double interactionS = 1.5; public double dipoleMagnitude = 1.5; public double QValue = 0; public int steps = 10000000; } }
package druid.examples.web; import org.junit.Test; import java.io.IOException; public class WebJsonSupplierTest { @Test(expected = IOException.class) public void checkInvalidUrl() throws Exception { String invalidURL = "http://invalid.url"; WebJsonSupplier supplier = new WebJsonSupplier(invalidURL); supplier.getInput(); } }
package org.exist.client.security; import java.util.Iterator; import java.util.regex.Pattern; import javax.swing.InputVerifier; import javax.swing.JOptionPane; import org.exist.client.InteractiveClient; import org.exist.security.AXSchemaType; import org.exist.security.EXistSchemaType; import org.exist.security.Permission; import org.exist.security.PermissionDeniedException; import org.exist.security.internal.aider.GroupAider; import org.exist.security.internal.aider.UserAider; import org.exist.xmldb.UserManagementService; import org.xmldb.api.base.XMLDBException; /** * * @author Adam Retter <adam.retter@googlemail.com> */ public class UserDialog extends javax.swing.JFrame { private static final long serialVersionUID = -7544980948396443454L; private final Pattern PTN_USERNAME = Pattern.compile("[a-zA-Z0-9\\-\\._@]{3,}"); private final Pattern PTN_PASSWORD = Pattern.compile(".{3,}"); private UserManagementService userManagementService; private SortedListModel<String> availableGroupsModel = null; private SortedListModel<String> memberOfGroupsModel = null; private String primaryGroup = null; private MemberOfGroupsListCellRenderer memberOfGroupsListCellRenderer = null; /** * Creates new form UserDialog */ public UserDialog(final UserManagementService userManagementService) { this.userManagementService = userManagementService; this.setIconImage(InteractiveClient.getExistIcon(getClass()).getImage()); initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { pmMemberOfGroups = new javax.swing.JPopupMenu(); cbmiPrimaryGroup = new javax.swing.JCheckBoxMenuItem(); jSeparator1 = new javax.swing.JSeparator(); lblUsername = new javax.swing.JLabel(); txtUsername = new javax.swing.JTextField(); lblFullName = new javax.swing.JLabel(); txtFullName = new javax.swing.JTextField(); lblDescription = new javax.swing.JLabel(); txtDescription = new javax.swing.JTextField(); lblPassword = new javax.swing.JLabel(); txtPassword = new javax.swing.JPasswordField(); lblPasswordConfirm = new javax.swing.JLabel(); txtPasswordConfirm = new javax.swing.JPasswordField(); cbDisabled = new javax.swing.JCheckBox(); jSeparator2 = new javax.swing.JSeparator(); spnUmask = new javax.swing.JSpinner(); lblUmask = new javax.swing.JLabel(); jSeparator3 = new javax.swing.JSeparator(); btnClose = new javax.swing.JButton(); btnCreate = new javax.swing.JButton(); cbPersonalGroup = new javax.swing.JCheckBox(); jScrollPane1 = new javax.swing.JScrollPane(); lstMemberOfGroups = new javax.swing.JList(); lblMemberOfGroups = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); lstAvailableGroups = new javax.swing.JList(); lblAvailableGroups = new javax.swing.JLabel(); btnAddGroup = new javax.swing.JButton(); btnRemoveGroup = new javax.swing.JButton(); jSeparator4 = new javax.swing.JSeparator(); cbmiPrimaryGroup.setSelected(true); cbmiPrimaryGroup.setText("Primary Group"); cbmiPrimaryGroup.addActionListener(this::cbmiPrimaryGroupActionPerformed); pmMemberOfGroups.add(cbmiPrimaryGroup); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("New User"); lblUsername.setText("User name:"); txtUsername.setInputVerifier(getUsernameInputVerifier()); lblFullName.setText("Full name:"); lblDescription.setText("Description:"); lblPassword.setText("Password:"); txtPassword.setInputVerifier(getPasswordInputVerifier()); lblPasswordConfirm.setText("Confirm password:"); txtPasswordConfirm.setInputVerifier(getPasswordInputVerifier()); cbDisabled.setText("Account is disabled"); spnUmask.setModel(new UmaskSpinnerModel()); spnUmask.setEditor(new UmaskEditor(spnUmask)); spnUmask.setValue(getUmask()); lblUmask.setText("umask:"); btnClose.setText("Close"); btnClose.addActionListener(this::btnCloseActionPerformed); btnCreate.setText("Create"); btnCreate.addActionListener(this::btnCreateActionPerformed); cbPersonalGroup.setSelected(true); cbPersonalGroup.setText("Create personal user group"); lstMemberOfGroups.setModel(getMemberOfGroupsListModel()); lstMemberOfGroups.setCellRenderer(getMemberOfGroupsListCellRenderer()); lstMemberOfGroups.setComponentPopupMenu(pmMemberOfGroups); lstMemberOfGroups.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { lstMemberOfGroupsMouseClicked(evt); } }); jScrollPane1.setViewportView(lstMemberOfGroups); lblMemberOfGroups.setText("Member of Groups:"); lstAvailableGroups.setModel(getAvailableGroupsListModel()); jScrollPane2.setViewportView(lstAvailableGroups); lblAvailableGroups.setText("Available Groups:"); btnAddGroup.setText("->"); btnAddGroup.setToolTipText("Add to Group"); btnAddGroup.addActionListener(this::btnAddGroupActionPerformed); btnRemoveGroup.setText("<-"); btnRemoveGroup.setToolTipText("Remove from Group"); btnRemoveGroup.addActionListener(this::btnRemoveGroupActionPerformed); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGap(6, 6, 6) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(btnClose) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnCreate) .addGap(6, 6, 6)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(btnAddGroup, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnRemoveGroup, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))) .addComponent(lblAvailableGroups)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblMemberOfGroups) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(25, 25, 25) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(lblDescription) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)) .addGroup(layout.createSequentialGroup() .addComponent(lblFullName) .addGap(24, 24, 24))) .addGroup(layout.createSequentialGroup() .addComponent(lblUsername) .addGap(3, 3, 3))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(txtUsername, javax.swing.GroupLayout.DEFAULT_SIZE, 296, Short.MAX_VALUE) .addComponent(txtFullName, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtDescription, javax.swing.GroupLayout.Alignment.LEADING))) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblPasswordConfirm) .addComponent(lblPassword)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE) .addComponent(txtPasswordConfirm)))) .addGap(0, 35, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jSeparator4) .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING)))) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(16, 16, 16) .addComponent(lblUmask) .addGap(18, 18, 18) .addComponent(spnUmask, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator2) .addComponent(jSeparator3)) .addContainerGap()))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(16, 16, 16) .addComponent(cbDisabled)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(cbPersonalGroup))) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(22, 22, 22) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblUsername) .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblFullName) .addComponent(txtFullName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblDescription) .addComponent(txtDescription, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblPassword) .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtPasswordConfirm, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblPasswordConfirm)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cbDisabled) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(spnUmask, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblUmask)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cbPersonalGroup) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblMemberOfGroups, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(lblAvailableGroups)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGap(52, 52, 52) .addComponent(btnAddGroup) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnRemoveGroup))) .addGap(10, 10, 10) .addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnClose) .addComponent(btnCreate)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed setVisible(false); dispose(); }//GEN-LAST:event_btnCloseActionPerformed private void btnCreateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCreateActionPerformed if(!isValidUserDetails()) { return; } //create the user createUser(); //close the dialog setVisible(false); dispose(); }//GEN-LAST:event_btnCreateActionPerformed protected void createUser() { //0 - determine the primary group final GroupAider primaryGroup; if (getPrimaryGroup() == null) { if (cbPersonalGroup.isSelected()) { primaryGroup = new GroupAider(txtUsername.getText()); } else { final String firstGroup = memberOfGroupsModel.firstElement(); if (firstGroup != null) { primaryGroup = new GroupAider(firstGroup); } else { JOptionPane.showMessageDialog(this, "Could not determine primary group for user '" + txtUsername.getText() + "'. User must create personal group or belong to at least one existing group", "Create User Error", JOptionPane.ERROR_MESSAGE); return; } } } else { primaryGroup = new GroupAider(getPrimaryGroup()); } //1 - create personal group GroupAider groupAider = null; if(cbPersonalGroup.isSelected()) { groupAider = new GroupAider(txtUsername.getText()); groupAider.setMetadataValue(EXistSchemaType.DESCRIPTION, "Personal group for " + txtUsername.getText()); try { getUserManagementService().addGroup(groupAider); } catch(final XMLDBException xmldbe) { JOptionPane.showMessageDialog(this, "Could not create personal group '" + txtUsername.getText() + "': " + xmldbe.getMessage(), "Create User Error", JOptionPane.ERROR_MESSAGE); return; } } //2 - create the user final UserAider userAider = new UserAider(txtUsername.getText()); userAider.setMetadataValue(AXSchemaType.FULLNAME, txtFullName.getText()); userAider.setMetadataValue(EXistSchemaType.DESCRIPTION, txtDescription.getText()); userAider.setPassword(txtPassword.getText()); userAider.setEnabled(!cbDisabled.isSelected()); userAider.setUserMask(UmaskSpinnerModel.octalUmaskToInt((String)spnUmask.getValue())); //add the personal group to the user if(cbPersonalGroup.isSelected()) { userAider.addGroup(txtUsername.getText()); } //add any other groups to the user final Iterator<String> itMemberOfGroups = memberOfGroupsModel.iterator(); while(itMemberOfGroups.hasNext()) { final String memberOfGroup = itMemberOfGroups.next(); userAider.addGroup(memberOfGroup); } //set the primary group try { userAider.setPrimaryGroup(primaryGroup); } catch(final PermissionDeniedException pde) { JOptionPane.showMessageDialog(this, "Could not set primary group '" + getPrimaryGroup() + "' of user '" + txtUsername.getText() + "': " + pde.getMessage(), "Create User Error", JOptionPane.ERROR_MESSAGE); return; } try { getUserManagementService().addAccount(userAider); } catch(final XMLDBException xmldbe) { JOptionPane.showMessageDialog(this, "Could not create user '" + txtUsername.getText() + "': " + xmldbe.getMessage(), "Create User Error", JOptionPane.ERROR_MESSAGE); return; } //3 - if created personal group, then add us as the manager if(cbPersonalGroup.isSelected()) { try { groupAider.addManager(userAider); getUserManagementService().updateGroup(groupAider); } catch(final XMLDBException xmldbe) { JOptionPane.showMessageDialog(this, "Could not set user '" + txtUsername.getText() + "' as manager of personal group '" + txtUsername.getText() + "': " + xmldbe.getMessage(), "Create User Error", JOptionPane.ERROR_MESSAGE); return; } catch(final PermissionDeniedException pde) { JOptionPane.showMessageDialog(this, "Could not set user '" + txtUsername.getText() + "' as manager of personal group '" + txtUsername.getText() + "': " + pde.getMessage(), "Create User Error", JOptionPane.ERROR_MESSAGE); return; } } } private void btnAddGroupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddGroupActionPerformed for(final Object value: lstAvailableGroups.getSelectedValues()) { memberOfGroupsModel.add(value.toString()); availableGroupsModel.removeElement(value.toString()); //is this the first group added to the user? if(getMemberOfGroupsListModel().getSize() == 1 && !cbPersonalGroup.isSelected()) { final String firstGroup = (String)getMemberOfGroupsListModel().getElementAt(0); setPrimaryGroup(firstGroup); getMemberOfGroupsListCellRenderer().setCellOfInterest(getPrimaryGroup()); } } }//GEN-LAST:event_btnAddGroupActionPerformed private void btnRemoveGroupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveGroupActionPerformed for(final Object value: lstMemberOfGroups.getSelectedValues()) { final String group = value.toString(); availableGroupsModel.add(group); memberOfGroupsModel.removeElement(group); //are we removing the users primary group? if(group.equals(getPrimaryGroup())) { if(getMemberOfGroupsListModel().getSize() == 0 || cbPersonalGroup.isSelected()) { setPrimaryGroup(null); } else { //default to the first group final String firstGroup = (String)getMemberOfGroupsListModel().getElementAt(0); setPrimaryGroup(firstGroup); } } getMemberOfGroupsListCellRenderer().setCellOfInterest(getPrimaryGroup()); } }//GEN-LAST:event_btnRemoveGroupActionPerformed private void cbmiPrimaryGroupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbmiPrimaryGroupActionPerformed final String newPrimaryGroup = (String)getMemberOfGroupsListModel().getElementAt(lstMemberOfGroups.getSelectedIndex()); if (newPrimaryGroup.equals(this.primaryGroup)) { // deselect existing primary group this.primaryGroup = null; } else { // select new primary group this.primaryGroup = newPrimaryGroup; } getMemberOfGroupsListCellRenderer().setCellOfInterest(primaryGroup); }//GEN-LAST:event_cbmiPrimaryGroupActionPerformed private void lstMemberOfGroupsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lstMemberOfGroupsMouseClicked cbmiPrimaryGroup.setState(((String)getMemberOfGroupsListModel().getElementAt(lstMemberOfGroups.getSelectedIndex())).equals(primaryGroup)); }//GEN-LAST:event_lstMemberOfGroupsMouseClicked private boolean isValidUserDetails() { return isValidUsername() && isValidPassword() && isValidGroups(); } private boolean isValidUsername() { if(PTN_USERNAME.matcher(txtUsername.getText()).matches()) { return true; } JOptionPane.showMessageDialog(this, "Username must be at least 3 characters (" + PTN_USERNAME.toString() + ")"); return false; } private boolean isValidPassword() { if(txtPassword != null && PTN_PASSWORD.matcher(txtPassword.getText()).matches() && txtPassword.getText().equals(txtPasswordConfirm.getText())) { return true; } JOptionPane.showMessageDialog(this, "Passwords do not match or are less than 3 characters."); return false; } private boolean isValidGroups() { if(cbPersonalGroup.isSelected() || memberOfGroupsModel.getSize() > 0) { return true; } JOptionPane.showMessageDialog(this, "The user must be in at least one group, or a personal group must be created for them."); return false; } private InputVerifier getUsernameInputVerifier() { return new RegExpInputVerifier(PTN_USERNAME); } private InputVerifier getPasswordInputVerifier() { return new RegExpInputVerifier(PTN_PASSWORD); } private String getUmask() { return String.format("%4s", Integer.toString(Permission.DEFAULT_UMASK, UmaskSpinnerModel.OCTAL_RADIX)).replace(' ', '0'); } protected SortedListModel getAvailableGroupsListModel() { if(availableGroupsModel == null) { try { final String groupNames[] = getUserManagementService().getGroups(); availableGroupsModel = new SortedListModel<String>(); availableGroupsModel.addAll(groupNames); } catch (final XMLDBException xmldbe) { JOptionPane.showMessageDialog(this, "Could not get available groups: " + xmldbe.getMessage(), "Create User Error", JOptionPane.ERROR_MESSAGE); } } return availableGroupsModel; } protected SortedListModel getMemberOfGroupsListModel() { if(memberOfGroupsModel == null) { memberOfGroupsModel = new SortedListModel<String>(); } return memberOfGroupsModel; } protected UserManagementService getUserManagementService() { return userManagementService; } protected void setPrimaryGroup(final String primaryGroup) { this.primaryGroup = primaryGroup; } protected String getPrimaryGroup() { return primaryGroup; } protected void setUserManagementService(final UserManagementService userManagementService) { this.userManagementService = userManagementService; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAddGroup; private javax.swing.JButton btnClose; protected javax.swing.JButton btnCreate; private javax.swing.JButton btnRemoveGroup; protected javax.swing.JCheckBox cbDisabled; protected javax.swing.JCheckBox cbPersonalGroup; private javax.swing.JCheckBoxMenuItem cbmiPrimaryGroup; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JSeparator jSeparator3; private javax.swing.JSeparator jSeparator4; private javax.swing.JLabel lblAvailableGroups; private javax.swing.JLabel lblDescription; private javax.swing.JLabel lblFullName; private javax.swing.JLabel lblMemberOfGroups; private javax.swing.JLabel lblPassword; private javax.swing.JLabel lblPasswordConfirm; private javax.swing.JLabel lblUmask; private javax.swing.JLabel lblUsername; private javax.swing.JList lstAvailableGroups; private javax.swing.JList lstMemberOfGroups; private javax.swing.JPopupMenu pmMemberOfGroups; protected javax.swing.JSpinner spnUmask; protected javax.swing.JTextField txtDescription; protected javax.swing.JTextField txtFullName; protected javax.swing.JPasswordField txtPassword; protected javax.swing.JPasswordField txtPasswordConfirm; protected javax.swing.JTextField txtUsername; // End of variables declaration//GEN-END:variables protected MemberOfGroupsListCellRenderer getMemberOfGroupsListCellRenderer() { if(memberOfGroupsListCellRenderer == null) { memberOfGroupsListCellRenderer = new MemberOfGroupsListCellRenderer(); } return memberOfGroupsListCellRenderer; } }