repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
digitalpetri/modbus
modbus-core/src/main/java/com/digitalpetri/modbus/requests/WriteSingleRegisterRequest.java
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java // public enum FunctionCode { // // ReadCoils(0x01), // ReadDiscreteInputs(0x02), // ReadHoldingRegisters(0x03), // ReadInputRegisters(0x04), // WriteSingleCoil(0x05), // WriteSingleRegister(0x06), // ReadExceptionStatus(0x07), // Diagnostics(0x08), // GetCommEventCounter(0x0B), // GetCommEventLog(0x0C), // WriteMultipleCoils(0x0F), // WriteMultipleRegisters(0x10), // ReportSlaveId(0x11), // ReadFileRecord(0x14), // WriteFileRecord(0x15), // MaskWriteRegister(0x16), // ReadWriteMultipleRegisters(0x17), // ReadFifoQueue(0x18), // EncapsulatedInterfaceTransport(0x2B); // // private final int code; // // FunctionCode(int code) { // this.code = code; // } // // public int getCode() { // return code; // } // // public static Optional<FunctionCode> fromCode(int code) { // switch(code) { // case 0x01: return Optional.of(ReadCoils); // case 0x02: return Optional.of(ReadDiscreteInputs); // case 0x03: return Optional.of(ReadHoldingRegisters); // case 0x04: return Optional.of(ReadInputRegisters); // case 0x05: return Optional.of(WriteSingleCoil); // case 0x06: return Optional.of(WriteSingleRegister); // case 0x07: return Optional.of(ReadExceptionStatus); // case 0x08: return Optional.of(Diagnostics); // case 0x0B: return Optional.of(GetCommEventCounter); // case 0x0C: return Optional.of(GetCommEventLog); // case 0x0F: return Optional.of(WriteMultipleCoils); // case 0x10: return Optional.of(WriteMultipleRegisters); // case 0x11: return Optional.of(ReportSlaveId); // case 0x14: return Optional.of(ReadFileRecord); // case 0x15: return Optional.of(WriteFileRecord); // case 0x16: return Optional.of(MaskWriteRegister); // case 0x17: return Optional.of(ReadWriteMultipleRegisters); // case 0x18: return Optional.of(ReadFifoQueue); // case 0x2B: return Optional.of(EncapsulatedInterfaceTransport); // } // // return Optional.empty(); // } // // public static boolean isExceptionCode(int code) { // return fromCode(code - 0x80).isPresent(); // } // // }
import com.digitalpetri.modbus.FunctionCode;
/* * Copyright 2016 Kevin Herron * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.digitalpetri.modbus.requests; /** * This function is used to write to a single holding register in a remote device. * <p> * The Request PDU specifies the address of the register to be written. Registers are addressed starting at zero. * Therefore register numbered 1 is addressed as 0. */ public class WriteSingleRegisterRequest extends SimpleModbusRequest { private final int address; private final int value; /** * @param address 0x0000 to 0xFFFF (0 to 65535) * @param value 0x0000 to 0xFFFF (0 to 65535) */ public WriteSingleRegisterRequest(int address, int value) {
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java // public enum FunctionCode { // // ReadCoils(0x01), // ReadDiscreteInputs(0x02), // ReadHoldingRegisters(0x03), // ReadInputRegisters(0x04), // WriteSingleCoil(0x05), // WriteSingleRegister(0x06), // ReadExceptionStatus(0x07), // Diagnostics(0x08), // GetCommEventCounter(0x0B), // GetCommEventLog(0x0C), // WriteMultipleCoils(0x0F), // WriteMultipleRegisters(0x10), // ReportSlaveId(0x11), // ReadFileRecord(0x14), // WriteFileRecord(0x15), // MaskWriteRegister(0x16), // ReadWriteMultipleRegisters(0x17), // ReadFifoQueue(0x18), // EncapsulatedInterfaceTransport(0x2B); // // private final int code; // // FunctionCode(int code) { // this.code = code; // } // // public int getCode() { // return code; // } // // public static Optional<FunctionCode> fromCode(int code) { // switch(code) { // case 0x01: return Optional.of(ReadCoils); // case 0x02: return Optional.of(ReadDiscreteInputs); // case 0x03: return Optional.of(ReadHoldingRegisters); // case 0x04: return Optional.of(ReadInputRegisters); // case 0x05: return Optional.of(WriteSingleCoil); // case 0x06: return Optional.of(WriteSingleRegister); // case 0x07: return Optional.of(ReadExceptionStatus); // case 0x08: return Optional.of(Diagnostics); // case 0x0B: return Optional.of(GetCommEventCounter); // case 0x0C: return Optional.of(GetCommEventLog); // case 0x0F: return Optional.of(WriteMultipleCoils); // case 0x10: return Optional.of(WriteMultipleRegisters); // case 0x11: return Optional.of(ReportSlaveId); // case 0x14: return Optional.of(ReadFileRecord); // case 0x15: return Optional.of(WriteFileRecord); // case 0x16: return Optional.of(MaskWriteRegister); // case 0x17: return Optional.of(ReadWriteMultipleRegisters); // case 0x18: return Optional.of(ReadFifoQueue); // case 0x2B: return Optional.of(EncapsulatedInterfaceTransport); // } // // return Optional.empty(); // } // // public static boolean isExceptionCode(int code) { // return fromCode(code - 0x80).isPresent(); // } // // } // Path: modbus-core/src/main/java/com/digitalpetri/modbus/requests/WriteSingleRegisterRequest.java import com.digitalpetri.modbus.FunctionCode; /* * Copyright 2016 Kevin Herron * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.digitalpetri.modbus.requests; /** * This function is used to write to a single holding register in a remote device. * <p> * The Request PDU specifies the address of the register to be written. Registers are addressed starting at zero. * Therefore register numbered 1 is addressed as 0. */ public class WriteSingleRegisterRequest extends SimpleModbusRequest { private final int address; private final int value; /** * @param address 0x0000 to 0xFFFF (0 to 65535) * @param value 0x0000 to 0xFFFF (0 to 65535) */ public WriteSingleRegisterRequest(int address, int value) {
super(FunctionCode.WriteSingleRegister);
Azure/azure-storage-android
microsoft-azure-storage-test/src/com/microsoft/azure/storage/table/TableEscapingTests.java
// Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/TestRunners.java // public interface CloudTests { // } // // Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/TestRunners.java // public interface DevFabricTests { // } // // Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/TestRunners.java // public interface DevStoreTests { // } // // Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/table/TableTestHelper.java // public static class Class1 extends TableServiceEntity implements PropertyResolver { // // public String A; // // public String B; // // public String C; // // public byte[] D; // // public Class1() { // // empty ctor // } // // public Class1(String pk, String rk) { // super(pk, rk); // } // // public synchronized String getA() { // return this.A; // } // // public synchronized String getB() { // return this.B; // } // // public synchronized String getC() { // return this.C; // } // // public synchronized byte[] getD() { // return this.D; // } // // public synchronized void setA(final String a) { // this.A = a; // } // // public synchronized void setB(final String b) { // this.B = b; // } // // public synchronized void setC(final String c) { // this.C = c; // } // // public synchronized void setD(final byte[] d) { // this.D = d; // } // // @Override // public EdmType propertyResolver(String pk, String rk, String key, String value) { // if (key.equals("A")) { // return EdmType.STRING; // } // else if (key.equals("B")) { // return EdmType.STRING; // } // else if (key.equals("C")) { // return EdmType.STRING; // } // else if (key.equals("D")) { // return EdmType.BINARY; // } // return null; // } // }
import com.microsoft.azure.storage.StorageException; import com.microsoft.azure.storage.TestRunners.CloudTests; import com.microsoft.azure.storage.TestRunners.DevFabricTests; import com.microsoft.azure.storage.TestRunners.DevStoreTests; import com.microsoft.azure.storage.table.TableTestHelper.Class1; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import java.net.URISyntaxException; import java.util.UUID; import static org.junit.Assert.*;
doEscapeTest("!<", false); doEscapeTest("<!%^&j", false); } @Test public void testXmlTestBatch() throws StorageException { doEscapeTest("</>", false); doEscapeTest("<tag>", false); doEscapeTest("</entry>", false); doEscapeTest("!<", false); doEscapeTest("<!%^&j", false); } private void doEscapeTest(String data, boolean useBatch) throws StorageException { doEscapeTest(data, useBatch, false); } private void doEscapeTest(String data, boolean useBatch, boolean includeInKey) throws StorageException { TableRequestOptions options = new TableRequestOptions(); options.setTablePayloadFormat(TablePayloadFormat.JsonFullMetadata); doEscapeTestHelper(data, useBatch, includeInKey, options); options.setTablePayloadFormat(TablePayloadFormat.Json); doEscapeTestHelper(data, useBatch, includeInKey, options); options.setTablePayloadFormat(TablePayloadFormat.JsonNoMetadata); doEscapeTestHelper(data, useBatch, includeInKey, options); options.setTablePayloadFormat(TablePayloadFormat.JsonNoMetadata);
// Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/TestRunners.java // public interface CloudTests { // } // // Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/TestRunners.java // public interface DevFabricTests { // } // // Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/TestRunners.java // public interface DevStoreTests { // } // // Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/table/TableTestHelper.java // public static class Class1 extends TableServiceEntity implements PropertyResolver { // // public String A; // // public String B; // // public String C; // // public byte[] D; // // public Class1() { // // empty ctor // } // // public Class1(String pk, String rk) { // super(pk, rk); // } // // public synchronized String getA() { // return this.A; // } // // public synchronized String getB() { // return this.B; // } // // public synchronized String getC() { // return this.C; // } // // public synchronized byte[] getD() { // return this.D; // } // // public synchronized void setA(final String a) { // this.A = a; // } // // public synchronized void setB(final String b) { // this.B = b; // } // // public synchronized void setC(final String c) { // this.C = c; // } // // public synchronized void setD(final byte[] d) { // this.D = d; // } // // @Override // public EdmType propertyResolver(String pk, String rk, String key, String value) { // if (key.equals("A")) { // return EdmType.STRING; // } // else if (key.equals("B")) { // return EdmType.STRING; // } // else if (key.equals("C")) { // return EdmType.STRING; // } // else if (key.equals("D")) { // return EdmType.BINARY; // } // return null; // } // } // Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/table/TableEscapingTests.java import com.microsoft.azure.storage.StorageException; import com.microsoft.azure.storage.TestRunners.CloudTests; import com.microsoft.azure.storage.TestRunners.DevFabricTests; import com.microsoft.azure.storage.TestRunners.DevStoreTests; import com.microsoft.azure.storage.table.TableTestHelper.Class1; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import java.net.URISyntaxException; import java.util.UUID; import static org.junit.Assert.*; doEscapeTest("!<", false); doEscapeTest("<!%^&j", false); } @Test public void testXmlTestBatch() throws StorageException { doEscapeTest("</>", false); doEscapeTest("<tag>", false); doEscapeTest("</entry>", false); doEscapeTest("!<", false); doEscapeTest("<!%^&j", false); } private void doEscapeTest(String data, boolean useBatch) throws StorageException { doEscapeTest(data, useBatch, false); } private void doEscapeTest(String data, boolean useBatch, boolean includeInKey) throws StorageException { TableRequestOptions options = new TableRequestOptions(); options.setTablePayloadFormat(TablePayloadFormat.JsonFullMetadata); doEscapeTestHelper(data, useBatch, includeInKey, options); options.setTablePayloadFormat(TablePayloadFormat.Json); doEscapeTestHelper(data, useBatch, includeInKey, options); options.setTablePayloadFormat(TablePayloadFormat.JsonNoMetadata); doEscapeTestHelper(data, useBatch, includeInKey, options); options.setTablePayloadFormat(TablePayloadFormat.JsonNoMetadata);
options.setPropertyResolver(new Class1());
Azure/azure-storage-android
microsoft-azure-storage-test/src/com/microsoft/azure/storage/table/TableODataTests.java
// Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/TestRunners.java // public interface CloudTests { // } // // Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/TestRunners.java // public interface DevFabricTests { // } // // Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/TestRunners.java // public interface DevStoreTests { // } // // Path: microsoft-azure-storage/src/com/microsoft/azure/storage/table/TableRequestOptions.java // public interface PropertyResolver { // // /** // * Given the partition key, row, key, and the property name, produces the EdmType // * // * @param pk // * A <code>String</code> which represents the partition key. // * @param rk // * A <code>String</code> which represents the row key. // * @param key // * A <code>String</code> which represents the property name. // * @param value // * A <code>String</code> which represents the property value. // * @return // * The {@link EdmType} of the property. // */ // public EdmType propertyResolver(String pk, String rk, String key, String value); // // } // // Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/table/TableTestHelper.java // public static class Class1 extends TableServiceEntity implements PropertyResolver { // // public String A; // // public String B; // // public String C; // // public byte[] D; // // public Class1() { // // empty ctor // } // // public Class1(String pk, String rk) { // super(pk, rk); // } // // public synchronized String getA() { // return this.A; // } // // public synchronized String getB() { // return this.B; // } // // public synchronized String getC() { // return this.C; // } // // public synchronized byte[] getD() { // return this.D; // } // // public synchronized void setA(final String a) { // this.A = a; // } // // public synchronized void setB(final String b) { // this.B = b; // } // // public synchronized void setC(final String c) { // this.C = c; // } // // public synchronized void setD(final byte[] d) { // this.D = d; // } // // @Override // public EdmType propertyResolver(String pk, String rk, String key, String value) { // if (key.equals("A")) { // return EdmType.STRING; // } // else if (key.equals("B")) { // return EdmType.STRING; // } // else if (key.equals("C")) { // return EdmType.STRING; // } // else if (key.equals("D")) { // return EdmType.BINARY; // } // return null; // } // }
import com.microsoft.azure.storage.StorageException; import com.microsoft.azure.storage.TestRunners.CloudTests; import com.microsoft.azure.storage.TestRunners.DevFabricTests; import com.microsoft.azure.storage.TestRunners.DevStoreTests; import com.microsoft.azure.storage.table.TableRequestOptions.PropertyResolver; import com.microsoft.azure.storage.table.TableTestHelper.Class1; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import java.net.URISyntaxException; import java.util.UUID; import static org.junit.Assert.*;
/** * Copyright Microsoft Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.microsoft.azure.storage.table; @Category({ DevFabricTests.class, DevStoreTests.class, CloudTests.class }) public class TableODataTests { TableRequestOptions options; DynamicTableEntity ent; private CloudTable table; @Before public void tableODataTestBeforeMethodSetUp() throws StorageException, URISyntaxException { this.table = TableTestHelper.getRandomTableReference(); this.table.createIfNotExists(); final CloudTableClient tClient = TableTestHelper.createCloudTableClient(); this.options = TableRequestOptions.populateAndApplyDefaults(this.options, tClient); this.options.setTablePayloadFormat(TablePayloadFormat.JsonNoMetadata); // Insert Entity this.ent = new DynamicTableEntity(); this.ent.setPartitionKey("jxscl_odata"); this.ent.setRowKey(UUID.randomUUID().toString()); this.ent.getProperties().put("foo2", new EntityProperty("bar2")); this.ent.getProperties().put("foo", new EntityProperty("bar")); this.ent.getProperties().put("fooint", new EntityProperty(1234)); this.table.execute(TableOperation.insert(this.ent), this.options, null); } @After public void tableODataTestBeforeMethodTearDown() throws StorageException { this.table.execute(TableOperation.delete(this.ent), this.options, null); this.table.deleteIfExists(); } @Test public void testTableOperationRetrieveJsonNoMetadataFail() { // set custom property resolver this.options.setPropertyResolver(new CustomPropertyResolver()); try {
// Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/TestRunners.java // public interface CloudTests { // } // // Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/TestRunners.java // public interface DevFabricTests { // } // // Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/TestRunners.java // public interface DevStoreTests { // } // // Path: microsoft-azure-storage/src/com/microsoft/azure/storage/table/TableRequestOptions.java // public interface PropertyResolver { // // /** // * Given the partition key, row, key, and the property name, produces the EdmType // * // * @param pk // * A <code>String</code> which represents the partition key. // * @param rk // * A <code>String</code> which represents the row key. // * @param key // * A <code>String</code> which represents the property name. // * @param value // * A <code>String</code> which represents the property value. // * @return // * The {@link EdmType} of the property. // */ // public EdmType propertyResolver(String pk, String rk, String key, String value); // // } // // Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/table/TableTestHelper.java // public static class Class1 extends TableServiceEntity implements PropertyResolver { // // public String A; // // public String B; // // public String C; // // public byte[] D; // // public Class1() { // // empty ctor // } // // public Class1(String pk, String rk) { // super(pk, rk); // } // // public synchronized String getA() { // return this.A; // } // // public synchronized String getB() { // return this.B; // } // // public synchronized String getC() { // return this.C; // } // // public synchronized byte[] getD() { // return this.D; // } // // public synchronized void setA(final String a) { // this.A = a; // } // // public synchronized void setB(final String b) { // this.B = b; // } // // public synchronized void setC(final String c) { // this.C = c; // } // // public synchronized void setD(final byte[] d) { // this.D = d; // } // // @Override // public EdmType propertyResolver(String pk, String rk, String key, String value) { // if (key.equals("A")) { // return EdmType.STRING; // } // else if (key.equals("B")) { // return EdmType.STRING; // } // else if (key.equals("C")) { // return EdmType.STRING; // } // else if (key.equals("D")) { // return EdmType.BINARY; // } // return null; // } // } // Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/table/TableODataTests.java import com.microsoft.azure.storage.StorageException; import com.microsoft.azure.storage.TestRunners.CloudTests; import com.microsoft.azure.storage.TestRunners.DevFabricTests; import com.microsoft.azure.storage.TestRunners.DevStoreTests; import com.microsoft.azure.storage.table.TableRequestOptions.PropertyResolver; import com.microsoft.azure.storage.table.TableTestHelper.Class1; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import java.net.URISyntaxException; import java.util.UUID; import static org.junit.Assert.*; /** * Copyright Microsoft Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.microsoft.azure.storage.table; @Category({ DevFabricTests.class, DevStoreTests.class, CloudTests.class }) public class TableODataTests { TableRequestOptions options; DynamicTableEntity ent; private CloudTable table; @Before public void tableODataTestBeforeMethodSetUp() throws StorageException, URISyntaxException { this.table = TableTestHelper.getRandomTableReference(); this.table.createIfNotExists(); final CloudTableClient tClient = TableTestHelper.createCloudTableClient(); this.options = TableRequestOptions.populateAndApplyDefaults(this.options, tClient); this.options.setTablePayloadFormat(TablePayloadFormat.JsonNoMetadata); // Insert Entity this.ent = new DynamicTableEntity(); this.ent.setPartitionKey("jxscl_odata"); this.ent.setRowKey(UUID.randomUUID().toString()); this.ent.getProperties().put("foo2", new EntityProperty("bar2")); this.ent.getProperties().put("foo", new EntityProperty("bar")); this.ent.getProperties().put("fooint", new EntityProperty(1234)); this.table.execute(TableOperation.insert(this.ent), this.options, null); } @After public void tableODataTestBeforeMethodTearDown() throws StorageException { this.table.execute(TableOperation.delete(this.ent), this.options, null); this.table.deleteIfExists(); } @Test public void testTableOperationRetrieveJsonNoMetadataFail() { // set custom property resolver this.options.setPropertyResolver(new CustomPropertyResolver()); try {
this.table.execute(TableOperation.retrieve(this.ent.getPartitionKey(), this.ent.getRowKey(), Class1.class),
Azure/azure-storage-android
microsoft-azure-storage-test/src/com/microsoft/azure/storage/table/TableODataTests.java
// Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/TestRunners.java // public interface CloudTests { // } // // Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/TestRunners.java // public interface DevFabricTests { // } // // Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/TestRunners.java // public interface DevStoreTests { // } // // Path: microsoft-azure-storage/src/com/microsoft/azure/storage/table/TableRequestOptions.java // public interface PropertyResolver { // // /** // * Given the partition key, row, key, and the property name, produces the EdmType // * // * @param pk // * A <code>String</code> which represents the partition key. // * @param rk // * A <code>String</code> which represents the row key. // * @param key // * A <code>String</code> which represents the property name. // * @param value // * A <code>String</code> which represents the property value. // * @return // * The {@link EdmType} of the property. // */ // public EdmType propertyResolver(String pk, String rk, String key, String value); // // } // // Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/table/TableTestHelper.java // public static class Class1 extends TableServiceEntity implements PropertyResolver { // // public String A; // // public String B; // // public String C; // // public byte[] D; // // public Class1() { // // empty ctor // } // // public Class1(String pk, String rk) { // super(pk, rk); // } // // public synchronized String getA() { // return this.A; // } // // public synchronized String getB() { // return this.B; // } // // public synchronized String getC() { // return this.C; // } // // public synchronized byte[] getD() { // return this.D; // } // // public synchronized void setA(final String a) { // this.A = a; // } // // public synchronized void setB(final String b) { // this.B = b; // } // // public synchronized void setC(final String c) { // this.C = c; // } // // public synchronized void setD(final byte[] d) { // this.D = d; // } // // @Override // public EdmType propertyResolver(String pk, String rk, String key, String value) { // if (key.equals("A")) { // return EdmType.STRING; // } // else if (key.equals("B")) { // return EdmType.STRING; // } // else if (key.equals("C")) { // return EdmType.STRING; // } // else if (key.equals("D")) { // return EdmType.BINARY; // } // return null; // } // }
import com.microsoft.azure.storage.StorageException; import com.microsoft.azure.storage.TestRunners.CloudTests; import com.microsoft.azure.storage.TestRunners.DevFabricTests; import com.microsoft.azure.storage.TestRunners.DevStoreTests; import com.microsoft.azure.storage.table.TableRequestOptions.PropertyResolver; import com.microsoft.azure.storage.table.TableTestHelper.Class1; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import java.net.URISyntaxException; import java.util.UUID; import static org.junit.Assert.*;
try { this.table.execute(TableOperation.retrieve(this.ent.getPartitionKey(), this.ent.getRowKey(), Class1.class), this.options, null); fail("Invalid property resolver should throw"); } catch (StorageException e) { assertEquals("Failed to parse property 'fooint' with value '1234' as type 'Edm.Guid'", e.getMessage()); } } @Test public void testTableOperationRetrieveJsonNoMetadataResolverFail() { // set custom property resolver which throws this.options.setPropertyResolver(new ThrowingPropertyResolver()); try { this.table.execute(TableOperation.retrieve(this.ent.getPartitionKey(), this.ent.getRowKey(), Class1.class), this.options, null); fail("Invalid property resolver should throw"); } catch (StorageException e) { assertEquals( "The custom property resolver delegate threw an exception. Check the inner exception for more details.", e.getMessage()); assertTrue(e.getCause().getClass() == IllegalArgumentException.class); } }
// Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/TestRunners.java // public interface CloudTests { // } // // Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/TestRunners.java // public interface DevFabricTests { // } // // Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/TestRunners.java // public interface DevStoreTests { // } // // Path: microsoft-azure-storage/src/com/microsoft/azure/storage/table/TableRequestOptions.java // public interface PropertyResolver { // // /** // * Given the partition key, row, key, and the property name, produces the EdmType // * // * @param pk // * A <code>String</code> which represents the partition key. // * @param rk // * A <code>String</code> which represents the row key. // * @param key // * A <code>String</code> which represents the property name. // * @param value // * A <code>String</code> which represents the property value. // * @return // * The {@link EdmType} of the property. // */ // public EdmType propertyResolver(String pk, String rk, String key, String value); // // } // // Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/table/TableTestHelper.java // public static class Class1 extends TableServiceEntity implements PropertyResolver { // // public String A; // // public String B; // // public String C; // // public byte[] D; // // public Class1() { // // empty ctor // } // // public Class1(String pk, String rk) { // super(pk, rk); // } // // public synchronized String getA() { // return this.A; // } // // public synchronized String getB() { // return this.B; // } // // public synchronized String getC() { // return this.C; // } // // public synchronized byte[] getD() { // return this.D; // } // // public synchronized void setA(final String a) { // this.A = a; // } // // public synchronized void setB(final String b) { // this.B = b; // } // // public synchronized void setC(final String c) { // this.C = c; // } // // public synchronized void setD(final byte[] d) { // this.D = d; // } // // @Override // public EdmType propertyResolver(String pk, String rk, String key, String value) { // if (key.equals("A")) { // return EdmType.STRING; // } // else if (key.equals("B")) { // return EdmType.STRING; // } // else if (key.equals("C")) { // return EdmType.STRING; // } // else if (key.equals("D")) { // return EdmType.BINARY; // } // return null; // } // } // Path: microsoft-azure-storage-test/src/com/microsoft/azure/storage/table/TableODataTests.java import com.microsoft.azure.storage.StorageException; import com.microsoft.azure.storage.TestRunners.CloudTests; import com.microsoft.azure.storage.TestRunners.DevFabricTests; import com.microsoft.azure.storage.TestRunners.DevStoreTests; import com.microsoft.azure.storage.table.TableRequestOptions.PropertyResolver; import com.microsoft.azure.storage.table.TableTestHelper.Class1; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import java.net.URISyntaxException; import java.util.UUID; import static org.junit.Assert.*; try { this.table.execute(TableOperation.retrieve(this.ent.getPartitionKey(), this.ent.getRowKey(), Class1.class), this.options, null); fail("Invalid property resolver should throw"); } catch (StorageException e) { assertEquals("Failed to parse property 'fooint' with value '1234' as type 'Edm.Guid'", e.getMessage()); } } @Test public void testTableOperationRetrieveJsonNoMetadataResolverFail() { // set custom property resolver which throws this.options.setPropertyResolver(new ThrowingPropertyResolver()); try { this.table.execute(TableOperation.retrieve(this.ent.getPartitionKey(), this.ent.getRowKey(), Class1.class), this.options, null); fail("Invalid property resolver should throw"); } catch (StorageException e) { assertEquals( "The custom property resolver delegate threw an exception. Check the inner exception for more details.", e.getMessage()); assertTrue(e.getCause().getClass() == IllegalArgumentException.class); } }
class CustomPropertyResolver implements PropertyResolver {
guoguibing/HappyCoding
happycoding/src/main/java/happy/coding/io/net/Browser.java
// Path: happycoding/src/main/java/happy/coding/system/Systems.java // public class Systems { // private static String desktopPath = null; // // public final static String FILE_SEPARATOR = System.getProperty("file.separator"); // public final static String USER_NAME = System.getProperty("user.name"); // public final static String USER_DIRECTORY = System.getProperty("user.home"); // public final static String WORKING_DIRECTORY = System.getProperty("user.dir"); // public final static String OPERATING_SYSTEM = System.getProperty("os.name"); // // public enum OS { // Windows, Linux, Mac // } // // private static OS os = null; // // /** // * @return path to the desktop with a file separator in the end // */ // public static String getDesktop() { // if (desktopPath == null) // desktopPath = USER_DIRECTORY + FILE_SEPARATOR + "Desktop" + FILE_SEPARATOR; // return desktopPath; // } // // public static String getIP() { // InetAddress ip = null; // try { // ip = InetAddress.getLocalHost(); // } catch (UnknownHostException e) { // e.printStackTrace(); // } // return ip.getHostName() + "@" + ip.getHostAddress(); // } // // public static OS getOs() { // if (os == null) { // for (OS m : OS.values()) { // if (OPERATING_SYSTEM.toLowerCase().contains(m.name().toLowerCase())) { // os = m; // break; // } // } // } // return os; // } // // public static void pause() { // try { // Logs.debug("System paused, press [enter] to continue ..."); // System.in.read(); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public static void captureScreen() throws Exception { // captureScreen("screenshot.png"); // } // // public static void captureScreen(String fileName) throws Exception { // // Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // Rectangle screenRectangle = new Rectangle(screenSize); // Robot robot = new Robot(); // BufferedImage image = robot.createScreenCapture(screenRectangle); // // File file = new File(fileName); // ImageIO.write(image, "png", file); // // Logs.debug("A screenshot is captured to: {}", file.getPath()); // } // // }
import happy.coding.system.Systems; import org.junit.Test;
package happy.coding.io.net; public class Browser { private final static Runtime rt = Runtime.getRuntime(); public static void startPages(String... urls) throws Exception { for (String url : urls) {
// Path: happycoding/src/main/java/happy/coding/system/Systems.java // public class Systems { // private static String desktopPath = null; // // public final static String FILE_SEPARATOR = System.getProperty("file.separator"); // public final static String USER_NAME = System.getProperty("user.name"); // public final static String USER_DIRECTORY = System.getProperty("user.home"); // public final static String WORKING_DIRECTORY = System.getProperty("user.dir"); // public final static String OPERATING_SYSTEM = System.getProperty("os.name"); // // public enum OS { // Windows, Linux, Mac // } // // private static OS os = null; // // /** // * @return path to the desktop with a file separator in the end // */ // public static String getDesktop() { // if (desktopPath == null) // desktopPath = USER_DIRECTORY + FILE_SEPARATOR + "Desktop" + FILE_SEPARATOR; // return desktopPath; // } // // public static String getIP() { // InetAddress ip = null; // try { // ip = InetAddress.getLocalHost(); // } catch (UnknownHostException e) { // e.printStackTrace(); // } // return ip.getHostName() + "@" + ip.getHostAddress(); // } // // public static OS getOs() { // if (os == null) { // for (OS m : OS.values()) { // if (OPERATING_SYSTEM.toLowerCase().contains(m.name().toLowerCase())) { // os = m; // break; // } // } // } // return os; // } // // public static void pause() { // try { // Logs.debug("System paused, press [enter] to continue ..."); // System.in.read(); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public static void captureScreen() throws Exception { // captureScreen("screenshot.png"); // } // // public static void captureScreen(String fileName) throws Exception { // // Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // Rectangle screenRectangle = new Rectangle(screenSize); // Robot robot = new Robot(); // BufferedImage image = robot.createScreenCapture(screenRectangle); // // File file = new File(fileName); // ImageIO.write(image, "png", file); // // Logs.debug("A screenshot is captured to: {}", file.getPath()); // } // // } // Path: happycoding/src/main/java/happy/coding/io/net/Browser.java import happy.coding.system.Systems; import org.junit.Test; package happy.coding.io.net; public class Browser { private final static Runtime rt = Runtime.getRuntime(); public static void startPages(String... urls) throws Exception { for (String url : urls) {
switch (Systems.getOs())
guoguibing/HappyCoding
happycoding/src/main/java/happy/coding/math/Randoms.java
// Path: happycoding/src/main/java/happy/coding/io/Logs.java // public class Logs { // private final static Logger logger = LoggerFactory.getLogger(Logs.class); // private static String conf = null; // // // default configuration // static { // if ((conf = FileIO.getResource("log4j.properties")) != null) // config(conf, false); // else if ((conf = FileIO.getResource("log4j.xml")) != null) // config(conf, true); // } // // public static Logger config(String config, boolean isXml) { // if (isXml) // DOMConfigurator.configure(config); // else // PropertyConfigurator.configure(config); // // return logger; // } // // public static void debug(double data) { // logger.debug(Strings.toString(data)); // } // // public static void debug(Object msg) { // logger.debug(msg.toString()); // } // // public static void debug(String msg) { // logger.debug(msg); // } // // public static void debug(String format, Object arg) { // logger.debug(format, arg); // } // // public static void debug(String format, Object... args) { // logger.debug(format, args); // } // // public static void debug() { // debug(""); // } // // public static void error() { // error(""); // } // // public static void warn() { // warn(""); // } // // public static void info() { // info(""); // } // // public static void info(double data) { // logger.info(Strings.toString(data)); // } // // public static void info(Object msg) { // if (msg == null) // logger.info(""); // else // logger.info(msg.toString()); // } // // public static void info(String format, Object arg) { // logger.info(format, arg); // } // // public static void info(String format, Object... args) { // logger.info(format, args); // } // // public static void error(double data) { // logger.error(Strings.toString(data)); // } // // public static void error(Object msg) { // logger.error(msg.toString()); // } // // public static void warn(String msg) { // logger.warn(msg); // } // // public static void warn(String format, Object arg) { // logger.warn(format, arg); // } // // public static void warn(String format, Object... args) { // logger.warn(format, args); // } // // public static void warn(double data) { // logger.warn(Strings.toString(data)); // } // // public static void warn(Object msg) { // logger.warn(msg.toString()); // } // // public static void error(String msg) { // logger.error(msg); // } // // public static void error(String format, Object arg) { // logger.error(format, arg); // } // // public static void error(String format, Object... args) { // logger.error(format, args); // } // // public static void off() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.OFF); // } // // public static void on() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.DEBUG); // } // // @Test // public void example() { // String[] msgs = new String[] { "Section content: ", "@author guoguibing" }; // // debug(msgs); // } // // }
import happy.coding.io.Logs; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import org.junit.Test;
* Generate a permutation from min to max * * @param min * the minimum value * @param max * the maximum value * @return a permutation */ public static List<Integer> permute(int min, int max) { List<Integer> list = new ArrayList<>(); int len = max - min + 1; for (int i = 0; i < len; i++) { while (true) { int index = uniform(min, max + 1); if (!list.contains(index)) { list.add(index); break; } } } return list; } @Test public void example_permute() { for (int i = 0; i < 20; i++) { List<Integer> perm = Randoms.permute(1, 5);
// Path: happycoding/src/main/java/happy/coding/io/Logs.java // public class Logs { // private final static Logger logger = LoggerFactory.getLogger(Logs.class); // private static String conf = null; // // // default configuration // static { // if ((conf = FileIO.getResource("log4j.properties")) != null) // config(conf, false); // else if ((conf = FileIO.getResource("log4j.xml")) != null) // config(conf, true); // } // // public static Logger config(String config, boolean isXml) { // if (isXml) // DOMConfigurator.configure(config); // else // PropertyConfigurator.configure(config); // // return logger; // } // // public static void debug(double data) { // logger.debug(Strings.toString(data)); // } // // public static void debug(Object msg) { // logger.debug(msg.toString()); // } // // public static void debug(String msg) { // logger.debug(msg); // } // // public static void debug(String format, Object arg) { // logger.debug(format, arg); // } // // public static void debug(String format, Object... args) { // logger.debug(format, args); // } // // public static void debug() { // debug(""); // } // // public static void error() { // error(""); // } // // public static void warn() { // warn(""); // } // // public static void info() { // info(""); // } // // public static void info(double data) { // logger.info(Strings.toString(data)); // } // // public static void info(Object msg) { // if (msg == null) // logger.info(""); // else // logger.info(msg.toString()); // } // // public static void info(String format, Object arg) { // logger.info(format, arg); // } // // public static void info(String format, Object... args) { // logger.info(format, args); // } // // public static void error(double data) { // logger.error(Strings.toString(data)); // } // // public static void error(Object msg) { // logger.error(msg.toString()); // } // // public static void warn(String msg) { // logger.warn(msg); // } // // public static void warn(String format, Object arg) { // logger.warn(format, arg); // } // // public static void warn(String format, Object... args) { // logger.warn(format, args); // } // // public static void warn(double data) { // logger.warn(Strings.toString(data)); // } // // public static void warn(Object msg) { // logger.warn(msg.toString()); // } // // public static void error(String msg) { // logger.error(msg); // } // // public static void error(String format, Object arg) { // logger.error(format, arg); // } // // public static void error(String format, Object... args) { // logger.error(format, args); // } // // public static void off() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.OFF); // } // // public static void on() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.DEBUG); // } // // @Test // public void example() { // String[] msgs = new String[] { "Section content: ", "@author guoguibing" }; // // debug(msgs); // } // // } // Path: happycoding/src/main/java/happy/coding/math/Randoms.java import happy.coding.io.Logs; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import org.junit.Test; * Generate a permutation from min to max * * @param min * the minimum value * @param max * the maximum value * @return a permutation */ public static List<Integer> permute(int min, int max) { List<Integer> list = new ArrayList<>(); int len = max - min + 1; for (int i = 0; i < len; i++) { while (true) { int index = uniform(min, max + 1); if (!list.contains(index)) { list.add(index); break; } } } return list; } @Test public void example_permute() { for (int i = 0; i < 20; i++) { List<Integer> perm = Randoms.permute(1, 5);
Logs.debug("Iteration " + (i + 1) + " : " + perm);
guoguibing/HappyCoding
happycoding/src/main/java/happy/coding/io/net/Gmailer.java
// Path: happycoding/src/main/java/happy/coding/system/Dates.java // public class Dates { // public final static String PATTERN_yyyy_MM_dd = "yyyy-MM-dd"; // public final static String PATTERN_dd_MM_yyyy = "dd/MM/yyyy"; // public final static String PATTERN_MM_dd_yyyy = "MM/dd/yyyy"; // public final static String PATTERN_yyyy_MM_dd_HH_mm_SS = "yyyy-MM-dd HH-mm-SS"; // // private static final SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_yyyy_MM_dd_HH_mm_SS); // // public static java.sql.Date parse(String date) throws Exception { // return parse(date, PATTERN_yyyy_MM_dd); // } // // public static java.sql.Date parse(String date, String pattern) throws Exception { // SimpleDateFormat sdf = new SimpleDateFormat(pattern); // return new java.sql.Date(sdf.parse(date).getTime()); // } // // public static String toString(long mms, String pattern) throws Exception { // SimpleDateFormat sdf = new SimpleDateFormat(pattern); // return sdf.format(new java.sql.Date(mms)); // } // // public static String toString(long mms) throws Exception { // return sdf.format(new java.sql.Date(mms)); // } // // public static String now() { // return sdf.format(new java.util.Date()); // } // // /** // * Convert time in milliseconds to human-readable format. // * // * @param msType // * The time in milliseconds // * @return a human-readable string version of the time // */ // public static String parse(long msType) { // long original = msType; // int ms = (int) (msType % 1000); // // original = original / 1000; // int sec = (int) (original % 60); // // original = original / 60; // int min = (int) (original % 60); // // original = original / 60; // int hr = (int) (original % 24); // // original = original / 24; // int day = (int) original; // // if (day > 1) { // return String.format("%d days, %02d:%02d:%02d.%03d", day, hr, min, sec, ms); // } else if (day > 0) { // return String.format("%d day, %02d:%02d:%02d.%03d", day, hr, min, sec, ms); // } else if (hr > 0) { // return String.format("%02d:%02d:%02d", hr, min, sec); // } else { // return String.format("%02d:%02d", min, sec); // } // } // // }
import happy.coding.system.Dates; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; import javax.mail.Session;
package happy.coding.io.net; public class Gmailer extends EMailer { public Gmailer() { configSSL(); defaultInstance(); } public void configTLS() { props.put("mail.smtp.starttls.enable", "true"); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.smtp.host", "smtp.gmail.com"); props.setProperty("mail.smtp.port", "587"); props.setProperty("mail.smtp.auth", "true"); } public void configSSL() { props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); } private void defaultInstance() { props.setProperty("mail.debug", "false"); final String userName = "happycodingprojects@gmail.com"; final String password = "dailycoding@ntu"; props.setProperty("mail.smtp.user", userName); props.setProperty("mail.smtp.password", password); props.setProperty("mail.from", userName); props.setProperty("mail.to", "gguo1@e.ntu.edu.sg"); props.setProperty("mail.subject", "Program Notifier from Gmail");
// Path: happycoding/src/main/java/happy/coding/system/Dates.java // public class Dates { // public final static String PATTERN_yyyy_MM_dd = "yyyy-MM-dd"; // public final static String PATTERN_dd_MM_yyyy = "dd/MM/yyyy"; // public final static String PATTERN_MM_dd_yyyy = "MM/dd/yyyy"; // public final static String PATTERN_yyyy_MM_dd_HH_mm_SS = "yyyy-MM-dd HH-mm-SS"; // // private static final SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_yyyy_MM_dd_HH_mm_SS); // // public static java.sql.Date parse(String date) throws Exception { // return parse(date, PATTERN_yyyy_MM_dd); // } // // public static java.sql.Date parse(String date, String pattern) throws Exception { // SimpleDateFormat sdf = new SimpleDateFormat(pattern); // return new java.sql.Date(sdf.parse(date).getTime()); // } // // public static String toString(long mms, String pattern) throws Exception { // SimpleDateFormat sdf = new SimpleDateFormat(pattern); // return sdf.format(new java.sql.Date(mms)); // } // // public static String toString(long mms) throws Exception { // return sdf.format(new java.sql.Date(mms)); // } // // public static String now() { // return sdf.format(new java.util.Date()); // } // // /** // * Convert time in milliseconds to human-readable format. // * // * @param msType // * The time in milliseconds // * @return a human-readable string version of the time // */ // public static String parse(long msType) { // long original = msType; // int ms = (int) (msType % 1000); // // original = original / 1000; // int sec = (int) (original % 60); // // original = original / 60; // int min = (int) (original % 60); // // original = original / 60; // int hr = (int) (original % 24); // // original = original / 24; // int day = (int) original; // // if (day > 1) { // return String.format("%d days, %02d:%02d:%02d.%03d", day, hr, min, sec, ms); // } else if (day > 0) { // return String.format("%d day, %02d:%02d:%02d.%03d", day, hr, min, sec, ms); // } else if (hr > 0) { // return String.format("%02d:%02d:%02d", hr, min, sec); // } else { // return String.format("%02d:%02d", min, sec); // } // } // // } // Path: happycoding/src/main/java/happy/coding/io/net/Gmailer.java import happy.coding.system.Dates; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; import javax.mail.Session; package happy.coding.io.net; public class Gmailer extends EMailer { public Gmailer() { configSSL(); defaultInstance(); } public void configTLS() { props.put("mail.smtp.starttls.enable", "true"); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.smtp.host", "smtp.gmail.com"); props.setProperty("mail.smtp.port", "587"); props.setProperty("mail.smtp.auth", "true"); } public void configSSL() { props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); } private void defaultInstance() { props.setProperty("mail.debug", "false"); final String userName = "happycodingprojects@gmail.com"; final String password = "dailycoding@ntu"; props.setProperty("mail.smtp.user", userName); props.setProperty("mail.smtp.password", password); props.setProperty("mail.from", userName); props.setProperty("mail.to", "gguo1@e.ntu.edu.sg"); props.setProperty("mail.subject", "Program Notifier from Gmail");
props.setProperty("mail.text", "Program was finished @" + Dates.now());
guoguibing/HappyCoding
happycoding/src/main/java/happy/coding/math/Maths.java
// Path: happycoding/src/main/java/happy/coding/io/Logs.java // public class Logs { // private final static Logger logger = LoggerFactory.getLogger(Logs.class); // private static String conf = null; // // // default configuration // static { // if ((conf = FileIO.getResource("log4j.properties")) != null) // config(conf, false); // else if ((conf = FileIO.getResource("log4j.xml")) != null) // config(conf, true); // } // // public static Logger config(String config, boolean isXml) { // if (isXml) // DOMConfigurator.configure(config); // else // PropertyConfigurator.configure(config); // // return logger; // } // // public static void debug(double data) { // logger.debug(Strings.toString(data)); // } // // public static void debug(Object msg) { // logger.debug(msg.toString()); // } // // public static void debug(String msg) { // logger.debug(msg); // } // // public static void debug(String format, Object arg) { // logger.debug(format, arg); // } // // public static void debug(String format, Object... args) { // logger.debug(format, args); // } // // public static void debug() { // debug(""); // } // // public static void error() { // error(""); // } // // public static void warn() { // warn(""); // } // // public static void info() { // info(""); // } // // public static void info(double data) { // logger.info(Strings.toString(data)); // } // // public static void info(Object msg) { // if (msg == null) // logger.info(""); // else // logger.info(msg.toString()); // } // // public static void info(String format, Object arg) { // logger.info(format, arg); // } // // public static void info(String format, Object... args) { // logger.info(format, args); // } // // public static void error(double data) { // logger.error(Strings.toString(data)); // } // // public static void error(Object msg) { // logger.error(msg.toString()); // } // // public static void warn(String msg) { // logger.warn(msg); // } // // public static void warn(String format, Object arg) { // logger.warn(format, arg); // } // // public static void warn(String format, Object... args) { // logger.warn(format, args); // } // // public static void warn(double data) { // logger.warn(Strings.toString(data)); // } // // public static void warn(Object msg) { // logger.warn(msg.toString()); // } // // public static void error(String msg) { // logger.error(msg); // } // // public static void error(String format, Object arg) { // logger.error(format, arg); // } // // public static void error(String format, Object... args) { // logger.error(format, args); // } // // public static void off() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.OFF); // } // // public static void on() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.DEBUG); // } // // @Test // public void example() { // String[] msgs = new String[] { "Section content: ", "@author guoguibing" }; // // debug(msgs); // } // // }
import static java.lang.Math.exp; import happy.coding.io.Logs; import org.junit.Test;
/** * least common multiple (lcm) * */ public static int lcm(int a, int b) { if (a > 0 && b > 0) return (int) ((0.0 + a * b) / gcd(a, b)); else return 0; } /** sqrt(a^2 + b^2) without under/overflow. **/ public static double hypot(double a, double b) { double r; if (Math.abs(a) > Math.abs(b)) { r = b / a; r = Math.abs(a) * Math.sqrt(1 + r * r); } else if (!isEqual(b, 0.0)) { r = a / b; r = Math.abs(b) * Math.sqrt(1 + r * r); } else { r = 0.0; } return r; } @Test public void e_numbers() {
// Path: happycoding/src/main/java/happy/coding/io/Logs.java // public class Logs { // private final static Logger logger = LoggerFactory.getLogger(Logs.class); // private static String conf = null; // // // default configuration // static { // if ((conf = FileIO.getResource("log4j.properties")) != null) // config(conf, false); // else if ((conf = FileIO.getResource("log4j.xml")) != null) // config(conf, true); // } // // public static Logger config(String config, boolean isXml) { // if (isXml) // DOMConfigurator.configure(config); // else // PropertyConfigurator.configure(config); // // return logger; // } // // public static void debug(double data) { // logger.debug(Strings.toString(data)); // } // // public static void debug(Object msg) { // logger.debug(msg.toString()); // } // // public static void debug(String msg) { // logger.debug(msg); // } // // public static void debug(String format, Object arg) { // logger.debug(format, arg); // } // // public static void debug(String format, Object... args) { // logger.debug(format, args); // } // // public static void debug() { // debug(""); // } // // public static void error() { // error(""); // } // // public static void warn() { // warn(""); // } // // public static void info() { // info(""); // } // // public static void info(double data) { // logger.info(Strings.toString(data)); // } // // public static void info(Object msg) { // if (msg == null) // logger.info(""); // else // logger.info(msg.toString()); // } // // public static void info(String format, Object arg) { // logger.info(format, arg); // } // // public static void info(String format, Object... args) { // logger.info(format, args); // } // // public static void error(double data) { // logger.error(Strings.toString(data)); // } // // public static void error(Object msg) { // logger.error(msg.toString()); // } // // public static void warn(String msg) { // logger.warn(msg); // } // // public static void warn(String format, Object arg) { // logger.warn(format, arg); // } // // public static void warn(String format, Object... args) { // logger.warn(format, args); // } // // public static void warn(double data) { // logger.warn(Strings.toString(data)); // } // // public static void warn(Object msg) { // logger.warn(msg.toString()); // } // // public static void error(String msg) { // logger.error(msg); // } // // public static void error(String format, Object arg) { // logger.error(format, arg); // } // // public static void error(String format, Object... args) { // logger.error(format, args); // } // // public static void off() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.OFF); // } // // public static void on() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.DEBUG); // } // // @Test // public void example() { // String[] msgs = new String[] { "Section content: ", "@author guoguibing" }; // // debug(msgs); // } // // } // Path: happycoding/src/main/java/happy/coding/math/Maths.java import static java.lang.Math.exp; import happy.coding.io.Logs; import org.junit.Test; /** * least common multiple (lcm) * */ public static int lcm(int a, int b) { if (a > 0 && b > 0) return (int) ((0.0 + a * b) / gcd(a, b)); else return 0; } /** sqrt(a^2 + b^2) without under/overflow. **/ public static double hypot(double a, double b) { double r; if (Math.abs(a) > Math.abs(b)) { r = b / a; r = Math.abs(a) * Math.sqrt(1 + r * r); } else if (!isEqual(b, 0.0)) { r = a / b; r = Math.abs(b) * Math.sqrt(1 + r * r); } else { r = 0.0; } return r; } @Test public void e_numbers() {
Logs.debug("Golden ratio = " + Maths.golden_ratio);
guoguibing/HappyCoding
happycoding/src/main/java/happy/coding/io/net/EMailer.java
// Path: happycoding/src/main/java/happy/coding/io/Logs.java // public class Logs { // private final static Logger logger = LoggerFactory.getLogger(Logs.class); // private static String conf = null; // // // default configuration // static { // if ((conf = FileIO.getResource("log4j.properties")) != null) // config(conf, false); // else if ((conf = FileIO.getResource("log4j.xml")) != null) // config(conf, true); // } // // public static Logger config(String config, boolean isXml) { // if (isXml) // DOMConfigurator.configure(config); // else // PropertyConfigurator.configure(config); // // return logger; // } // // public static void debug(double data) { // logger.debug(Strings.toString(data)); // } // // public static void debug(Object msg) { // logger.debug(msg.toString()); // } // // public static void debug(String msg) { // logger.debug(msg); // } // // public static void debug(String format, Object arg) { // logger.debug(format, arg); // } // // public static void debug(String format, Object... args) { // logger.debug(format, args); // } // // public static void debug() { // debug(""); // } // // public static void error() { // error(""); // } // // public static void warn() { // warn(""); // } // // public static void info() { // info(""); // } // // public static void info(double data) { // logger.info(Strings.toString(data)); // } // // public static void info(Object msg) { // if (msg == null) // logger.info(""); // else // logger.info(msg.toString()); // } // // public static void info(String format, Object arg) { // logger.info(format, arg); // } // // public static void info(String format, Object... args) { // logger.info(format, args); // } // // public static void error(double data) { // logger.error(Strings.toString(data)); // } // // public static void error(Object msg) { // logger.error(msg.toString()); // } // // public static void warn(String msg) { // logger.warn(msg); // } // // public static void warn(String format, Object arg) { // logger.warn(format, arg); // } // // public static void warn(String format, Object... args) { // logger.warn(format, args); // } // // public static void warn(double data) { // logger.warn(Strings.toString(data)); // } // // public static void warn(Object msg) { // logger.warn(msg.toString()); // } // // public static void error(String msg) { // logger.error(msg); // } // // public static void error(String format, Object arg) { // logger.error(format, arg); // } // // public static void error(String format, Object... args) { // logger.error(format, args); // } // // public static void off() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.OFF); // } // // public static void on() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.DEBUG); // } // // @Test // public void example() { // String[] msgs = new String[] { "Section content: ", "@author guoguibing" }; // // debug(msgs); // } // // }
import happy.coding.io.Logs; import java.io.FileInputStream; import java.util.Date; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart;
msg.setFrom(new InternetAddress(from)); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); if (cc != null) msg.setRecipient(Message.RecipientType.CC, new InternetAddress(cc)); if (bcc != null) msg.setRecipient(Message.RecipientType.BCC, new InternetAddress(bcc)); msg.setSubject(subject); msg.setSentDate(new Date()); if (attachment != null) { MimeBodyPart tp = new MimeBodyPart(); tp.setText(text); MimeBodyPart ap = new MimeBodyPart(); FileDataSource fds = new FileDataSource(attachment); ap.setDataHandler(new DataHandler(fds)); ap.setFileName(fds.getName()); Multipart mp = new MimeMultipart(); mp.addBodyPart(tp); mp.addBodyPart(ap); msg.setContent(mp); } else { msg.setText(text); } Transport.send(msg);
// Path: happycoding/src/main/java/happy/coding/io/Logs.java // public class Logs { // private final static Logger logger = LoggerFactory.getLogger(Logs.class); // private static String conf = null; // // // default configuration // static { // if ((conf = FileIO.getResource("log4j.properties")) != null) // config(conf, false); // else if ((conf = FileIO.getResource("log4j.xml")) != null) // config(conf, true); // } // // public static Logger config(String config, boolean isXml) { // if (isXml) // DOMConfigurator.configure(config); // else // PropertyConfigurator.configure(config); // // return logger; // } // // public static void debug(double data) { // logger.debug(Strings.toString(data)); // } // // public static void debug(Object msg) { // logger.debug(msg.toString()); // } // // public static void debug(String msg) { // logger.debug(msg); // } // // public static void debug(String format, Object arg) { // logger.debug(format, arg); // } // // public static void debug(String format, Object... args) { // logger.debug(format, args); // } // // public static void debug() { // debug(""); // } // // public static void error() { // error(""); // } // // public static void warn() { // warn(""); // } // // public static void info() { // info(""); // } // // public static void info(double data) { // logger.info(Strings.toString(data)); // } // // public static void info(Object msg) { // if (msg == null) // logger.info(""); // else // logger.info(msg.toString()); // } // // public static void info(String format, Object arg) { // logger.info(format, arg); // } // // public static void info(String format, Object... args) { // logger.info(format, args); // } // // public static void error(double data) { // logger.error(Strings.toString(data)); // } // // public static void error(Object msg) { // logger.error(msg.toString()); // } // // public static void warn(String msg) { // logger.warn(msg); // } // // public static void warn(String format, Object arg) { // logger.warn(format, arg); // } // // public static void warn(String format, Object... args) { // logger.warn(format, args); // } // // public static void warn(double data) { // logger.warn(Strings.toString(data)); // } // // public static void warn(Object msg) { // logger.warn(msg.toString()); // } // // public static void error(String msg) { // logger.error(msg); // } // // public static void error(String format, Object arg) { // logger.error(format, arg); // } // // public static void error(String format, Object... args) { // logger.error(format, args); // } // // public static void off() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.OFF); // } // // public static void on() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.DEBUG); // } // // @Test // public void example() { // String[] msgs = new String[] { "Section content: ", "@author guoguibing" }; // // debug(msgs); // } // // } // Path: happycoding/src/main/java/happy/coding/io/net/EMailer.java import happy.coding.io.Logs; import java.io.FileInputStream; import java.util.Date; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; msg.setFrom(new InternetAddress(from)); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); if (cc != null) msg.setRecipient(Message.RecipientType.CC, new InternetAddress(cc)); if (bcc != null) msg.setRecipient(Message.RecipientType.BCC, new InternetAddress(bcc)); msg.setSubject(subject); msg.setSentDate(new Date()); if (attachment != null) { MimeBodyPart tp = new MimeBodyPart(); tp.setText(text); MimeBodyPart ap = new MimeBodyPart(); FileDataSource fds = new FileDataSource(attachment); ap.setDataHandler(new DataHandler(fds)); ap.setFileName(fds.getName()); Multipart mp = new MimeMultipart(); mp.addBodyPart(tp); mp.addBodyPart(ap); msg.setContent(mp); } else { msg.setText(text); } Transport.send(msg);
Logs.debug("Have sent an email notification to {}. ", to);
guoguibing/HappyCoding
happycoding/src/main/java/happy/coding/system/Systems.java
// Path: happycoding/src/main/java/happy/coding/io/Logs.java // public class Logs { // private final static Logger logger = LoggerFactory.getLogger(Logs.class); // private static String conf = null; // // // default configuration // static { // if ((conf = FileIO.getResource("log4j.properties")) != null) // config(conf, false); // else if ((conf = FileIO.getResource("log4j.xml")) != null) // config(conf, true); // } // // public static Logger config(String config, boolean isXml) { // if (isXml) // DOMConfigurator.configure(config); // else // PropertyConfigurator.configure(config); // // return logger; // } // // public static void debug(double data) { // logger.debug(Strings.toString(data)); // } // // public static void debug(Object msg) { // logger.debug(msg.toString()); // } // // public static void debug(String msg) { // logger.debug(msg); // } // // public static void debug(String format, Object arg) { // logger.debug(format, arg); // } // // public static void debug(String format, Object... args) { // logger.debug(format, args); // } // // public static void debug() { // debug(""); // } // // public static void error() { // error(""); // } // // public static void warn() { // warn(""); // } // // public static void info() { // info(""); // } // // public static void info(double data) { // logger.info(Strings.toString(data)); // } // // public static void info(Object msg) { // if (msg == null) // logger.info(""); // else // logger.info(msg.toString()); // } // // public static void info(String format, Object arg) { // logger.info(format, arg); // } // // public static void info(String format, Object... args) { // logger.info(format, args); // } // // public static void error(double data) { // logger.error(Strings.toString(data)); // } // // public static void error(Object msg) { // logger.error(msg.toString()); // } // // public static void warn(String msg) { // logger.warn(msg); // } // // public static void warn(String format, Object arg) { // logger.warn(format, arg); // } // // public static void warn(String format, Object... args) { // logger.warn(format, args); // } // // public static void warn(double data) { // logger.warn(Strings.toString(data)); // } // // public static void warn(Object msg) { // logger.warn(msg.toString()); // } // // public static void error(String msg) { // logger.error(msg); // } // // public static void error(String format, Object arg) { // logger.error(format, arg); // } // // public static void error(String format, Object... args) { // logger.error(format, args); // } // // public static void off() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.OFF); // } // // public static void on() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.DEBUG); // } // // @Test // public void example() { // String[] msgs = new String[] { "Section content: ", "@author guoguibing" }; // // debug(msgs); // } // // }
import happy.coding.io.Logs; import java.awt.Dimension; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import javax.imageio.ImageIO;
public static String getDesktop() { if (desktopPath == null) desktopPath = USER_DIRECTORY + FILE_SEPARATOR + "Desktop" + FILE_SEPARATOR; return desktopPath; } public static String getIP() { InetAddress ip = null; try { ip = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } return ip.getHostName() + "@" + ip.getHostAddress(); } public static OS getOs() { if (os == null) { for (OS m : OS.values()) { if (OPERATING_SYSTEM.toLowerCase().contains(m.name().toLowerCase())) { os = m; break; } } } return os; } public static void pause() { try {
// Path: happycoding/src/main/java/happy/coding/io/Logs.java // public class Logs { // private final static Logger logger = LoggerFactory.getLogger(Logs.class); // private static String conf = null; // // // default configuration // static { // if ((conf = FileIO.getResource("log4j.properties")) != null) // config(conf, false); // else if ((conf = FileIO.getResource("log4j.xml")) != null) // config(conf, true); // } // // public static Logger config(String config, boolean isXml) { // if (isXml) // DOMConfigurator.configure(config); // else // PropertyConfigurator.configure(config); // // return logger; // } // // public static void debug(double data) { // logger.debug(Strings.toString(data)); // } // // public static void debug(Object msg) { // logger.debug(msg.toString()); // } // // public static void debug(String msg) { // logger.debug(msg); // } // // public static void debug(String format, Object arg) { // logger.debug(format, arg); // } // // public static void debug(String format, Object... args) { // logger.debug(format, args); // } // // public static void debug() { // debug(""); // } // // public static void error() { // error(""); // } // // public static void warn() { // warn(""); // } // // public static void info() { // info(""); // } // // public static void info(double data) { // logger.info(Strings.toString(data)); // } // // public static void info(Object msg) { // if (msg == null) // logger.info(""); // else // logger.info(msg.toString()); // } // // public static void info(String format, Object arg) { // logger.info(format, arg); // } // // public static void info(String format, Object... args) { // logger.info(format, args); // } // // public static void error(double data) { // logger.error(Strings.toString(data)); // } // // public static void error(Object msg) { // logger.error(msg.toString()); // } // // public static void warn(String msg) { // logger.warn(msg); // } // // public static void warn(String format, Object arg) { // logger.warn(format, arg); // } // // public static void warn(String format, Object... args) { // logger.warn(format, args); // } // // public static void warn(double data) { // logger.warn(Strings.toString(data)); // } // // public static void warn(Object msg) { // logger.warn(msg.toString()); // } // // public static void error(String msg) { // logger.error(msg); // } // // public static void error(String format, Object arg) { // logger.error(format, arg); // } // // public static void error(String format, Object... args) { // logger.error(format, args); // } // // public static void off() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.OFF); // } // // public static void on() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.DEBUG); // } // // @Test // public void example() { // String[] msgs = new String[] { "Section content: ", "@author guoguibing" }; // // debug(msgs); // } // // } // Path: happycoding/src/main/java/happy/coding/system/Systems.java import happy.coding.io.Logs; import java.awt.Dimension; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import javax.imageio.ImageIO; public static String getDesktop() { if (desktopPath == null) desktopPath = USER_DIRECTORY + FILE_SEPARATOR + "Desktop" + FILE_SEPARATOR; return desktopPath; } public static String getIP() { InetAddress ip = null; try { ip = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } return ip.getHostName() + "@" + ip.getHostAddress(); } public static OS getOs() { if (os == null) { for (OS m : OS.values()) { if (OPERATING_SYSTEM.toLowerCase().contains(m.name().toLowerCase())) { os = m; break; } } } return os; } public static void pause() { try {
Logs.debug("System paused, press [enter] to continue ...");
guoguibing/HappyCoding
happycoding/src/main/java/happy/coding/io/net/SocketClient.java
// Path: happycoding/src/main/java/happy/coding/io/Logs.java // public class Logs { // private final static Logger logger = LoggerFactory.getLogger(Logs.class); // private static String conf = null; // // // default configuration // static { // if ((conf = FileIO.getResource("log4j.properties")) != null) // config(conf, false); // else if ((conf = FileIO.getResource("log4j.xml")) != null) // config(conf, true); // } // // public static Logger config(String config, boolean isXml) { // if (isXml) // DOMConfigurator.configure(config); // else // PropertyConfigurator.configure(config); // // return logger; // } // // public static void debug(double data) { // logger.debug(Strings.toString(data)); // } // // public static void debug(Object msg) { // logger.debug(msg.toString()); // } // // public static void debug(String msg) { // logger.debug(msg); // } // // public static void debug(String format, Object arg) { // logger.debug(format, arg); // } // // public static void debug(String format, Object... args) { // logger.debug(format, args); // } // // public static void debug() { // debug(""); // } // // public static void error() { // error(""); // } // // public static void warn() { // warn(""); // } // // public static void info() { // info(""); // } // // public static void info(double data) { // logger.info(Strings.toString(data)); // } // // public static void info(Object msg) { // if (msg == null) // logger.info(""); // else // logger.info(msg.toString()); // } // // public static void info(String format, Object arg) { // logger.info(format, arg); // } // // public static void info(String format, Object... args) { // logger.info(format, args); // } // // public static void error(double data) { // logger.error(Strings.toString(data)); // } // // public static void error(Object msg) { // logger.error(msg.toString()); // } // // public static void warn(String msg) { // logger.warn(msg); // } // // public static void warn(String format, Object arg) { // logger.warn(format, arg); // } // // public static void warn(String format, Object... args) { // logger.warn(format, args); // } // // public static void warn(double data) { // logger.warn(Strings.toString(data)); // } // // public static void warn(Object msg) { // logger.warn(msg.toString()); // } // // public static void error(String msg) { // logger.error(msg); // } // // public static void error(String format, Object arg) { // logger.error(format, arg); // } // // public static void error(String format, Object... args) { // logger.error(format, args); // } // // public static void off() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.OFF); // } // // public static void on() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.DEBUG); // } // // @Test // public void example() { // String[] msgs = new String[] { "Section content: ", "@author guoguibing" }; // // debug(msgs); // } // // }
import happy.coding.io.Logs; import java.io.OutputStream; import java.net.Socket;
package happy.coding.io.net; public class SocketClient { private Socket socket; private String remoteHost; private int remotePort; public SocketClient(String host, int port) { this.remoteHost = host; this.remotePort = port; } public void write(String content) throws Exception { socket = new Socket(remoteHost, remotePort); OutputStream os = socket.getOutputStream(); content += "\r\n"; os.write(content.getBytes()); os.flush();
// Path: happycoding/src/main/java/happy/coding/io/Logs.java // public class Logs { // private final static Logger logger = LoggerFactory.getLogger(Logs.class); // private static String conf = null; // // // default configuration // static { // if ((conf = FileIO.getResource("log4j.properties")) != null) // config(conf, false); // else if ((conf = FileIO.getResource("log4j.xml")) != null) // config(conf, true); // } // // public static Logger config(String config, boolean isXml) { // if (isXml) // DOMConfigurator.configure(config); // else // PropertyConfigurator.configure(config); // // return logger; // } // // public static void debug(double data) { // logger.debug(Strings.toString(data)); // } // // public static void debug(Object msg) { // logger.debug(msg.toString()); // } // // public static void debug(String msg) { // logger.debug(msg); // } // // public static void debug(String format, Object arg) { // logger.debug(format, arg); // } // // public static void debug(String format, Object... args) { // logger.debug(format, args); // } // // public static void debug() { // debug(""); // } // // public static void error() { // error(""); // } // // public static void warn() { // warn(""); // } // // public static void info() { // info(""); // } // // public static void info(double data) { // logger.info(Strings.toString(data)); // } // // public static void info(Object msg) { // if (msg == null) // logger.info(""); // else // logger.info(msg.toString()); // } // // public static void info(String format, Object arg) { // logger.info(format, arg); // } // // public static void info(String format, Object... args) { // logger.info(format, args); // } // // public static void error(double data) { // logger.error(Strings.toString(data)); // } // // public static void error(Object msg) { // logger.error(msg.toString()); // } // // public static void warn(String msg) { // logger.warn(msg); // } // // public static void warn(String format, Object arg) { // logger.warn(format, arg); // } // // public static void warn(String format, Object... args) { // logger.warn(format, args); // } // // public static void warn(double data) { // logger.warn(Strings.toString(data)); // } // // public static void warn(Object msg) { // logger.warn(msg.toString()); // } // // public static void error(String msg) { // logger.error(msg); // } // // public static void error(String format, Object arg) { // logger.error(format, arg); // } // // public static void error(String format, Object... args) { // logger.error(format, args); // } // // public static void off() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.OFF); // } // // public static void on() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.DEBUG); // } // // @Test // public void example() { // String[] msgs = new String[] { "Section content: ", "@author guoguibing" }; // // debug(msgs); // } // // } // Path: happycoding/src/main/java/happy/coding/io/net/SocketClient.java import happy.coding.io.Logs; import java.io.OutputStream; import java.net.Socket; package happy.coding.io.net; public class SocketClient { private Socket socket; private String remoteHost; private int remotePort; public SocketClient(String host, int port) { this.remoteHost = host; this.remotePort = port; } public void write(String content) throws Exception { socket = new Socket(remoteHost, remotePort); OutputStream os = socket.getOutputStream(); content += "\r\n"; os.write(content.getBytes()); os.flush();
Logs.info("Output to Server: {}", content);
guoguibing/HappyCoding
happycoding/src/main/java/happy/coding/io/net/SocketServer.java
// Path: happycoding/src/main/java/happy/coding/io/Logs.java // public class Logs { // private final static Logger logger = LoggerFactory.getLogger(Logs.class); // private static String conf = null; // // // default configuration // static { // if ((conf = FileIO.getResource("log4j.properties")) != null) // config(conf, false); // else if ((conf = FileIO.getResource("log4j.xml")) != null) // config(conf, true); // } // // public static Logger config(String config, boolean isXml) { // if (isXml) // DOMConfigurator.configure(config); // else // PropertyConfigurator.configure(config); // // return logger; // } // // public static void debug(double data) { // logger.debug(Strings.toString(data)); // } // // public static void debug(Object msg) { // logger.debug(msg.toString()); // } // // public static void debug(String msg) { // logger.debug(msg); // } // // public static void debug(String format, Object arg) { // logger.debug(format, arg); // } // // public static void debug(String format, Object... args) { // logger.debug(format, args); // } // // public static void debug() { // debug(""); // } // // public static void error() { // error(""); // } // // public static void warn() { // warn(""); // } // // public static void info() { // info(""); // } // // public static void info(double data) { // logger.info(Strings.toString(data)); // } // // public static void info(Object msg) { // if (msg == null) // logger.info(""); // else // logger.info(msg.toString()); // } // // public static void info(String format, Object arg) { // logger.info(format, arg); // } // // public static void info(String format, Object... args) { // logger.info(format, args); // } // // public static void error(double data) { // logger.error(Strings.toString(data)); // } // // public static void error(Object msg) { // logger.error(msg.toString()); // } // // public static void warn(String msg) { // logger.warn(msg); // } // // public static void warn(String format, Object arg) { // logger.warn(format, arg); // } // // public static void warn(String format, Object... args) { // logger.warn(format, args); // } // // public static void warn(double data) { // logger.warn(Strings.toString(data)); // } // // public static void warn(Object msg) { // logger.warn(msg.toString()); // } // // public static void error(String msg) { // logger.error(msg); // } // // public static void error(String format, Object arg) { // logger.error(format, arg); // } // // public static void error(String format, Object... args) { // logger.error(format, args); // } // // public static void off() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.OFF); // } // // public static void on() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.DEBUG); // } // // @Test // public void example() { // String[] msgs = new String[] { "Section content: ", "@author guoguibing" }; // // debug(msgs); // } // // }
import happy.coding.io.Logs; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket;
package happy.coding.io.net; public class SocketServer { private ServerSocket ss; public SocketServer(int port) throws Exception { ss = new ServerSocket(port);
// Path: happycoding/src/main/java/happy/coding/io/Logs.java // public class Logs { // private final static Logger logger = LoggerFactory.getLogger(Logs.class); // private static String conf = null; // // // default configuration // static { // if ((conf = FileIO.getResource("log4j.properties")) != null) // config(conf, false); // else if ((conf = FileIO.getResource("log4j.xml")) != null) // config(conf, true); // } // // public static Logger config(String config, boolean isXml) { // if (isXml) // DOMConfigurator.configure(config); // else // PropertyConfigurator.configure(config); // // return logger; // } // // public static void debug(double data) { // logger.debug(Strings.toString(data)); // } // // public static void debug(Object msg) { // logger.debug(msg.toString()); // } // // public static void debug(String msg) { // logger.debug(msg); // } // // public static void debug(String format, Object arg) { // logger.debug(format, arg); // } // // public static void debug(String format, Object... args) { // logger.debug(format, args); // } // // public static void debug() { // debug(""); // } // // public static void error() { // error(""); // } // // public static void warn() { // warn(""); // } // // public static void info() { // info(""); // } // // public static void info(double data) { // logger.info(Strings.toString(data)); // } // // public static void info(Object msg) { // if (msg == null) // logger.info(""); // else // logger.info(msg.toString()); // } // // public static void info(String format, Object arg) { // logger.info(format, arg); // } // // public static void info(String format, Object... args) { // logger.info(format, args); // } // // public static void error(double data) { // logger.error(Strings.toString(data)); // } // // public static void error(Object msg) { // logger.error(msg.toString()); // } // // public static void warn(String msg) { // logger.warn(msg); // } // // public static void warn(String format, Object arg) { // logger.warn(format, arg); // } // // public static void warn(String format, Object... args) { // logger.warn(format, args); // } // // public static void warn(double data) { // logger.warn(Strings.toString(data)); // } // // public static void warn(Object msg) { // logger.warn(msg.toString()); // } // // public static void error(String msg) { // logger.error(msg); // } // // public static void error(String format, Object arg) { // logger.error(format, arg); // } // // public static void error(String format, Object... args) { // logger.error(format, args); // } // // public static void off() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.OFF); // } // // public static void on() { // org.apache.log4j.Logger.getRootLogger().setLevel(Level.DEBUG); // } // // @Test // public void example() { // String[] msgs = new String[] { "Section content: ", "@author guoguibing" }; // // debug(msgs); // } // // } // Path: happycoding/src/main/java/happy/coding/io/net/SocketServer.java import happy.coding.io.Logs; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; package happy.coding.io.net; public class SocketServer { private ServerSocket ss; public SocketServer(int port) throws Exception { ss = new ServerSocket(port);
Logs.info("Server Listen to Port: {}", port);
guoguibing/HappyCoding
happycoding/src/main/java/happy/coding/io/FileConfiger.java
// Path: happycoding/src/main/java/happy/coding/system/Systems.java // public class Systems { // private static String desktopPath = null; // // public final static String FILE_SEPARATOR = System.getProperty("file.separator"); // public final static String USER_NAME = System.getProperty("user.name"); // public final static String USER_DIRECTORY = System.getProperty("user.home"); // public final static String WORKING_DIRECTORY = System.getProperty("user.dir"); // public final static String OPERATING_SYSTEM = System.getProperty("os.name"); // // public enum OS { // Windows, Linux, Mac // } // // private static OS os = null; // // /** // * @return path to the desktop with a file separator in the end // */ // public static String getDesktop() { // if (desktopPath == null) // desktopPath = USER_DIRECTORY + FILE_SEPARATOR + "Desktop" + FILE_SEPARATOR; // return desktopPath; // } // // public static String getIP() { // InetAddress ip = null; // try { // ip = InetAddress.getLocalHost(); // } catch (UnknownHostException e) { // e.printStackTrace(); // } // return ip.getHostName() + "@" + ip.getHostAddress(); // } // // public static OS getOs() { // if (os == null) { // for (OS m : OS.values()) { // if (OPERATING_SYSTEM.toLowerCase().contains(m.name().toLowerCase())) { // os = m; // break; // } // } // } // return os; // } // // public static void pause() { // try { // Logs.debug("System paused, press [enter] to continue ..."); // System.in.read(); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public static void captureScreen() throws Exception { // captureScreen("screenshot.png"); // } // // public static void captureScreen(String fileName) throws Exception { // // Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // Rectangle screenRectangle = new Rectangle(screenSize); // Robot robot = new Robot(); // BufferedImage image = robot.createScreenCapture(screenRectangle); // // File file = new File(fileName); // ImageIO.write(image, "png", file); // // Logs.debug("A screenshot is captured to: {}", file.getPath()); // } // // }
import happy.coding.system.Systems; import java.io.FileInputStream; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.StringTokenizer;
package happy.coding.io; /** * A configure class for .conf/.properties file * * @author guoguibing * */ public class FileConfiger extends StringMap { private Properties p = null; public FileConfiger(String conf) throws Exception { p = new Properties(); p.load(new FileInputStream(FileIO.getResource(conf))); } public LineConfiger getParamOptions(String key) { String lineOptions = getString(key); return lineOptions == null ? null : new LineConfiger(lineOptions); } /** * @return the key value as a trimmed string * */ public String getString(String key) { String str = p.getProperty(key); return str == null ? str : str.trim(); } /** * set a value to a specific key * * @param key * property key * @param val * property value */ public void setString(String key, String val) { p.setProperty(key, val); } /** * @return the file IO path: supporting windows, linux and unix */ public String getPath(String key) { // first search key itself String path = getString(key); if (path != null) return path; // if not, considering the following cases
// Path: happycoding/src/main/java/happy/coding/system/Systems.java // public class Systems { // private static String desktopPath = null; // // public final static String FILE_SEPARATOR = System.getProperty("file.separator"); // public final static String USER_NAME = System.getProperty("user.name"); // public final static String USER_DIRECTORY = System.getProperty("user.home"); // public final static String WORKING_DIRECTORY = System.getProperty("user.dir"); // public final static String OPERATING_SYSTEM = System.getProperty("os.name"); // // public enum OS { // Windows, Linux, Mac // } // // private static OS os = null; // // /** // * @return path to the desktop with a file separator in the end // */ // public static String getDesktop() { // if (desktopPath == null) // desktopPath = USER_DIRECTORY + FILE_SEPARATOR + "Desktop" + FILE_SEPARATOR; // return desktopPath; // } // // public static String getIP() { // InetAddress ip = null; // try { // ip = InetAddress.getLocalHost(); // } catch (UnknownHostException e) { // e.printStackTrace(); // } // return ip.getHostName() + "@" + ip.getHostAddress(); // } // // public static OS getOs() { // if (os == null) { // for (OS m : OS.values()) { // if (OPERATING_SYSTEM.toLowerCase().contains(m.name().toLowerCase())) { // os = m; // break; // } // } // } // return os; // } // // public static void pause() { // try { // Logs.debug("System paused, press [enter] to continue ..."); // System.in.read(); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public static void captureScreen() throws Exception { // captureScreen("screenshot.png"); // } // // public static void captureScreen(String fileName) throws Exception { // // Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // Rectangle screenRectangle = new Rectangle(screenSize); // Robot robot = new Robot(); // BufferedImage image = robot.createScreenCapture(screenRectangle); // // File file = new File(fileName); // ImageIO.write(image, "png", file); // // Logs.debug("A screenshot is captured to: {}", file.getPath()); // } // // } // Path: happycoding/src/main/java/happy/coding/io/FileConfiger.java import happy.coding.system.Systems; import java.io.FileInputStream; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.StringTokenizer; package happy.coding.io; /** * A configure class for .conf/.properties file * * @author guoguibing * */ public class FileConfiger extends StringMap { private Properties p = null; public FileConfiger(String conf) throws Exception { p = new Properties(); p.load(new FileInputStream(FileIO.getResource(conf))); } public LineConfiger getParamOptions(String key) { String lineOptions = getString(key); return lineOptions == null ? null : new LineConfiger(lineOptions); } /** * @return the key value as a trimmed string * */ public String getString(String key) { String str = p.getProperty(key); return str == null ? str : str.trim(); } /** * set a value to a specific key * * @param key * property key * @param val * property value */ public void setString(String key, String val) { p.setProperty(key, val); } /** * @return the file IO path: supporting windows, linux and unix */ public String getPath(String key) { // first search key itself String path = getString(key); if (path != null) return path; // if not, considering the following cases
switch (Systems.getOs()) {
tuenti/android-deferred
deferred/src/test/java/com/tuenti/deferred/SinglePromiseTest.java
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // }
import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Assert; import org.junit.Test; import com.tuenti.deferred.Promise.State;
} }).fail(new FailCallback() { public void onFail(Object result) { failCount.incrementAndGet(); } }); waitForCompletion(); holder.assertEquals(100); Assert.assertEquals(0, failCount.get()); } @Test public void testAlwaysDone() { final AtomicInteger failCount = new AtomicInteger(); final AtomicInteger alwaysCount = new AtomicInteger(); final ValueHolder<Integer> holder = new ValueHolder<Integer>(); deferredManager.when(successCallable(100, 1000)) .done(new DoneCallback() { public void onDone(Object result) { Assert.assertEquals(result, 100); holder.set((Integer) result); } }).fail(new FailCallback() { public void onFail(Object result) { failCount.incrementAndGet(); } }).always(new AlwaysCallback<Integer, Throwable>() { @Override
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // } // Path: deferred/src/test/java/com/tuenti/deferred/SinglePromiseTest.java import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Assert; import org.junit.Test; import com.tuenti.deferred.Promise.State; } }).fail(new FailCallback() { public void onFail(Object result) { failCount.incrementAndGet(); } }); waitForCompletion(); holder.assertEquals(100); Assert.assertEquals(0, failCount.get()); } @Test public void testAlwaysDone() { final AtomicInteger failCount = new AtomicInteger(); final AtomicInteger alwaysCount = new AtomicInteger(); final ValueHolder<Integer> holder = new ValueHolder<Integer>(); deferredManager.when(successCallable(100, 1000)) .done(new DoneCallback() { public void onDone(Object result) { Assert.assertEquals(result, 100); holder.set((Integer) result); } }).fail(new FailCallback() { public void onFail(Object result) { failCount.incrementAndGet(); } }).always(new AlwaysCallback<Integer, Throwable>() { @Override
public void onAlways(State state, Integer resolved,
tuenti/android-deferred
deferred/src/main/java/com/tuenti/deferred/Always.java
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // } // // Path: deferred/src/main/java/com/tuenti/deferred/context/ViewContextHolder.java // public class ViewContextHolder<V> { // // public static final ViewContextHolder NOP = new ViewContextHolder<>(new Object()); // // private final WeakReference<V> reference; // // @SuppressWarnings("unchecked") // public static <V> ViewContextHolder<V> of(V viewContext) { // ViewContextHolder viewContextHolder; // if (viewContext instanceof Activity) { // viewContextHolder = new ActivityContextHolder<>((AppCompatActivity) viewContext); // } else if (viewContext instanceof Fragment) { // viewContextHolder = new FragmentContextHolder<>((Fragment) viewContext); // } else { // viewContextHolder = new ViewContextHolder(viewContext); // } // return viewContextHolder; // } // // protected ViewContextHolder(V viewContext) { // reference = new WeakReference<>(viewContext); // } // // public boolean isValid() { // return reference.get() != null; // } // // public V get() { // return reference.get(); // } // // }
import com.tuenti.deferred.Promise.State; import com.tuenti.deferred.context.ViewContextHolder;
/* * Copyright (c) Tuenti Technologies S.L. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; /** * @author Rayco Araña <rayco@tuenti.com> */ public interface Always { interface Immediately<D, R> extends AlwaysCallback<D, R> { } /** * Please use UIAlwaysContextualCallback if your callback depends on a view */ interface UI<D, R> extends AlwaysCallback<D, R>, UICallback { } abstract class UIContextual<D, R, V> implements Always.UI<D, R> {
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // } // // Path: deferred/src/main/java/com/tuenti/deferred/context/ViewContextHolder.java // public class ViewContextHolder<V> { // // public static final ViewContextHolder NOP = new ViewContextHolder<>(new Object()); // // private final WeakReference<V> reference; // // @SuppressWarnings("unchecked") // public static <V> ViewContextHolder<V> of(V viewContext) { // ViewContextHolder viewContextHolder; // if (viewContext instanceof Activity) { // viewContextHolder = new ActivityContextHolder<>((AppCompatActivity) viewContext); // } else if (viewContext instanceof Fragment) { // viewContextHolder = new FragmentContextHolder<>((Fragment) viewContext); // } else { // viewContextHolder = new ViewContextHolder(viewContext); // } // return viewContextHolder; // } // // protected ViewContextHolder(V viewContext) { // reference = new WeakReference<>(viewContext); // } // // public boolean isValid() { // return reference.get() != null; // } // // public V get() { // return reference.get(); // } // // } // Path: deferred/src/main/java/com/tuenti/deferred/Always.java import com.tuenti.deferred.Promise.State; import com.tuenti.deferred.context.ViewContextHolder; /* * Copyright (c) Tuenti Technologies S.L. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; /** * @author Rayco Araña <rayco@tuenti.com> */ public interface Always { interface Immediately<D, R> extends AlwaysCallback<D, R> { } /** * Please use UIAlwaysContextualCallback if your callback depends on a view */ interface UI<D, R> extends AlwaysCallback<D, R>, UICallback { } abstract class UIContextual<D, R, V> implements Always.UI<D, R> {
private final ViewContextHolder<V> viewContextHolder;
tuenti/android-deferred
deferred/src/main/java/com/tuenti/deferred/Always.java
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // } // // Path: deferred/src/main/java/com/tuenti/deferred/context/ViewContextHolder.java // public class ViewContextHolder<V> { // // public static final ViewContextHolder NOP = new ViewContextHolder<>(new Object()); // // private final WeakReference<V> reference; // // @SuppressWarnings("unchecked") // public static <V> ViewContextHolder<V> of(V viewContext) { // ViewContextHolder viewContextHolder; // if (viewContext instanceof Activity) { // viewContextHolder = new ActivityContextHolder<>((AppCompatActivity) viewContext); // } else if (viewContext instanceof Fragment) { // viewContextHolder = new FragmentContextHolder<>((Fragment) viewContext); // } else { // viewContextHolder = new ViewContextHolder(viewContext); // } // return viewContextHolder; // } // // protected ViewContextHolder(V viewContext) { // reference = new WeakReference<>(viewContext); // } // // public boolean isValid() { // return reference.get() != null; // } // // public V get() { // return reference.get(); // } // // }
import com.tuenti.deferred.Promise.State; import com.tuenti.deferred.context.ViewContextHolder;
/* * Copyright (c) Tuenti Technologies S.L. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; /** * @author Rayco Araña <rayco@tuenti.com> */ public interface Always { interface Immediately<D, R> extends AlwaysCallback<D, R> { } /** * Please use UIAlwaysContextualCallback if your callback depends on a view */ interface UI<D, R> extends AlwaysCallback<D, R>, UICallback { } abstract class UIContextual<D, R, V> implements Always.UI<D, R> { private final ViewContextHolder<V> viewContextHolder; public UIContextual(V view) { this.viewContextHolder = ViewContextHolder.of(view); }
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // } // // Path: deferred/src/main/java/com/tuenti/deferred/context/ViewContextHolder.java // public class ViewContextHolder<V> { // // public static final ViewContextHolder NOP = new ViewContextHolder<>(new Object()); // // private final WeakReference<V> reference; // // @SuppressWarnings("unchecked") // public static <V> ViewContextHolder<V> of(V viewContext) { // ViewContextHolder viewContextHolder; // if (viewContext instanceof Activity) { // viewContextHolder = new ActivityContextHolder<>((AppCompatActivity) viewContext); // } else if (viewContext instanceof Fragment) { // viewContextHolder = new FragmentContextHolder<>((Fragment) viewContext); // } else { // viewContextHolder = new ViewContextHolder(viewContext); // } // return viewContextHolder; // } // // protected ViewContextHolder(V viewContext) { // reference = new WeakReference<>(viewContext); // } // // public boolean isValid() { // return reference.get() != null; // } // // public V get() { // return reference.get(); // } // // } // Path: deferred/src/main/java/com/tuenti/deferred/Always.java import com.tuenti.deferred.Promise.State; import com.tuenti.deferred.context.ViewContextHolder; /* * Copyright (c) Tuenti Technologies S.L. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; /** * @author Rayco Araña <rayco@tuenti.com> */ public interface Always { interface Immediately<D, R> extends AlwaysCallback<D, R> { } /** * Please use UIAlwaysContextualCallback if your callback depends on a view */ interface UI<D, R> extends AlwaysCallback<D, R>, UICallback { } abstract class UIContextual<D, R, V> implements Always.UI<D, R> { private final ViewContextHolder<V> viewContextHolder; public UIContextual(V view) { this.viewContextHolder = ViewContextHolder.of(view); }
public final void onAlways(final State state, final D resolved, final R rejected) {
tuenti/android-deferred
deferred/src/main/java/com/tuenti/deferred/ComputationStrategyCallback.java
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // }
import java.util.concurrent.Executor; import com.tuenti.deferred.Promise.State;
/* * Copyright (c) Tuenti Technologies S.L. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; class ComputationStrategyCallback implements CallbackStrategy { public <D, F, P> void triggerDone(AbstractPromise<D, F, P> promise, DoneCallback<D> callback, D resolved) { promise.triggerDoneOnExecutor(callback, resolved, getExecutor(promise)); } @Override public <D, F, P> void triggerFail(AbstractPromise<D, F, P> promise, FailCallback<F> callback, F rejected) { promise.triggerFailOnExecutor(callback, rejected, getExecutor(promise)); } @Override public <D, F, P> void triggerProgress(AbstractPromise<D, F, P> promise, ProgressCallback<P> callback, P progress) { promise.triggerProgressOnExecutor(callback, progress, getExecutor(promise)); } @Override public <D, F, P> void triggerAlways(AbstractPromise<D, F, P> promise,
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // } // Path: deferred/src/main/java/com/tuenti/deferred/ComputationStrategyCallback.java import java.util.concurrent.Executor; import com.tuenti.deferred.Promise.State; /* * Copyright (c) Tuenti Technologies S.L. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; class ComputationStrategyCallback implements CallbackStrategy { public <D, F, P> void triggerDone(AbstractPromise<D, F, P> promise, DoneCallback<D> callback, D resolved) { promise.triggerDoneOnExecutor(callback, resolved, getExecutor(promise)); } @Override public <D, F, P> void triggerFail(AbstractPromise<D, F, P> promise, FailCallback<F> callback, F rejected) { promise.triggerFailOnExecutor(callback, rejected, getExecutor(promise)); } @Override public <D, F, P> void triggerProgress(AbstractPromise<D, F, P> promise, ProgressCallback<P> callback, P progress) { promise.triggerProgressOnExecutor(callback, progress, getExecutor(promise)); } @Override public <D, F, P> void triggerAlways(AbstractPromise<D, F, P> promise,
AlwaysCallback<D, F> callback, State state, D resolve, F reject) {
tuenti/android-deferred
deferred/src/test/java/com/tuenti/deferred/MultiplePromisesTest.java
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // }
import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Assert; import org.junit.Test; import com.tuenti.deferred.Promise.State;
final AtomicInteger alwaysCount = new AtomicInteger(); deferredManager.when(new Callable<Integer>() { public Integer call() { try { Thread.sleep(1000); } catch (InterruptedException e) { } return 100; } }, new Callable<String>() { public String call() { try { Thread.sleep(1000); } catch (InterruptedException e) { } return "Hello"; } }).then(new DoneCallback<MultipleResults>() { public void onDone(MultipleResults results) { Assert.assertEquals(2, results.size()); Assert.assertEquals(100, results.get(0).getResult()); Assert.assertEquals("Hello", results.get(1).getResult()); doneCount.incrementAndGet(); } }).always(new AlwaysCallback<MultipleResults, OneReject>() { @Override
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // } // Path: deferred/src/test/java/com/tuenti/deferred/MultiplePromisesTest.java import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Assert; import org.junit.Test; import com.tuenti.deferred.Promise.State; final AtomicInteger alwaysCount = new AtomicInteger(); deferredManager.when(new Callable<Integer>() { public Integer call() { try { Thread.sleep(1000); } catch (InterruptedException e) { } return 100; } }, new Callable<String>() { public String call() { try { Thread.sleep(1000); } catch (InterruptedException e) { } return "Hello"; } }).then(new DoneCallback<MultipleResults>() { public void onDone(MultipleResults results) { Assert.assertEquals(2, results.size()); Assert.assertEquals(100, results.get(0).getResult()); Assert.assertEquals("Hello", results.get(1).getResult()); doneCount.incrementAndGet(); } }).always(new AlwaysCallback<MultipleResults, OneReject>() { @Override
public void onAlways(State state, MultipleResults results,
tuenti/android-deferred
deferred/src/main/java/com/tuenti/deferred/Fail.java
// Path: deferred/src/main/java/com/tuenti/deferred/context/ViewContextHolder.java // public class ViewContextHolder<V> { // // public static final ViewContextHolder NOP = new ViewContextHolder<>(new Object()); // // private final WeakReference<V> reference; // // @SuppressWarnings("unchecked") // public static <V> ViewContextHolder<V> of(V viewContext) { // ViewContextHolder viewContextHolder; // if (viewContext instanceof Activity) { // viewContextHolder = new ActivityContextHolder<>((AppCompatActivity) viewContext); // } else if (viewContext instanceof Fragment) { // viewContextHolder = new FragmentContextHolder<>((Fragment) viewContext); // } else { // viewContextHolder = new ViewContextHolder(viewContext); // } // return viewContextHolder; // } // // protected ViewContextHolder(V viewContext) { // reference = new WeakReference<>(viewContext); // } // // public boolean isValid() { // return reference.get() != null; // } // // public V get() { // return reference.get(); // } // // }
import com.tuenti.deferred.context.ViewContextHolder;
/* * Copyright (c) Tuenti Technologies S.L. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; public interface Fail { interface Immediately<F> extends FailCallback<F> { } /** *Please use Fail.UIContextual if your callback depends on a view */ interface UI<F> extends FailCallback<F>, UICallback { } /** * Fail callback that gets executed always on a UI thread */ abstract class UIContextual<F, V> implements Fail.UI<F> {
// Path: deferred/src/main/java/com/tuenti/deferred/context/ViewContextHolder.java // public class ViewContextHolder<V> { // // public static final ViewContextHolder NOP = new ViewContextHolder<>(new Object()); // // private final WeakReference<V> reference; // // @SuppressWarnings("unchecked") // public static <V> ViewContextHolder<V> of(V viewContext) { // ViewContextHolder viewContextHolder; // if (viewContext instanceof Activity) { // viewContextHolder = new ActivityContextHolder<>((AppCompatActivity) viewContext); // } else if (viewContext instanceof Fragment) { // viewContextHolder = new FragmentContextHolder<>((Fragment) viewContext); // } else { // viewContextHolder = new ViewContextHolder(viewContext); // } // return viewContextHolder; // } // // protected ViewContextHolder(V viewContext) { // reference = new WeakReference<>(viewContext); // } // // public boolean isValid() { // return reference.get() != null; // } // // public V get() { // return reference.get(); // } // // } // Path: deferred/src/main/java/com/tuenti/deferred/Fail.java import com.tuenti.deferred.context.ViewContextHolder; /* * Copyright (c) Tuenti Technologies S.L. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; public interface Fail { interface Immediately<F> extends FailCallback<F> { } /** *Please use Fail.UIContextual if your callback depends on a view */ interface UI<F> extends FailCallback<F>, UICallback { } /** * Fail callback that gets executed always on a UI thread */ abstract class UIContextual<F, V> implements Fail.UI<F> {
private final ViewContextHolder<V> viewContextHolder;
tuenti/android-deferred
deferred/src/main/java/com/tuenti/deferred/AbstractPromise.java
// Path: deferred/src/main/java/com/tuenti/deferred/LoggerProvider.java // public static Logger getLogger() { // return logger; // }
import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executor; import static com.tuenti.deferred.LoggerProvider.getLogger;
@Override public Promise<D, F, P> fail(FailCallback<F> callback) { synchronized (this) { if (isRejected()) { triggerFail(callback, rejectResult); } else { failCallbacks.add(callback); } } return this; } @Override public Promise<D, F, P> always(AlwaysCallback<D, F> callback) { synchronized (this) { if (isPending()) { alwaysCallbacks.add(callback); } else { triggerAlways(callback, state, resolveResult, rejectResult); } } return this; } protected void triggerDone(D resolved) { for (DoneCallback<D> callback : doneCallbacks) { try { triggerDone(callback, resolved); } catch (Exception e) {
// Path: deferred/src/main/java/com/tuenti/deferred/LoggerProvider.java // public static Logger getLogger() { // return logger; // } // Path: deferred/src/main/java/com/tuenti/deferred/AbstractPromise.java import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executor; import static com.tuenti.deferred.LoggerProvider.getLogger; @Override public Promise<D, F, P> fail(FailCallback<F> callback) { synchronized (this) { if (isRejected()) { triggerFail(callback, rejectResult); } else { failCallbacks.add(callback); } } return this; } @Override public Promise<D, F, P> always(AlwaysCallback<D, F> callback) { synchronized (this) { if (isPending()) { alwaysCallbacks.add(callback); } else { triggerAlways(callback, state, resolveResult, rejectResult); } } return this; } protected void triggerDone(D resolved) { for (DoneCallback<D> callback : doneCallbacks) { try { triggerDone(callback, resolved); } catch (Exception e) {
getLogger().error("an uncaught exception occured in a DoneCallback", e);
tuenti/android-deferred
deferred/src/main/java/com/tuenti/deferred/AbstractDeferredManager.java
// Path: deferred/src/main/java/com/tuenti/deferred/PromiseObjectTask.java // public interface Filter<D> { // boolean success(D result); // }
import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import com.tuenti.deferred.PromiseObjectTask.Filter;
if (task.getStartPolicy() == StartPolicy.AUTO || task.getStartPolicy() == StartPolicy.DEFAULT && isAutoSubmit()) { submit(task); } return task.promise(); } @Override public <D> Promise<D, Throwable, Void> when(final Future<D> future) { // make sure the task is automatically started return when(new DeferredCallable<D, Void>(executorProvider, StartPolicy.AUTO) { @Override public D call() throws Exception { try { return future.get(); } catch (InterruptedException e) { throw e; } catch (ExecutionException e) { if (e.getCause() instanceof Exception) { throw (Exception) e.getCause(); } else { throw e; } } } }); } @Override
// Path: deferred/src/main/java/com/tuenti/deferred/PromiseObjectTask.java // public interface Filter<D> { // boolean success(D result); // } // Path: deferred/src/main/java/com/tuenti/deferred/AbstractDeferredManager.java import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import com.tuenti.deferred.PromiseObjectTask.Filter; if (task.getStartPolicy() == StartPolicy.AUTO || task.getStartPolicy() == StartPolicy.DEFAULT && isAutoSubmit()) { submit(task); } return task.promise(); } @Override public <D> Promise<D, Throwable, Void> when(final Future<D> future) { // make sure the task is automatically started return when(new DeferredCallable<D, Void>(executorProvider, StartPolicy.AUTO) { @Override public D call() throws Exception { try { return future.get(); } catch (InterruptedException e) { throw e; } catch (ExecutionException e) { if (e.getCause() instanceof Exception) { throw (Exception) e.getCause(); } else { throw e; } } } }); } @Override
public <D, F, P> Promise<D, F, P> sequentiallyRunUntilFirstDone(final PromiseObjectTask.Filter<D> filter,
tuenti/android-deferred
deferred/src/main/java/com/tuenti/deferred/DeferredRunnable.java
// Path: deferred/src/main/java/com/tuenti/deferred/DeferredManager.java // enum StartPolicy { // /** // * Let Deferred Manager to determine whether to start the task at its own // * discretion. // */ // DEFAULT, // // /** // * Tells Deferred Manager to automatically start the task // */ // AUTO, // // /** // * Tells Deferred Manager that this task will be manually started // */ // MANUAL // }
import com.tuenti.deferred.DeferredManager.StartPolicy;
/* * Copyright 2013 Ray Tsang * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; /** * Use this as superclass in case you need to be able to be able to notify progress. * If you don't need to notify progress, you can simply use {@link Runnable} * * @see #notify(Object) * @author Ray Tsang * * @param <P> Type used for {@link Deferred#notify(Object)} */ abstract class DeferredRunnable<P> implements Runnable { private final Deferred<Void, Throwable, P> deferred;
// Path: deferred/src/main/java/com/tuenti/deferred/DeferredManager.java // enum StartPolicy { // /** // * Let Deferred Manager to determine whether to start the task at its own // * discretion. // */ // DEFAULT, // // /** // * Tells Deferred Manager to automatically start the task // */ // AUTO, // // /** // * Tells Deferred Manager that this task will be manually started // */ // MANUAL // } // Path: deferred/src/main/java/com/tuenti/deferred/DeferredRunnable.java import com.tuenti.deferred.DeferredManager.StartPolicy; /* * Copyright 2013 Ray Tsang * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; /** * Use this as superclass in case you need to be able to be able to notify progress. * If you don't need to notify progress, you can simply use {@link Runnable} * * @see #notify(Object) * @author Ray Tsang * * @param <P> Type used for {@link Deferred#notify(Object)} */ abstract class DeferredRunnable<P> implements Runnable { private final Deferred<Void, Throwable, P> deferred;
private final StartPolicy startPolicy;
tuenti/android-deferred
deferred/src/main/java/com/tuenti/deferred/DeferredCallable.java
// Path: deferred/src/main/java/com/tuenti/deferred/DeferredManager.java // enum StartPolicy { // /** // * Let Deferred Manager to determine whether to start the task at its own // * discretion. // */ // DEFAULT, // // /** // * Tells Deferred Manager to automatically start the task // */ // AUTO, // // /** // * Tells Deferred Manager that this task will be manually started // */ // MANUAL // }
import java.util.concurrent.Callable; import com.tuenti.deferred.DeferredManager.StartPolicy;
/* * Copyright 2013 Ray Tsang * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; /** * Use this as superclass in case you need to be able to return a result and notify progress. * If you don't need to notify progress, you can simply use {@link Callable} * * @see #notify(Object) * @author Ray Tsang * * @param <D> Type used as return type of {@link Callable#call()}, and {@link Deferred#resolve(Object)} * @param <P> Type used for {@link Deferred#notify(Object)} */ abstract class DeferredCallable<D, P> implements Callable<D> { private final Deferred<D, Throwable, P> deferred;
// Path: deferred/src/main/java/com/tuenti/deferred/DeferredManager.java // enum StartPolicy { // /** // * Let Deferred Manager to determine whether to start the task at its own // * discretion. // */ // DEFAULT, // // /** // * Tells Deferred Manager to automatically start the task // */ // AUTO, // // /** // * Tells Deferred Manager that this task will be manually started // */ // MANUAL // } // Path: deferred/src/main/java/com/tuenti/deferred/DeferredCallable.java import java.util.concurrent.Callable; import com.tuenti.deferred.DeferredManager.StartPolicy; /* * Copyright 2013 Ray Tsang * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; /** * Use this as superclass in case you need to be able to return a result and notify progress. * If you don't need to notify progress, you can simply use {@link Callable} * * @see #notify(Object) * @author Ray Tsang * * @param <D> Type used as return type of {@link Callable#call()}, and {@link Deferred#resolve(Object)} * @param <P> Type used for {@link Deferred#notify(Object)} */ abstract class DeferredCallable<D, P> implements Callable<D> { private final Deferred<D, Throwable, P> deferred;
private final StartPolicy startPolicy;
tuenti/android-deferred
deferred/src/main/java/com/tuenti/deferred/DiskStrategyCallback.java
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // }
import java.util.concurrent.Executor; import com.tuenti.deferred.Promise.State;
/* * Copyright (c) Tuenti Technologies S.L. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; class DiskStrategyCallback implements CallbackStrategy { public <D, F, P> void triggerDone(AbstractPromise<D, F, P> abstractPromise, DoneCallback<D> callback, D resolved) { abstractPromise.triggerDoneOnExecutor(callback, resolved, getExecutor(abstractPromise)); } @Override public <D, F, P> void triggerFail(AbstractPromise<D, F, P> abstractPromise, FailCallback<F> callback, F rejected) { abstractPromise.triggerFailOnExecutor(callback, rejected, getExecutor(abstractPromise)); } @Override public <D, F, P> void triggerProgress(AbstractPromise<D, F, P> abstractPromise, ProgressCallback<P> callback, P progress) { abstractPromise.triggerProgressOnExecutor(callback, progress, getExecutor(abstractPromise)); } @Override
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // } // Path: deferred/src/main/java/com/tuenti/deferred/DiskStrategyCallback.java import java.util.concurrent.Executor; import com.tuenti.deferred.Promise.State; /* * Copyright (c) Tuenti Technologies S.L. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; class DiskStrategyCallback implements CallbackStrategy { public <D, F, P> void triggerDone(AbstractPromise<D, F, P> abstractPromise, DoneCallback<D> callback, D resolved) { abstractPromise.triggerDoneOnExecutor(callback, resolved, getExecutor(abstractPromise)); } @Override public <D, F, P> void triggerFail(AbstractPromise<D, F, P> abstractPromise, FailCallback<F> callback, F rejected) { abstractPromise.triggerFailOnExecutor(callback, rejected, getExecutor(abstractPromise)); } @Override public <D, F, P> void triggerProgress(AbstractPromise<D, F, P> abstractPromise, ProgressCallback<P> callback, P progress) { abstractPromise.triggerProgressOnExecutor(callback, progress, getExecutor(abstractPromise)); } @Override
public <D, F, P> void triggerAlways(AbstractPromise<D, F, P> abstractPromise, AlwaysCallback<D, F> callback, State state, D resolve, F reject) {
tuenti/android-deferred
deferred/src/main/java/com/tuenti/deferred/DeferredFutureTask.java
// Path: deferred/src/main/java/com/tuenti/deferred/DeferredManager.java // enum StartPolicy { // /** // * Let Deferred Manager to determine whether to start the task at its own // * discretion. // */ // DEFAULT, // // /** // * Tells Deferred Manager to automatically start the task // */ // AUTO, // // /** // * Tells Deferred Manager that this task will be manually started // */ // MANUAL // }
import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import com.tuenti.deferred.DeferredManager.StartPolicy;
/* * Copyright 2013 Ray Tsang * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; /** * FutureTask can wrap around {@link Callable} and {@link Runnable}. * In these two cases, a new {@link Deferred} object will be created. * This class will override {@link FutureTask#done} to trigger the * appropriate {@link Deferred} actions. * * Note, type used for {@link Deferred#reject(Object)} is always {@link Throwable}. * * When the task is completed successfully, {@link Deferred#resolve(Object)} will be called. * When a task is canceled, {@link Deferred#reject(Object)} will be called with an instance of {@link CancellationException} * If any Exception occured, {@link Deferred#reject(Object)} will be called with the Exception instance. * * @author Ray Tsang * * @param <D> Type used for {@link Deferred#resolve(Object)} * @param <P> Type used for {@link Deferred#notify(Object)} */ class DeferredFutureTask<D, P> extends FutureTask<D> { protected final Deferred<D, Throwable, P> deferred;
// Path: deferred/src/main/java/com/tuenti/deferred/DeferredManager.java // enum StartPolicy { // /** // * Let Deferred Manager to determine whether to start the task at its own // * discretion. // */ // DEFAULT, // // /** // * Tells Deferred Manager to automatically start the task // */ // AUTO, // // /** // * Tells Deferred Manager that this task will be manually started // */ // MANUAL // } // Path: deferred/src/main/java/com/tuenti/deferred/DeferredFutureTask.java import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import com.tuenti.deferred.DeferredManager.StartPolicy; /* * Copyright 2013 Ray Tsang * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; /** * FutureTask can wrap around {@link Callable} and {@link Runnable}. * In these two cases, a new {@link Deferred} object will be created. * This class will override {@link FutureTask#done} to trigger the * appropriate {@link Deferred} actions. * * Note, type used for {@link Deferred#reject(Object)} is always {@link Throwable}. * * When the task is completed successfully, {@link Deferred#resolve(Object)} will be called. * When a task is canceled, {@link Deferred#reject(Object)} will be called with an instance of {@link CancellationException} * If any Exception occured, {@link Deferred#reject(Object)} will be called with the Exception instance. * * @author Ray Tsang * * @param <D> Type used for {@link Deferred#resolve(Object)} * @param <P> Type used for {@link Deferred#notify(Object)} */ class DeferredFutureTask<D, P> extends FutureTask<D> { protected final Deferred<D, Throwable, P> deferred;
protected final StartPolicy startPolicy;
tuenti/android-deferred
deferred/src/main/java/com/tuenti/deferred/Progress.java
// Path: deferred/src/main/java/com/tuenti/deferred/context/ViewContextHolder.java // public class ViewContextHolder<V> { // // public static final ViewContextHolder NOP = new ViewContextHolder<>(new Object()); // // private final WeakReference<V> reference; // // @SuppressWarnings("unchecked") // public static <V> ViewContextHolder<V> of(V viewContext) { // ViewContextHolder viewContextHolder; // if (viewContext instanceof Activity) { // viewContextHolder = new ActivityContextHolder<>((AppCompatActivity) viewContext); // } else if (viewContext instanceof Fragment) { // viewContextHolder = new FragmentContextHolder<>((Fragment) viewContext); // } else { // viewContextHolder = new ViewContextHolder(viewContext); // } // return viewContextHolder; // } // // protected ViewContextHolder(V viewContext) { // reference = new WeakReference<>(viewContext); // } // // public boolean isValid() { // return reference.get() != null; // } // // public V get() { // return reference.get(); // } // // }
import com.tuenti.deferred.context.ViewContextHolder;
/* * Copyright (c) Tuenti Technologies S.L. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; public interface Progress { interface Immediately<P> extends ProgressCallback<P> { } /** * Please use Progress.UIContextual if your callback depends on a view */ interface UI<P> extends ProgressCallback<P>, UICallback { } abstract class UIContextual<P, V> implements Progress.UI<P> {
// Path: deferred/src/main/java/com/tuenti/deferred/context/ViewContextHolder.java // public class ViewContextHolder<V> { // // public static final ViewContextHolder NOP = new ViewContextHolder<>(new Object()); // // private final WeakReference<V> reference; // // @SuppressWarnings("unchecked") // public static <V> ViewContextHolder<V> of(V viewContext) { // ViewContextHolder viewContextHolder; // if (viewContext instanceof Activity) { // viewContextHolder = new ActivityContextHolder<>((AppCompatActivity) viewContext); // } else if (viewContext instanceof Fragment) { // viewContextHolder = new FragmentContextHolder<>((Fragment) viewContext); // } else { // viewContextHolder = new ViewContextHolder(viewContext); // } // return viewContextHolder; // } // // protected ViewContextHolder(V viewContext) { // reference = new WeakReference<>(viewContext); // } // // public boolean isValid() { // return reference.get() != null; // } // // public V get() { // return reference.get(); // } // // } // Path: deferred/src/main/java/com/tuenti/deferred/Progress.java import com.tuenti.deferred.context.ViewContextHolder; /* * Copyright (c) Tuenti Technologies S.L. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; public interface Progress { interface Immediately<P> extends ProgressCallback<P> { } /** * Please use Progress.UIContextual if your callback depends on a view */ interface UI<P> extends ProgressCallback<P>, UICallback { } abstract class UIContextual<P, V> implements Progress.UI<P> {
private final ViewContextHolder<V> viewContextHolder;
tuenti/android-deferred
deferred/src/main/java/com/tuenti/deferred/CallbackStrategy.java
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // }
import com.tuenti.deferred.Promise.State;
/* * Copyright (c) Tuenti Technologies S.L. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; interface CallbackStrategy { <D, F, P> void triggerDone(AbstractPromise<D, F, P> promise, DoneCallback<D> callback, D resolved); <D, F, P> void triggerFail(AbstractPromise<D, F, P> promise, FailCallback<F> callback, F rejected); <D, F, P> void triggerProgress(AbstractPromise<D, F, P> promise, ProgressCallback<P> callback, P progress);
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // } // Path: deferred/src/main/java/com/tuenti/deferred/CallbackStrategy.java import com.tuenti.deferred.Promise.State; /* * Copyright (c) Tuenti Technologies S.L. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; interface CallbackStrategy { <D, F, P> void triggerDone(AbstractPromise<D, F, P> promise, DoneCallback<D> callback, D resolved); <D, F, P> void triggerFail(AbstractPromise<D, F, P> promise, FailCallback<F> callback, F rejected); <D, F, P> void triggerProgress(AbstractPromise<D, F, P> promise, ProgressCallback<P> callback, P progress);
<D, F, P> void triggerAlways(AbstractPromise<D, F, P> promise, AlwaysCallback<D, F> callback, State state, D resolve, F reject);
tuenti/android-deferred
deferred/src/main/java/com/tuenti/deferred/NetworkStrategyCallback.java
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // }
import java.util.concurrent.Executor; import com.tuenti.deferred.Promise.State;
/* * Copyright (c) Tuenti Technologies S.L. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; class NetworkStrategyCallback implements CallbackStrategy { public <D, F, P> void triggerDone(AbstractPromise<D, F, P> abstractPromise, DoneCallback<D> callback, D resolved) { abstractPromise.triggerDoneOnExecutor(callback, resolved, getExecutor(abstractPromise)); } @Override public <D, F, P> void triggerFail(AbstractPromise<D, F, P> abstractPromise, FailCallback<F> callback, F rejected) { abstractPromise.triggerFailOnExecutor(callback, rejected, getExecutor(abstractPromise)); } @Override public <D, F, P> void triggerProgress(AbstractPromise<D, F, P> abstractPromise, ProgressCallback<P> callback, P progress) { abstractPromise.triggerProgressOnExecutor(callback, progress, getExecutor(abstractPromise)); } @Override
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // } // Path: deferred/src/main/java/com/tuenti/deferred/NetworkStrategyCallback.java import java.util.concurrent.Executor; import com.tuenti.deferred.Promise.State; /* * Copyright (c) Tuenti Technologies S.L. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; class NetworkStrategyCallback implements CallbackStrategy { public <D, F, P> void triggerDone(AbstractPromise<D, F, P> abstractPromise, DoneCallback<D> callback, D resolved) { abstractPromise.triggerDoneOnExecutor(callback, resolved, getExecutor(abstractPromise)); } @Override public <D, F, P> void triggerFail(AbstractPromise<D, F, P> abstractPromise, FailCallback<F> callback, F rejected) { abstractPromise.triggerFailOnExecutor(callback, rejected, getExecutor(abstractPromise)); } @Override public <D, F, P> void triggerProgress(AbstractPromise<D, F, P> abstractPromise, ProgressCallback<P> callback, P progress) { abstractPromise.triggerProgressOnExecutor(callback, progress, getExecutor(abstractPromise)); } @Override
public <D, F, P> void triggerAlways(AbstractPromise<D, F, P> abstractPromise, AlwaysCallback<D, F> callback, State state, D resolve, F reject) {
tuenti/android-deferred
deferred/src/test/java/com/tuenti/deferred/FailureTest.java
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // }
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Assert; import org.junit.Test; import com.tuenti.deferred.Promise.State;
/* * Copyright 2013 Ray Tsang * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; @SuppressWarnings({"unchecked", "rawtypes"}) public class FailureTest extends AbstractDeferredTest { @Test public void testBadCallback() { final AtomicInteger counter = new AtomicInteger(); deferredManager.when(successCallable(100, 1000)) .done(new DoneCallback() { public void onDone(Object result) { counter.incrementAndGet(); throw new RuntimeException("this exception is expected"); } }).done(new DoneCallback<Integer>() { @Override public void onDone(Integer result) { counter.incrementAndGet(); } }).fail(new FailCallback() { public void onFail(Object result) { Assert.fail("Shouldn't be here"); } }).always(new AlwaysCallback<Integer, Throwable>() { @Override
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // } // Path: deferred/src/test/java/com/tuenti/deferred/FailureTest.java import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Assert; import org.junit.Test; import com.tuenti.deferred.Promise.State; /* * Copyright 2013 Ray Tsang * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; @SuppressWarnings({"unchecked", "rawtypes"}) public class FailureTest extends AbstractDeferredTest { @Test public void testBadCallback() { final AtomicInteger counter = new AtomicInteger(); deferredManager.when(successCallable(100, 1000)) .done(new DoneCallback() { public void onDone(Object result) { counter.incrementAndGet(); throw new RuntimeException("this exception is expected"); } }).done(new DoneCallback<Integer>() { @Override public void onDone(Integer result) { counter.incrementAndGet(); } }).fail(new FailCallback() { public void onFail(Object result) { Assert.fail("Shouldn't be here"); } }).always(new AlwaysCallback<Integer, Throwable>() { @Override
public void onAlways(State state, Integer resolved, Throwable rejected) {
tuenti/android-deferred
deferred/src/main/java/com/tuenti/deferred/UIStrategyCallback.java
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // }
import java.util.concurrent.Executor; import com.tuenti.deferred.Promise.State;
/* * Copyright (c) Tuenti Technologies S.L. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; class UIStrategyCallback implements CallbackStrategy { public <D, F, P> void triggerDone(AbstractPromise<D, F, P> abstractPromise, DoneCallback<D> callback, D resolved) { abstractPromise.triggerDoneOnExecutor(callback, resolved, getExecutor(abstractPromise)); } @Override public <D, F, P> void triggerFail(AbstractPromise<D, F, P> abstractPromise, FailCallback<F> callback, F rejected) { abstractPromise.triggerFailOnExecutor(callback, rejected, getExecutor(abstractPromise)); } @Override public <D, F, P> void triggerProgress(AbstractPromise<D, F, P> abstractPromise, ProgressCallback<P> callback, P progress) { abstractPromise.triggerProgressOnExecutor(callback, progress, getExecutor(abstractPromise)); } @Override
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // } // Path: deferred/src/main/java/com/tuenti/deferred/UIStrategyCallback.java import java.util.concurrent.Executor; import com.tuenti.deferred.Promise.State; /* * Copyright (c) Tuenti Technologies S.L. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; class UIStrategyCallback implements CallbackStrategy { public <D, F, P> void triggerDone(AbstractPromise<D, F, P> abstractPromise, DoneCallback<D> callback, D resolved) { abstractPromise.triggerDoneOnExecutor(callback, resolved, getExecutor(abstractPromise)); } @Override public <D, F, P> void triggerFail(AbstractPromise<D, F, P> abstractPromise, FailCallback<F> callback, F rejected) { abstractPromise.triggerFailOnExecutor(callback, rejected, getExecutor(abstractPromise)); } @Override public <D, F, P> void triggerProgress(AbstractPromise<D, F, P> abstractPromise, ProgressCallback<P> callback, P progress) { abstractPromise.triggerProgressOnExecutor(callback, progress, getExecutor(abstractPromise)); } @Override
public <D, F, P> void triggerAlways(AbstractPromise<D, F, P> abstractPromise, AlwaysCallback<D, F> callback, State state, D resolve, F reject) {
tuenti/android-deferred
deferred/src/test/java/com/tuenti/deferred/AlwaysCallbacksTest.java
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // }
import org.junit.Test; import com.tuenti.deferred.Promise.State;
thenTheCallbackIsExecutedOnTheExecutor(computationExecutor); } @Test public void testAlwaysDiskIsExecutedInDiskExecutor() { givenADeferredObject(); Always.Disk<Void, Void> callback = givenADiskCallback(); whenTheDeferredIsFinishedAndAnAlwaysCallbackIsSet(callback); thenTheCallbackIsExecutedOnTheExecutor(diskExecutor); } @Test public void testAlwaysNetworkIsExecutedInNetworkExecutor() { givenADeferredObject(); Always.Network<Void, Void> callback = givenANetworkCallback(); whenTheDeferredIsFinishedAndAnAlwaysCallbackIsSet(callback); thenTheCallbackIsExecutedOnTheExecutor(networkExecutor); } private void whenTheDeferredIsFinishedAndAnAlwaysCallbackIsSet(AlwaysCallback<Void, Void> callback) { deferred.resolve(null).always(callback); } private Always.UI<Void, Void> givenAUICallback() { return new Always.UI<Void, Void>() { @Override
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // } // Path: deferred/src/test/java/com/tuenti/deferred/AlwaysCallbacksTest.java import org.junit.Test; import com.tuenti.deferred.Promise.State; thenTheCallbackIsExecutedOnTheExecutor(computationExecutor); } @Test public void testAlwaysDiskIsExecutedInDiskExecutor() { givenADeferredObject(); Always.Disk<Void, Void> callback = givenADiskCallback(); whenTheDeferredIsFinishedAndAnAlwaysCallbackIsSet(callback); thenTheCallbackIsExecutedOnTheExecutor(diskExecutor); } @Test public void testAlwaysNetworkIsExecutedInNetworkExecutor() { givenADeferredObject(); Always.Network<Void, Void> callback = givenANetworkCallback(); whenTheDeferredIsFinishedAndAnAlwaysCallbackIsSet(callback); thenTheCallbackIsExecutedOnTheExecutor(networkExecutor); } private void whenTheDeferredIsFinishedAndAnAlwaysCallbackIsSet(AlwaysCallback<Void, Void> callback) { deferred.resolve(null).always(callback); } private Always.UI<Void, Void> givenAUICallback() { return new Always.UI<Void, Void>() { @Override
public void onAlways(State state, Void resolved, Void rejected) {
tuenti/android-deferred
deferred/src/main/java/com/tuenti/deferred/ImmediatelyStrategyCallback.java
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // }
import com.tuenti.deferred.Promise.State;
/* * Copyright (c) Tuenti Technologies S.L. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; class ImmediatelyStrategyCallback implements CallbackStrategy { @Override public <D, F, P> void triggerDone(AbstractPromise<D, F, P> abstractPromise, DoneCallback<D> callback, D resolved) { abstractPromise.triggerDoneImmediately(callback, resolved); } @Override public <D, F, P> void triggerFail(AbstractPromise<D, F, P> abstractPromise, FailCallback<F> callback, F rejected) { abstractPromise.triggerFailImmediately(callback, rejected); } @Override public <D, F, P> void triggerProgress(AbstractPromise<D, F, P> abstractPromise, ProgressCallback<P> callback, P progress) { abstractPromise.triggerProgressImmediately(callback, progress); } @Override
// Path: deferred/src/main/java/com/tuenti/deferred/Promise.java // enum State { // /** // * The Promise is still pending - it could be created, submitted for execution, // * or currently running, but not yet finished. // */ // PENDING, // // /** // * The Promise has finished running and a failure occurred. // * Thus, the Promise is rejected. // * // * @see Deferred#reject(Object) // */ // REJECTED, // // /** // * The Promise has finished running successfully. // * Thus the Promise is resolved. // * // * @see Deferred#resolve(Object) // */ // RESOLVED // } // Path: deferred/src/main/java/com/tuenti/deferred/ImmediatelyStrategyCallback.java import com.tuenti.deferred.Promise.State; /* * Copyright (c) Tuenti Technologies S.L. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; class ImmediatelyStrategyCallback implements CallbackStrategy { @Override public <D, F, P> void triggerDone(AbstractPromise<D, F, P> abstractPromise, DoneCallback<D> callback, D resolved) { abstractPromise.triggerDoneImmediately(callback, resolved); } @Override public <D, F, P> void triggerFail(AbstractPromise<D, F, P> abstractPromise, FailCallback<F> callback, F rejected) { abstractPromise.triggerFailImmediately(callback, rejected); } @Override public <D, F, P> void triggerProgress(AbstractPromise<D, F, P> abstractPromise, ProgressCallback<P> callback, P progress) { abstractPromise.triggerProgressImmediately(callback, progress); } @Override
public <D, F, P> void triggerAlways(AbstractPromise<D, F, P> abstractPromise, AlwaysCallback<D, F> callback, State state, D resolve, F reject) {
tuenti/android-deferred
deferred/src/main/java/com/tuenti/deferred/Done.java
// Path: deferred/src/main/java/com/tuenti/deferred/context/ViewContextHolder.java // public class ViewContextHolder<V> { // // public static final ViewContextHolder NOP = new ViewContextHolder<>(new Object()); // // private final WeakReference<V> reference; // // @SuppressWarnings("unchecked") // public static <V> ViewContextHolder<V> of(V viewContext) { // ViewContextHolder viewContextHolder; // if (viewContext instanceof Activity) { // viewContextHolder = new ActivityContextHolder<>((AppCompatActivity) viewContext); // } else if (viewContext instanceof Fragment) { // viewContextHolder = new FragmentContextHolder<>((Fragment) viewContext); // } else { // viewContextHolder = new ViewContextHolder(viewContext); // } // return viewContextHolder; // } // // protected ViewContextHolder(V viewContext) { // reference = new WeakReference<>(viewContext); // } // // public boolean isValid() { // return reference.get() != null; // } // // public V get() { // return reference.get(); // } // // }
import com.tuenti.deferred.context.ViewContextHolder;
/* * Copyright (c) Tuenti Technologies S.L. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; public interface Done { interface Immediately<D> extends DoneCallback<D> { } /** * Please use UIDoneContextualCallback if your callback depends on a view */ interface UI<D> extends DoneCallback<D>, UICallback { } /** * Done callback that gets executed always on a UI thread */ abstract class UIContextual<D, V> implements Done.UI<D> {
// Path: deferred/src/main/java/com/tuenti/deferred/context/ViewContextHolder.java // public class ViewContextHolder<V> { // // public static final ViewContextHolder NOP = new ViewContextHolder<>(new Object()); // // private final WeakReference<V> reference; // // @SuppressWarnings("unchecked") // public static <V> ViewContextHolder<V> of(V viewContext) { // ViewContextHolder viewContextHolder; // if (viewContext instanceof Activity) { // viewContextHolder = new ActivityContextHolder<>((AppCompatActivity) viewContext); // } else if (viewContext instanceof Fragment) { // viewContextHolder = new FragmentContextHolder<>((Fragment) viewContext); // } else { // viewContextHolder = new ViewContextHolder(viewContext); // } // return viewContextHolder; // } // // protected ViewContextHolder(V viewContext) { // reference = new WeakReference<>(viewContext); // } // // public boolean isValid() { // return reference.get() != null; // } // // public V get() { // return reference.get(); // } // // } // Path: deferred/src/main/java/com/tuenti/deferred/Done.java import com.tuenti.deferred.context.ViewContextHolder; /* * Copyright (c) Tuenti Technologies S.L. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuenti.deferred; public interface Done { interface Immediately<D> extends DoneCallback<D> { } /** * Please use UIDoneContextualCallback if your callback depends on a view */ interface UI<D> extends DoneCallback<D>, UICallback { } /** * Done callback that gets executed always on a UI thread */ abstract class UIContextual<D, V> implements Done.UI<D> {
private final ViewContextHolder<V> viewContextHolder;
nlfiedler/burstsort4j
test/org/burstsort4j/benchmark/DataGeneratorTest.java
// Path: src/org/burstsort4j/Quicksort.java // public class Quicksort { // // /** As with GCC std::sort delegate to insertion sort for ranges of // * size below 16. */ // private static final int THRESHOLD = 16; // // /** // * Creates a new instance of Quicksort. // */ // private Quicksort() { // } // // /** // * Sorts the given array of comparable objects using the standard // * quicksort algorithm. This sort is <em>not</em> stable. The objects // * are sorted in place with constant additional memory (not counting // * the stack due to recursion). // * // * @param <T> type of comparable to be sorted. // * @param arr an array of Comparable items to sort. // */ // public static <T extends Comparable<? super T>> void sort(T[] arr) { // if (arr != null && arr.length > 1) { // sort(arr, 0, arr.length - 1); // } // } // // /** // * Basic implementation of quicksort. Uses median-of-three partitioning // * and a cutoff at which point insertion sort is used. // * // * @param <T> type of comparable to be sorted. // * @param arr an array of Comparable items. // * @param low the left-most index of the subarray. // * @param high the right-most index of the subarray. // */ // public static <T extends Comparable<? super T>> void sort(T[] arr, int low, int high) { // if (low + THRESHOLD > high) { // // Insertion sort for small partitions. // Insertionsort.sort(arr, low, high); // } else { // // Choose a partition element // int middle = (low + high) / 2; // // Order the low, middle, and high elements // if (arr[middle].compareTo(arr[low]) < 0) { // swap(arr, low, middle); // } // if (arr[high].compareTo(arr[low]) < 0) { // swap(arr, low, high); // } // if (arr[high].compareTo(arr[middle]) < 0) { // swap(arr, middle, high); // } // // Place pivot element at the high end in preparation // // for the ensuing swapping of elements. // swap(arr, middle, high - 1); // T pivot = arr[high - 1]; // // // Order the elements such that those below the pivot // // point appear earlier, and those higher than the pivot // // appear later. // int i = low; // int j = high - 1; // while (true) { // while (arr[++i].compareTo(pivot) < 0) { // } // while (pivot.compareTo(arr[--j]) < 0) { // } // if (i >= j) { // break; // } // swap(arr, i, j); // } // // // Restore pivot element to its rightful position. // swap(arr, i, high - 1); // // Sort low partition recursively. // sort(arr, low, i - 1); // // Sort high partition recursively. // sort(arr, i + 1, high); // } // } // // /** // * Method to swap to elements in an array. // * // * @param a an array of objects. // * @param x the index of the first object. // * @param y the index of the second object. // */ // private static void swap(Object[] a, int x, int y) { // Object tmp = a[x]; // a[x] = a[y]; // a[y] = tmp; // } // }
import org.junit.Test; import static org.junit.Assert.*; import org.burstsort4j.Quicksort;
/* * Copyright 2011 Nathan Fiedler. All rights reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file. */ package org.burstsort4j.benchmark; /** * Unit tests for the DataGenerator class. * * @author Nathan Fiedler */ public class DataGeneratorTest { @Test public void testMedianOf3Killer() { DataGenerator generator = DataGenerator.MEDIAN_OF_3_KILLER; String[] results = generator.generate(DataSize.N_20); String[] sorted = new String[results.length]; System.arraycopy(results, 0, sorted, 0, results.length);
// Path: src/org/burstsort4j/Quicksort.java // public class Quicksort { // // /** As with GCC std::sort delegate to insertion sort for ranges of // * size below 16. */ // private static final int THRESHOLD = 16; // // /** // * Creates a new instance of Quicksort. // */ // private Quicksort() { // } // // /** // * Sorts the given array of comparable objects using the standard // * quicksort algorithm. This sort is <em>not</em> stable. The objects // * are sorted in place with constant additional memory (not counting // * the stack due to recursion). // * // * @param <T> type of comparable to be sorted. // * @param arr an array of Comparable items to sort. // */ // public static <T extends Comparable<? super T>> void sort(T[] arr) { // if (arr != null && arr.length > 1) { // sort(arr, 0, arr.length - 1); // } // } // // /** // * Basic implementation of quicksort. Uses median-of-three partitioning // * and a cutoff at which point insertion sort is used. // * // * @param <T> type of comparable to be sorted. // * @param arr an array of Comparable items. // * @param low the left-most index of the subarray. // * @param high the right-most index of the subarray. // */ // public static <T extends Comparable<? super T>> void sort(T[] arr, int low, int high) { // if (low + THRESHOLD > high) { // // Insertion sort for small partitions. // Insertionsort.sort(arr, low, high); // } else { // // Choose a partition element // int middle = (low + high) / 2; // // Order the low, middle, and high elements // if (arr[middle].compareTo(arr[low]) < 0) { // swap(arr, low, middle); // } // if (arr[high].compareTo(arr[low]) < 0) { // swap(arr, low, high); // } // if (arr[high].compareTo(arr[middle]) < 0) { // swap(arr, middle, high); // } // // Place pivot element at the high end in preparation // // for the ensuing swapping of elements. // swap(arr, middle, high - 1); // T pivot = arr[high - 1]; // // // Order the elements such that those below the pivot // // point appear earlier, and those higher than the pivot // // appear later. // int i = low; // int j = high - 1; // while (true) { // while (arr[++i].compareTo(pivot) < 0) { // } // while (pivot.compareTo(arr[--j]) < 0) { // } // if (i >= j) { // break; // } // swap(arr, i, j); // } // // // Restore pivot element to its rightful position. // swap(arr, i, high - 1); // // Sort low partition recursively. // sort(arr, low, i - 1); // // Sort high partition recursively. // sort(arr, i + 1, high); // } // } // // /** // * Method to swap to elements in an array. // * // * @param a an array of objects. // * @param x the index of the first object. // * @param y the index of the second object. // */ // private static void swap(Object[] a, int x, int y) { // Object tmp = a[x]; // a[x] = a[y]; // a[y] = tmp; // } // } // Path: test/org/burstsort4j/benchmark/DataGeneratorTest.java import org.junit.Test; import static org.junit.Assert.*; import org.burstsort4j.Quicksort; /* * Copyright 2011 Nathan Fiedler. All rights reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file. */ package org.burstsort4j.benchmark; /** * Unit tests for the DataGenerator class. * * @author Nathan Fiedler */ public class DataGeneratorTest { @Test public void testMedianOf3Killer() { DataGenerator generator = DataGenerator.MEDIAN_OF_3_KILLER; String[] results = generator.generate(DataSize.N_20); String[] sorted = new String[results.length]; System.arraycopy(results, 0, sorted, 0, results.length);
Quicksort.sort(sorted);
nlfiedler/burstsort4j
test/org/burstsort4j/LazyFunnelsortTest.java
// Path: src/org/burstsort4j/LazyFunnelsort.java // static interface Kmerger { // // /** // * Merges k^3 elements from the inputs and writes them to the output. // */ // void merge(); // } // // Path: src/org/burstsort4j/LazyFunnelsort.java // static class MergerFactory { // // private MergerFactory() { // } // // /** // * Creates a new instance of Kmerger to merge the input buffers. // * // * @param inputs streams of sorted input to be merged. // * @param offset first element in list to be merged. // * @param count number of elements in list to be merged, starting // * from the {@code offset} position. // * @param output buffer to which merged results are written. // * @return a Kmerger instance. // */ // @SuppressWarnings("unchecked") // public static Kmerger createMerger( // List<CircularBuffer<Comparable>> inputs, int offset, // int count, CircularBuffer<Comparable> output) { // // Tests indicate the values of 8 and 16 do not help performance. // if (count > 4) { // return new BufferMerger(inputs, offset, count, output); // } else { // // Convert the sublist to an array for insertion merger. // CircularBuffer[] buffers = new CircularBuffer[count]; // ListIterator<CircularBuffer<Comparable>> li = // inputs.listIterator(offset); // for (int ii = 0; ii < count; ii++) { // buffers[ii] = li.next(); // } // return new InsertionMerger(buffers, output); // } // } // }
import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.burstsort4j.LazyFunnelsort.Kmerger; import org.burstsort4j.LazyFunnelsort.MergerFactory; import org.junit.Test; import static org.junit.Assert.*;
test_Mergers(data, 4); test_Mergers(data, 8); test_Mergers(data, 16); test_Mergers(data, 32); test_Mergers(data, 64); } /** * Tests the merger implementations for correctness using the given * data. This only tests the case where the inputs are circular buffers. * * @param data data to use for testing (will not be modified). * @param partitions number of partitions to create, sort and merge */ private void test_Mergers(List<String> data, int partitions) { String[] arr = data.toArray(new String[data.size()]); // Split up the inputs for the insertion d-way merger. List<CircularBuffer<Comparable>> inputs = new ArrayList<CircularBuffer<Comparable>>(); int size = arr.length / partitions; int offset = 0; while (offset < arr.length) { if (offset + size > arr.length) { size = arr.length - offset; } Arrays.sort(arr, offset, offset + size); inputs.add(new CircularBuffer<Comparable>(arr, offset, size, false)); offset += size; } CircularBuffer<Comparable> output = new CircularBuffer<Comparable>(arr.length); // Test the merger.
// Path: src/org/burstsort4j/LazyFunnelsort.java // static interface Kmerger { // // /** // * Merges k^3 elements from the inputs and writes them to the output. // */ // void merge(); // } // // Path: src/org/burstsort4j/LazyFunnelsort.java // static class MergerFactory { // // private MergerFactory() { // } // // /** // * Creates a new instance of Kmerger to merge the input buffers. // * // * @param inputs streams of sorted input to be merged. // * @param offset first element in list to be merged. // * @param count number of elements in list to be merged, starting // * from the {@code offset} position. // * @param output buffer to which merged results are written. // * @return a Kmerger instance. // */ // @SuppressWarnings("unchecked") // public static Kmerger createMerger( // List<CircularBuffer<Comparable>> inputs, int offset, // int count, CircularBuffer<Comparable> output) { // // Tests indicate the values of 8 and 16 do not help performance. // if (count > 4) { // return new BufferMerger(inputs, offset, count, output); // } else { // // Convert the sublist to an array for insertion merger. // CircularBuffer[] buffers = new CircularBuffer[count]; // ListIterator<CircularBuffer<Comparable>> li = // inputs.listIterator(offset); // for (int ii = 0; ii < count; ii++) { // buffers[ii] = li.next(); // } // return new InsertionMerger(buffers, output); // } // } // } // Path: test/org/burstsort4j/LazyFunnelsortTest.java import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.burstsort4j.LazyFunnelsort.Kmerger; import org.burstsort4j.LazyFunnelsort.MergerFactory; import org.junit.Test; import static org.junit.Assert.*; test_Mergers(data, 4); test_Mergers(data, 8); test_Mergers(data, 16); test_Mergers(data, 32); test_Mergers(data, 64); } /** * Tests the merger implementations for correctness using the given * data. This only tests the case where the inputs are circular buffers. * * @param data data to use for testing (will not be modified). * @param partitions number of partitions to create, sort and merge */ private void test_Mergers(List<String> data, int partitions) { String[] arr = data.toArray(new String[data.size()]); // Split up the inputs for the insertion d-way merger. List<CircularBuffer<Comparable>> inputs = new ArrayList<CircularBuffer<Comparable>>(); int size = arr.length / partitions; int offset = 0; while (offset < arr.length) { if (offset + size > arr.length) { size = arr.length - offset; } Arrays.sort(arr, offset, offset + size); inputs.add(new CircularBuffer<Comparable>(arr, offset, size, false)); offset += size; } CircularBuffer<Comparable> output = new CircularBuffer<Comparable>(arr.length); // Test the merger.
Kmerger merger = MergerFactory.createMerger(inputs, 0, inputs.size(), output);
nlfiedler/burstsort4j
test/org/burstsort4j/LazyFunnelsortTest.java
// Path: src/org/burstsort4j/LazyFunnelsort.java // static interface Kmerger { // // /** // * Merges k^3 elements from the inputs and writes them to the output. // */ // void merge(); // } // // Path: src/org/burstsort4j/LazyFunnelsort.java // static class MergerFactory { // // private MergerFactory() { // } // // /** // * Creates a new instance of Kmerger to merge the input buffers. // * // * @param inputs streams of sorted input to be merged. // * @param offset first element in list to be merged. // * @param count number of elements in list to be merged, starting // * from the {@code offset} position. // * @param output buffer to which merged results are written. // * @return a Kmerger instance. // */ // @SuppressWarnings("unchecked") // public static Kmerger createMerger( // List<CircularBuffer<Comparable>> inputs, int offset, // int count, CircularBuffer<Comparable> output) { // // Tests indicate the values of 8 and 16 do not help performance. // if (count > 4) { // return new BufferMerger(inputs, offset, count, output); // } else { // // Convert the sublist to an array for insertion merger. // CircularBuffer[] buffers = new CircularBuffer[count]; // ListIterator<CircularBuffer<Comparable>> li = // inputs.listIterator(offset); // for (int ii = 0; ii < count; ii++) { // buffers[ii] = li.next(); // } // return new InsertionMerger(buffers, output); // } // } // }
import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.burstsort4j.LazyFunnelsort.Kmerger; import org.burstsort4j.LazyFunnelsort.MergerFactory; import org.junit.Test; import static org.junit.Assert.*;
test_Mergers(data, 4); test_Mergers(data, 8); test_Mergers(data, 16); test_Mergers(data, 32); test_Mergers(data, 64); } /** * Tests the merger implementations for correctness using the given * data. This only tests the case where the inputs are circular buffers. * * @param data data to use for testing (will not be modified). * @param partitions number of partitions to create, sort and merge */ private void test_Mergers(List<String> data, int partitions) { String[] arr = data.toArray(new String[data.size()]); // Split up the inputs for the insertion d-way merger. List<CircularBuffer<Comparable>> inputs = new ArrayList<CircularBuffer<Comparable>>(); int size = arr.length / partitions; int offset = 0; while (offset < arr.length) { if (offset + size > arr.length) { size = arr.length - offset; } Arrays.sort(arr, offset, offset + size); inputs.add(new CircularBuffer<Comparable>(arr, offset, size, false)); offset += size; } CircularBuffer<Comparable> output = new CircularBuffer<Comparable>(arr.length); // Test the merger.
// Path: src/org/burstsort4j/LazyFunnelsort.java // static interface Kmerger { // // /** // * Merges k^3 elements from the inputs and writes them to the output. // */ // void merge(); // } // // Path: src/org/burstsort4j/LazyFunnelsort.java // static class MergerFactory { // // private MergerFactory() { // } // // /** // * Creates a new instance of Kmerger to merge the input buffers. // * // * @param inputs streams of sorted input to be merged. // * @param offset first element in list to be merged. // * @param count number of elements in list to be merged, starting // * from the {@code offset} position. // * @param output buffer to which merged results are written. // * @return a Kmerger instance. // */ // @SuppressWarnings("unchecked") // public static Kmerger createMerger( // List<CircularBuffer<Comparable>> inputs, int offset, // int count, CircularBuffer<Comparable> output) { // // Tests indicate the values of 8 and 16 do not help performance. // if (count > 4) { // return new BufferMerger(inputs, offset, count, output); // } else { // // Convert the sublist to an array for insertion merger. // CircularBuffer[] buffers = new CircularBuffer[count]; // ListIterator<CircularBuffer<Comparable>> li = // inputs.listIterator(offset); // for (int ii = 0; ii < count; ii++) { // buffers[ii] = li.next(); // } // return new InsertionMerger(buffers, output); // } // } // } // Path: test/org/burstsort4j/LazyFunnelsortTest.java import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.burstsort4j.LazyFunnelsort.Kmerger; import org.burstsort4j.LazyFunnelsort.MergerFactory; import org.junit.Test; import static org.junit.Assert.*; test_Mergers(data, 4); test_Mergers(data, 8); test_Mergers(data, 16); test_Mergers(data, 32); test_Mergers(data, 64); } /** * Tests the merger implementations for correctness using the given * data. This only tests the case where the inputs are circular buffers. * * @param data data to use for testing (will not be modified). * @param partitions number of partitions to create, sort and merge */ private void test_Mergers(List<String> data, int partitions) { String[] arr = data.toArray(new String[data.size()]); // Split up the inputs for the insertion d-way merger. List<CircularBuffer<Comparable>> inputs = new ArrayList<CircularBuffer<Comparable>>(); int size = arr.length / partitions; int offset = 0; while (offset < arr.length) { if (offset + size > arr.length) { size = arr.length - offset; } Arrays.sort(arr, offset, offset + size); inputs.add(new CircularBuffer<Comparable>(arr, offset, size, false)); offset += size; } CircularBuffer<Comparable> output = new CircularBuffer<Comparable>(arr.length); // Test the merger.
Kmerger merger = MergerFactory.createMerger(inputs, 0, inputs.size(), output);
martinheidegger/java-image-scaling
src/test/java/com/mortennobel/imagescaling/MultistepRescaleOpTest.java
// Path: src/main/java/com/mortennobel/imagescaling/experimental/ImprovedMultistepRescaleOp.java // public class ImprovedMultistepRescaleOp extends AdvancedResizeOp { // private final Object renderingHintInterpolation; // // public ImprovedMultistepRescaleOp(int dstWidth, int dstHeight) { // this (dstWidth, dstHeight, RenderingHints.VALUE_INTERPOLATION_BILINEAR); // } // // public ImprovedMultistepRescaleOp(int dstWidth, int dstHeight, Object renderingHintInterpolation) { // this(DimensionConstrain.createAbsolutionDimension(dstWidth, dstHeight), renderingHintInterpolation); // } // // public ImprovedMultistepRescaleOp(DimensionConstrain dimensionConstain) { // this (dimensionConstain, RenderingHints.VALUE_INTERPOLATION_BILINEAR); // } // // public ImprovedMultistepRescaleOp(DimensionConstrain dimensionConstain, Object renderingHintInterpolation) { // super(dimensionConstain); // this.renderingHintInterpolation = renderingHintInterpolation; // assert RenderingHints.KEY_INTERPOLATION.isCompatibleValue(renderingHintInterpolation) : // "Rendering hint "+renderingHintInterpolation+" is not compatible with interpolation"; // } // // // public BufferedImage doFilter(BufferedImage img, BufferedImage dest, int dstWidth, int dstHeight) { // int type = (img.getTransparency() == Transparency.OPAQUE) ? // BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB; // BufferedImage ret = img; // int w, h; // // // Use multi-step technique: start with original size, then // // scale down in multiple passes with drawImage() // // until the target size is reached // w = img.getWidth(); // h = img.getHeight(); // // do { // if (w > dstWidth) { // w /= 2; // if (w < dstWidth) { // w = dstWidth; // } // } else { // w = dstWidth; // } // // if (h > dstHeight) { // h /= 2; // if (h < dstHeight) { // h = dstHeight; // } // } else { // h = dstHeight; // } // // BufferedImage tmp; // if (dest!=null && dest.getWidth()== w && dest.getHeight()== h && w==dstWidth && h==dstHeight){ // tmp = dest; // } else { // tmp = new BufferedImage(w,h,type); // } // Graphics2D g2 = tmp.createGraphics(); // g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, renderingHintInterpolation); // g2.drawImage(ret, 0, 0, w, h, null); // g2.dispose(); // // ret = tmp; // } while (w != dstWidth || h != dstHeight); // // return ret; // } // }
import java.awt.RenderingHints; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import junit.framework.TestCase; import com.mortennobel.imagescaling.experimental.ImprovedMultistepRescaleOp;
/* * Copyright 2009, Morten Nobel-Joergensen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.mortennobel.imagescaling; public class MultistepRescaleOpTest extends TestCase { protected BufferedImage image; /** * Sets up the fixture, for example, open a network connection. * This method is called before a test is executed. */ @Override protected void setUp() throws Exception { this.image = ImageIO.read(getClass().getResource("largeimage-thump.jpg")); } public void testCorrect(){ final BufferedImage reference = new MultiStepRescaleOp(this.image.getWidth()/4, this.image.getHeight()/4,RenderingHints.VALUE_INTERPOLATION_BILINEAR).filter(this.image, null);
// Path: src/main/java/com/mortennobel/imagescaling/experimental/ImprovedMultistepRescaleOp.java // public class ImprovedMultistepRescaleOp extends AdvancedResizeOp { // private final Object renderingHintInterpolation; // // public ImprovedMultistepRescaleOp(int dstWidth, int dstHeight) { // this (dstWidth, dstHeight, RenderingHints.VALUE_INTERPOLATION_BILINEAR); // } // // public ImprovedMultistepRescaleOp(int dstWidth, int dstHeight, Object renderingHintInterpolation) { // this(DimensionConstrain.createAbsolutionDimension(dstWidth, dstHeight), renderingHintInterpolation); // } // // public ImprovedMultistepRescaleOp(DimensionConstrain dimensionConstain) { // this (dimensionConstain, RenderingHints.VALUE_INTERPOLATION_BILINEAR); // } // // public ImprovedMultistepRescaleOp(DimensionConstrain dimensionConstain, Object renderingHintInterpolation) { // super(dimensionConstain); // this.renderingHintInterpolation = renderingHintInterpolation; // assert RenderingHints.KEY_INTERPOLATION.isCompatibleValue(renderingHintInterpolation) : // "Rendering hint "+renderingHintInterpolation+" is not compatible with interpolation"; // } // // // public BufferedImage doFilter(BufferedImage img, BufferedImage dest, int dstWidth, int dstHeight) { // int type = (img.getTransparency() == Transparency.OPAQUE) ? // BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB; // BufferedImage ret = img; // int w, h; // // // Use multi-step technique: start with original size, then // // scale down in multiple passes with drawImage() // // until the target size is reached // w = img.getWidth(); // h = img.getHeight(); // // do { // if (w > dstWidth) { // w /= 2; // if (w < dstWidth) { // w = dstWidth; // } // } else { // w = dstWidth; // } // // if (h > dstHeight) { // h /= 2; // if (h < dstHeight) { // h = dstHeight; // } // } else { // h = dstHeight; // } // // BufferedImage tmp; // if (dest!=null && dest.getWidth()== w && dest.getHeight()== h && w==dstWidth && h==dstHeight){ // tmp = dest; // } else { // tmp = new BufferedImage(w,h,type); // } // Graphics2D g2 = tmp.createGraphics(); // g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, renderingHintInterpolation); // g2.drawImage(ret, 0, 0, w, h, null); // g2.dispose(); // // ret = tmp; // } while (w != dstWidth || h != dstHeight); // // return ret; // } // } // Path: src/test/java/com/mortennobel/imagescaling/MultistepRescaleOpTest.java import java.awt.RenderingHints; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import junit.framework.TestCase; import com.mortennobel.imagescaling.experimental.ImprovedMultistepRescaleOp; /* * Copyright 2009, Morten Nobel-Joergensen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.mortennobel.imagescaling; public class MultistepRescaleOpTest extends TestCase { protected BufferedImage image; /** * Sets up the fixture, for example, open a network connection. * This method is called before a test is executed. */ @Override protected void setUp() throws Exception { this.image = ImageIO.read(getClass().getResource("largeimage-thump.jpg")); } public void testCorrect(){ final BufferedImage reference = new MultiStepRescaleOp(this.image.getWidth()/4, this.image.getHeight()/4,RenderingHints.VALUE_INTERPOLATION_BILINEAR).filter(this.image, null);
final BufferedImage result = new ImprovedMultistepRescaleOp(this.image.getWidth()/4, this.image.getHeight()/4,RenderingHints.VALUE_INTERPOLATION_BILINEAR).filter(this.image, null);
Fireply/Enter
src/main/java/org/fireply/enter/action/NewsAction.java
// Path: src/main/java/org/fireply/enter/model/News.java // public class News implements java.io.Serializable { // // private String id; // private User user; // private String title; // private String content; // private Date createTime; // private Set<Commit> commits = new HashSet<Commit>(0); // // public News() { // } // // public News(String id, String title, String content, Date createTime) { // this.id = id; // this.title = title; // this.content = content; // this.createTime = createTime; // } // // public News(String id, User user, String title, String content, Date createTime, Set<Commit> commits) { // this.id = id; // this.user = user; // this.title = title; // this.content = content; // this.createTime = createTime; // this.commits = commits; // } // // @Override // public String toString() { // return "News [id=" + id + ", user=" + user + ", title=" + title + ", content=" + content + ", createTime=" // + createTime + "]"; // } // // public String getId() { // return this.id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return this.user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getTitle() { // return this.title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getContent() { // return this.content; // } // // public void setContent(String content) { // this.content = content; // } // // public Date getCreateTime() { // return this.createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Set<Commit> getCommits() { // return this.commits; // } // // public void setCommits(Set<Commit> commits) { // this.commits = commits; // } // // } // // Path: src/main/java/org/fireply/enter/service/NewsService.java // public interface NewsService extends BaseService { // // List<News> getAllNews(); // // News getNews(Serializable id); // // }
import java.util.List; import java.util.Map; import org.apache.struts2.interceptor.RequestAware; import org.apache.struts2.interceptor.SessionAware; import org.fireply.enter.model.News; import org.fireply.enter.service.NewsService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import com.opensymphony.xwork2.ActionSupport;
package org.fireply.enter.action; @Controller public class NewsAction extends ActionSupport implements RequestAware, SessionAware { @Autowired @Qualifier("newsServiceImpl")
// Path: src/main/java/org/fireply/enter/model/News.java // public class News implements java.io.Serializable { // // private String id; // private User user; // private String title; // private String content; // private Date createTime; // private Set<Commit> commits = new HashSet<Commit>(0); // // public News() { // } // // public News(String id, String title, String content, Date createTime) { // this.id = id; // this.title = title; // this.content = content; // this.createTime = createTime; // } // // public News(String id, User user, String title, String content, Date createTime, Set<Commit> commits) { // this.id = id; // this.user = user; // this.title = title; // this.content = content; // this.createTime = createTime; // this.commits = commits; // } // // @Override // public String toString() { // return "News [id=" + id + ", user=" + user + ", title=" + title + ", content=" + content + ", createTime=" // + createTime + "]"; // } // // public String getId() { // return this.id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return this.user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getTitle() { // return this.title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getContent() { // return this.content; // } // // public void setContent(String content) { // this.content = content; // } // // public Date getCreateTime() { // return this.createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Set<Commit> getCommits() { // return this.commits; // } // // public void setCommits(Set<Commit> commits) { // this.commits = commits; // } // // } // // Path: src/main/java/org/fireply/enter/service/NewsService.java // public interface NewsService extends BaseService { // // List<News> getAllNews(); // // News getNews(Serializable id); // // } // Path: src/main/java/org/fireply/enter/action/NewsAction.java import java.util.List; import java.util.Map; import org.apache.struts2.interceptor.RequestAware; import org.apache.struts2.interceptor.SessionAware; import org.fireply.enter.model.News; import org.fireply.enter.service.NewsService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import com.opensymphony.xwork2.ActionSupport; package org.fireply.enter.action; @Controller public class NewsAction extends ActionSupport implements RequestAware, SessionAware { @Autowired @Qualifier("newsServiceImpl")
private NewsService newsService;
Fireply/Enter
src/main/java/org/fireply/enter/action/NewsAction.java
// Path: src/main/java/org/fireply/enter/model/News.java // public class News implements java.io.Serializable { // // private String id; // private User user; // private String title; // private String content; // private Date createTime; // private Set<Commit> commits = new HashSet<Commit>(0); // // public News() { // } // // public News(String id, String title, String content, Date createTime) { // this.id = id; // this.title = title; // this.content = content; // this.createTime = createTime; // } // // public News(String id, User user, String title, String content, Date createTime, Set<Commit> commits) { // this.id = id; // this.user = user; // this.title = title; // this.content = content; // this.createTime = createTime; // this.commits = commits; // } // // @Override // public String toString() { // return "News [id=" + id + ", user=" + user + ", title=" + title + ", content=" + content + ", createTime=" // + createTime + "]"; // } // // public String getId() { // return this.id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return this.user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getTitle() { // return this.title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getContent() { // return this.content; // } // // public void setContent(String content) { // this.content = content; // } // // public Date getCreateTime() { // return this.createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Set<Commit> getCommits() { // return this.commits; // } // // public void setCommits(Set<Commit> commits) { // this.commits = commits; // } // // } // // Path: src/main/java/org/fireply/enter/service/NewsService.java // public interface NewsService extends BaseService { // // List<News> getAllNews(); // // News getNews(Serializable id); // // }
import java.util.List; import java.util.Map; import org.apache.struts2.interceptor.RequestAware; import org.apache.struts2.interceptor.SessionAware; import org.fireply.enter.model.News; import org.fireply.enter.service.NewsService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import com.opensymphony.xwork2.ActionSupport;
package org.fireply.enter.action; @Controller public class NewsAction extends ActionSupport implements RequestAware, SessionAware { @Autowired @Qualifier("newsServiceImpl") private NewsService newsService; private Map<String, Object> request; private Map<String, Object> session;
// Path: src/main/java/org/fireply/enter/model/News.java // public class News implements java.io.Serializable { // // private String id; // private User user; // private String title; // private String content; // private Date createTime; // private Set<Commit> commits = new HashSet<Commit>(0); // // public News() { // } // // public News(String id, String title, String content, Date createTime) { // this.id = id; // this.title = title; // this.content = content; // this.createTime = createTime; // } // // public News(String id, User user, String title, String content, Date createTime, Set<Commit> commits) { // this.id = id; // this.user = user; // this.title = title; // this.content = content; // this.createTime = createTime; // this.commits = commits; // } // // @Override // public String toString() { // return "News [id=" + id + ", user=" + user + ", title=" + title + ", content=" + content + ", createTime=" // + createTime + "]"; // } // // public String getId() { // return this.id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return this.user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getTitle() { // return this.title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getContent() { // return this.content; // } // // public void setContent(String content) { // this.content = content; // } // // public Date getCreateTime() { // return this.createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Set<Commit> getCommits() { // return this.commits; // } // // public void setCommits(Set<Commit> commits) { // this.commits = commits; // } // // } // // Path: src/main/java/org/fireply/enter/service/NewsService.java // public interface NewsService extends BaseService { // // List<News> getAllNews(); // // News getNews(Serializable id); // // } // Path: src/main/java/org/fireply/enter/action/NewsAction.java import java.util.List; import java.util.Map; import org.apache.struts2.interceptor.RequestAware; import org.apache.struts2.interceptor.SessionAware; import org.fireply.enter.model.News; import org.fireply.enter.service.NewsService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import com.opensymphony.xwork2.ActionSupport; package org.fireply.enter.action; @Controller public class NewsAction extends ActionSupport implements RequestAware, SessionAware { @Autowired @Qualifier("newsServiceImpl") private NewsService newsService; private Map<String, Object> request; private Map<String, Object> session;
private List<News> newsList; // 请求新闻列表时将数据库查询结果存放在 newsList
Fireply/Enter
src/test/java/org/fireply/enter/test/service/ServiceAutowiredTest.java
// Path: src/main/java/org/fireply/enter/service/BaseService.java // public interface BaseService { // // void persist(Object object); // // Serializable save(Object object); // // void delete(Object object); // // Object merge(Object object); // // Object get(Class<?> clazz, Serializable id); // // Object get(String entityName, Serializable id); // // List<?> getAll(Class<?> clazz); // // List<?> getAll(String modeName); // // List<?> get(Class<?> clazz, String fieldName, Object fieldValue); // // List<?> get(String modelName, String fieldName, Object fieldValue); // // List<?> get(Class<?> clazz, Map<String, Object> fieldsMap); // // } // // Path: src/main/java/org/fireply/enter/service/LoginService.java // public interface LoginService extends BaseService { // // String loginByPassword(String userId, String signedPassword, String remoteAddr); // // String loginByCookie(String userId, String sequence, String token, String remoteAddr); // // boolean allowsLogin(String userId, String remoteAddr); // // /** // * 是否曾经登陆过 // * @param userId 用户 ID // * @return boolean 如果用户曾经登陆过返回 {@code true}, 否则返回 {@code false} // */ // <T> List<T> userLoginHistory(String userId); // // /** // * 是否曾经登陆过 // * @param userId 用户 ID // * @return boolean 如果曾经管理员登陆过返回 {@code true}, 否则返回 {@code false} // */ // <T> List<T> adminLoginHistory(String userId); // } // // Path: src/test/java/org/fireply/enter/test/BaseSpringJunit4Test.java // @RunWith(SpringJUnit4ClassRunner.class) // @ContextConfiguration(locations = "classpath*:applicationContext.xml") // public abstract class BaseSpringJunit4Test { // // }
import static org.junit.Assert.*; import org.fireply.enter.service.BaseService; import org.fireply.enter.service.LoginService; import org.fireply.enter.test.BaseSpringJunit4Test; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier;
package org.fireply.enter.test.service; public class ServiceAutowiredTest extends BaseSpringJunit4Test { @Autowired @Qualifier("baseServiceImpl")
// Path: src/main/java/org/fireply/enter/service/BaseService.java // public interface BaseService { // // void persist(Object object); // // Serializable save(Object object); // // void delete(Object object); // // Object merge(Object object); // // Object get(Class<?> clazz, Serializable id); // // Object get(String entityName, Serializable id); // // List<?> getAll(Class<?> clazz); // // List<?> getAll(String modeName); // // List<?> get(Class<?> clazz, String fieldName, Object fieldValue); // // List<?> get(String modelName, String fieldName, Object fieldValue); // // List<?> get(Class<?> clazz, Map<String, Object> fieldsMap); // // } // // Path: src/main/java/org/fireply/enter/service/LoginService.java // public interface LoginService extends BaseService { // // String loginByPassword(String userId, String signedPassword, String remoteAddr); // // String loginByCookie(String userId, String sequence, String token, String remoteAddr); // // boolean allowsLogin(String userId, String remoteAddr); // // /** // * 是否曾经登陆过 // * @param userId 用户 ID // * @return boolean 如果用户曾经登陆过返回 {@code true}, 否则返回 {@code false} // */ // <T> List<T> userLoginHistory(String userId); // // /** // * 是否曾经登陆过 // * @param userId 用户 ID // * @return boolean 如果曾经管理员登陆过返回 {@code true}, 否则返回 {@code false} // */ // <T> List<T> adminLoginHistory(String userId); // } // // Path: src/test/java/org/fireply/enter/test/BaseSpringJunit4Test.java // @RunWith(SpringJUnit4ClassRunner.class) // @ContextConfiguration(locations = "classpath*:applicationContext.xml") // public abstract class BaseSpringJunit4Test { // // } // Path: src/test/java/org/fireply/enter/test/service/ServiceAutowiredTest.java import static org.junit.Assert.*; import org.fireply.enter.service.BaseService; import org.fireply.enter.service.LoginService; import org.fireply.enter.test.BaseSpringJunit4Test; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; package org.fireply.enter.test.service; public class ServiceAutowiredTest extends BaseSpringJunit4Test { @Autowired @Qualifier("baseServiceImpl")
BaseService baseService;
Fireply/Enter
src/test/java/org/fireply/enter/test/service/ServiceAutowiredTest.java
// Path: src/main/java/org/fireply/enter/service/BaseService.java // public interface BaseService { // // void persist(Object object); // // Serializable save(Object object); // // void delete(Object object); // // Object merge(Object object); // // Object get(Class<?> clazz, Serializable id); // // Object get(String entityName, Serializable id); // // List<?> getAll(Class<?> clazz); // // List<?> getAll(String modeName); // // List<?> get(Class<?> clazz, String fieldName, Object fieldValue); // // List<?> get(String modelName, String fieldName, Object fieldValue); // // List<?> get(Class<?> clazz, Map<String, Object> fieldsMap); // // } // // Path: src/main/java/org/fireply/enter/service/LoginService.java // public interface LoginService extends BaseService { // // String loginByPassword(String userId, String signedPassword, String remoteAddr); // // String loginByCookie(String userId, String sequence, String token, String remoteAddr); // // boolean allowsLogin(String userId, String remoteAddr); // // /** // * 是否曾经登陆过 // * @param userId 用户 ID // * @return boolean 如果用户曾经登陆过返回 {@code true}, 否则返回 {@code false} // */ // <T> List<T> userLoginHistory(String userId); // // /** // * 是否曾经登陆过 // * @param userId 用户 ID // * @return boolean 如果曾经管理员登陆过返回 {@code true}, 否则返回 {@code false} // */ // <T> List<T> adminLoginHistory(String userId); // } // // Path: src/test/java/org/fireply/enter/test/BaseSpringJunit4Test.java // @RunWith(SpringJUnit4ClassRunner.class) // @ContextConfiguration(locations = "classpath*:applicationContext.xml") // public abstract class BaseSpringJunit4Test { // // }
import static org.junit.Assert.*; import org.fireply.enter.service.BaseService; import org.fireply.enter.service.LoginService; import org.fireply.enter.test.BaseSpringJunit4Test; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier;
package org.fireply.enter.test.service; public class ServiceAutowiredTest extends BaseSpringJunit4Test { @Autowired @Qualifier("baseServiceImpl") BaseService baseService; @Autowired @Qualifier("loginServiceImpl")
// Path: src/main/java/org/fireply/enter/service/BaseService.java // public interface BaseService { // // void persist(Object object); // // Serializable save(Object object); // // void delete(Object object); // // Object merge(Object object); // // Object get(Class<?> clazz, Serializable id); // // Object get(String entityName, Serializable id); // // List<?> getAll(Class<?> clazz); // // List<?> getAll(String modeName); // // List<?> get(Class<?> clazz, String fieldName, Object fieldValue); // // List<?> get(String modelName, String fieldName, Object fieldValue); // // List<?> get(Class<?> clazz, Map<String, Object> fieldsMap); // // } // // Path: src/main/java/org/fireply/enter/service/LoginService.java // public interface LoginService extends BaseService { // // String loginByPassword(String userId, String signedPassword, String remoteAddr); // // String loginByCookie(String userId, String sequence, String token, String remoteAddr); // // boolean allowsLogin(String userId, String remoteAddr); // // /** // * 是否曾经登陆过 // * @param userId 用户 ID // * @return boolean 如果用户曾经登陆过返回 {@code true}, 否则返回 {@code false} // */ // <T> List<T> userLoginHistory(String userId); // // /** // * 是否曾经登陆过 // * @param userId 用户 ID // * @return boolean 如果曾经管理员登陆过返回 {@code true}, 否则返回 {@code false} // */ // <T> List<T> adminLoginHistory(String userId); // } // // Path: src/test/java/org/fireply/enter/test/BaseSpringJunit4Test.java // @RunWith(SpringJUnit4ClassRunner.class) // @ContextConfiguration(locations = "classpath*:applicationContext.xml") // public abstract class BaseSpringJunit4Test { // // } // Path: src/test/java/org/fireply/enter/test/service/ServiceAutowiredTest.java import static org.junit.Assert.*; import org.fireply.enter.service.BaseService; import org.fireply.enter.service.LoginService; import org.fireply.enter.test.BaseSpringJunit4Test; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; package org.fireply.enter.test.service; public class ServiceAutowiredTest extends BaseSpringJunit4Test { @Autowired @Qualifier("baseServiceImpl") BaseService baseService; @Autowired @Qualifier("loginServiceImpl")
LoginService loginService;
Fireply/Enter
src/main/java/org/fireply/enter/service/impl/NewsServiceImpl.java
// Path: src/main/java/org/fireply/enter/model/News.java // public class News implements java.io.Serializable { // // private String id; // private User user; // private String title; // private String content; // private Date createTime; // private Set<Commit> commits = new HashSet<Commit>(0); // // public News() { // } // // public News(String id, String title, String content, Date createTime) { // this.id = id; // this.title = title; // this.content = content; // this.createTime = createTime; // } // // public News(String id, User user, String title, String content, Date createTime, Set<Commit> commits) { // this.id = id; // this.user = user; // this.title = title; // this.content = content; // this.createTime = createTime; // this.commits = commits; // } // // @Override // public String toString() { // return "News [id=" + id + ", user=" + user + ", title=" + title + ", content=" + content + ", createTime=" // + createTime + "]"; // } // // public String getId() { // return this.id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return this.user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getTitle() { // return this.title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getContent() { // return this.content; // } // // public void setContent(String content) { // this.content = content; // } // // public Date getCreateTime() { // return this.createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Set<Commit> getCommits() { // return this.commits; // } // // public void setCommits(Set<Commit> commits) { // this.commits = commits; // } // // } // // Path: src/main/java/org/fireply/enter/service/NewsService.java // public interface NewsService extends BaseService { // // List<News> getAllNews(); // // News getNews(Serializable id); // // }
import java.io.Serializable; import java.util.List; import org.fireply.enter.model.News; import org.fireply.enter.service.NewsService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;
package org.fireply.enter.service.impl; @Service @Transactional(readOnly=true)
// Path: src/main/java/org/fireply/enter/model/News.java // public class News implements java.io.Serializable { // // private String id; // private User user; // private String title; // private String content; // private Date createTime; // private Set<Commit> commits = new HashSet<Commit>(0); // // public News() { // } // // public News(String id, String title, String content, Date createTime) { // this.id = id; // this.title = title; // this.content = content; // this.createTime = createTime; // } // // public News(String id, User user, String title, String content, Date createTime, Set<Commit> commits) { // this.id = id; // this.user = user; // this.title = title; // this.content = content; // this.createTime = createTime; // this.commits = commits; // } // // @Override // public String toString() { // return "News [id=" + id + ", user=" + user + ", title=" + title + ", content=" + content + ", createTime=" // + createTime + "]"; // } // // public String getId() { // return this.id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return this.user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getTitle() { // return this.title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getContent() { // return this.content; // } // // public void setContent(String content) { // this.content = content; // } // // public Date getCreateTime() { // return this.createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Set<Commit> getCommits() { // return this.commits; // } // // public void setCommits(Set<Commit> commits) { // this.commits = commits; // } // // } // // Path: src/main/java/org/fireply/enter/service/NewsService.java // public interface NewsService extends BaseService { // // List<News> getAllNews(); // // News getNews(Serializable id); // // } // Path: src/main/java/org/fireply/enter/service/impl/NewsServiceImpl.java import java.io.Serializable; import java.util.List; import org.fireply.enter.model.News; import org.fireply.enter.service.NewsService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; package org.fireply.enter.service.impl; @Service @Transactional(readOnly=true)
public class NewsServiceImpl extends BaseServiceImpl implements NewsService{
Fireply/Enter
src/main/java/org/fireply/enter/service/impl/NewsServiceImpl.java
// Path: src/main/java/org/fireply/enter/model/News.java // public class News implements java.io.Serializable { // // private String id; // private User user; // private String title; // private String content; // private Date createTime; // private Set<Commit> commits = new HashSet<Commit>(0); // // public News() { // } // // public News(String id, String title, String content, Date createTime) { // this.id = id; // this.title = title; // this.content = content; // this.createTime = createTime; // } // // public News(String id, User user, String title, String content, Date createTime, Set<Commit> commits) { // this.id = id; // this.user = user; // this.title = title; // this.content = content; // this.createTime = createTime; // this.commits = commits; // } // // @Override // public String toString() { // return "News [id=" + id + ", user=" + user + ", title=" + title + ", content=" + content + ", createTime=" // + createTime + "]"; // } // // public String getId() { // return this.id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return this.user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getTitle() { // return this.title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getContent() { // return this.content; // } // // public void setContent(String content) { // this.content = content; // } // // public Date getCreateTime() { // return this.createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Set<Commit> getCommits() { // return this.commits; // } // // public void setCommits(Set<Commit> commits) { // this.commits = commits; // } // // } // // Path: src/main/java/org/fireply/enter/service/NewsService.java // public interface NewsService extends BaseService { // // List<News> getAllNews(); // // News getNews(Serializable id); // // }
import java.io.Serializable; import java.util.List; import org.fireply.enter.model.News; import org.fireply.enter.service.NewsService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;
package org.fireply.enter.service.impl; @Service @Transactional(readOnly=true) public class NewsServiceImpl extends BaseServiceImpl implements NewsService{ @Override
// Path: src/main/java/org/fireply/enter/model/News.java // public class News implements java.io.Serializable { // // private String id; // private User user; // private String title; // private String content; // private Date createTime; // private Set<Commit> commits = new HashSet<Commit>(0); // // public News() { // } // // public News(String id, String title, String content, Date createTime) { // this.id = id; // this.title = title; // this.content = content; // this.createTime = createTime; // } // // public News(String id, User user, String title, String content, Date createTime, Set<Commit> commits) { // this.id = id; // this.user = user; // this.title = title; // this.content = content; // this.createTime = createTime; // this.commits = commits; // } // // @Override // public String toString() { // return "News [id=" + id + ", user=" + user + ", title=" + title + ", content=" + content + ", createTime=" // + createTime + "]"; // } // // public String getId() { // return this.id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return this.user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getTitle() { // return this.title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getContent() { // return this.content; // } // // public void setContent(String content) { // this.content = content; // } // // public Date getCreateTime() { // return this.createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Set<Commit> getCommits() { // return this.commits; // } // // public void setCommits(Set<Commit> commits) { // this.commits = commits; // } // // } // // Path: src/main/java/org/fireply/enter/service/NewsService.java // public interface NewsService extends BaseService { // // List<News> getAllNews(); // // News getNews(Serializable id); // // } // Path: src/main/java/org/fireply/enter/service/impl/NewsServiceImpl.java import java.io.Serializable; import java.util.List; import org.fireply.enter.model.News; import org.fireply.enter.service.NewsService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; package org.fireply.enter.service.impl; @Service @Transactional(readOnly=true) public class NewsServiceImpl extends BaseServiceImpl implements NewsService{ @Override
public List<News> getAllNews() {
Fireply/Enter
src/test/java/org/fireply/enter/test/service/AdminServiceTest.java
// Path: src/main/java/org/fireply/enter/model/Admin.java // public class Admin implements java.io.Serializable { // // private String id; // private User user; // private String password; // private Set<AdminAuthorization> adminAuthorizations = new HashSet<AdminAuthorization>(0); // // public Admin() { // } // // public Admin(String id, User user, String password) { // this.id = id; // this.user = user; // this.password = password; // } // // public Admin(String id, User user, String password, Set<AdminAuthorization> adminAuthorizations) { // this.id = id; // this.user = user; // this.password = password; // this.adminAuthorizations = adminAuthorizations; // } // // public String getId() { // return this.id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return this.user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Set<AdminAuthorization> getAdminAuthorizations() { // return this.adminAuthorizations; // } // // public void setAdminAuthorizations(Set<AdminAuthorization> adminAuthorizations) { // this.adminAuthorizations = adminAuthorizations; // } // // } // // Path: src/main/java/org/fireply/enter/service/BaseService.java // public interface BaseService { // // void persist(Object object); // // Serializable save(Object object); // // void delete(Object object); // // Object merge(Object object); // // Object get(Class<?> clazz, Serializable id); // // Object get(String entityName, Serializable id); // // List<?> getAll(Class<?> clazz); // // List<?> getAll(String modeName); // // List<?> get(Class<?> clazz, String fieldName, Object fieldValue); // // List<?> get(String modelName, String fieldName, Object fieldValue); // // List<?> get(Class<?> clazz, Map<String, Object> fieldsMap); // // } // // Path: src/test/java/org/fireply/enter/test/BaseSpringJunit4Test.java // @RunWith(SpringJUnit4ClassRunner.class) // @ContextConfiguration(locations = "classpath*:applicationContext.xml") // public abstract class BaseSpringJunit4Test { // // }
import static org.junit.Assert.*; import org.fireply.enter.model.Admin; import org.fireply.enter.service.BaseService; import org.fireply.enter.test.BaseSpringJunit4Test; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier;
package org.fireply.enter.test.service; public class AdminServiceTest extends BaseSpringJunit4Test { @Autowired @Qualifier("baseServiceImpl")
// Path: src/main/java/org/fireply/enter/model/Admin.java // public class Admin implements java.io.Serializable { // // private String id; // private User user; // private String password; // private Set<AdminAuthorization> adminAuthorizations = new HashSet<AdminAuthorization>(0); // // public Admin() { // } // // public Admin(String id, User user, String password) { // this.id = id; // this.user = user; // this.password = password; // } // // public Admin(String id, User user, String password, Set<AdminAuthorization> adminAuthorizations) { // this.id = id; // this.user = user; // this.password = password; // this.adminAuthorizations = adminAuthorizations; // } // // public String getId() { // return this.id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return this.user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Set<AdminAuthorization> getAdminAuthorizations() { // return this.adminAuthorizations; // } // // public void setAdminAuthorizations(Set<AdminAuthorization> adminAuthorizations) { // this.adminAuthorizations = adminAuthorizations; // } // // } // // Path: src/main/java/org/fireply/enter/service/BaseService.java // public interface BaseService { // // void persist(Object object); // // Serializable save(Object object); // // void delete(Object object); // // Object merge(Object object); // // Object get(Class<?> clazz, Serializable id); // // Object get(String entityName, Serializable id); // // List<?> getAll(Class<?> clazz); // // List<?> getAll(String modeName); // // List<?> get(Class<?> clazz, String fieldName, Object fieldValue); // // List<?> get(String modelName, String fieldName, Object fieldValue); // // List<?> get(Class<?> clazz, Map<String, Object> fieldsMap); // // } // // Path: src/test/java/org/fireply/enter/test/BaseSpringJunit4Test.java // @RunWith(SpringJUnit4ClassRunner.class) // @ContextConfiguration(locations = "classpath*:applicationContext.xml") // public abstract class BaseSpringJunit4Test { // // } // Path: src/test/java/org/fireply/enter/test/service/AdminServiceTest.java import static org.junit.Assert.*; import org.fireply.enter.model.Admin; import org.fireply.enter.service.BaseService; import org.fireply.enter.test.BaseSpringJunit4Test; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; package org.fireply.enter.test.service; public class AdminServiceTest extends BaseSpringJunit4Test { @Autowired @Qualifier("baseServiceImpl")
BaseService baseService;
Fireply/Enter
src/test/java/org/fireply/enter/test/service/AdminServiceTest.java
// Path: src/main/java/org/fireply/enter/model/Admin.java // public class Admin implements java.io.Serializable { // // private String id; // private User user; // private String password; // private Set<AdminAuthorization> adminAuthorizations = new HashSet<AdminAuthorization>(0); // // public Admin() { // } // // public Admin(String id, User user, String password) { // this.id = id; // this.user = user; // this.password = password; // } // // public Admin(String id, User user, String password, Set<AdminAuthorization> adminAuthorizations) { // this.id = id; // this.user = user; // this.password = password; // this.adminAuthorizations = adminAuthorizations; // } // // public String getId() { // return this.id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return this.user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Set<AdminAuthorization> getAdminAuthorizations() { // return this.adminAuthorizations; // } // // public void setAdminAuthorizations(Set<AdminAuthorization> adminAuthorizations) { // this.adminAuthorizations = adminAuthorizations; // } // // } // // Path: src/main/java/org/fireply/enter/service/BaseService.java // public interface BaseService { // // void persist(Object object); // // Serializable save(Object object); // // void delete(Object object); // // Object merge(Object object); // // Object get(Class<?> clazz, Serializable id); // // Object get(String entityName, Serializable id); // // List<?> getAll(Class<?> clazz); // // List<?> getAll(String modeName); // // List<?> get(Class<?> clazz, String fieldName, Object fieldValue); // // List<?> get(String modelName, String fieldName, Object fieldValue); // // List<?> get(Class<?> clazz, Map<String, Object> fieldsMap); // // } // // Path: src/test/java/org/fireply/enter/test/BaseSpringJunit4Test.java // @RunWith(SpringJUnit4ClassRunner.class) // @ContextConfiguration(locations = "classpath*:applicationContext.xml") // public abstract class BaseSpringJunit4Test { // // }
import static org.junit.Assert.*; import org.fireply.enter.model.Admin; import org.fireply.enter.service.BaseService; import org.fireply.enter.test.BaseSpringJunit4Test; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier;
package org.fireply.enter.test.service; public class AdminServiceTest extends BaseSpringJunit4Test { @Autowired @Qualifier("baseServiceImpl") BaseService baseService; @Test public void getAdminTest() { String adminId = "admin";
// Path: src/main/java/org/fireply/enter/model/Admin.java // public class Admin implements java.io.Serializable { // // private String id; // private User user; // private String password; // private Set<AdminAuthorization> adminAuthorizations = new HashSet<AdminAuthorization>(0); // // public Admin() { // } // // public Admin(String id, User user, String password) { // this.id = id; // this.user = user; // this.password = password; // } // // public Admin(String id, User user, String password, Set<AdminAuthorization> adminAuthorizations) { // this.id = id; // this.user = user; // this.password = password; // this.adminAuthorizations = adminAuthorizations; // } // // public String getId() { // return this.id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return this.user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Set<AdminAuthorization> getAdminAuthorizations() { // return this.adminAuthorizations; // } // // public void setAdminAuthorizations(Set<AdminAuthorization> adminAuthorizations) { // this.adminAuthorizations = adminAuthorizations; // } // // } // // Path: src/main/java/org/fireply/enter/service/BaseService.java // public interface BaseService { // // void persist(Object object); // // Serializable save(Object object); // // void delete(Object object); // // Object merge(Object object); // // Object get(Class<?> clazz, Serializable id); // // Object get(String entityName, Serializable id); // // List<?> getAll(Class<?> clazz); // // List<?> getAll(String modeName); // // List<?> get(Class<?> clazz, String fieldName, Object fieldValue); // // List<?> get(String modelName, String fieldName, Object fieldValue); // // List<?> get(Class<?> clazz, Map<String, Object> fieldsMap); // // } // // Path: src/test/java/org/fireply/enter/test/BaseSpringJunit4Test.java // @RunWith(SpringJUnit4ClassRunner.class) // @ContextConfiguration(locations = "classpath*:applicationContext.xml") // public abstract class BaseSpringJunit4Test { // // } // Path: src/test/java/org/fireply/enter/test/service/AdminServiceTest.java import static org.junit.Assert.*; import org.fireply.enter.model.Admin; import org.fireply.enter.service.BaseService; import org.fireply.enter.test.BaseSpringJunit4Test; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; package org.fireply.enter.test.service; public class AdminServiceTest extends BaseSpringJunit4Test { @Autowired @Qualifier("baseServiceImpl") BaseService baseService; @Test public void getAdminTest() { String adminId = "admin";
Admin admin = (Admin) baseService.get(Admin.class, adminId);
Fireply/Enter
src/main/java/org/fireply/enter/service/impl/BaseServiceImpl.java
// Path: src/main/java/org/fireply/enter/dao/Dao.java // public interface Dao { // // void persist(Object object); // Serializable save(Object object); // void delete(Object object); // Object merge(Object object); // // Object get(Class<?> clazz, Serializable id); // Object get(String modelName, Serializable id); // List<?> getAll(Class<?> clazz); // List<?> getAll(String modeName); // // List<?> get(Class<?> clazz, String fieldName, Object fieldValue); // List<?> get(String modelName, String fieldName, Object fieldValue); // List<?> get(Class<?> clazz, Map<String, Object> fieldsMap); // // List<?> executeQuery(String hql); // List<?> executeQuery(String hql,int firstResult,int maxResults); // List<?> executeSqlQuery(String sql); // List<?> executeSqlQuery(String sql,int firstResult,int maxResults); // // List<?> executeUpdate(String hql); // List<?> executeUpdate(String hql,int firstResult,int maxResults); // List<?> executeSqlUpdate(String sql); // List<?> executeSqlUpdate(String sql,int firstResult,int maxResults); // // // Object findById(String id); // // List<?> findByExample(Object object); // // } // // Path: src/main/java/org/fireply/enter/service/BaseService.java // public interface BaseService { // // void persist(Object object); // // Serializable save(Object object); // // void delete(Object object); // // Object merge(Object object); // // Object get(Class<?> clazz, Serializable id); // // Object get(String entityName, Serializable id); // // List<?> getAll(Class<?> clazz); // // List<?> getAll(String modeName); // // List<?> get(Class<?> clazz, String fieldName, Object fieldValue); // // List<?> get(String modelName, String fieldName, Object fieldValue); // // List<?> get(Class<?> clazz, Map<String, Object> fieldsMap); // // }
import java.io.Serializable; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.fireply.enter.dao.Dao; import org.fireply.enter.service.BaseService; import org.hibernate.HibernateException;
package org.fireply.enter.service.impl; @Service @Transactional(readOnly=true)
// Path: src/main/java/org/fireply/enter/dao/Dao.java // public interface Dao { // // void persist(Object object); // Serializable save(Object object); // void delete(Object object); // Object merge(Object object); // // Object get(Class<?> clazz, Serializable id); // Object get(String modelName, Serializable id); // List<?> getAll(Class<?> clazz); // List<?> getAll(String modeName); // // List<?> get(Class<?> clazz, String fieldName, Object fieldValue); // List<?> get(String modelName, String fieldName, Object fieldValue); // List<?> get(Class<?> clazz, Map<String, Object> fieldsMap); // // List<?> executeQuery(String hql); // List<?> executeQuery(String hql,int firstResult,int maxResults); // List<?> executeSqlQuery(String sql); // List<?> executeSqlQuery(String sql,int firstResult,int maxResults); // // List<?> executeUpdate(String hql); // List<?> executeUpdate(String hql,int firstResult,int maxResults); // List<?> executeSqlUpdate(String sql); // List<?> executeSqlUpdate(String sql,int firstResult,int maxResults); // // // Object findById(String id); // // List<?> findByExample(Object object); // // } // // Path: src/main/java/org/fireply/enter/service/BaseService.java // public interface BaseService { // // void persist(Object object); // // Serializable save(Object object); // // void delete(Object object); // // Object merge(Object object); // // Object get(Class<?> clazz, Serializable id); // // Object get(String entityName, Serializable id); // // List<?> getAll(Class<?> clazz); // // List<?> getAll(String modeName); // // List<?> get(Class<?> clazz, String fieldName, Object fieldValue); // // List<?> get(String modelName, String fieldName, Object fieldValue); // // List<?> get(Class<?> clazz, Map<String, Object> fieldsMap); // // } // Path: src/main/java/org/fireply/enter/service/impl/BaseServiceImpl.java import java.io.Serializable; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.fireply.enter.dao.Dao; import org.fireply.enter.service.BaseService; import org.hibernate.HibernateException; package org.fireply.enter.service.impl; @Service @Transactional(readOnly=true)
public class BaseServiceImpl implements BaseService {
Fireply/Enter
src/main/java/org/fireply/enter/service/impl/BaseServiceImpl.java
// Path: src/main/java/org/fireply/enter/dao/Dao.java // public interface Dao { // // void persist(Object object); // Serializable save(Object object); // void delete(Object object); // Object merge(Object object); // // Object get(Class<?> clazz, Serializable id); // Object get(String modelName, Serializable id); // List<?> getAll(Class<?> clazz); // List<?> getAll(String modeName); // // List<?> get(Class<?> clazz, String fieldName, Object fieldValue); // List<?> get(String modelName, String fieldName, Object fieldValue); // List<?> get(Class<?> clazz, Map<String, Object> fieldsMap); // // List<?> executeQuery(String hql); // List<?> executeQuery(String hql,int firstResult,int maxResults); // List<?> executeSqlQuery(String sql); // List<?> executeSqlQuery(String sql,int firstResult,int maxResults); // // List<?> executeUpdate(String hql); // List<?> executeUpdate(String hql,int firstResult,int maxResults); // List<?> executeSqlUpdate(String sql); // List<?> executeSqlUpdate(String sql,int firstResult,int maxResults); // // // Object findById(String id); // // List<?> findByExample(Object object); // // } // // Path: src/main/java/org/fireply/enter/service/BaseService.java // public interface BaseService { // // void persist(Object object); // // Serializable save(Object object); // // void delete(Object object); // // Object merge(Object object); // // Object get(Class<?> clazz, Serializable id); // // Object get(String entityName, Serializable id); // // List<?> getAll(Class<?> clazz); // // List<?> getAll(String modeName); // // List<?> get(Class<?> clazz, String fieldName, Object fieldValue); // // List<?> get(String modelName, String fieldName, Object fieldValue); // // List<?> get(Class<?> clazz, Map<String, Object> fieldsMap); // // }
import java.io.Serializable; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.fireply.enter.dao.Dao; import org.fireply.enter.service.BaseService; import org.hibernate.HibernateException;
package org.fireply.enter.service.impl; @Service @Transactional(readOnly=true) public class BaseServiceImpl implements BaseService { private static final Logger logger = LoggerFactory.getLogger(BaseServiceImpl.class); @Autowired @Qualifier("daoImpl")
// Path: src/main/java/org/fireply/enter/dao/Dao.java // public interface Dao { // // void persist(Object object); // Serializable save(Object object); // void delete(Object object); // Object merge(Object object); // // Object get(Class<?> clazz, Serializable id); // Object get(String modelName, Serializable id); // List<?> getAll(Class<?> clazz); // List<?> getAll(String modeName); // // List<?> get(Class<?> clazz, String fieldName, Object fieldValue); // List<?> get(String modelName, String fieldName, Object fieldValue); // List<?> get(Class<?> clazz, Map<String, Object> fieldsMap); // // List<?> executeQuery(String hql); // List<?> executeQuery(String hql,int firstResult,int maxResults); // List<?> executeSqlQuery(String sql); // List<?> executeSqlQuery(String sql,int firstResult,int maxResults); // // List<?> executeUpdate(String hql); // List<?> executeUpdate(String hql,int firstResult,int maxResults); // List<?> executeSqlUpdate(String sql); // List<?> executeSqlUpdate(String sql,int firstResult,int maxResults); // // // Object findById(String id); // // List<?> findByExample(Object object); // // } // // Path: src/main/java/org/fireply/enter/service/BaseService.java // public interface BaseService { // // void persist(Object object); // // Serializable save(Object object); // // void delete(Object object); // // Object merge(Object object); // // Object get(Class<?> clazz, Serializable id); // // Object get(String entityName, Serializable id); // // List<?> getAll(Class<?> clazz); // // List<?> getAll(String modeName); // // List<?> get(Class<?> clazz, String fieldName, Object fieldValue); // // List<?> get(String modelName, String fieldName, Object fieldValue); // // List<?> get(Class<?> clazz, Map<String, Object> fieldsMap); // // } // Path: src/main/java/org/fireply/enter/service/impl/BaseServiceImpl.java import java.io.Serializable; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.fireply.enter.dao.Dao; import org.fireply.enter.service.BaseService; import org.hibernate.HibernateException; package org.fireply.enter.service.impl; @Service @Transactional(readOnly=true) public class BaseServiceImpl implements BaseService { private static final Logger logger = LoggerFactory.getLogger(BaseServiceImpl.class); @Autowired @Qualifier("daoImpl")
private Dao dao;
Fireply/Enter
src/test/java/org/fireply/enter/test/util/ClumnNameUtilTest.java
// Path: src/main/java/org/fireply/enter/util/ClumnNameUtil.java // public class ClumnNameUtil { // // private static final char SEPARATOR = '_'; // // public static String getClumnName(String fieldName) { // return getUnderlineCase(fieldName); // } // // public static String getUnderlineCase(String camelCase) { // if (camelCase == null) { // return null; // } // // StringBuilder sb = new StringBuilder(); // boolean upperCase = false; // boolean nextUpperCase = false; // char c; // // for (int i = 0; i < camelCase.length(); i++) { // c = camelCase.charAt(i); // sb.append(Character.toLowerCase(c)); // // if (i < (camelCase.length() - 1)) { // upperCase = Character.isUpperCase(camelCase.charAt(i)); // nextUpperCase = Character.isUpperCase(camelCase.charAt(i + 1)); // if (!upperCase && nextUpperCase) { // sb.append(SEPARATOR); // } // } // } // // return sb.toString(); // } // }
import static org.junit.Assert.assertEquals; import org.fireply.enter.util.ClumnNameUtil; import org.junit.Test;
package org.fireply.enter.test.util; public class ClumnNameUtilTest { @Test public void getUnderlineCaseTest() {
// Path: src/main/java/org/fireply/enter/util/ClumnNameUtil.java // public class ClumnNameUtil { // // private static final char SEPARATOR = '_'; // // public static String getClumnName(String fieldName) { // return getUnderlineCase(fieldName); // } // // public static String getUnderlineCase(String camelCase) { // if (camelCase == null) { // return null; // } // // StringBuilder sb = new StringBuilder(); // boolean upperCase = false; // boolean nextUpperCase = false; // char c; // // for (int i = 0; i < camelCase.length(); i++) { // c = camelCase.charAt(i); // sb.append(Character.toLowerCase(c)); // // if (i < (camelCase.length() - 1)) { // upperCase = Character.isUpperCase(camelCase.charAt(i)); // nextUpperCase = Character.isUpperCase(camelCase.charAt(i + 1)); // if (!upperCase && nextUpperCase) { // sb.append(SEPARATOR); // } // } // } // // return sb.toString(); // } // } // Path: src/test/java/org/fireply/enter/test/util/ClumnNameUtilTest.java import static org.junit.Assert.assertEquals; import org.fireply.enter.util.ClumnNameUtil; import org.junit.Test; package org.fireply.enter.test.util; public class ClumnNameUtilTest { @Test public void getUnderlineCaseTest() {
assertEquals("user_id", ClumnNameUtil.getUnderlineCase("userId"));
Fireply/Enter
src/main/java/org/fireply/enter/dao/impl/DaoImpl.java
// Path: src/main/java/org/fireply/enter/dao/Dao.java // public interface Dao { // // void persist(Object object); // Serializable save(Object object); // void delete(Object object); // Object merge(Object object); // // Object get(Class<?> clazz, Serializable id); // Object get(String modelName, Serializable id); // List<?> getAll(Class<?> clazz); // List<?> getAll(String modeName); // // List<?> get(Class<?> clazz, String fieldName, Object fieldValue); // List<?> get(String modelName, String fieldName, Object fieldValue); // List<?> get(Class<?> clazz, Map<String, Object> fieldsMap); // // List<?> executeQuery(String hql); // List<?> executeQuery(String hql,int firstResult,int maxResults); // List<?> executeSqlQuery(String sql); // List<?> executeSqlQuery(String sql,int firstResult,int maxResults); // // List<?> executeUpdate(String hql); // List<?> executeUpdate(String hql,int firstResult,int maxResults); // List<?> executeSqlUpdate(String sql); // List<?> executeSqlUpdate(String sql,int firstResult,int maxResults); // // // Object findById(String id); // // List<?> findByExample(Object object); // // } // // Path: src/main/java/org/fireply/enter/util/ClumnNameUtil.java // public class ClumnNameUtil { // // private static final char SEPARATOR = '_'; // // public static String getClumnName(String fieldName) { // return getUnderlineCase(fieldName); // } // // public static String getUnderlineCase(String camelCase) { // if (camelCase == null) { // return null; // } // // StringBuilder sb = new StringBuilder(); // boolean upperCase = false; // boolean nextUpperCase = false; // char c; // // for (int i = 0; i < camelCase.length(); i++) { // c = camelCase.charAt(i); // sb.append(Character.toLowerCase(c)); // // if (i < (camelCase.length() - 1)) { // upperCase = Character.isUpperCase(camelCase.charAt(i)); // nextUpperCase = Character.isUpperCase(camelCase.charAt(i + 1)); // if (!upperCase && nextUpperCase) { // sb.append(SEPARATOR); // } // } // } // // return sb.toString(); // } // }
import java.io.Serializable; import java.util.List; import java.util.Map; import org.fireply.enter.dao.Dao; import org.fireply.enter.util.ClumnNameUtil; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository;
package org.fireply.enter.dao.impl; @Repository @SuppressWarnings("rawtypes") // 本类所有返回类型为 List 的方法返回的 List 都是调用 Hibernate 的方法后返回的
// Path: src/main/java/org/fireply/enter/dao/Dao.java // public interface Dao { // // void persist(Object object); // Serializable save(Object object); // void delete(Object object); // Object merge(Object object); // // Object get(Class<?> clazz, Serializable id); // Object get(String modelName, Serializable id); // List<?> getAll(Class<?> clazz); // List<?> getAll(String modeName); // // List<?> get(Class<?> clazz, String fieldName, Object fieldValue); // List<?> get(String modelName, String fieldName, Object fieldValue); // List<?> get(Class<?> clazz, Map<String, Object> fieldsMap); // // List<?> executeQuery(String hql); // List<?> executeQuery(String hql,int firstResult,int maxResults); // List<?> executeSqlQuery(String sql); // List<?> executeSqlQuery(String sql,int firstResult,int maxResults); // // List<?> executeUpdate(String hql); // List<?> executeUpdate(String hql,int firstResult,int maxResults); // List<?> executeSqlUpdate(String sql); // List<?> executeSqlUpdate(String sql,int firstResult,int maxResults); // // // Object findById(String id); // // List<?> findByExample(Object object); // // } // // Path: src/main/java/org/fireply/enter/util/ClumnNameUtil.java // public class ClumnNameUtil { // // private static final char SEPARATOR = '_'; // // public static String getClumnName(String fieldName) { // return getUnderlineCase(fieldName); // } // // public static String getUnderlineCase(String camelCase) { // if (camelCase == null) { // return null; // } // // StringBuilder sb = new StringBuilder(); // boolean upperCase = false; // boolean nextUpperCase = false; // char c; // // for (int i = 0; i < camelCase.length(); i++) { // c = camelCase.charAt(i); // sb.append(Character.toLowerCase(c)); // // if (i < (camelCase.length() - 1)) { // upperCase = Character.isUpperCase(camelCase.charAt(i)); // nextUpperCase = Character.isUpperCase(camelCase.charAt(i + 1)); // if (!upperCase && nextUpperCase) { // sb.append(SEPARATOR); // } // } // } // // return sb.toString(); // } // } // Path: src/main/java/org/fireply/enter/dao/impl/DaoImpl.java import java.io.Serializable; import java.util.List; import java.util.Map; import org.fireply.enter.dao.Dao; import org.fireply.enter.util.ClumnNameUtil; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; package org.fireply.enter.dao.impl; @Repository @SuppressWarnings("rawtypes") // 本类所有返回类型为 List 的方法返回的 List 都是调用 Hibernate 的方法后返回的
public class DaoImpl implements Dao {
Fireply/Enter
src/main/java/org/fireply/enter/dao/impl/DaoImpl.java
// Path: src/main/java/org/fireply/enter/dao/Dao.java // public interface Dao { // // void persist(Object object); // Serializable save(Object object); // void delete(Object object); // Object merge(Object object); // // Object get(Class<?> clazz, Serializable id); // Object get(String modelName, Serializable id); // List<?> getAll(Class<?> clazz); // List<?> getAll(String modeName); // // List<?> get(Class<?> clazz, String fieldName, Object fieldValue); // List<?> get(String modelName, String fieldName, Object fieldValue); // List<?> get(Class<?> clazz, Map<String, Object> fieldsMap); // // List<?> executeQuery(String hql); // List<?> executeQuery(String hql,int firstResult,int maxResults); // List<?> executeSqlQuery(String sql); // List<?> executeSqlQuery(String sql,int firstResult,int maxResults); // // List<?> executeUpdate(String hql); // List<?> executeUpdate(String hql,int firstResult,int maxResults); // List<?> executeSqlUpdate(String sql); // List<?> executeSqlUpdate(String sql,int firstResult,int maxResults); // // // Object findById(String id); // // List<?> findByExample(Object object); // // } // // Path: src/main/java/org/fireply/enter/util/ClumnNameUtil.java // public class ClumnNameUtil { // // private static final char SEPARATOR = '_'; // // public static String getClumnName(String fieldName) { // return getUnderlineCase(fieldName); // } // // public static String getUnderlineCase(String camelCase) { // if (camelCase == null) { // return null; // } // // StringBuilder sb = new StringBuilder(); // boolean upperCase = false; // boolean nextUpperCase = false; // char c; // // for (int i = 0; i < camelCase.length(); i++) { // c = camelCase.charAt(i); // sb.append(Character.toLowerCase(c)); // // if (i < (camelCase.length() - 1)) { // upperCase = Character.isUpperCase(camelCase.charAt(i)); // nextUpperCase = Character.isUpperCase(camelCase.charAt(i + 1)); // if (!upperCase && nextUpperCase) { // sb.append(SEPARATOR); // } // } // } // // return sb.toString(); // } // }
import java.io.Serializable; import java.util.List; import java.util.Map; import org.fireply.enter.dao.Dao; import org.fireply.enter.util.ClumnNameUtil; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository;
sessionFactory.getCurrentSession().persist(object); } @Override public Serializable save(Object object) { return sessionFactory.getCurrentSession().save(object); } @Override public void delete(Object object) { sessionFactory.getCurrentSession().delete(object); } @Override public Object merge(Object object) { return sessionFactory.getCurrentSession().merge(object); } @Override public Object get(Class<?> clazz, Serializable id) throws HibernateException { return sessionFactory.getCurrentSession().get(clazz, id); } @Override public Object get(String modelName, Serializable id) { return sessionFactory.getCurrentSession().get(modelName, id); } @Override public List get(Class<?> clazz, String fieldName, Object fieldValue) {
// Path: src/main/java/org/fireply/enter/dao/Dao.java // public interface Dao { // // void persist(Object object); // Serializable save(Object object); // void delete(Object object); // Object merge(Object object); // // Object get(Class<?> clazz, Serializable id); // Object get(String modelName, Serializable id); // List<?> getAll(Class<?> clazz); // List<?> getAll(String modeName); // // List<?> get(Class<?> clazz, String fieldName, Object fieldValue); // List<?> get(String modelName, String fieldName, Object fieldValue); // List<?> get(Class<?> clazz, Map<String, Object> fieldsMap); // // List<?> executeQuery(String hql); // List<?> executeQuery(String hql,int firstResult,int maxResults); // List<?> executeSqlQuery(String sql); // List<?> executeSqlQuery(String sql,int firstResult,int maxResults); // // List<?> executeUpdate(String hql); // List<?> executeUpdate(String hql,int firstResult,int maxResults); // List<?> executeSqlUpdate(String sql); // List<?> executeSqlUpdate(String sql,int firstResult,int maxResults); // // // Object findById(String id); // // List<?> findByExample(Object object); // // } // // Path: src/main/java/org/fireply/enter/util/ClumnNameUtil.java // public class ClumnNameUtil { // // private static final char SEPARATOR = '_'; // // public static String getClumnName(String fieldName) { // return getUnderlineCase(fieldName); // } // // public static String getUnderlineCase(String camelCase) { // if (camelCase == null) { // return null; // } // // StringBuilder sb = new StringBuilder(); // boolean upperCase = false; // boolean nextUpperCase = false; // char c; // // for (int i = 0; i < camelCase.length(); i++) { // c = camelCase.charAt(i); // sb.append(Character.toLowerCase(c)); // // if (i < (camelCase.length() - 1)) { // upperCase = Character.isUpperCase(camelCase.charAt(i)); // nextUpperCase = Character.isUpperCase(camelCase.charAt(i + 1)); // if (!upperCase && nextUpperCase) { // sb.append(SEPARATOR); // } // } // } // // return sb.toString(); // } // } // Path: src/main/java/org/fireply/enter/dao/impl/DaoImpl.java import java.io.Serializable; import java.util.List; import java.util.Map; import org.fireply.enter.dao.Dao; import org.fireply.enter.util.ClumnNameUtil; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; sessionFactory.getCurrentSession().persist(object); } @Override public Serializable save(Object object) { return sessionFactory.getCurrentSession().save(object); } @Override public void delete(Object object) { sessionFactory.getCurrentSession().delete(object); } @Override public Object merge(Object object) { return sessionFactory.getCurrentSession().merge(object); } @Override public Object get(Class<?> clazz, Serializable id) throws HibernateException { return sessionFactory.getCurrentSession().get(clazz, id); } @Override public Object get(String modelName, Serializable id) { return sessionFactory.getCurrentSession().get(modelName, id); } @Override public List get(Class<?> clazz, String fieldName, Object fieldValue) {
String hql = "from " + clazz.getSimpleName() + " where " + ClumnNameUtil.getClumnName(fieldName) + "='" + fieldValue + "'";
sputnikdev/bluetooth-manager
src/main/java/org/sputnikdev/bluetooth/manager/transport/Device.java
// Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothAddressType.java // public enum BluetoothAddressType { // // /** // * Address type is unknown. // */ // UNKNOWN, // /** // * This is the standard, IEEE-assigned 48-bit universal LAN MAC address which must be obtained from the // * IEEE Registration Authority. // */ // PUBLIC, // /** // * Random type address. BLE standard adds the ability to periodically change the address to insure device privacy. // * <p>Two random types are provided: // * <ul> // * <li>Static Address. A 48-bit randomly generated address. A new value is generated after each power cycle. // * </li> // * <li>Private Address. When a device wants to remain private, it uses private addresses. These are addresses // * that can be periodically changed so that the device can not be tracked. These may be resolvable or not.</li> // * </ul> // */ // RANDOM // // }
import java.util.List; import java.util.Map; import org.sputnikdev.bluetooth.manager.BluetoothAddressType;
package org.sputnikdev.bluetooth.manager.transport; /*- * #%L * org.sputnikdev:bluetooth-manager * %% * Copyright (C) 2017 Sputnik Dev * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ /** * * @author Vlad Kolotov */ public interface Device extends BluetoothObject { int getBluetoothClass(); boolean disconnect(); boolean connect(); String getName(); String getAlias(); void setAlias(String alias); boolean isBlocked(); boolean isBleEnabled(); void enableBlockedNotifications(Notification<Boolean> notification); void disableBlockedNotifications(); void setBlocked(boolean blocked); short getRSSI(); short getTxPower(); void enableRSSINotifications(Notification<Short> notification); void disableRSSINotifications(); boolean isConnected(); void enableConnectedNotifications(Notification<Boolean> notification); void disableConnectedNotifications(); boolean isServicesResolved(); void enableServicesResolvedNotifications(Notification<Boolean> notification); void disableServicesResolvedNotifications(); List<Service> getServices(); Map<String, byte[]> getServiceData(); Map<Short, byte[]> getManufacturerData();
// Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothAddressType.java // public enum BluetoothAddressType { // // /** // * Address type is unknown. // */ // UNKNOWN, // /** // * This is the standard, IEEE-assigned 48-bit universal LAN MAC address which must be obtained from the // * IEEE Registration Authority. // */ // PUBLIC, // /** // * Random type address. BLE standard adds the ability to periodically change the address to insure device privacy. // * <p>Two random types are provided: // * <ul> // * <li>Static Address. A 48-bit randomly generated address. A new value is generated after each power cycle. // * </li> // * <li>Private Address. When a device wants to remain private, it uses private addresses. These are addresses // * that can be periodically changed so that the device can not be tracked. These may be resolvable or not.</li> // * </ul> // */ // RANDOM // // } // Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/Device.java import java.util.List; import java.util.Map; import org.sputnikdev.bluetooth.manager.BluetoothAddressType; package org.sputnikdev.bluetooth.manager.transport; /*- * #%L * org.sputnikdev:bluetooth-manager * %% * Copyright (C) 2017 Sputnik Dev * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ /** * * @author Vlad Kolotov */ public interface Device extends BluetoothObject { int getBluetoothClass(); boolean disconnect(); boolean connect(); String getName(); String getAlias(); void setAlias(String alias); boolean isBlocked(); boolean isBleEnabled(); void enableBlockedNotifications(Notification<Boolean> notification); void disableBlockedNotifications(); void setBlocked(boolean blocked); short getRSSI(); short getTxPower(); void enableRSSINotifications(Notification<Short> notification); void disableRSSINotifications(); boolean isConnected(); void enableConnectedNotifications(Notification<Boolean> notification); void disableConnectedNotifications(); boolean isServicesResolved(); void enableServicesResolvedNotifications(Notification<Boolean> notification); void disableServicesResolvedNotifications(); List<Service> getServices(); Map<String, byte[]> getServiceData(); Map<Short, byte[]> getManufacturerData();
BluetoothAddressType getAddressType();
sputnikdev/bluetooth-manager
src/test/java/org/sputnikdev/bluetooth/manager/util/BluetoothFactoryEmulator.java
// Path: src/main/java/org/sputnikdev/bluetooth/manager/DiscoveredAdapter.java // public class DiscoveredAdapter implements DiscoveredObject { // // private static final String COMBINED_ADAPTER_ADDRESS = CombinedGovernor.COMBINED_ADDRESS; // // private final URL url; // private final String name; // private final String alias; // // /** // * Creates a new object. // * @param url bluetooth object URL // * @param name bluetooth object name // * @param alias bluetooth object alias // */ // public DiscoveredAdapter(URL url, String name, String alias) { // this.url = url; // this.name = name; // this.alias = alias; // } // // /** // * Returns bluetooth object URL. // * @return bluetooth object URL // */ // @Override // public URL getURL() { // return url; // } // // /** // * Returns bluetooth object name. // * @return bluetooth object name // */ // @Override // public String getName() { // return name; // } // // /** // * Returns bluetooth object alias. // * @return bluetooth object alias // */ // @Override // public String getAlias() { // return alias; // } // // @Override // public boolean isCombined() { // return COMBINED_ADAPTER_ADDRESS.equalsIgnoreCase(url.getAdapterAddress()); // } // // @Override // public boolean equals(Object object) { // if (this == object) { // return true; // } // if (object == null || getClass() != object.getClass()) { // return false; // } // // DiscoveredAdapter that = (DiscoveredAdapter) object; // return url.equals(that.url); // // } // // @Override // public int hashCode() { // int result = url.hashCode(); // result = 31 * result + url.hashCode(); // return result; // } // // @Override // public String toString() { // String displayName = getDisplayName(); // return "[Adapter] " + getURL() + " [" + displayName + "]"; // } // // @Override // public String getDisplayName() { // return alias != null ? alias : name; // } // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/BluetoothObjectFactory.java // public interface BluetoothObjectFactory { // // // /** // * Returns an adapter by its URl. URL may not contain 'protocol' part. // * @param url adapter URL // * @return an adapter // */ // Adapter getAdapter(URL url); // // /** // * Returns a device by its URl. URL may not contain 'protocol' part. // * @param url device URL // * @return a device // */ // Device getDevice(URL url); // // /** // * Returns a characteristic by its URl. URL may not contain 'protocol' part. // * @param url characteristic URL // * @return a characteristic // */ // Characteristic getCharacteristic(URL url); // // /** // * Returns all discovered adapters by all registered transports. // * @return all discovered adapters // */ // Set<DiscoveredAdapter> getDiscoveredAdapters(); // // /** // * Returns all discovered devices by all registered transports. // * @return all discovered devices // */ // Set<DiscoveredDevice> getDiscoveredDevices(); // // /** // * Returns transport protocol name. // * @return transport protocol name // */ // String getProtocolName(); // // /** // * The bluetooth manager might call this method in order to pass some configuration variables. // * @param config configuration // */ // void configure(Map<String, Object> config); // // /** // * Disposes and removes registered object from the transport. // * @param url device to remove // */ // void dispose(URL url); // // }
import org.sputnikdev.bluetooth.URL; import org.sputnikdev.bluetooth.manager.DiscoveredAdapter; import org.sputnikdev.bluetooth.manager.transport.BluetoothObjectFactory; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.stream.Collectors; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package org.sputnikdev.bluetooth.manager.util; public class BluetoothFactoryEmulator { private BluetoothObjectFactory objectFactory;
// Path: src/main/java/org/sputnikdev/bluetooth/manager/DiscoveredAdapter.java // public class DiscoveredAdapter implements DiscoveredObject { // // private static final String COMBINED_ADAPTER_ADDRESS = CombinedGovernor.COMBINED_ADDRESS; // // private final URL url; // private final String name; // private final String alias; // // /** // * Creates a new object. // * @param url bluetooth object URL // * @param name bluetooth object name // * @param alias bluetooth object alias // */ // public DiscoveredAdapter(URL url, String name, String alias) { // this.url = url; // this.name = name; // this.alias = alias; // } // // /** // * Returns bluetooth object URL. // * @return bluetooth object URL // */ // @Override // public URL getURL() { // return url; // } // // /** // * Returns bluetooth object name. // * @return bluetooth object name // */ // @Override // public String getName() { // return name; // } // // /** // * Returns bluetooth object alias. // * @return bluetooth object alias // */ // @Override // public String getAlias() { // return alias; // } // // @Override // public boolean isCombined() { // return COMBINED_ADAPTER_ADDRESS.equalsIgnoreCase(url.getAdapterAddress()); // } // // @Override // public boolean equals(Object object) { // if (this == object) { // return true; // } // if (object == null || getClass() != object.getClass()) { // return false; // } // // DiscoveredAdapter that = (DiscoveredAdapter) object; // return url.equals(that.url); // // } // // @Override // public int hashCode() { // int result = url.hashCode(); // result = 31 * result + url.hashCode(); // return result; // } // // @Override // public String toString() { // String displayName = getDisplayName(); // return "[Adapter] " + getURL() + " [" + displayName + "]"; // } // // @Override // public String getDisplayName() { // return alias != null ? alias : name; // } // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/BluetoothObjectFactory.java // public interface BluetoothObjectFactory { // // // /** // * Returns an adapter by its URl. URL may not contain 'protocol' part. // * @param url adapter URL // * @return an adapter // */ // Adapter getAdapter(URL url); // // /** // * Returns a device by its URl. URL may not contain 'protocol' part. // * @param url device URL // * @return a device // */ // Device getDevice(URL url); // // /** // * Returns a characteristic by its URl. URL may not contain 'protocol' part. // * @param url characteristic URL // * @return a characteristic // */ // Characteristic getCharacteristic(URL url); // // /** // * Returns all discovered adapters by all registered transports. // * @return all discovered adapters // */ // Set<DiscoveredAdapter> getDiscoveredAdapters(); // // /** // * Returns all discovered devices by all registered transports. // * @return all discovered devices // */ // Set<DiscoveredDevice> getDiscoveredDevices(); // // /** // * Returns transport protocol name. // * @return transport protocol name // */ // String getProtocolName(); // // /** // * The bluetooth manager might call this method in order to pass some configuration variables. // * @param config configuration // */ // void configure(Map<String, Object> config); // // /** // * Disposes and removes registered object from the transport. // * @param url device to remove // */ // void dispose(URL url); // // } // Path: src/test/java/org/sputnikdev/bluetooth/manager/util/BluetoothFactoryEmulator.java import org.sputnikdev.bluetooth.URL; import org.sputnikdev.bluetooth.manager.DiscoveredAdapter; import org.sputnikdev.bluetooth.manager.transport.BluetoothObjectFactory; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.stream.Collectors; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package org.sputnikdev.bluetooth.manager.util; public class BluetoothFactoryEmulator { private BluetoothObjectFactory objectFactory;
private Map<DiscoveredAdapter, AdapterEmulator> adapters = new HashMap<>();
sputnikdev/bluetooth-manager
src/test/java/org/sputnikdev/bluetooth/manager/impl/AbstractBluetoothObjectGovernorTest.java
// Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothInteractionException.java // public class BluetoothInteractionException extends RuntimeException { // // public BluetoothInteractionException() { } // // public BluetoothInteractionException(String message) { // super(message); // } // // public BluetoothInteractionException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothObjectType.java // public enum BluetoothObjectType { // // ADAPTER, // DEVICE, // CHARACTERISTIC // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothObjectVisitor.java // public interface BluetoothObjectVisitor { // // void visit(AdapterGovernor governor) throws Exception; // // void visit(DeviceGovernor governor) throws Exception; // // void visit(CharacteristicGovernor governor) throws Exception; // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/GovernorListener.java // @FunctionalInterface // public interface GovernorListener { // // /** // * Reports when a device/governor changes its status. See {@link BluetoothGovernor} for more info. // * @param isReady true if a device/adapter becomes ready for interactions (hardware acquired), false otherwise // */ // void ready(boolean isReady); // // /** // * Reports when a device/governor was last active (receiving events, sending commands etc). // * @param lastActivity a date when a device was last active // */ // default void lastUpdatedChanged(Instant lastActivity) { } // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/BluetoothObject.java // public interface BluetoothObject { // // URL getURL(); // // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.sputnikdev.bluetooth.URL; import org.sputnikdev.bluetooth.manager.BluetoothInteractionException; import org.sputnikdev.bluetooth.manager.BluetoothObjectType; import org.sputnikdev.bluetooth.manager.BluetoothObjectVisitor; import org.sputnikdev.bluetooth.manager.GovernorListener; import org.sputnikdev.bluetooth.manager.transport.BluetoothObject; import java.time.Instant; import java.util.function.Function; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.spy;
package org.sputnikdev.bluetooth.manager.impl; @RunWith(MockitoJUnitRunner.class) public class AbstractBluetoothObjectGovernorTest { private static final URL URL= new URL("/11:22:33:44:55:66");
// Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothInteractionException.java // public class BluetoothInteractionException extends RuntimeException { // // public BluetoothInteractionException() { } // // public BluetoothInteractionException(String message) { // super(message); // } // // public BluetoothInteractionException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothObjectType.java // public enum BluetoothObjectType { // // ADAPTER, // DEVICE, // CHARACTERISTIC // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothObjectVisitor.java // public interface BluetoothObjectVisitor { // // void visit(AdapterGovernor governor) throws Exception; // // void visit(DeviceGovernor governor) throws Exception; // // void visit(CharacteristicGovernor governor) throws Exception; // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/GovernorListener.java // @FunctionalInterface // public interface GovernorListener { // // /** // * Reports when a device/governor changes its status. See {@link BluetoothGovernor} for more info. // * @param isReady true if a device/adapter becomes ready for interactions (hardware acquired), false otherwise // */ // void ready(boolean isReady); // // /** // * Reports when a device/governor was last active (receiving events, sending commands etc). // * @param lastActivity a date when a device was last active // */ // default void lastUpdatedChanged(Instant lastActivity) { } // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/BluetoothObject.java // public interface BluetoothObject { // // URL getURL(); // // } // Path: src/test/java/org/sputnikdev/bluetooth/manager/impl/AbstractBluetoothObjectGovernorTest.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.sputnikdev.bluetooth.URL; import org.sputnikdev.bluetooth.manager.BluetoothInteractionException; import org.sputnikdev.bluetooth.manager.BluetoothObjectType; import org.sputnikdev.bluetooth.manager.BluetoothObjectVisitor; import org.sputnikdev.bluetooth.manager.GovernorListener; import org.sputnikdev.bluetooth.manager.transport.BluetoothObject; import java.time.Instant; import java.util.function.Function; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.spy; package org.sputnikdev.bluetooth.manager.impl; @RunWith(MockitoJUnitRunner.class) public class AbstractBluetoothObjectGovernorTest { private static final URL URL= new URL("/11:22:33:44:55:66");
private BluetoothObject bluetoothObject = mock(BluetoothObject.class);
sputnikdev/bluetooth-manager
src/test/java/org/sputnikdev/bluetooth/manager/impl/AbstractBluetoothObjectGovernorTest.java
// Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothInteractionException.java // public class BluetoothInteractionException extends RuntimeException { // // public BluetoothInteractionException() { } // // public BluetoothInteractionException(String message) { // super(message); // } // // public BluetoothInteractionException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothObjectType.java // public enum BluetoothObjectType { // // ADAPTER, // DEVICE, // CHARACTERISTIC // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothObjectVisitor.java // public interface BluetoothObjectVisitor { // // void visit(AdapterGovernor governor) throws Exception; // // void visit(DeviceGovernor governor) throws Exception; // // void visit(CharacteristicGovernor governor) throws Exception; // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/GovernorListener.java // @FunctionalInterface // public interface GovernorListener { // // /** // * Reports when a device/governor changes its status. See {@link BluetoothGovernor} for more info. // * @param isReady true if a device/adapter becomes ready for interactions (hardware acquired), false otherwise // */ // void ready(boolean isReady); // // /** // * Reports when a device/governor was last active (receiving events, sending commands etc). // * @param lastActivity a date when a device was last active // */ // default void lastUpdatedChanged(Instant lastActivity) { } // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/BluetoothObject.java // public interface BluetoothObject { // // URL getURL(); // // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.sputnikdev.bluetooth.URL; import org.sputnikdev.bluetooth.manager.BluetoothInteractionException; import org.sputnikdev.bluetooth.manager.BluetoothObjectType; import org.sputnikdev.bluetooth.manager.BluetoothObjectVisitor; import org.sputnikdev.bluetooth.manager.GovernorListener; import org.sputnikdev.bluetooth.manager.transport.BluetoothObject; import java.time.Instant; import java.util.function.Function; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.spy;
package org.sputnikdev.bluetooth.manager.impl; @RunWith(MockitoJUnitRunner.class) public class AbstractBluetoothObjectGovernorTest { private static final URL URL= new URL("/11:22:33:44:55:66"); private BluetoothObject bluetoothObject = mock(BluetoothObject.class); private BluetoothManagerImpl bluetoothManager = mock(BluetoothManagerImpl.class); @Mock
// Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothInteractionException.java // public class BluetoothInteractionException extends RuntimeException { // // public BluetoothInteractionException() { } // // public BluetoothInteractionException(String message) { // super(message); // } // // public BluetoothInteractionException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothObjectType.java // public enum BluetoothObjectType { // // ADAPTER, // DEVICE, // CHARACTERISTIC // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothObjectVisitor.java // public interface BluetoothObjectVisitor { // // void visit(AdapterGovernor governor) throws Exception; // // void visit(DeviceGovernor governor) throws Exception; // // void visit(CharacteristicGovernor governor) throws Exception; // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/GovernorListener.java // @FunctionalInterface // public interface GovernorListener { // // /** // * Reports when a device/governor changes its status. See {@link BluetoothGovernor} for more info. // * @param isReady true if a device/adapter becomes ready for interactions (hardware acquired), false otherwise // */ // void ready(boolean isReady); // // /** // * Reports when a device/governor was last active (receiving events, sending commands etc). // * @param lastActivity a date when a device was last active // */ // default void lastUpdatedChanged(Instant lastActivity) { } // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/BluetoothObject.java // public interface BluetoothObject { // // URL getURL(); // // } // Path: src/test/java/org/sputnikdev/bluetooth/manager/impl/AbstractBluetoothObjectGovernorTest.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.sputnikdev.bluetooth.URL; import org.sputnikdev.bluetooth.manager.BluetoothInteractionException; import org.sputnikdev.bluetooth.manager.BluetoothObjectType; import org.sputnikdev.bluetooth.manager.BluetoothObjectVisitor; import org.sputnikdev.bluetooth.manager.GovernorListener; import org.sputnikdev.bluetooth.manager.transport.BluetoothObject; import java.time.Instant; import java.util.function.Function; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.spy; package org.sputnikdev.bluetooth.manager.impl; @RunWith(MockitoJUnitRunner.class) public class AbstractBluetoothObjectGovernorTest { private static final URL URL= new URL("/11:22:33:44:55:66"); private BluetoothObject bluetoothObject = mock(BluetoothObject.class); private BluetoothManagerImpl bluetoothManager = mock(BluetoothManagerImpl.class); @Mock
private GovernorListener governorListener;
sputnikdev/bluetooth-manager
src/test/java/org/sputnikdev/bluetooth/manager/impl/AbstractBluetoothObjectGovernorTest.java
// Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothInteractionException.java // public class BluetoothInteractionException extends RuntimeException { // // public BluetoothInteractionException() { } // // public BluetoothInteractionException(String message) { // super(message); // } // // public BluetoothInteractionException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothObjectType.java // public enum BluetoothObjectType { // // ADAPTER, // DEVICE, // CHARACTERISTIC // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothObjectVisitor.java // public interface BluetoothObjectVisitor { // // void visit(AdapterGovernor governor) throws Exception; // // void visit(DeviceGovernor governor) throws Exception; // // void visit(CharacteristicGovernor governor) throws Exception; // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/GovernorListener.java // @FunctionalInterface // public interface GovernorListener { // // /** // * Reports when a device/governor changes its status. See {@link BluetoothGovernor} for more info. // * @param isReady true if a device/adapter becomes ready for interactions (hardware acquired), false otherwise // */ // void ready(boolean isReady); // // /** // * Reports when a device/governor was last active (receiving events, sending commands etc). // * @param lastActivity a date when a device was last active // */ // default void lastUpdatedChanged(Instant lastActivity) { } // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/BluetoothObject.java // public interface BluetoothObject { // // URL getURL(); // // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.sputnikdev.bluetooth.URL; import org.sputnikdev.bluetooth.manager.BluetoothInteractionException; import org.sputnikdev.bluetooth.manager.BluetoothObjectType; import org.sputnikdev.bluetooth.manager.BluetoothObjectVisitor; import org.sputnikdev.bluetooth.manager.GovernorListener; import org.sputnikdev.bluetooth.manager.transport.BluetoothObject; import java.time.Instant; import java.util.function.Function; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.spy;
package org.sputnikdev.bluetooth.manager.impl; @RunWith(MockitoJUnitRunner.class) public class AbstractBluetoothObjectGovernorTest { private static final URL URL= new URL("/11:22:33:44:55:66"); private BluetoothObject bluetoothObject = mock(BluetoothObject.class); private BluetoothManagerImpl bluetoothManager = mock(BluetoothManagerImpl.class); @Mock private GovernorListener governorListener; //@InjectMocks @Spy private AbstractBluetoothObjectGovernor governor = new AbstractBluetoothObjectGovernor(bluetoothManager, URL) { @Override public boolean isUpdatable() { return true; } @Override void reset(BluetoothObject object) { } @Override void update(BluetoothObject object) { } @Override void init(BluetoothObject object) { }
// Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothInteractionException.java // public class BluetoothInteractionException extends RuntimeException { // // public BluetoothInteractionException() { } // // public BluetoothInteractionException(String message) { // super(message); // } // // public BluetoothInteractionException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothObjectType.java // public enum BluetoothObjectType { // // ADAPTER, // DEVICE, // CHARACTERISTIC // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothObjectVisitor.java // public interface BluetoothObjectVisitor { // // void visit(AdapterGovernor governor) throws Exception; // // void visit(DeviceGovernor governor) throws Exception; // // void visit(CharacteristicGovernor governor) throws Exception; // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/GovernorListener.java // @FunctionalInterface // public interface GovernorListener { // // /** // * Reports when a device/governor changes its status. See {@link BluetoothGovernor} for more info. // * @param isReady true if a device/adapter becomes ready for interactions (hardware acquired), false otherwise // */ // void ready(boolean isReady); // // /** // * Reports when a device/governor was last active (receiving events, sending commands etc). // * @param lastActivity a date when a device was last active // */ // default void lastUpdatedChanged(Instant lastActivity) { } // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/BluetoothObject.java // public interface BluetoothObject { // // URL getURL(); // // } // Path: src/test/java/org/sputnikdev/bluetooth/manager/impl/AbstractBluetoothObjectGovernorTest.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.sputnikdev.bluetooth.URL; import org.sputnikdev.bluetooth.manager.BluetoothInteractionException; import org.sputnikdev.bluetooth.manager.BluetoothObjectType; import org.sputnikdev.bluetooth.manager.BluetoothObjectVisitor; import org.sputnikdev.bluetooth.manager.GovernorListener; import org.sputnikdev.bluetooth.manager.transport.BluetoothObject; import java.time.Instant; import java.util.function.Function; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.spy; package org.sputnikdev.bluetooth.manager.impl; @RunWith(MockitoJUnitRunner.class) public class AbstractBluetoothObjectGovernorTest { private static final URL URL= new URL("/11:22:33:44:55:66"); private BluetoothObject bluetoothObject = mock(BluetoothObject.class); private BluetoothManagerImpl bluetoothManager = mock(BluetoothManagerImpl.class); @Mock private GovernorListener governorListener; //@InjectMocks @Spy private AbstractBluetoothObjectGovernor governor = new AbstractBluetoothObjectGovernor(bluetoothManager, URL) { @Override public boolean isUpdatable() { return true; } @Override void reset(BluetoothObject object) { } @Override void update(BluetoothObject object) { } @Override void init(BluetoothObject object) { }
@Override public BluetoothObjectType getType() {
sputnikdev/bluetooth-manager
src/test/java/org/sputnikdev/bluetooth/manager/impl/AbstractBluetoothObjectGovernorTest.java
// Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothInteractionException.java // public class BluetoothInteractionException extends RuntimeException { // // public BluetoothInteractionException() { } // // public BluetoothInteractionException(String message) { // super(message); // } // // public BluetoothInteractionException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothObjectType.java // public enum BluetoothObjectType { // // ADAPTER, // DEVICE, // CHARACTERISTIC // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothObjectVisitor.java // public interface BluetoothObjectVisitor { // // void visit(AdapterGovernor governor) throws Exception; // // void visit(DeviceGovernor governor) throws Exception; // // void visit(CharacteristicGovernor governor) throws Exception; // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/GovernorListener.java // @FunctionalInterface // public interface GovernorListener { // // /** // * Reports when a device/governor changes its status. See {@link BluetoothGovernor} for more info. // * @param isReady true if a device/adapter becomes ready for interactions (hardware acquired), false otherwise // */ // void ready(boolean isReady); // // /** // * Reports when a device/governor was last active (receiving events, sending commands etc). // * @param lastActivity a date when a device was last active // */ // default void lastUpdatedChanged(Instant lastActivity) { } // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/BluetoothObject.java // public interface BluetoothObject { // // URL getURL(); // // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.sputnikdev.bluetooth.URL; import org.sputnikdev.bluetooth.manager.BluetoothInteractionException; import org.sputnikdev.bluetooth.manager.BluetoothObjectType; import org.sputnikdev.bluetooth.manager.BluetoothObjectVisitor; import org.sputnikdev.bluetooth.manager.GovernorListener; import org.sputnikdev.bluetooth.manager.transport.BluetoothObject; import java.time.Instant; import java.util.function.Function; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.spy;
package org.sputnikdev.bluetooth.manager.impl; @RunWith(MockitoJUnitRunner.class) public class AbstractBluetoothObjectGovernorTest { private static final URL URL= new URL("/11:22:33:44:55:66"); private BluetoothObject bluetoothObject = mock(BluetoothObject.class); private BluetoothManagerImpl bluetoothManager = mock(BluetoothManagerImpl.class); @Mock private GovernorListener governorListener; //@InjectMocks @Spy private AbstractBluetoothObjectGovernor governor = new AbstractBluetoothObjectGovernor(bluetoothManager, URL) { @Override public boolean isUpdatable() { return true; } @Override void reset(BluetoothObject object) { } @Override void update(BluetoothObject object) { } @Override void init(BluetoothObject object) { } @Override public BluetoothObjectType getType() { return BluetoothObjectType.ADAPTER; }
// Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothInteractionException.java // public class BluetoothInteractionException extends RuntimeException { // // public BluetoothInteractionException() { } // // public BluetoothInteractionException(String message) { // super(message); // } // // public BluetoothInteractionException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothObjectType.java // public enum BluetoothObjectType { // // ADAPTER, // DEVICE, // CHARACTERISTIC // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothObjectVisitor.java // public interface BluetoothObjectVisitor { // // void visit(AdapterGovernor governor) throws Exception; // // void visit(DeviceGovernor governor) throws Exception; // // void visit(CharacteristicGovernor governor) throws Exception; // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/GovernorListener.java // @FunctionalInterface // public interface GovernorListener { // // /** // * Reports when a device/governor changes its status. See {@link BluetoothGovernor} for more info. // * @param isReady true if a device/adapter becomes ready for interactions (hardware acquired), false otherwise // */ // void ready(boolean isReady); // // /** // * Reports when a device/governor was last active (receiving events, sending commands etc). // * @param lastActivity a date when a device was last active // */ // default void lastUpdatedChanged(Instant lastActivity) { } // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/BluetoothObject.java // public interface BluetoothObject { // // URL getURL(); // // } // Path: src/test/java/org/sputnikdev/bluetooth/manager/impl/AbstractBluetoothObjectGovernorTest.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.sputnikdev.bluetooth.URL; import org.sputnikdev.bluetooth.manager.BluetoothInteractionException; import org.sputnikdev.bluetooth.manager.BluetoothObjectType; import org.sputnikdev.bluetooth.manager.BluetoothObjectVisitor; import org.sputnikdev.bluetooth.manager.GovernorListener; import org.sputnikdev.bluetooth.manager.transport.BluetoothObject; import java.time.Instant; import java.util.function.Function; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.spy; package org.sputnikdev.bluetooth.manager.impl; @RunWith(MockitoJUnitRunner.class) public class AbstractBluetoothObjectGovernorTest { private static final URL URL= new URL("/11:22:33:44:55:66"); private BluetoothObject bluetoothObject = mock(BluetoothObject.class); private BluetoothManagerImpl bluetoothManager = mock(BluetoothManagerImpl.class); @Mock private GovernorListener governorListener; //@InjectMocks @Spy private AbstractBluetoothObjectGovernor governor = new AbstractBluetoothObjectGovernor(bluetoothManager, URL) { @Override public boolean isUpdatable() { return true; } @Override void reset(BluetoothObject object) { } @Override void update(BluetoothObject object) { } @Override void init(BluetoothObject object) { } @Override public BluetoothObjectType getType() { return BluetoothObjectType.ADAPTER; }
@Override public void accept(BluetoothObjectVisitor visitor) throws Exception {
sputnikdev/bluetooth-manager
src/test/java/org/sputnikdev/bluetooth/manager/impl/AbstractBluetoothObjectGovernorTest.java
// Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothInteractionException.java // public class BluetoothInteractionException extends RuntimeException { // // public BluetoothInteractionException() { } // // public BluetoothInteractionException(String message) { // super(message); // } // // public BluetoothInteractionException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothObjectType.java // public enum BluetoothObjectType { // // ADAPTER, // DEVICE, // CHARACTERISTIC // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothObjectVisitor.java // public interface BluetoothObjectVisitor { // // void visit(AdapterGovernor governor) throws Exception; // // void visit(DeviceGovernor governor) throws Exception; // // void visit(CharacteristicGovernor governor) throws Exception; // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/GovernorListener.java // @FunctionalInterface // public interface GovernorListener { // // /** // * Reports when a device/governor changes its status. See {@link BluetoothGovernor} for more info. // * @param isReady true if a device/adapter becomes ready for interactions (hardware acquired), false otherwise // */ // void ready(boolean isReady); // // /** // * Reports when a device/governor was last active (receiving events, sending commands etc). // * @param lastActivity a date when a device was last active // */ // default void lastUpdatedChanged(Instant lastActivity) { } // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/BluetoothObject.java // public interface BluetoothObject { // // URL getURL(); // // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.sputnikdev.bluetooth.URL; import org.sputnikdev.bluetooth.manager.BluetoothInteractionException; import org.sputnikdev.bluetooth.manager.BluetoothObjectType; import org.sputnikdev.bluetooth.manager.BluetoothObjectVisitor; import org.sputnikdev.bluetooth.manager.GovernorListener; import org.sputnikdev.bluetooth.manager.transport.BluetoothObject; import java.time.Instant; import java.util.function.Function; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.spy;
@Override public boolean isUpdatable() { return true; } @Override void reset(BluetoothObject object) { } @Override void update(BluetoothObject object) { } @Override void init(BluetoothObject object) { } @Override public BluetoothObjectType getType() { return BluetoothObjectType.ADAPTER; } @Override public void accept(BluetoothObjectVisitor visitor) throws Exception { } }; @Before public void setUp() { when(bluetoothObject.getURL()).thenReturn(URL.copyWithProtocol("tinyb")); when(bluetoothManager.getBluetoothObject(URL)).thenReturn(bluetoothObject); MockUtils.mockImplicitNotifications(bluetoothManager); }
// Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothInteractionException.java // public class BluetoothInteractionException extends RuntimeException { // // public BluetoothInteractionException() { } // // public BluetoothInteractionException(String message) { // super(message); // } // // public BluetoothInteractionException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothObjectType.java // public enum BluetoothObjectType { // // ADAPTER, // DEVICE, // CHARACTERISTIC // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothObjectVisitor.java // public interface BluetoothObjectVisitor { // // void visit(AdapterGovernor governor) throws Exception; // // void visit(DeviceGovernor governor) throws Exception; // // void visit(CharacteristicGovernor governor) throws Exception; // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/GovernorListener.java // @FunctionalInterface // public interface GovernorListener { // // /** // * Reports when a device/governor changes its status. See {@link BluetoothGovernor} for more info. // * @param isReady true if a device/adapter becomes ready for interactions (hardware acquired), false otherwise // */ // void ready(boolean isReady); // // /** // * Reports when a device/governor was last active (receiving events, sending commands etc). // * @param lastActivity a date when a device was last active // */ // default void lastUpdatedChanged(Instant lastActivity) { } // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/BluetoothObject.java // public interface BluetoothObject { // // URL getURL(); // // } // Path: src/test/java/org/sputnikdev/bluetooth/manager/impl/AbstractBluetoothObjectGovernorTest.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.sputnikdev.bluetooth.URL; import org.sputnikdev.bluetooth.manager.BluetoothInteractionException; import org.sputnikdev.bluetooth.manager.BluetoothObjectType; import org.sputnikdev.bluetooth.manager.BluetoothObjectVisitor; import org.sputnikdev.bluetooth.manager.GovernorListener; import org.sputnikdev.bluetooth.manager.transport.BluetoothObject; import java.time.Instant; import java.util.function.Function; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.spy; @Override public boolean isUpdatable() { return true; } @Override void reset(BluetoothObject object) { } @Override void update(BluetoothObject object) { } @Override void init(BluetoothObject object) { } @Override public BluetoothObjectType getType() { return BluetoothObjectType.ADAPTER; } @Override public void accept(BluetoothObjectVisitor visitor) throws Exception { } }; @Before public void setUp() { when(bluetoothObject.getURL()).thenReturn(URL.copyWithProtocol("tinyb")); when(bluetoothManager.getBluetoothObject(URL)).thenReturn(bluetoothObject); MockUtils.mockImplicitNotifications(bluetoothManager); }
@Test(expected = BluetoothInteractionException.class)
sputnikdev/bluetooth-manager
src/main/java/org/sputnikdev/bluetooth/manager/GattCharacteristic.java
// Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/CharacteristicAccessType.java // public enum CharacteristicAccessType { // // BROADCAST(0x01), // READ(0x02), // WRITE_WITHOUT_RESPONSE(0x04), // WRITE(0x08), // NOTIFY(0x10), // INDICATE(0x20), // AUTHENTICATED_SIGNED_WRITES(0x40), // EXTENDED_PROPERTIES(0x80); // // int bitField; // // CharacteristicAccessType(int bitField) { // this.bitField = bitField; // } // // public int getBitField() { // return bitField; // } // // public static CharacteristicAccessType fromBitField(int bitField) { // return Stream.of(CharacteristicAccessType.values()) // .filter(c -> c.bitField == bitField) // .findFirst().orElse(null); // } // // public static Set<CharacteristicAccessType> parse(int flags) { // return Stream.of(CharacteristicAccessType.values()) // .filter(c -> (c.bitField & flags) > 0) // .collect(Collectors.toSet()); // } // // }
import java.util.Collections; import java.util.Set; import org.sputnikdev.bluetooth.URL; import org.sputnikdev.bluetooth.manager.transport.CharacteristicAccessType;
package org.sputnikdev.bluetooth.manager; /*- * #%L * org.sputnikdev:bluetooth-manager * %% * Copyright (C) 2017 Sputnik Dev * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ /** * A class to capture discovered GATT characteristics. * * @author Vlad Kolotov */ public class GattCharacteristic { private final URL url;
// Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/CharacteristicAccessType.java // public enum CharacteristicAccessType { // // BROADCAST(0x01), // READ(0x02), // WRITE_WITHOUT_RESPONSE(0x04), // WRITE(0x08), // NOTIFY(0x10), // INDICATE(0x20), // AUTHENTICATED_SIGNED_WRITES(0x40), // EXTENDED_PROPERTIES(0x80); // // int bitField; // // CharacteristicAccessType(int bitField) { // this.bitField = bitField; // } // // public int getBitField() { // return bitField; // } // // public static CharacteristicAccessType fromBitField(int bitField) { // return Stream.of(CharacteristicAccessType.values()) // .filter(c -> c.bitField == bitField) // .findFirst().orElse(null); // } // // public static Set<CharacteristicAccessType> parse(int flags) { // return Stream.of(CharacteristicAccessType.values()) // .filter(c -> (c.bitField & flags) > 0) // .collect(Collectors.toSet()); // } // // } // Path: src/main/java/org/sputnikdev/bluetooth/manager/GattCharacteristic.java import java.util.Collections; import java.util.Set; import org.sputnikdev.bluetooth.URL; import org.sputnikdev.bluetooth.manager.transport.CharacteristicAccessType; package org.sputnikdev.bluetooth.manager; /*- * #%L * org.sputnikdev:bluetooth-manager * %% * Copyright (C) 2017 Sputnik Dev * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ /** * A class to capture discovered GATT characteristics. * * @author Vlad Kolotov */ public class GattCharacteristic { private final URL url;
private final Set<CharacteristicAccessType> flags;
sputnikdev/bluetooth-manager
src/test/java/org/sputnikdev/bluetooth/manager/transport/CharacteristicAccessTypeTest.java
// Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/CharacteristicAccessType.java // public enum CharacteristicAccessType { // // BROADCAST(0x01), // READ(0x02), // WRITE_WITHOUT_RESPONSE(0x04), // WRITE(0x08), // NOTIFY(0x10), // INDICATE(0x20), // AUTHENTICATED_SIGNED_WRITES(0x40), // EXTENDED_PROPERTIES(0x80); // // int bitField; // // CharacteristicAccessType(int bitField) { // this.bitField = bitField; // } // // public int getBitField() { // return bitField; // } // // public static CharacteristicAccessType fromBitField(int bitField) { // return Stream.of(CharacteristicAccessType.values()) // .filter(c -> c.bitField == bitField) // .findFirst().orElse(null); // } // // public static Set<CharacteristicAccessType> parse(int flags) { // return Stream.of(CharacteristicAccessType.values()) // .filter(c -> (c.bitField & flags) > 0) // .collect(Collectors.toSet()); // } // // }
import org.junit.Test; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.sputnikdev.bluetooth.manager.transport.CharacteristicAccessType.*;
package org.sputnikdev.bluetooth.manager.transport; public class CharacteristicAccessTypeTest { @Test public void testGetBitField() throws Exception { assertEquals(0x01, BROADCAST.getBitField()); assertEquals(0x02, READ.getBitField()); assertEquals(0x04, WRITE_WITHOUT_RESPONSE.getBitField()); assertEquals(0x08, WRITE.getBitField()); assertEquals(0x10, NOTIFY.getBitField()); assertEquals(0x20, INDICATE.getBitField()); assertEquals(0x40, AUTHENTICATED_SIGNED_WRITES.getBitField()); assertEquals(0x80, EXTENDED_PROPERTIES.getBitField()); } @Test public void testFromBitField() throws Exception { assertEquals(BROADCAST, fromBitField(0b00000001)); assertEquals(READ, fromBitField(0b00000010)); assertEquals(WRITE_WITHOUT_RESPONSE, fromBitField(0b00000100)); assertEquals(WRITE, fromBitField(0b00001000)); assertEquals(NOTIFY, fromBitField(0b00010000)); assertEquals(INDICATE, fromBitField(0b00100000)); assertEquals(AUTHENTICATED_SIGNED_WRITES, fromBitField(0b01000000)); assertEquals(EXTENDED_PROPERTIES, fromBitField(0b10000000)); } @Test public void testParse() throws Exception { int notify = 0b00010000;
// Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/CharacteristicAccessType.java // public enum CharacteristicAccessType { // // BROADCAST(0x01), // READ(0x02), // WRITE_WITHOUT_RESPONSE(0x04), // WRITE(0x08), // NOTIFY(0x10), // INDICATE(0x20), // AUTHENTICATED_SIGNED_WRITES(0x40), // EXTENDED_PROPERTIES(0x80); // // int bitField; // // CharacteristicAccessType(int bitField) { // this.bitField = bitField; // } // // public int getBitField() { // return bitField; // } // // public static CharacteristicAccessType fromBitField(int bitField) { // return Stream.of(CharacteristicAccessType.values()) // .filter(c -> c.bitField == bitField) // .findFirst().orElse(null); // } // // public static Set<CharacteristicAccessType> parse(int flags) { // return Stream.of(CharacteristicAccessType.values()) // .filter(c -> (c.bitField & flags) > 0) // .collect(Collectors.toSet()); // } // // } // Path: src/test/java/org/sputnikdev/bluetooth/manager/transport/CharacteristicAccessTypeTest.java import org.junit.Test; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.sputnikdev.bluetooth.manager.transport.CharacteristicAccessType.*; package org.sputnikdev.bluetooth.manager.transport; public class CharacteristicAccessTypeTest { @Test public void testGetBitField() throws Exception { assertEquals(0x01, BROADCAST.getBitField()); assertEquals(0x02, READ.getBitField()); assertEquals(0x04, WRITE_WITHOUT_RESPONSE.getBitField()); assertEquals(0x08, WRITE.getBitField()); assertEquals(0x10, NOTIFY.getBitField()); assertEquals(0x20, INDICATE.getBitField()); assertEquals(0x40, AUTHENTICATED_SIGNED_WRITES.getBitField()); assertEquals(0x80, EXTENDED_PROPERTIES.getBitField()); } @Test public void testFromBitField() throws Exception { assertEquals(BROADCAST, fromBitField(0b00000001)); assertEquals(READ, fromBitField(0b00000010)); assertEquals(WRITE_WITHOUT_RESPONSE, fromBitField(0b00000100)); assertEquals(WRITE, fromBitField(0b00001000)); assertEquals(NOTIFY, fromBitField(0b00010000)); assertEquals(INDICATE, fromBitField(0b00100000)); assertEquals(AUTHENTICATED_SIGNED_WRITES, fromBitField(0b01000000)); assertEquals(EXTENDED_PROPERTIES, fromBitField(0b10000000)); } @Test public void testParse() throws Exception { int notify = 0b00010000;
Set<CharacteristicAccessType> actual = parse(notify);
sputnikdev/bluetooth-manager
src/main/java/org/sputnikdev/bluetooth/manager/impl/BluetoothManagerUtils.java
// Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/BluetoothObject.java // public interface BluetoothObject { // // URL getURL(); // // }
import java.util.function.Consumer; import java.util.regex.Pattern; import org.slf4j.Logger; import org.sputnikdev.bluetooth.URL; import org.sputnikdev.bluetooth.manager.transport.BluetoothObject; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.function.BiConsumer;
package org.sputnikdev.bluetooth.manager.impl; /*- * #%L * org.sputnikdev:bluetooth-manager * %% * Copyright (C) 2017 Sputnik Dev * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ /** * Utility class. * @author Vlad Kolotov */ final class BluetoothManagerUtils { private static final Pattern MAC_PATTERN = Pattern.compile("(\\w\\w[:-]){5}\\w\\w"); private BluetoothManagerUtils() { }
// Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/BluetoothObject.java // public interface BluetoothObject { // // URL getURL(); // // } // Path: src/main/java/org/sputnikdev/bluetooth/manager/impl/BluetoothManagerUtils.java import java.util.function.Consumer; import java.util.regex.Pattern; import org.slf4j.Logger; import org.sputnikdev.bluetooth.URL; import org.sputnikdev.bluetooth.manager.transport.BluetoothObject; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.function.BiConsumer; package org.sputnikdev.bluetooth.manager.impl; /*- * #%L * org.sputnikdev:bluetooth-manager * %% * Copyright (C) 2017 Sputnik Dev * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ /** * Utility class. * @author Vlad Kolotov */ final class BluetoothManagerUtils { private static final Pattern MAC_PATTERN = Pattern.compile("(\\w\\w[:-]){5}\\w\\w"); private BluetoothManagerUtils() { }
static List<URL> getURLs(List<? extends BluetoothObject> objects) {
sputnikdev/bluetooth-manager
src/main/java/org/sputnikdev/bluetooth/manager/DeviceGovernor.java
// Path: src/main/java/org/sputnikdev/bluetooth/manager/auth/AuthenticationProvider.java // @FunctionalInterface // public interface AuthenticationProvider { // // void authenticate(BluetoothManager bluetoothManager, DeviceGovernor governor); // // }
import org.sputnikdev.bluetooth.Filter; import org.sputnikdev.bluetooth.URL; import org.sputnikdev.bluetooth.manager.auth.AuthenticationProvider; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import java.util.function.Function;
* @return a list of characteristic URLs of the device * @throws NotReadyException if the device object is not ready */ List<URL> getCharacteristics() throws NotReadyException; /** * Returns a list of characteristic governors associated to the device. * @return a list of characteristic governors associated to the device * @throws NotReadyException if the device object is not ready */ List<CharacteristicGovernor> getCharacteristicGovernors() throws NotReadyException; /** * Returns advertised manufacturer data. The key is manufacturer ID, the value is manufacturer data. * @return advertised manufacturer data */ Map<Short, byte[]> getManufacturerData(); /** * Returns advertised service data. The key is service UUID (16, 32 or 128 bit UUID), the value is service data. * @return advertised service data */ Map<URL, byte[]> getServiceData(); /** * Returns the date/time of last known advertised packet. * @return the date/time of last known advertised packet */ Instant getLastAdvertised();
// Path: src/main/java/org/sputnikdev/bluetooth/manager/auth/AuthenticationProvider.java // @FunctionalInterface // public interface AuthenticationProvider { // // void authenticate(BluetoothManager bluetoothManager, DeviceGovernor governor); // // } // Path: src/main/java/org/sputnikdev/bluetooth/manager/DeviceGovernor.java import org.sputnikdev.bluetooth.Filter; import org.sputnikdev.bluetooth.URL; import org.sputnikdev.bluetooth.manager.auth.AuthenticationProvider; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import java.util.function.Function; * @return a list of characteristic URLs of the device * @throws NotReadyException if the device object is not ready */ List<URL> getCharacteristics() throws NotReadyException; /** * Returns a list of characteristic governors associated to the device. * @return a list of characteristic governors associated to the device * @throws NotReadyException if the device object is not ready */ List<CharacteristicGovernor> getCharacteristicGovernors() throws NotReadyException; /** * Returns advertised manufacturer data. The key is manufacturer ID, the value is manufacturer data. * @return advertised manufacturer data */ Map<Short, byte[]> getManufacturerData(); /** * Returns advertised service data. The key is service UUID (16, 32 or 128 bit UUID), the value is service data. * @return advertised service data */ Map<URL, byte[]> getServiceData(); /** * Returns the date/time of last known advertised packet. * @return the date/time of last known advertised packet */ Instant getLastAdvertised();
void setAuthenticationProvider(AuthenticationProvider authenticationProvider);
sputnikdev/bluetooth-manager
src/main/java/org/sputnikdev/bluetooth/manager/impl/CompletableFutureService.java
// Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothGovernor.java // public interface BluetoothGovernor { // // /** // * Returns the URL of the corresponding Bluetooth object. // * @return the URL of the corresponding Bluetooth object // */ // URL getURL(); // // /** // * Checks whether the governor is in state when its corresponding bluetooth object is acquired // * and ready for manipulations. // * @return true if the corresponding bluetooth object is acquired and ready for manipulations // */ // boolean isReady(); // // /** // * Returns type of the corresponding Bluetooth object. // * @return type of the corresponding Bluetooth object // */ // BluetoothObjectType getType(); // // /** // * Returns the date/time of last known successful interaction with the corresponding native object. // * @return the date/time of last known successful interaction with the corresponding native object // */ // Instant getLastInteracted(); // // /** // * An accept method of the visitor pattern to process different bluetooth governors at once. // * @param visitor bluetooth governor visitor // * @throws Exception in case of any error // */ // void accept(BluetoothObjectVisitor visitor) throws Exception; // // /** // * Register a new governor listener. // * @param listener a new governor listener // */ // void addGovernorListener(GovernorListener listener); // // /** // * Unregister a governor listener. // * @param listener a governor listener // */ // void removeGovernorListener(GovernorListener listener); // // // <G extends BluetoothGovernor, V> CompletableFuture<V> when(Predicate<G> condition, Function<G, V> function); // // default <G extends BluetoothGovernor> CompletableFuture<Void> doWhen(Predicate<G> predicate, // Consumer<G> consumer) { // return when(predicate, g -> { // consumer.accept((G) this); // return null; // }); // } // // /** // * Returns a completable future that gets completed when governor becomes ready. // * @param function a function that is invoked when governor becomes ready, the completable future is // * completed with the result of this function // * @param <G> bluetooth governor // * @param <V> returned value // * @return a completable future // */ // default <G extends BluetoothGovernor, V> CompletableFuture<V> whenReady(Function<G, V> function) { // return when(BluetoothGovernor::isReady, function); // } // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothInteractionException.java // public class BluetoothInteractionException extends RuntimeException { // // public BluetoothInteractionException() { } // // public BluetoothInteractionException(String message) { // super(message); // } // // public BluetoothInteractionException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/NotReadyException.java // public class NotReadyException extends RuntimeException { // // /** // * A constructor without message. // */ // public NotReadyException() { // super(); // } // // /** // * A constructor with a message. // * @param message a message // */ // public NotReadyException(String message) { // super(message); // } // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/auth/BluetoothAuthenticationException.java // public class BluetoothAuthenticationException extends RuntimeException { // // public BluetoothAuthenticationException() { } // // public BluetoothAuthenticationException(String message) { // super(message); // } // // public BluetoothAuthenticationException(String message, Throwable cause) { // super(message, cause); // } // // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sputnikdev.bluetooth.manager.BluetoothGovernor; import org.sputnikdev.bluetooth.manager.BluetoothInteractionException; import org.sputnikdev.bluetooth.manager.NotReadyException; import org.sputnikdev.bluetooth.manager.auth.BluetoothAuthenticationException; import java.util.Iterator; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.Function; import java.util.function.Predicate;
package org.sputnikdev.bluetooth.manager.impl; class CompletableFutureService<G extends BluetoothGovernor> { private Logger logger = LoggerFactory.getLogger(CompletableFutureService.class); private final ConcurrentLinkedQueue<DeferredCompletableFuture<G, ?>> futures = new ConcurrentLinkedQueue<>(); <V> CompletableFuture<V> submit(G governor, Predicate<G> predicate, Function<G, V> function) { DeferredCompletableFuture<G, V> future = new DeferredCompletableFuture<>(predicate, function); try { if (!predicate.test(governor)) { logger.debug("Future is not ready to be completed immediately: {} : {}", governor.getURL(), predicate); futures.add(future); return future; } logger.debug("Trying to complete future immediately: {} : {}", governor.getURL(), predicate); future.complete(function.apply(governor));
// Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothGovernor.java // public interface BluetoothGovernor { // // /** // * Returns the URL of the corresponding Bluetooth object. // * @return the URL of the corresponding Bluetooth object // */ // URL getURL(); // // /** // * Checks whether the governor is in state when its corresponding bluetooth object is acquired // * and ready for manipulations. // * @return true if the corresponding bluetooth object is acquired and ready for manipulations // */ // boolean isReady(); // // /** // * Returns type of the corresponding Bluetooth object. // * @return type of the corresponding Bluetooth object // */ // BluetoothObjectType getType(); // // /** // * Returns the date/time of last known successful interaction with the corresponding native object. // * @return the date/time of last known successful interaction with the corresponding native object // */ // Instant getLastInteracted(); // // /** // * An accept method of the visitor pattern to process different bluetooth governors at once. // * @param visitor bluetooth governor visitor // * @throws Exception in case of any error // */ // void accept(BluetoothObjectVisitor visitor) throws Exception; // // /** // * Register a new governor listener. // * @param listener a new governor listener // */ // void addGovernorListener(GovernorListener listener); // // /** // * Unregister a governor listener. // * @param listener a governor listener // */ // void removeGovernorListener(GovernorListener listener); // // // <G extends BluetoothGovernor, V> CompletableFuture<V> when(Predicate<G> condition, Function<G, V> function); // // default <G extends BluetoothGovernor> CompletableFuture<Void> doWhen(Predicate<G> predicate, // Consumer<G> consumer) { // return when(predicate, g -> { // consumer.accept((G) this); // return null; // }); // } // // /** // * Returns a completable future that gets completed when governor becomes ready. // * @param function a function that is invoked when governor becomes ready, the completable future is // * completed with the result of this function // * @param <G> bluetooth governor // * @param <V> returned value // * @return a completable future // */ // default <G extends BluetoothGovernor, V> CompletableFuture<V> whenReady(Function<G, V> function) { // return when(BluetoothGovernor::isReady, function); // } // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothInteractionException.java // public class BluetoothInteractionException extends RuntimeException { // // public BluetoothInteractionException() { } // // public BluetoothInteractionException(String message) { // super(message); // } // // public BluetoothInteractionException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/NotReadyException.java // public class NotReadyException extends RuntimeException { // // /** // * A constructor without message. // */ // public NotReadyException() { // super(); // } // // /** // * A constructor with a message. // * @param message a message // */ // public NotReadyException(String message) { // super(message); // } // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/auth/BluetoothAuthenticationException.java // public class BluetoothAuthenticationException extends RuntimeException { // // public BluetoothAuthenticationException() { } // // public BluetoothAuthenticationException(String message) { // super(message); // } // // public BluetoothAuthenticationException(String message, Throwable cause) { // super(message, cause); // } // // } // Path: src/main/java/org/sputnikdev/bluetooth/manager/impl/CompletableFutureService.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sputnikdev.bluetooth.manager.BluetoothGovernor; import org.sputnikdev.bluetooth.manager.BluetoothInteractionException; import org.sputnikdev.bluetooth.manager.NotReadyException; import org.sputnikdev.bluetooth.manager.auth.BluetoothAuthenticationException; import java.util.Iterator; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.Function; import java.util.function.Predicate; package org.sputnikdev.bluetooth.manager.impl; class CompletableFutureService<G extends BluetoothGovernor> { private Logger logger = LoggerFactory.getLogger(CompletableFutureService.class); private final ConcurrentLinkedQueue<DeferredCompletableFuture<G, ?>> futures = new ConcurrentLinkedQueue<>(); <V> CompletableFuture<V> submit(G governor, Predicate<G> predicate, Function<G, V> function) { DeferredCompletableFuture<G, V> future = new DeferredCompletableFuture<>(predicate, function); try { if (!predicate.test(governor)) { logger.debug("Future is not ready to be completed immediately: {} : {}", governor.getURL(), predicate); futures.add(future); return future; } logger.debug("Trying to complete future immediately: {} : {}", governor.getURL(), predicate); future.complete(function.apply(governor));
} catch (BluetoothInteractionException | NotReadyException | BluetoothAuthenticationException nativeException) {
sputnikdev/bluetooth-manager
src/main/java/org/sputnikdev/bluetooth/manager/impl/CompletableFutureService.java
// Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothGovernor.java // public interface BluetoothGovernor { // // /** // * Returns the URL of the corresponding Bluetooth object. // * @return the URL of the corresponding Bluetooth object // */ // URL getURL(); // // /** // * Checks whether the governor is in state when its corresponding bluetooth object is acquired // * and ready for manipulations. // * @return true if the corresponding bluetooth object is acquired and ready for manipulations // */ // boolean isReady(); // // /** // * Returns type of the corresponding Bluetooth object. // * @return type of the corresponding Bluetooth object // */ // BluetoothObjectType getType(); // // /** // * Returns the date/time of last known successful interaction with the corresponding native object. // * @return the date/time of last known successful interaction with the corresponding native object // */ // Instant getLastInteracted(); // // /** // * An accept method of the visitor pattern to process different bluetooth governors at once. // * @param visitor bluetooth governor visitor // * @throws Exception in case of any error // */ // void accept(BluetoothObjectVisitor visitor) throws Exception; // // /** // * Register a new governor listener. // * @param listener a new governor listener // */ // void addGovernorListener(GovernorListener listener); // // /** // * Unregister a governor listener. // * @param listener a governor listener // */ // void removeGovernorListener(GovernorListener listener); // // // <G extends BluetoothGovernor, V> CompletableFuture<V> when(Predicate<G> condition, Function<G, V> function); // // default <G extends BluetoothGovernor> CompletableFuture<Void> doWhen(Predicate<G> predicate, // Consumer<G> consumer) { // return when(predicate, g -> { // consumer.accept((G) this); // return null; // }); // } // // /** // * Returns a completable future that gets completed when governor becomes ready. // * @param function a function that is invoked when governor becomes ready, the completable future is // * completed with the result of this function // * @param <G> bluetooth governor // * @param <V> returned value // * @return a completable future // */ // default <G extends BluetoothGovernor, V> CompletableFuture<V> whenReady(Function<G, V> function) { // return when(BluetoothGovernor::isReady, function); // } // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothInteractionException.java // public class BluetoothInteractionException extends RuntimeException { // // public BluetoothInteractionException() { } // // public BluetoothInteractionException(String message) { // super(message); // } // // public BluetoothInteractionException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/NotReadyException.java // public class NotReadyException extends RuntimeException { // // /** // * A constructor without message. // */ // public NotReadyException() { // super(); // } // // /** // * A constructor with a message. // * @param message a message // */ // public NotReadyException(String message) { // super(message); // } // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/auth/BluetoothAuthenticationException.java // public class BluetoothAuthenticationException extends RuntimeException { // // public BluetoothAuthenticationException() { } // // public BluetoothAuthenticationException(String message) { // super(message); // } // // public BluetoothAuthenticationException(String message, Throwable cause) { // super(message, cause); // } // // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sputnikdev.bluetooth.manager.BluetoothGovernor; import org.sputnikdev.bluetooth.manager.BluetoothInteractionException; import org.sputnikdev.bluetooth.manager.NotReadyException; import org.sputnikdev.bluetooth.manager.auth.BluetoothAuthenticationException; import java.util.Iterator; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.Function; import java.util.function.Predicate;
package org.sputnikdev.bluetooth.manager.impl; class CompletableFutureService<G extends BluetoothGovernor> { private Logger logger = LoggerFactory.getLogger(CompletableFutureService.class); private final ConcurrentLinkedQueue<DeferredCompletableFuture<G, ?>> futures = new ConcurrentLinkedQueue<>(); <V> CompletableFuture<V> submit(G governor, Predicate<G> predicate, Function<G, V> function) { DeferredCompletableFuture<G, V> future = new DeferredCompletableFuture<>(predicate, function); try { if (!predicate.test(governor)) { logger.debug("Future is not ready to be completed immediately: {} : {}", governor.getURL(), predicate); futures.add(future); return future; } logger.debug("Trying to complete future immediately: {} : {}", governor.getURL(), predicate); future.complete(function.apply(governor));
// Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothGovernor.java // public interface BluetoothGovernor { // // /** // * Returns the URL of the corresponding Bluetooth object. // * @return the URL of the corresponding Bluetooth object // */ // URL getURL(); // // /** // * Checks whether the governor is in state when its corresponding bluetooth object is acquired // * and ready for manipulations. // * @return true if the corresponding bluetooth object is acquired and ready for manipulations // */ // boolean isReady(); // // /** // * Returns type of the corresponding Bluetooth object. // * @return type of the corresponding Bluetooth object // */ // BluetoothObjectType getType(); // // /** // * Returns the date/time of last known successful interaction with the corresponding native object. // * @return the date/time of last known successful interaction with the corresponding native object // */ // Instant getLastInteracted(); // // /** // * An accept method of the visitor pattern to process different bluetooth governors at once. // * @param visitor bluetooth governor visitor // * @throws Exception in case of any error // */ // void accept(BluetoothObjectVisitor visitor) throws Exception; // // /** // * Register a new governor listener. // * @param listener a new governor listener // */ // void addGovernorListener(GovernorListener listener); // // /** // * Unregister a governor listener. // * @param listener a governor listener // */ // void removeGovernorListener(GovernorListener listener); // // // <G extends BluetoothGovernor, V> CompletableFuture<V> when(Predicate<G> condition, Function<G, V> function); // // default <G extends BluetoothGovernor> CompletableFuture<Void> doWhen(Predicate<G> predicate, // Consumer<G> consumer) { // return when(predicate, g -> { // consumer.accept((G) this); // return null; // }); // } // // /** // * Returns a completable future that gets completed when governor becomes ready. // * @param function a function that is invoked when governor becomes ready, the completable future is // * completed with the result of this function // * @param <G> bluetooth governor // * @param <V> returned value // * @return a completable future // */ // default <G extends BluetoothGovernor, V> CompletableFuture<V> whenReady(Function<G, V> function) { // return when(BluetoothGovernor::isReady, function); // } // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothInteractionException.java // public class BluetoothInteractionException extends RuntimeException { // // public BluetoothInteractionException() { } // // public BluetoothInteractionException(String message) { // super(message); // } // // public BluetoothInteractionException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/NotReadyException.java // public class NotReadyException extends RuntimeException { // // /** // * A constructor without message. // */ // public NotReadyException() { // super(); // } // // /** // * A constructor with a message. // * @param message a message // */ // public NotReadyException(String message) { // super(message); // } // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/auth/BluetoothAuthenticationException.java // public class BluetoothAuthenticationException extends RuntimeException { // // public BluetoothAuthenticationException() { } // // public BluetoothAuthenticationException(String message) { // super(message); // } // // public BluetoothAuthenticationException(String message, Throwable cause) { // super(message, cause); // } // // } // Path: src/main/java/org/sputnikdev/bluetooth/manager/impl/CompletableFutureService.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sputnikdev.bluetooth.manager.BluetoothGovernor; import org.sputnikdev.bluetooth.manager.BluetoothInteractionException; import org.sputnikdev.bluetooth.manager.NotReadyException; import org.sputnikdev.bluetooth.manager.auth.BluetoothAuthenticationException; import java.util.Iterator; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.Function; import java.util.function.Predicate; package org.sputnikdev.bluetooth.manager.impl; class CompletableFutureService<G extends BluetoothGovernor> { private Logger logger = LoggerFactory.getLogger(CompletableFutureService.class); private final ConcurrentLinkedQueue<DeferredCompletableFuture<G, ?>> futures = new ConcurrentLinkedQueue<>(); <V> CompletableFuture<V> submit(G governor, Predicate<G> predicate, Function<G, V> function) { DeferredCompletableFuture<G, V> future = new DeferredCompletableFuture<>(predicate, function); try { if (!predicate.test(governor)) { logger.debug("Future is not ready to be completed immediately: {} : {}", governor.getURL(), predicate); futures.add(future); return future; } logger.debug("Trying to complete future immediately: {} : {}", governor.getURL(), predicate); future.complete(function.apply(governor));
} catch (BluetoothInteractionException | NotReadyException | BluetoothAuthenticationException nativeException) {
sputnikdev/bluetooth-manager
src/main/java/org/sputnikdev/bluetooth/manager/impl/CompletableFutureService.java
// Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothGovernor.java // public interface BluetoothGovernor { // // /** // * Returns the URL of the corresponding Bluetooth object. // * @return the URL of the corresponding Bluetooth object // */ // URL getURL(); // // /** // * Checks whether the governor is in state when its corresponding bluetooth object is acquired // * and ready for manipulations. // * @return true if the corresponding bluetooth object is acquired and ready for manipulations // */ // boolean isReady(); // // /** // * Returns type of the corresponding Bluetooth object. // * @return type of the corresponding Bluetooth object // */ // BluetoothObjectType getType(); // // /** // * Returns the date/time of last known successful interaction with the corresponding native object. // * @return the date/time of last known successful interaction with the corresponding native object // */ // Instant getLastInteracted(); // // /** // * An accept method of the visitor pattern to process different bluetooth governors at once. // * @param visitor bluetooth governor visitor // * @throws Exception in case of any error // */ // void accept(BluetoothObjectVisitor visitor) throws Exception; // // /** // * Register a new governor listener. // * @param listener a new governor listener // */ // void addGovernorListener(GovernorListener listener); // // /** // * Unregister a governor listener. // * @param listener a governor listener // */ // void removeGovernorListener(GovernorListener listener); // // // <G extends BluetoothGovernor, V> CompletableFuture<V> when(Predicate<G> condition, Function<G, V> function); // // default <G extends BluetoothGovernor> CompletableFuture<Void> doWhen(Predicate<G> predicate, // Consumer<G> consumer) { // return when(predicate, g -> { // consumer.accept((G) this); // return null; // }); // } // // /** // * Returns a completable future that gets completed when governor becomes ready. // * @param function a function that is invoked when governor becomes ready, the completable future is // * completed with the result of this function // * @param <G> bluetooth governor // * @param <V> returned value // * @return a completable future // */ // default <G extends BluetoothGovernor, V> CompletableFuture<V> whenReady(Function<G, V> function) { // return when(BluetoothGovernor::isReady, function); // } // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothInteractionException.java // public class BluetoothInteractionException extends RuntimeException { // // public BluetoothInteractionException() { } // // public BluetoothInteractionException(String message) { // super(message); // } // // public BluetoothInteractionException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/NotReadyException.java // public class NotReadyException extends RuntimeException { // // /** // * A constructor without message. // */ // public NotReadyException() { // super(); // } // // /** // * A constructor with a message. // * @param message a message // */ // public NotReadyException(String message) { // super(message); // } // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/auth/BluetoothAuthenticationException.java // public class BluetoothAuthenticationException extends RuntimeException { // // public BluetoothAuthenticationException() { } // // public BluetoothAuthenticationException(String message) { // super(message); // } // // public BluetoothAuthenticationException(String message, Throwable cause) { // super(message, cause); // } // // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sputnikdev.bluetooth.manager.BluetoothGovernor; import org.sputnikdev.bluetooth.manager.BluetoothInteractionException; import org.sputnikdev.bluetooth.manager.NotReadyException; import org.sputnikdev.bluetooth.manager.auth.BluetoothAuthenticationException; import java.util.Iterator; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.Function; import java.util.function.Predicate;
package org.sputnikdev.bluetooth.manager.impl; class CompletableFutureService<G extends BluetoothGovernor> { private Logger logger = LoggerFactory.getLogger(CompletableFutureService.class); private final ConcurrentLinkedQueue<DeferredCompletableFuture<G, ?>> futures = new ConcurrentLinkedQueue<>(); <V> CompletableFuture<V> submit(G governor, Predicate<G> predicate, Function<G, V> function) { DeferredCompletableFuture<G, V> future = new DeferredCompletableFuture<>(predicate, function); try { if (!predicate.test(governor)) { logger.debug("Future is not ready to be completed immediately: {} : {}", governor.getURL(), predicate); futures.add(future); return future; } logger.debug("Trying to complete future immediately: {} : {}", governor.getURL(), predicate); future.complete(function.apply(governor));
// Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothGovernor.java // public interface BluetoothGovernor { // // /** // * Returns the URL of the corresponding Bluetooth object. // * @return the URL of the corresponding Bluetooth object // */ // URL getURL(); // // /** // * Checks whether the governor is in state when its corresponding bluetooth object is acquired // * and ready for manipulations. // * @return true if the corresponding bluetooth object is acquired and ready for manipulations // */ // boolean isReady(); // // /** // * Returns type of the corresponding Bluetooth object. // * @return type of the corresponding Bluetooth object // */ // BluetoothObjectType getType(); // // /** // * Returns the date/time of last known successful interaction with the corresponding native object. // * @return the date/time of last known successful interaction with the corresponding native object // */ // Instant getLastInteracted(); // // /** // * An accept method of the visitor pattern to process different bluetooth governors at once. // * @param visitor bluetooth governor visitor // * @throws Exception in case of any error // */ // void accept(BluetoothObjectVisitor visitor) throws Exception; // // /** // * Register a new governor listener. // * @param listener a new governor listener // */ // void addGovernorListener(GovernorListener listener); // // /** // * Unregister a governor listener. // * @param listener a governor listener // */ // void removeGovernorListener(GovernorListener listener); // // // <G extends BluetoothGovernor, V> CompletableFuture<V> when(Predicate<G> condition, Function<G, V> function); // // default <G extends BluetoothGovernor> CompletableFuture<Void> doWhen(Predicate<G> predicate, // Consumer<G> consumer) { // return when(predicate, g -> { // consumer.accept((G) this); // return null; // }); // } // // /** // * Returns a completable future that gets completed when governor becomes ready. // * @param function a function that is invoked when governor becomes ready, the completable future is // * completed with the result of this function // * @param <G> bluetooth governor // * @param <V> returned value // * @return a completable future // */ // default <G extends BluetoothGovernor, V> CompletableFuture<V> whenReady(Function<G, V> function) { // return when(BluetoothGovernor::isReady, function); // } // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/BluetoothInteractionException.java // public class BluetoothInteractionException extends RuntimeException { // // public BluetoothInteractionException() { } // // public BluetoothInteractionException(String message) { // super(message); // } // // public BluetoothInteractionException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/NotReadyException.java // public class NotReadyException extends RuntimeException { // // /** // * A constructor without message. // */ // public NotReadyException() { // super(); // } // // /** // * A constructor with a message. // * @param message a message // */ // public NotReadyException(String message) { // super(message); // } // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/auth/BluetoothAuthenticationException.java // public class BluetoothAuthenticationException extends RuntimeException { // // public BluetoothAuthenticationException() { } // // public BluetoothAuthenticationException(String message) { // super(message); // } // // public BluetoothAuthenticationException(String message, Throwable cause) { // super(message, cause); // } // // } // Path: src/main/java/org/sputnikdev/bluetooth/manager/impl/CompletableFutureService.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sputnikdev.bluetooth.manager.BluetoothGovernor; import org.sputnikdev.bluetooth.manager.BluetoothInteractionException; import org.sputnikdev.bluetooth.manager.NotReadyException; import org.sputnikdev.bluetooth.manager.auth.BluetoothAuthenticationException; import java.util.Iterator; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.Function; import java.util.function.Predicate; package org.sputnikdev.bluetooth.manager.impl; class CompletableFutureService<G extends BluetoothGovernor> { private Logger logger = LoggerFactory.getLogger(CompletableFutureService.class); private final ConcurrentLinkedQueue<DeferredCompletableFuture<G, ?>> futures = new ConcurrentLinkedQueue<>(); <V> CompletableFuture<V> submit(G governor, Predicate<G> predicate, Function<G, V> function) { DeferredCompletableFuture<G, V> future = new DeferredCompletableFuture<>(predicate, function); try { if (!predicate.test(governor)) { logger.debug("Future is not ready to be completed immediately: {} : {}", governor.getURL(), predicate); futures.add(future); return future; } logger.debug("Trying to complete future immediately: {} : {}", governor.getURL(), predicate); future.complete(function.apply(governor));
} catch (BluetoothInteractionException | NotReadyException | BluetoothAuthenticationException nativeException) {
sputnikdev/bluetooth-manager
src/test/java/org/sputnikdev/bluetooth/manager/util/CharacteristicEmulator.java
// Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/Characteristic.java // public interface Characteristic extends BluetoothObject { // // Set<CharacteristicAccessType> getFlags(); // // boolean isNotifying(); // // void disableValueNotifications(); // // byte[] readValue(); // // boolean writeValue(byte[] data); // // void enableValueNotifications(Notification<byte[]> notification); // // boolean isNotificationConfigurable(); // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/CharacteristicAccessType.java // public enum CharacteristicAccessType { // // BROADCAST(0x01), // READ(0x02), // WRITE_WITHOUT_RESPONSE(0x04), // WRITE(0x08), // NOTIFY(0x10), // INDICATE(0x20), // AUTHENTICATED_SIGNED_WRITES(0x40), // EXTENDED_PROPERTIES(0x80); // // int bitField; // // CharacteristicAccessType(int bitField) { // this.bitField = bitField; // } // // public int getBitField() { // return bitField; // } // // public static CharacteristicAccessType fromBitField(int bitField) { // return Stream.of(CharacteristicAccessType.values()) // .filter(c -> c.bitField == bitField) // .findFirst().orElse(null); // } // // public static Set<CharacteristicAccessType> parse(int flags) { // return Stream.of(CharacteristicAccessType.values()) // .filter(c -> (c.bitField & flags) > 0) // .collect(Collectors.toSet()); // } // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/Notification.java // public interface Notification <T> { // // void notify(T value); // // }
import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.sputnikdev.bluetooth.URL; import org.sputnikdev.bluetooth.manager.transport.Characteristic; import org.sputnikdev.bluetooth.manager.transport.CharacteristicAccessType; import org.sputnikdev.bluetooth.manager.transport.Notification; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package org.sputnikdev.bluetooth.manager.util; public class CharacteristicEmulator { private Characteristic characteristic;
// Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/Characteristic.java // public interface Characteristic extends BluetoothObject { // // Set<CharacteristicAccessType> getFlags(); // // boolean isNotifying(); // // void disableValueNotifications(); // // byte[] readValue(); // // boolean writeValue(byte[] data); // // void enableValueNotifications(Notification<byte[]> notification); // // boolean isNotificationConfigurable(); // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/CharacteristicAccessType.java // public enum CharacteristicAccessType { // // BROADCAST(0x01), // READ(0x02), // WRITE_WITHOUT_RESPONSE(0x04), // WRITE(0x08), // NOTIFY(0x10), // INDICATE(0x20), // AUTHENTICATED_SIGNED_WRITES(0x40), // EXTENDED_PROPERTIES(0x80); // // int bitField; // // CharacteristicAccessType(int bitField) { // this.bitField = bitField; // } // // public int getBitField() { // return bitField; // } // // public static CharacteristicAccessType fromBitField(int bitField) { // return Stream.of(CharacteristicAccessType.values()) // .filter(c -> c.bitField == bitField) // .findFirst().orElse(null); // } // // public static Set<CharacteristicAccessType> parse(int flags) { // return Stream.of(CharacteristicAccessType.values()) // .filter(c -> (c.bitField & flags) > 0) // .collect(Collectors.toSet()); // } // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/Notification.java // public interface Notification <T> { // // void notify(T value); // // } // Path: src/test/java/org/sputnikdev/bluetooth/manager/util/CharacteristicEmulator.java import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.sputnikdev.bluetooth.URL; import org.sputnikdev.bluetooth.manager.transport.Characteristic; import org.sputnikdev.bluetooth.manager.transport.CharacteristicAccessType; import org.sputnikdev.bluetooth.manager.transport.Notification; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package org.sputnikdev.bluetooth.manager.util; public class CharacteristicEmulator { private Characteristic characteristic;
private ArgumentCaptor<Notification> valueNotificationCaptor = ArgumentCaptor.forClass(Notification.class);
sputnikdev/bluetooth-manager
src/test/java/org/sputnikdev/bluetooth/manager/util/CharacteristicEmulator.java
// Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/Characteristic.java // public interface Characteristic extends BluetoothObject { // // Set<CharacteristicAccessType> getFlags(); // // boolean isNotifying(); // // void disableValueNotifications(); // // byte[] readValue(); // // boolean writeValue(byte[] data); // // void enableValueNotifications(Notification<byte[]> notification); // // boolean isNotificationConfigurable(); // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/CharacteristicAccessType.java // public enum CharacteristicAccessType { // // BROADCAST(0x01), // READ(0x02), // WRITE_WITHOUT_RESPONSE(0x04), // WRITE(0x08), // NOTIFY(0x10), // INDICATE(0x20), // AUTHENTICATED_SIGNED_WRITES(0x40), // EXTENDED_PROPERTIES(0x80); // // int bitField; // // CharacteristicAccessType(int bitField) { // this.bitField = bitField; // } // // public int getBitField() { // return bitField; // } // // public static CharacteristicAccessType fromBitField(int bitField) { // return Stream.of(CharacteristicAccessType.values()) // .filter(c -> c.bitField == bitField) // .findFirst().orElse(null); // } // // public static Set<CharacteristicAccessType> parse(int flags) { // return Stream.of(CharacteristicAccessType.values()) // .filter(c -> (c.bitField & flags) > 0) // .collect(Collectors.toSet()); // } // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/Notification.java // public interface Notification <T> { // // void notify(T value); // // }
import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.sputnikdev.bluetooth.URL; import org.sputnikdev.bluetooth.manager.transport.Characteristic; import org.sputnikdev.bluetooth.manager.transport.CharacteristicAccessType; import org.sputnikdev.bluetooth.manager.transport.Notification; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package org.sputnikdev.bluetooth.manager.util; public class CharacteristicEmulator { private Characteristic characteristic; private ArgumentCaptor<Notification> valueNotificationCaptor = ArgumentCaptor.forClass(Notification.class);
// Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/Characteristic.java // public interface Characteristic extends BluetoothObject { // // Set<CharacteristicAccessType> getFlags(); // // boolean isNotifying(); // // void disableValueNotifications(); // // byte[] readValue(); // // boolean writeValue(byte[] data); // // void enableValueNotifications(Notification<byte[]> notification); // // boolean isNotificationConfigurable(); // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/CharacteristicAccessType.java // public enum CharacteristicAccessType { // // BROADCAST(0x01), // READ(0x02), // WRITE_WITHOUT_RESPONSE(0x04), // WRITE(0x08), // NOTIFY(0x10), // INDICATE(0x20), // AUTHENTICATED_SIGNED_WRITES(0x40), // EXTENDED_PROPERTIES(0x80); // // int bitField; // // CharacteristicAccessType(int bitField) { // this.bitField = bitField; // } // // public int getBitField() { // return bitField; // } // // public static CharacteristicAccessType fromBitField(int bitField) { // return Stream.of(CharacteristicAccessType.values()) // .filter(c -> c.bitField == bitField) // .findFirst().orElse(null); // } // // public static Set<CharacteristicAccessType> parse(int flags) { // return Stream.of(CharacteristicAccessType.values()) // .filter(c -> (c.bitField & flags) > 0) // .collect(Collectors.toSet()); // } // // } // // Path: src/main/java/org/sputnikdev/bluetooth/manager/transport/Notification.java // public interface Notification <T> { // // void notify(T value); // // } // Path: src/test/java/org/sputnikdev/bluetooth/manager/util/CharacteristicEmulator.java import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.sputnikdev.bluetooth.URL; import org.sputnikdev.bluetooth.manager.transport.Characteristic; import org.sputnikdev.bluetooth.manager.transport.CharacteristicAccessType; import org.sputnikdev.bluetooth.manager.transport.Notification; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package org.sputnikdev.bluetooth.manager.util; public class CharacteristicEmulator { private Characteristic characteristic; private ArgumentCaptor<Notification> valueNotificationCaptor = ArgumentCaptor.forClass(Notification.class);
public CharacteristicEmulator(URL url, CharacteristicAccessType... flags) {
PurePerfect/ferret
src/main/java/com/pureperfect/ferret/vfs/WebFileSystem.java
// Path: src/main/java/com/pureperfect/ferret/ScanException.java // public class ScanException extends RuntimeException // { // private static final long serialVersionUID = 1L; // // /** // * The underlying cause. // * // * @param cause // * The underlying cause // */ // public ScanException(final Throwable cause) // { // super(cause); // } // }
import java.net.MalformedURLException; import java.net.URL; import javax.servlet.ServletContext; import com.pureperfect.ferret.ScanException;
package com.pureperfect.ferret.vfs; /** * An implementation of a lightweight Virtual File System (VFS) appropriate for * scanning in a WAR file / web application. * * @author J. Chris Folsom * @version 1.0 * @since 1.0 * @see FileSystem */ public class WebFileSystem { private static final WebFileSystem singleton = new WebFileSystem(); private WebFileSystem() { // singleton } /** * Get the appropriate virtual web resource. * * @param parent * The parent directory * * @param context * the servlet context for the application * @param path * the path to the folder or file * @return the appropriate virtual resource */ public PathElement getVirtualPath(WebDirectory parent, ServletContext context, String path) { // Directories if (isWebDirectory(context, path)) { return new ImplWebDirectory(parent, context, path); } // Handle Archives as URLs else if (path.endsWith(".jar")) { try { final URL jar = context.getResource(path); return new ImplArchive(parent, jar); } catch (Throwable t) {
// Path: src/main/java/com/pureperfect/ferret/ScanException.java // public class ScanException extends RuntimeException // { // private static final long serialVersionUID = 1L; // // /** // * The underlying cause. // * // * @param cause // * The underlying cause // */ // public ScanException(final Throwable cause) // { // super(cause); // } // } // Path: src/main/java/com/pureperfect/ferret/vfs/WebFileSystem.java import java.net.MalformedURLException; import java.net.URL; import javax.servlet.ServletContext; import com.pureperfect.ferret.ScanException; package com.pureperfect.ferret.vfs; /** * An implementation of a lightweight Virtual File System (VFS) appropriate for * scanning in a WAR file / web application. * * @author J. Chris Folsom * @version 1.0 * @since 1.0 * @see FileSystem */ public class WebFileSystem { private static final WebFileSystem singleton = new WebFileSystem(); private WebFileSystem() { // singleton } /** * Get the appropriate virtual web resource. * * @param parent * The parent directory * * @param context * the servlet context for the application * @param path * the path to the folder or file * @return the appropriate virtual resource */ public PathElement getVirtualPath(WebDirectory parent, ServletContext context, String path) { // Directories if (isWebDirectory(context, path)) { return new ImplWebDirectory(parent, context, path); } // Handle Archives as URLs else if (path.endsWith(".jar")) { try { final URL jar = context.getResource(path); return new ImplArchive(parent, jar); } catch (Throwable t) {
throw new ScanException(t);
PurePerfect/ferret
testdata/wartest/src/main/java/com/pureperfect/ferret/InfoServlet.java
// Path: src/main/java/com/pureperfect/ferret/vfs/PathElement.java // public interface PathElement // { // /** // * Get the parent container for this path. // * // * @return the parent container for this path. // */ // public Container getParent(); // // /** // * Get the name of this path, relative to its parent. // * // * @return the name of this path // */ // public String getName(); // // /** // * Get the full path, which should be unique on the file system. // * // * @return the full path, which should be unique on the file system. // */ // public String getFullPath(); // // /** // * Open a stream to this resource. // * // * @return the input stream to this resource // * @throws IOException // * if an error occurs opening the stream // * @throws UnsupportedOperationException // * if the resource cannot be opened. // */ // public InputStream openStream() throws IOException, // UnsupportedOperationException; // }
import java.io.IOException; import java.io.PrintWriter; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.pureperfect.ferret.vfs.PathElement;
package com.pureperfect.ferret; public class InfoServlet extends HttpServlet { private static final long serialVersionUID = 4612276238009605146L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final PrintWriter out = response.getWriter(); long startTime = System.currentTimeMillis(); out.println("Checking WEB-INF/classes..."); out.println(); WebScanner scanner = new WebScanner(); scanner.add(this.getServletContext(), "/WEB-INF/classes"); ScanFilter allowAll = new ScanFilter() { @Override
// Path: src/main/java/com/pureperfect/ferret/vfs/PathElement.java // public interface PathElement // { // /** // * Get the parent container for this path. // * // * @return the parent container for this path. // */ // public Container getParent(); // // /** // * Get the name of this path, relative to its parent. // * // * @return the name of this path // */ // public String getName(); // // /** // * Get the full path, which should be unique on the file system. // * // * @return the full path, which should be unique on the file system. // */ // public String getFullPath(); // // /** // * Open a stream to this resource. // * // * @return the input stream to this resource // * @throws IOException // * if an error occurs opening the stream // * @throws UnsupportedOperationException // * if the resource cannot be opened. // */ // public InputStream openStream() throws IOException, // UnsupportedOperationException; // } // Path: testdata/wartest/src/main/java/com/pureperfect/ferret/InfoServlet.java import java.io.IOException; import java.io.PrintWriter; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.pureperfect.ferret.vfs.PathElement; package com.pureperfect.ferret; public class InfoServlet extends HttpServlet { private static final long serialVersionUID = 4612276238009605146L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final PrintWriter out = response.getWriter(); long startTime = System.currentTimeMillis(); out.println("Checking WEB-INF/classes..."); out.println(); WebScanner scanner = new WebScanner(); scanner.add(this.getServletContext(), "/WEB-INF/classes"); ScanFilter allowAll = new ScanFilter() { @Override
public boolean accept(PathElement resource)
PurePerfect/ferret
src/main/java/com/pureperfect/ferret/WebScanner.java
// Path: src/main/java/com/pureperfect/ferret/vfs/WebFileSystem.java // public class WebFileSystem // { // private static final WebFileSystem singleton = new WebFileSystem(); // // private WebFileSystem() // { // // singleton // } // // /** // * Get the appropriate virtual web resource. // * // * @param parent // * The parent directory // * // * @param context // * the servlet context for the application // * @param path // * the path to the folder or file // * @return the appropriate virtual resource // */ // public PathElement getVirtualPath(WebDirectory parent, // ServletContext context, String path) // { // // Directories // if (isWebDirectory(context, path)) // { // return new ImplWebDirectory(parent, context, path); // } // // Handle Archives as URLs // else if (path.endsWith(".jar")) // { // try // { // final URL jar = context.getResource(path); // // return new ImplArchive(parent, jar); // } // catch (Throwable t) // { // throw new ScanException(t); // } // } // // Class files // else if (path.endsWith(".class")) // { // return new ImplWebClassFile(parent, context, path); // } // // Plain files // else // { // return new ImplWebFile(parent, context, path); // } // } // // private static boolean isWebDirectory(ServletContext context, String path) // { // /* // * If it ends with a '/' its definitely a directory. However not ending // * with a slash is equally valid (e.g. /WEB-INF/lib). The only way to // * resolve this is to see if the resource actually exists, but does not // * have a stream since directories cannot be streamed. This is a rather // * resource intensive approach, but I don't have a quicker solution at // * the moment for reliably testing whether or not a give path is a // * directory. // */ // try // { // return path.endsWith("/") // || (context.getResource(path) != null && context // .getResourceAsStream(path) == null); // } // catch (MalformedURLException e) // { // throw new ScanException(e); // } // } // // /** // * Get an instance of the file system. // * // * @return an instance of the file system // */ // public static WebFileSystem getInstance() // { // return singleton; // } // }
import java.util.Set; import javax.servlet.ServletContext; import com.pureperfect.ferret.vfs.WebFileSystem;
/** * Add all files outside of WEB-INF/ to the scan path. * * @param context * the servlet context */ public void addPublicResources(final ServletContext context) { Set<String> paths = context.getResourcePaths("/"); for (String path : paths) { // Skip /WEB-INF/ if (!("/WEB-INF/".equals(path))) { add(context, path); } } } /** * Add a file in the WAR to the scan path. * * @param context * The servlet context * @param path * The path to the file */ public void add(ServletContext context, String path) {
// Path: src/main/java/com/pureperfect/ferret/vfs/WebFileSystem.java // public class WebFileSystem // { // private static final WebFileSystem singleton = new WebFileSystem(); // // private WebFileSystem() // { // // singleton // } // // /** // * Get the appropriate virtual web resource. // * // * @param parent // * The parent directory // * // * @param context // * the servlet context for the application // * @param path // * the path to the folder or file // * @return the appropriate virtual resource // */ // public PathElement getVirtualPath(WebDirectory parent, // ServletContext context, String path) // { // // Directories // if (isWebDirectory(context, path)) // { // return new ImplWebDirectory(parent, context, path); // } // // Handle Archives as URLs // else if (path.endsWith(".jar")) // { // try // { // final URL jar = context.getResource(path); // // return new ImplArchive(parent, jar); // } // catch (Throwable t) // { // throw new ScanException(t); // } // } // // Class files // else if (path.endsWith(".class")) // { // return new ImplWebClassFile(parent, context, path); // } // // Plain files // else // { // return new ImplWebFile(parent, context, path); // } // } // // private static boolean isWebDirectory(ServletContext context, String path) // { // /* // * If it ends with a '/' its definitely a directory. However not ending // * with a slash is equally valid (e.g. /WEB-INF/lib). The only way to // * resolve this is to see if the resource actually exists, but does not // * have a stream since directories cannot be streamed. This is a rather // * resource intensive approach, but I don't have a quicker solution at // * the moment for reliably testing whether or not a give path is a // * directory. // */ // try // { // return path.endsWith("/") // || (context.getResource(path) != null && context // .getResourceAsStream(path) == null); // } // catch (MalformedURLException e) // { // throw new ScanException(e); // } // } // // /** // * Get an instance of the file system. // * // * @return an instance of the file system // */ // public static WebFileSystem getInstance() // { // return singleton; // } // } // Path: src/main/java/com/pureperfect/ferret/WebScanner.java import java.util.Set; import javax.servlet.ServletContext; import com.pureperfect.ferret.vfs.WebFileSystem; /** * Add all files outside of WEB-INF/ to the scan path. * * @param context * the servlet context */ public void addPublicResources(final ServletContext context) { Set<String> paths = context.getResourcePaths("/"); for (String path : paths) { // Skip /WEB-INF/ if (!("/WEB-INF/".equals(path))) { add(context, path); } } } /** * Add a file in the WAR to the scan path. * * @param context * The servlet context * @param path * The path to the file */ public void add(ServletContext context, String path) {
super.add(WebFileSystem.getInstance().getVirtualPath(null, context,
PurePerfect/ferret
src/main/java/com/pureperfect/ferret/vfs/FileSystem.java
// Path: src/main/java/com/pureperfect/ferret/ScanException.java // public class ScanException extends RuntimeException // { // private static final long serialVersionUID = 1L; // // /** // * The underlying cause. // * // * @param cause // * The underlying cause // */ // public ScanException(final Throwable cause) // { // super(cause); // } // }
import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.zip.ZipEntry; import com.pureperfect.ferret.ScanException;
* @return an instance of the file system */ public static FileSystem getInstance() { return singleton; } /** * Get the appropriate type of resource for the file. * * @param parent * the parent directory if applicable. This can be null * @param file * the file * @return the virtual resource */ public PathElement getVirtualPath(Directory parent, File file) { if (file.isDirectory()) { return new ImplDirectory(parent, file); } else if (isArchive(file)) { try { return new ImplArchive(parent, file.toURI().toURL()); } catch (MalformedURLException e) {
// Path: src/main/java/com/pureperfect/ferret/ScanException.java // public class ScanException extends RuntimeException // { // private static final long serialVersionUID = 1L; // // /** // * The underlying cause. // * // * @param cause // * The underlying cause // */ // public ScanException(final Throwable cause) // { // super(cause); // } // } // Path: src/main/java/com/pureperfect/ferret/vfs/FileSystem.java import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.zip.ZipEntry; import com.pureperfect.ferret.ScanException; * @return an instance of the file system */ public static FileSystem getInstance() { return singleton; } /** * Get the appropriate type of resource for the file. * * @param parent * the parent directory if applicable. This can be null * @param file * the file * @return the virtual resource */ public PathElement getVirtualPath(Directory parent, File file) { if (file.isDirectory()) { return new ImplDirectory(parent, file); } else if (isArchive(file)) { try { return new ImplArchive(parent, file.toURI().toURL()); } catch (MalformedURLException e) {
throw new ScanException(e);
PurePerfect/ferret
src/test/java/com/pureperfect/ferret/ClasspathScannerTest.java
// Path: src/main/java/com/pureperfect/ferret/vfs/PathElement.java // public interface PathElement // { // /** // * Get the parent container for this path. // * // * @return the parent container for this path. // */ // public Container getParent(); // // /** // * Get the name of this path, relative to its parent. // * // * @return the name of this path // */ // public String getName(); // // /** // * Get the full path, which should be unique on the file system. // * // * @return the full path, which should be unique on the file system. // */ // public String getFullPath(); // // /** // * Open a stream to this resource. // * // * @return the input stream to this resource // * @throws IOException // * if an error occurs opening the stream // * @throws UnsupportedOperationException // * if the resource cannot be opened. // */ // public InputStream openStream() throws IOException, // UnsupportedOperationException; // }
import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Enumeration; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import junit.framework.Assert; import junit.framework.TestCase; import com.pureperfect.ferret.vfs.PathElement;
for (final String expect : expectedSet) { final URL url = new File(expect).toURI().toURL(); expectedURLS.add(url); } Assert.assertEquals(expectedSet.size(), ferret.getScanPath().size()); } public void testAddPaths() throws Exception { // Testing bad path only. Happy path is tested elsewhere final Scanner ferret = new Scanner(); ferret.add("IDONTEXIST"); Assert.assertEquals(0, ferret.getScanPath().size()); } public void testJarLoadFromNetwork() throws Exception { final String url = "https://s3.amazonaws.com/MinecraftDownload/launcher/minecraft.jar"; final Scanner ferret = new Scanner(); ferret.add(new URL(url)); Assert.assertEquals(1, ferret.getScanPath().size());
// Path: src/main/java/com/pureperfect/ferret/vfs/PathElement.java // public interface PathElement // { // /** // * Get the parent container for this path. // * // * @return the parent container for this path. // */ // public Container getParent(); // // /** // * Get the name of this path, relative to its parent. // * // * @return the name of this path // */ // public String getName(); // // /** // * Get the full path, which should be unique on the file system. // * // * @return the full path, which should be unique on the file system. // */ // public String getFullPath(); // // /** // * Open a stream to this resource. // * // * @return the input stream to this resource // * @throws IOException // * if an error occurs opening the stream // * @throws UnsupportedOperationException // * if the resource cannot be opened. // */ // public InputStream openStream() throws IOException, // UnsupportedOperationException; // } // Path: src/test/java/com/pureperfect/ferret/ClasspathScannerTest.java import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Enumeration; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import junit.framework.Assert; import junit.framework.TestCase; import com.pureperfect.ferret.vfs.PathElement; for (final String expect : expectedSet) { final URL url = new File(expect).toURI().toURL(); expectedURLS.add(url); } Assert.assertEquals(expectedSet.size(), ferret.getScanPath().size()); } public void testAddPaths() throws Exception { // Testing bad path only. Happy path is tested elsewhere final Scanner ferret = new Scanner(); ferret.add("IDONTEXIST"); Assert.assertEquals(0, ferret.getScanPath().size()); } public void testJarLoadFromNetwork() throws Exception { final String url = "https://s3.amazonaws.com/MinecraftDownload/launcher/minecraft.jar"; final Scanner ferret = new Scanner(); ferret.add(new URL(url)); Assert.assertEquals(1, ferret.getScanPath().size());
final List<PathElement> filesInJar = new LinkedList<PathElement>();
PurePerfect/ferret
src/main/java/com/pureperfect/ferret/ScanFilter.java
// Path: src/main/java/com/pureperfect/ferret/vfs/PathElement.java // public interface PathElement // { // /** // * Get the parent container for this path. // * // * @return the parent container for this path. // */ // public Container getParent(); // // /** // * Get the name of this path, relative to its parent. // * // * @return the name of this path // */ // public String getName(); // // /** // * Get the full path, which should be unique on the file system. // * // * @return the full path, which should be unique on the file system. // */ // public String getFullPath(); // // /** // * Open a stream to this resource. // * // * @return the input stream to this resource // * @throws IOException // * if an error occurs opening the stream // * @throws UnsupportedOperationException // * if the resource cannot be opened. // */ // public InputStream openStream() throws IOException, // UnsupportedOperationException; // }
import com.pureperfect.ferret.vfs.PathElement;
package com.pureperfect.ferret; /** * Implement this interface to scan. * * @author J. Chris Folsom * @version 1.0 * @since 1.0 */ public interface ScanFilter { /** * Define search criteria for scanning. If this method returns true, the * visited resource will be added to the result set. * * @param resource * The current resource being visited. * * @return whether or not the resource should be included in the scan * results. */
// Path: src/main/java/com/pureperfect/ferret/vfs/PathElement.java // public interface PathElement // { // /** // * Get the parent container for this path. // * // * @return the parent container for this path. // */ // public Container getParent(); // // /** // * Get the name of this path, relative to its parent. // * // * @return the name of this path // */ // public String getName(); // // /** // * Get the full path, which should be unique on the file system. // * // * @return the full path, which should be unique on the file system. // */ // public String getFullPath(); // // /** // * Open a stream to this resource. // * // * @return the input stream to this resource // * @throws IOException // * if an error occurs opening the stream // * @throws UnsupportedOperationException // * if the resource cannot be opened. // */ // public InputStream openStream() throws IOException, // UnsupportedOperationException; // } // Path: src/main/java/com/pureperfect/ferret/ScanFilter.java import com.pureperfect.ferret.vfs.PathElement; package com.pureperfect.ferret; /** * Implement this interface to scan. * * @author J. Chris Folsom * @version 1.0 * @since 1.0 */ public interface ScanFilter { /** * Define search criteria for scanning. If this method returns true, the * visited resource will be added to the result set. * * @param resource * The current resource being visited. * * @return whether or not the resource should be included in the scan * results. */
public boolean accept(PathElement resource);
sunnygoyal/neon-clock-gl
src/com/painless/glclock/spirit/ClockSpirit.java
// Path: src/com/painless/glclock/Grid.java // public final class Grid { // private final FloatBuffer mFloatVertexBuffer; // private final FloatBuffer mFloatTexCoordBuffer; // // private final CharBuffer mIndexBuffer; // // private final int mW; // private final int mH; // private final int mIndexCount; // // public Grid(int vertsAcross, int vertsDown) { // mW = vertsAcross; // mH = vertsDown; // final int size = vertsAcross * vertsDown; // final int FLOAT_SIZE = 4; // final int CHAR_SIZE = 2; // // mFloatVertexBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 3) // .order(ByteOrder.nativeOrder()).asFloatBuffer(); // mFloatTexCoordBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 2) // .order(ByteOrder.nativeOrder()).asFloatBuffer(); // // final int quadW = mW - 1; // final int quadH = mH - 1; // final int quadCount = quadW * quadH; // final int indexCount = quadCount * 6; // mIndexCount = indexCount; // mIndexBuffer = ByteBuffer.allocateDirect(CHAR_SIZE * indexCount) // .order(ByteOrder.nativeOrder()).asCharBuffer(); // // /* // * Initialize triangle list mesh. // * // * [0]-----[ 1] ... // * | / | // * | / | // * | / | // * [w]-----[w+1] ... // * | | // * // */ // // { // int i = 0; // for (int y = 0; y < quadH; y++) { // for (int x = 0; x < quadW; x++) { // final char a = (char) (y * mW + x); // final char b = (char) (y * mW + x + 1); // final char c = (char) ((y + 1) * mW + x); // final char d = (char) ((y + 1) * mW + x + 1); // // mIndexBuffer.put(i++, a); // mIndexBuffer.put(i++, b); // mIndexBuffer.put(i++, c); // // mIndexBuffer.put(i++, b); // mIndexBuffer.put(i++, c); // mIndexBuffer.put(i++, d); // } // } // } // } // // public void set(int i, int j, float x, float y, float z, float u, float v) { // if (i < 0 || i >= mW) { // throw new IllegalArgumentException("i"); // } // if (j < 0 || j >= mH) { // throw new IllegalArgumentException("j"); // } // // final int index = mW * j + i; // // final int posIndex = index * 3; // final int texIndex = index * 2; // // mFloatVertexBuffer.put(posIndex, x); // mFloatVertexBuffer.put(posIndex + 1, y); // mFloatVertexBuffer.put(posIndex + 2, z); // // mFloatTexCoordBuffer.put(texIndex, u); // mFloatTexCoordBuffer.put(texIndex + 1, v); // } // // public void draw(GL10 gl) { // gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFloatVertexBuffer); // // gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mFloatTexCoordBuffer); // // gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount, // GL10.GL_UNSIGNED_SHORT, mIndexBuffer); // } // // public static Grid getSimpleGrid(int width, int height) { // final Grid grid = new Grid(2, 2); // grid.set(0, 0, -width / 2, -height / 2, 0.0f, 0.0f, 1.0f); // grid.set(1, 0, width / 2, -height / 2, 0.0f, 1.0f, 1.0f); // grid.set(0, 1, -width / 2, height / 2, 0.0f, 0.0f, 0.0f); // grid.set(1, 1, width / 2, height / 2, 0.0f, 1.0f, 0.0f); // return grid; // } // }
import java.util.Date; import javax.microedition.khronos.opengles.GL10; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Rect; import com.painless.glclock.Grid; import com.painless.glclock.R;
package com.painless.glclock.spirit; final class ClockSpirit extends MovableSpirit { private static final int[][] DIGIT_CONFIG = new int[][] { new int[]{0, 2, 3, 4, 5, 6}, new int[]{0, 2}, new int[]{5, 0, 1, 6, 3}, new int[]{5, 0, 1, 2, 3}, new int[]{4, 1, 0, 2}, new int[]{5, 4, 1, 2, 3}, new int[]{5, 6, 4, 3, 2, 1}, new int[]{5, 0, 2}, new int[]{0, 1, 2, 3, 4, 5, 6}, new int[]{0, 1, 2, 3, 4, 5} };
// Path: src/com/painless/glclock/Grid.java // public final class Grid { // private final FloatBuffer mFloatVertexBuffer; // private final FloatBuffer mFloatTexCoordBuffer; // // private final CharBuffer mIndexBuffer; // // private final int mW; // private final int mH; // private final int mIndexCount; // // public Grid(int vertsAcross, int vertsDown) { // mW = vertsAcross; // mH = vertsDown; // final int size = vertsAcross * vertsDown; // final int FLOAT_SIZE = 4; // final int CHAR_SIZE = 2; // // mFloatVertexBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 3) // .order(ByteOrder.nativeOrder()).asFloatBuffer(); // mFloatTexCoordBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 2) // .order(ByteOrder.nativeOrder()).asFloatBuffer(); // // final int quadW = mW - 1; // final int quadH = mH - 1; // final int quadCount = quadW * quadH; // final int indexCount = quadCount * 6; // mIndexCount = indexCount; // mIndexBuffer = ByteBuffer.allocateDirect(CHAR_SIZE * indexCount) // .order(ByteOrder.nativeOrder()).asCharBuffer(); // // /* // * Initialize triangle list mesh. // * // * [0]-----[ 1] ... // * | / | // * | / | // * | / | // * [w]-----[w+1] ... // * | | // * // */ // // { // int i = 0; // for (int y = 0; y < quadH; y++) { // for (int x = 0; x < quadW; x++) { // final char a = (char) (y * mW + x); // final char b = (char) (y * mW + x + 1); // final char c = (char) ((y + 1) * mW + x); // final char d = (char) ((y + 1) * mW + x + 1); // // mIndexBuffer.put(i++, a); // mIndexBuffer.put(i++, b); // mIndexBuffer.put(i++, c); // // mIndexBuffer.put(i++, b); // mIndexBuffer.put(i++, c); // mIndexBuffer.put(i++, d); // } // } // } // } // // public void set(int i, int j, float x, float y, float z, float u, float v) { // if (i < 0 || i >= mW) { // throw new IllegalArgumentException("i"); // } // if (j < 0 || j >= mH) { // throw new IllegalArgumentException("j"); // } // // final int index = mW * j + i; // // final int posIndex = index * 3; // final int texIndex = index * 2; // // mFloatVertexBuffer.put(posIndex, x); // mFloatVertexBuffer.put(posIndex + 1, y); // mFloatVertexBuffer.put(posIndex + 2, z); // // mFloatTexCoordBuffer.put(texIndex, u); // mFloatTexCoordBuffer.put(texIndex + 1, v); // } // // public void draw(GL10 gl) { // gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFloatVertexBuffer); // // gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mFloatTexCoordBuffer); // // gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount, // GL10.GL_UNSIGNED_SHORT, mIndexBuffer); // } // // public static Grid getSimpleGrid(int width, int height) { // final Grid grid = new Grid(2, 2); // grid.set(0, 0, -width / 2, -height / 2, 0.0f, 0.0f, 1.0f); // grid.set(1, 0, width / 2, -height / 2, 0.0f, 1.0f, 1.0f); // grid.set(0, 1, -width / 2, height / 2, 0.0f, 0.0f, 0.0f); // grid.set(1, 1, width / 2, height / 2, 0.0f, 1.0f, 0.0f); // return grid; // } // } // Path: src/com/painless/glclock/spirit/ClockSpirit.java import java.util.Date; import javax.microedition.khronos.opengles.GL10; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Rect; import com.painless.glclock.Grid; import com.painless.glclock.R; package com.painless.glclock.spirit; final class ClockSpirit extends MovableSpirit { private static final int[][] DIGIT_CONFIG = new int[][] { new int[]{0, 2, 3, 4, 5, 6}, new int[]{0, 2}, new int[]{5, 0, 1, 6, 3}, new int[]{5, 0, 1, 2, 3}, new int[]{4, 1, 0, 2}, new int[]{5, 4, 1, 2, 3}, new int[]{5, 6, 4, 3, 2, 1}, new int[]{5, 0, 2}, new int[]{0, 1, 2, 3, 4, 5, 6}, new int[]{0, 1, 2, 3, 4, 5} };
private final Grid frameGrid;
sunnygoyal/neon-clock-gl
src/com/painless/glclock/spirit/BackSpirit.java
// Path: src/com/painless/glclock/ColorUtils.java // public class ColorUtils { // // public static Paint getPaintFromColor(int color) { // final float[] array = new float[20]; // array[18] = 1; // array[1] = (float) Color.red(color) / 255; // array[6] = (float) Color.green(color) / 255; // array[11] = (float) Color.blue(color) / 255; // final Paint paint = new Paint(); // paint.setColorFilter(new ColorMatrixColorFilter(array)); // return paint; // } // // public static Bitmap getPaintedBitmap(Bitmap bitmap, Paint paint, boolean deleteOld) { // final Bitmap colorBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig()); // final Canvas c = new Canvas(colorBitmap); // c.drawBitmap(bitmap, 0, 0, paint); // if (deleteOld) { // bitmap.recycle(); // } // return colorBitmap; // } // } // // Path: src/com/painless/glclock/Constants.java // public final class Constants { // // public static final String SHARED_PREFS_NAME = "wallpaperSettings"; // // public static final String BACK1_URL = "back1.jpg"; // public static final String BACK2_URL = "back2.jpg"; // public static final String BACK_NONE = "none"; // public static final String BACK_IMG_CODE = "back"; // public static final String BACK_CCODE = "backcolor"; // // public static final String THEME_CODE = "theme"; // public static final int DEFAULT_THEME = 0xFF4CAF50; // // public static final String TRAILS_COUNT = "trails"; // public static final String TRAILS_CCODE = "tcolor"; // // public static final String WEATHER_DEFAULT = "2,35,94,68"; // public static final String WEATHER_VALUE = "weather_val"; // public static final String LAST_WEATHER_CHECK = "last_weather_check"; // public static final String WEATHER_NIGHT_MODE = "weather_night"; // // public static final String USE_FARENHIET = "weather_fahren"; // // public static final WidgetCode CLOCK = new WidgetCode("clock", "-92,17"); // public static final WidgetCode COMPASS = new WidgetCode("compass", "96,-176"); // public static final WidgetCode BATTERY = new WidgetCode("battery", "155,-48"); // public static final WidgetCode CPU = new WidgetCode("cpu", "113,84"); // public static final WidgetCode RAM = new WidgetCode("ram", "-41,192"); // public static final WidgetCode CALENDAR = new WidgetCode("calendar", "-110,-174"); // public static final WidgetCode WEATHER = new WidgetCode("weather", "125,265"); // // public static final class WidgetCode { // public final String code; // public final String prefix; // // public final String offset; // public final String offsetDefault; // // public final String color; // public final String zoom; // // private WidgetCode(String code, String defaultOffset) { // this.code = code + "Enabled"; // this.offset = code + "Offset"; // this.color = code + "color"; // this.zoom = code + "zoom"; // this.prefix = code + "_"; // // this.offsetDefault = defaultOffset; // } // // public int[] getOffset(SharedPreferences pref) { // final String[] values = pref.getString(offset, offsetDefault).split(","); // // final int[] offsets = new int[2]; // try { // offsets[0] = Integer.valueOf(values[0]); // offsets[1] = Integer.valueOf(values[1]); // } catch (final Exception e) { // offsets[0] = 0; // offsets[1] = 0; // } // return offsets; // } // // public float getZoom(SharedPreferences pref) { // return pref.getFloat(zoom, 1); // } // } // }
import java.io.InputStream; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11Ext; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Paint; import com.painless.glclock.ColorUtils; import com.painless.glclock.Constants; import com.painless.glclock.R;
@Override public int[] getResources() { return new int[] { R.drawable.sample_back }; } @Override public void draw(GL10 gl) { gl.glBindTexture(GL10.GL_TEXTURE_2D, textureNames[0]); ((GL11Ext) gl).glDrawTexfOES(0, 0, 0, width, height); } public void setColor(int color, String type) { if ((this.color == color) && this.type.equals(type)) { return; } this.color = color; this.type = type; shutdown(); } @Override protected void bindBitmap(GL10 gl, Bitmap bitmap, int textureName, boolean onlyAlpha) { super.bindBitmap(gl, getActualBitmap(bitmap), textureName, false); } /** * Returns the actual appliable bitmap. * @param bitmap sample back */ public Bitmap getActualBitmap(Bitmap bitmap) {
// Path: src/com/painless/glclock/ColorUtils.java // public class ColorUtils { // // public static Paint getPaintFromColor(int color) { // final float[] array = new float[20]; // array[18] = 1; // array[1] = (float) Color.red(color) / 255; // array[6] = (float) Color.green(color) / 255; // array[11] = (float) Color.blue(color) / 255; // final Paint paint = new Paint(); // paint.setColorFilter(new ColorMatrixColorFilter(array)); // return paint; // } // // public static Bitmap getPaintedBitmap(Bitmap bitmap, Paint paint, boolean deleteOld) { // final Bitmap colorBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig()); // final Canvas c = new Canvas(colorBitmap); // c.drawBitmap(bitmap, 0, 0, paint); // if (deleteOld) { // bitmap.recycle(); // } // return colorBitmap; // } // } // // Path: src/com/painless/glclock/Constants.java // public final class Constants { // // public static final String SHARED_PREFS_NAME = "wallpaperSettings"; // // public static final String BACK1_URL = "back1.jpg"; // public static final String BACK2_URL = "back2.jpg"; // public static final String BACK_NONE = "none"; // public static final String BACK_IMG_CODE = "back"; // public static final String BACK_CCODE = "backcolor"; // // public static final String THEME_CODE = "theme"; // public static final int DEFAULT_THEME = 0xFF4CAF50; // // public static final String TRAILS_COUNT = "trails"; // public static final String TRAILS_CCODE = "tcolor"; // // public static final String WEATHER_DEFAULT = "2,35,94,68"; // public static final String WEATHER_VALUE = "weather_val"; // public static final String LAST_WEATHER_CHECK = "last_weather_check"; // public static final String WEATHER_NIGHT_MODE = "weather_night"; // // public static final String USE_FARENHIET = "weather_fahren"; // // public static final WidgetCode CLOCK = new WidgetCode("clock", "-92,17"); // public static final WidgetCode COMPASS = new WidgetCode("compass", "96,-176"); // public static final WidgetCode BATTERY = new WidgetCode("battery", "155,-48"); // public static final WidgetCode CPU = new WidgetCode("cpu", "113,84"); // public static final WidgetCode RAM = new WidgetCode("ram", "-41,192"); // public static final WidgetCode CALENDAR = new WidgetCode("calendar", "-110,-174"); // public static final WidgetCode WEATHER = new WidgetCode("weather", "125,265"); // // public static final class WidgetCode { // public final String code; // public final String prefix; // // public final String offset; // public final String offsetDefault; // // public final String color; // public final String zoom; // // private WidgetCode(String code, String defaultOffset) { // this.code = code + "Enabled"; // this.offset = code + "Offset"; // this.color = code + "color"; // this.zoom = code + "zoom"; // this.prefix = code + "_"; // // this.offsetDefault = defaultOffset; // } // // public int[] getOffset(SharedPreferences pref) { // final String[] values = pref.getString(offset, offsetDefault).split(","); // // final int[] offsets = new int[2]; // try { // offsets[0] = Integer.valueOf(values[0]); // offsets[1] = Integer.valueOf(values[1]); // } catch (final Exception e) { // offsets[0] = 0; // offsets[1] = 0; // } // return offsets; // } // // public float getZoom(SharedPreferences pref) { // return pref.getFloat(zoom, 1); // } // } // } // Path: src/com/painless/glclock/spirit/BackSpirit.java import java.io.InputStream; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11Ext; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Paint; import com.painless.glclock.ColorUtils; import com.painless.glclock.Constants; import com.painless.glclock.R; @Override public int[] getResources() { return new int[] { R.drawable.sample_back }; } @Override public void draw(GL10 gl) { gl.glBindTexture(GL10.GL_TEXTURE_2D, textureNames[0]); ((GL11Ext) gl).glDrawTexfOES(0, 0, 0, width, height); } public void setColor(int color, String type) { if ((this.color == color) && this.type.equals(type)) { return; } this.color = color; this.type = type; shutdown(); } @Override protected void bindBitmap(GL10 gl, Bitmap bitmap, int textureName, boolean onlyAlpha) { super.bindBitmap(gl, getActualBitmap(bitmap), textureName, false); } /** * Returns the actual appliable bitmap. * @param bitmap sample back */ public Bitmap getActualBitmap(Bitmap bitmap) {
final Paint paint = ColorUtils.getPaintFromColor(color);
sunnygoyal/neon-clock-gl
src/com/painless/glclock/spirit/BackSpirit.java
// Path: src/com/painless/glclock/ColorUtils.java // public class ColorUtils { // // public static Paint getPaintFromColor(int color) { // final float[] array = new float[20]; // array[18] = 1; // array[1] = (float) Color.red(color) / 255; // array[6] = (float) Color.green(color) / 255; // array[11] = (float) Color.blue(color) / 255; // final Paint paint = new Paint(); // paint.setColorFilter(new ColorMatrixColorFilter(array)); // return paint; // } // // public static Bitmap getPaintedBitmap(Bitmap bitmap, Paint paint, boolean deleteOld) { // final Bitmap colorBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig()); // final Canvas c = new Canvas(colorBitmap); // c.drawBitmap(bitmap, 0, 0, paint); // if (deleteOld) { // bitmap.recycle(); // } // return colorBitmap; // } // } // // Path: src/com/painless/glclock/Constants.java // public final class Constants { // // public static final String SHARED_PREFS_NAME = "wallpaperSettings"; // // public static final String BACK1_URL = "back1.jpg"; // public static final String BACK2_URL = "back2.jpg"; // public static final String BACK_NONE = "none"; // public static final String BACK_IMG_CODE = "back"; // public static final String BACK_CCODE = "backcolor"; // // public static final String THEME_CODE = "theme"; // public static final int DEFAULT_THEME = 0xFF4CAF50; // // public static final String TRAILS_COUNT = "trails"; // public static final String TRAILS_CCODE = "tcolor"; // // public static final String WEATHER_DEFAULT = "2,35,94,68"; // public static final String WEATHER_VALUE = "weather_val"; // public static final String LAST_WEATHER_CHECK = "last_weather_check"; // public static final String WEATHER_NIGHT_MODE = "weather_night"; // // public static final String USE_FARENHIET = "weather_fahren"; // // public static final WidgetCode CLOCK = new WidgetCode("clock", "-92,17"); // public static final WidgetCode COMPASS = new WidgetCode("compass", "96,-176"); // public static final WidgetCode BATTERY = new WidgetCode("battery", "155,-48"); // public static final WidgetCode CPU = new WidgetCode("cpu", "113,84"); // public static final WidgetCode RAM = new WidgetCode("ram", "-41,192"); // public static final WidgetCode CALENDAR = new WidgetCode("calendar", "-110,-174"); // public static final WidgetCode WEATHER = new WidgetCode("weather", "125,265"); // // public static final class WidgetCode { // public final String code; // public final String prefix; // // public final String offset; // public final String offsetDefault; // // public final String color; // public final String zoom; // // private WidgetCode(String code, String defaultOffset) { // this.code = code + "Enabled"; // this.offset = code + "Offset"; // this.color = code + "color"; // this.zoom = code + "zoom"; // this.prefix = code + "_"; // // this.offsetDefault = defaultOffset; // } // // public int[] getOffset(SharedPreferences pref) { // final String[] values = pref.getString(offset, offsetDefault).split(","); // // final int[] offsets = new int[2]; // try { // offsets[0] = Integer.valueOf(values[0]); // offsets[1] = Integer.valueOf(values[1]); // } catch (final Exception e) { // offsets[0] = 0; // offsets[1] = 0; // } // return offsets; // } // // public float getZoom(SharedPreferences pref) { // return pref.getFloat(zoom, 1); // } // } // }
import java.io.InputStream; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11Ext; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Paint; import com.painless.glclock.ColorUtils; import com.painless.glclock.Constants; import com.painless.glclock.R;
public int[] getResources() { return new int[] { R.drawable.sample_back }; } @Override public void draw(GL10 gl) { gl.glBindTexture(GL10.GL_TEXTURE_2D, textureNames[0]); ((GL11Ext) gl).glDrawTexfOES(0, 0, 0, width, height); } public void setColor(int color, String type) { if ((this.color == color) && this.type.equals(type)) { return; } this.color = color; this.type = type; shutdown(); } @Override protected void bindBitmap(GL10 gl, Bitmap bitmap, int textureName, boolean onlyAlpha) { super.bindBitmap(gl, getActualBitmap(bitmap), textureName, false); } /** * Returns the actual appliable bitmap. * @param bitmap sample back */ public Bitmap getActualBitmap(Bitmap bitmap) { final Paint paint = ColorUtils.getPaintFromColor(color);
// Path: src/com/painless/glclock/ColorUtils.java // public class ColorUtils { // // public static Paint getPaintFromColor(int color) { // final float[] array = new float[20]; // array[18] = 1; // array[1] = (float) Color.red(color) / 255; // array[6] = (float) Color.green(color) / 255; // array[11] = (float) Color.blue(color) / 255; // final Paint paint = new Paint(); // paint.setColorFilter(new ColorMatrixColorFilter(array)); // return paint; // } // // public static Bitmap getPaintedBitmap(Bitmap bitmap, Paint paint, boolean deleteOld) { // final Bitmap colorBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig()); // final Canvas c = new Canvas(colorBitmap); // c.drawBitmap(bitmap, 0, 0, paint); // if (deleteOld) { // bitmap.recycle(); // } // return colorBitmap; // } // } // // Path: src/com/painless/glclock/Constants.java // public final class Constants { // // public static final String SHARED_PREFS_NAME = "wallpaperSettings"; // // public static final String BACK1_URL = "back1.jpg"; // public static final String BACK2_URL = "back2.jpg"; // public static final String BACK_NONE = "none"; // public static final String BACK_IMG_CODE = "back"; // public static final String BACK_CCODE = "backcolor"; // // public static final String THEME_CODE = "theme"; // public static final int DEFAULT_THEME = 0xFF4CAF50; // // public static final String TRAILS_COUNT = "trails"; // public static final String TRAILS_CCODE = "tcolor"; // // public static final String WEATHER_DEFAULT = "2,35,94,68"; // public static final String WEATHER_VALUE = "weather_val"; // public static final String LAST_WEATHER_CHECK = "last_weather_check"; // public static final String WEATHER_NIGHT_MODE = "weather_night"; // // public static final String USE_FARENHIET = "weather_fahren"; // // public static final WidgetCode CLOCK = new WidgetCode("clock", "-92,17"); // public static final WidgetCode COMPASS = new WidgetCode("compass", "96,-176"); // public static final WidgetCode BATTERY = new WidgetCode("battery", "155,-48"); // public static final WidgetCode CPU = new WidgetCode("cpu", "113,84"); // public static final WidgetCode RAM = new WidgetCode("ram", "-41,192"); // public static final WidgetCode CALENDAR = new WidgetCode("calendar", "-110,-174"); // public static final WidgetCode WEATHER = new WidgetCode("weather", "125,265"); // // public static final class WidgetCode { // public final String code; // public final String prefix; // // public final String offset; // public final String offsetDefault; // // public final String color; // public final String zoom; // // private WidgetCode(String code, String defaultOffset) { // this.code = code + "Enabled"; // this.offset = code + "Offset"; // this.color = code + "color"; // this.zoom = code + "zoom"; // this.prefix = code + "_"; // // this.offsetDefault = defaultOffset; // } // // public int[] getOffset(SharedPreferences pref) { // final String[] values = pref.getString(offset, offsetDefault).split(","); // // final int[] offsets = new int[2]; // try { // offsets[0] = Integer.valueOf(values[0]); // offsets[1] = Integer.valueOf(values[1]); // } catch (final Exception e) { // offsets[0] = 0; // offsets[1] = 0; // } // return offsets; // } // // public float getZoom(SharedPreferences pref) { // return pref.getFloat(zoom, 1); // } // } // } // Path: src/com/painless/glclock/spirit/BackSpirit.java import java.io.InputStream; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11Ext; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Paint; import com.painless.glclock.ColorUtils; import com.painless.glclock.Constants; import com.painless.glclock.R; public int[] getResources() { return new int[] { R.drawable.sample_back }; } @Override public void draw(GL10 gl) { gl.glBindTexture(GL10.GL_TEXTURE_2D, textureNames[0]); ((GL11Ext) gl).glDrawTexfOES(0, 0, 0, width, height); } public void setColor(int color, String type) { if ((this.color == color) && this.type.equals(type)) { return; } this.color = color; this.type = type; shutdown(); } @Override protected void bindBitmap(GL10 gl, Bitmap bitmap, int textureName, boolean onlyAlpha) { super.bindBitmap(gl, getActualBitmap(bitmap), textureName, false); } /** * Returns the actual appliable bitmap. * @param bitmap sample back */ public Bitmap getActualBitmap(Bitmap bitmap) { final Paint paint = ColorUtils.getPaintFromColor(color);
if (type.equals(Constants.BACK_NONE)) {
sunnygoyal/neon-clock-gl
src/com/painless/glclock/spirit/MovableSpirit.java
// Path: src/com/painless/glclock/service/RService.java // public interface RService { // // public void start(); // // public void stop(); // }
import javax.microedition.khronos.opengles.GL10; import android.content.Context; import android.content.SharedPreferences; import com.painless.glclock.service.RService;
package com.painless.glclock.spirit; abstract class MovableSpirit extends Spirit { private int x, y;
// Path: src/com/painless/glclock/service/RService.java // public interface RService { // // public void start(); // // public void stop(); // } // Path: src/com/painless/glclock/spirit/MovableSpirit.java import javax.microedition.khronos.opengles.GL10; import android.content.Context; import android.content.SharedPreferences; import com.painless.glclock.service.RService; package com.painless.glclock.spirit; abstract class MovableSpirit extends Spirit { private int x, y;
private final RService service;
sunnygoyal/neon-clock-gl
src/com/painless/glclock/service/RamService.java
// Path: src/com/painless/glclock/Globals.java // public class Globals { // // public static float compassRotation = 0; // // public static int cpuUsage = 0; // public static int cpuUsageAngle = 0; // // public static int battery = 0; // public static int batteryCount = 0; // // public static int ramUsage = 0; // }
import android.os.Handler; import com.painless.glclock.Globals; import java.io.RandomAccessFile;
package com.painless.glclock.service; public final class RamService implements Runnable, RService { private static final long REFRESH_RATE = 15000; // 15 seconds. private final Handler updateHandler; private boolean running = false; public RamService() { updateHandler = new Handler(); } @Override public void run() { try { final RandomAccessFile reader = new RandomAccessFile("/proc/meminfo", "r"); long memFree = 0, memTotal = 0; int readCount = 0, foundCount = 0; String line; // read maximum 10 lines and find 3 items. while (readCount < 10 && foundCount < 3) { line = reader.readLine().toLowerCase(); if (line.startsWith("memtotal")) { memTotal = readMemInfo(line); foundCount++; } else if (line.startsWith("memfree") || line.startsWith("cached")) { memFree += readMemInfo(line); foundCount++; } readCount++; } reader.close(); final long percent = 100 - (memFree * 100 / memTotal);
// Path: src/com/painless/glclock/Globals.java // public class Globals { // // public static float compassRotation = 0; // // public static int cpuUsage = 0; // public static int cpuUsageAngle = 0; // // public static int battery = 0; // public static int batteryCount = 0; // // public static int ramUsage = 0; // } // Path: src/com/painless/glclock/service/RamService.java import android.os.Handler; import com.painless.glclock.Globals; import java.io.RandomAccessFile; package com.painless.glclock.service; public final class RamService implements Runnable, RService { private static final long REFRESH_RATE = 15000; // 15 seconds. private final Handler updateHandler; private boolean running = false; public RamService() { updateHandler = new Handler(); } @Override public void run() { try { final RandomAccessFile reader = new RandomAccessFile("/proc/meminfo", "r"); long memFree = 0, memTotal = 0; int readCount = 0, foundCount = 0; String line; // read maximum 10 lines and find 3 items. while (readCount < 10 && foundCount < 3) { line = reader.readLine().toLowerCase(); if (line.startsWith("memtotal")) { memTotal = readMemInfo(line); foundCount++; } else if (line.startsWith("memfree") || line.startsWith("cached")) { memFree += readMemInfo(line); foundCount++; } readCount++; } reader.close(); final long percent = 100 - (memFree * 100 / memTotal);
Globals.ramUsage = (int) percent;
sunnygoyal/neon-clock-gl
src/com/painless/glclock/setting/ColorPicker.java
// Path: src/com/painless/glclock/Constants.java // public final class Constants { // // public static final String SHARED_PREFS_NAME = "wallpaperSettings"; // // public static final String BACK1_URL = "back1.jpg"; // public static final String BACK2_URL = "back2.jpg"; // public static final String BACK_NONE = "none"; // public static final String BACK_IMG_CODE = "back"; // public static final String BACK_CCODE = "backcolor"; // // public static final String THEME_CODE = "theme"; // public static final int DEFAULT_THEME = 0xFF4CAF50; // // public static final String TRAILS_COUNT = "trails"; // public static final String TRAILS_CCODE = "tcolor"; // // public static final String WEATHER_DEFAULT = "2,35,94,68"; // public static final String WEATHER_VALUE = "weather_val"; // public static final String LAST_WEATHER_CHECK = "last_weather_check"; // public static final String WEATHER_NIGHT_MODE = "weather_night"; // // public static final String USE_FARENHIET = "weather_fahren"; // // public static final WidgetCode CLOCK = new WidgetCode("clock", "-92,17"); // public static final WidgetCode COMPASS = new WidgetCode("compass", "96,-176"); // public static final WidgetCode BATTERY = new WidgetCode("battery", "155,-48"); // public static final WidgetCode CPU = new WidgetCode("cpu", "113,84"); // public static final WidgetCode RAM = new WidgetCode("ram", "-41,192"); // public static final WidgetCode CALENDAR = new WidgetCode("calendar", "-110,-174"); // public static final WidgetCode WEATHER = new WidgetCode("weather", "125,265"); // // public static final class WidgetCode { // public final String code; // public final String prefix; // // public final String offset; // public final String offsetDefault; // // public final String color; // public final String zoom; // // private WidgetCode(String code, String defaultOffset) { // this.code = code + "Enabled"; // this.offset = code + "Offset"; // this.color = code + "color"; // this.zoom = code + "zoom"; // this.prefix = code + "_"; // // this.offsetDefault = defaultOffset; // } // // public int[] getOffset(SharedPreferences pref) { // final String[] values = pref.getString(offset, offsetDefault).split(","); // // final int[] offsets = new int[2]; // try { // offsets[0] = Integer.valueOf(values[0]); // offsets[1] = Integer.valueOf(values[1]); // } catch (final Exception e) { // offsets[0] = 0; // offsets[1] = 0; // } // return offsets; // } // // public float getZoom(SharedPreferences pref) { // return pref.getFloat(zoom, 1); // } // } // } // // Path: src/com/painless/glclock/Debug.java // public class Debug { // // private static final String TAG = "ClockGL"; // // public static void log(Object msg) { // Log.e(getTag(), msg + ""); // } // // public static void log(Throwable err) { // Log.e(getTag(), err.getMessage() + " "); // err.printStackTrace(); // } // // private static String getTag() { // boolean startFound = false; // String className = Debug.class.getName(); // // StackTraceElement[] trace = Thread.currentThread().getStackTrace(); // for(StackTraceElement item : trace){ // if (item.getClassName().equals(className)) { // startFound = true; // } else if (startFound) { // return String.format( // "[%s/%s/%s]", item.getFileName(), item.getMethodName(), item.getLineNumber()); // } // } // // return TAG; // } // } // // Path: src/com/painless/glclock/setting/ColorPickerView.java // public interface OnColorChangedListener{ // public void onColorChanged(int color); // }
import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.Toast; import com.painless.glclock.Constants; import com.painless.glclock.Debug; import com.painless.glclock.R; import com.painless.glclock.setting.ColorPickerView.OnColorChangedListener;
package com.painless.glclock.setting; public class ColorPicker extends Activity { private static final int UN_SELECTED = R.drawable.picker1; private static final int SELECTED = R.drawable.picker2; private final OnClickListener sameAsThemeClicked = new OnClickListener() { @Override public void onClick(View v) { if (sameAsTheme.isChecked()) { customColorView.setImageResource(UN_SELECTED); } else { customColorView.setImageResource(SELECTED); } } }; private final OnClickListener customColorClicked = new OnClickListener() { @Override public void onClick(View v) { customColorView.setImageResource(SELECTED); sameAsTheme.setChecked(false); } };
// Path: src/com/painless/glclock/Constants.java // public final class Constants { // // public static final String SHARED_PREFS_NAME = "wallpaperSettings"; // // public static final String BACK1_URL = "back1.jpg"; // public static final String BACK2_URL = "back2.jpg"; // public static final String BACK_NONE = "none"; // public static final String BACK_IMG_CODE = "back"; // public static final String BACK_CCODE = "backcolor"; // // public static final String THEME_CODE = "theme"; // public static final int DEFAULT_THEME = 0xFF4CAF50; // // public static final String TRAILS_COUNT = "trails"; // public static final String TRAILS_CCODE = "tcolor"; // // public static final String WEATHER_DEFAULT = "2,35,94,68"; // public static final String WEATHER_VALUE = "weather_val"; // public static final String LAST_WEATHER_CHECK = "last_weather_check"; // public static final String WEATHER_NIGHT_MODE = "weather_night"; // // public static final String USE_FARENHIET = "weather_fahren"; // // public static final WidgetCode CLOCK = new WidgetCode("clock", "-92,17"); // public static final WidgetCode COMPASS = new WidgetCode("compass", "96,-176"); // public static final WidgetCode BATTERY = new WidgetCode("battery", "155,-48"); // public static final WidgetCode CPU = new WidgetCode("cpu", "113,84"); // public static final WidgetCode RAM = new WidgetCode("ram", "-41,192"); // public static final WidgetCode CALENDAR = new WidgetCode("calendar", "-110,-174"); // public static final WidgetCode WEATHER = new WidgetCode("weather", "125,265"); // // public static final class WidgetCode { // public final String code; // public final String prefix; // // public final String offset; // public final String offsetDefault; // // public final String color; // public final String zoom; // // private WidgetCode(String code, String defaultOffset) { // this.code = code + "Enabled"; // this.offset = code + "Offset"; // this.color = code + "color"; // this.zoom = code + "zoom"; // this.prefix = code + "_"; // // this.offsetDefault = defaultOffset; // } // // public int[] getOffset(SharedPreferences pref) { // final String[] values = pref.getString(offset, offsetDefault).split(","); // // final int[] offsets = new int[2]; // try { // offsets[0] = Integer.valueOf(values[0]); // offsets[1] = Integer.valueOf(values[1]); // } catch (final Exception e) { // offsets[0] = 0; // offsets[1] = 0; // } // return offsets; // } // // public float getZoom(SharedPreferences pref) { // return pref.getFloat(zoom, 1); // } // } // } // // Path: src/com/painless/glclock/Debug.java // public class Debug { // // private static final String TAG = "ClockGL"; // // public static void log(Object msg) { // Log.e(getTag(), msg + ""); // } // // public static void log(Throwable err) { // Log.e(getTag(), err.getMessage() + " "); // err.printStackTrace(); // } // // private static String getTag() { // boolean startFound = false; // String className = Debug.class.getName(); // // StackTraceElement[] trace = Thread.currentThread().getStackTrace(); // for(StackTraceElement item : trace){ // if (item.getClassName().equals(className)) { // startFound = true; // } else if (startFound) { // return String.format( // "[%s/%s/%s]", item.getFileName(), item.getMethodName(), item.getLineNumber()); // } // } // // return TAG; // } // } // // Path: src/com/painless/glclock/setting/ColorPickerView.java // public interface OnColorChangedListener{ // public void onColorChanged(int color); // } // Path: src/com/painless/glclock/setting/ColorPicker.java import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.Toast; import com.painless.glclock.Constants; import com.painless.glclock.Debug; import com.painless.glclock.R; import com.painless.glclock.setting.ColorPickerView.OnColorChangedListener; package com.painless.glclock.setting; public class ColorPicker extends Activity { private static final int UN_SELECTED = R.drawable.picker1; private static final int SELECTED = R.drawable.picker2; private final OnClickListener sameAsThemeClicked = new OnClickListener() { @Override public void onClick(View v) { if (sameAsTheme.isChecked()) { customColorView.setImageResource(UN_SELECTED); } else { customColorView.setImageResource(SELECTED); } } }; private final OnClickListener customColorClicked = new OnClickListener() { @Override public void onClick(View v) { customColorView.setImageResource(SELECTED); sameAsTheme.setChecked(false); } };
private final OnColorChangedListener colorChange = new OnColorChangedListener() {
sunnygoyal/neon-clock-gl
src/com/painless/glclock/setting/ColorPicker.java
// Path: src/com/painless/glclock/Constants.java // public final class Constants { // // public static final String SHARED_PREFS_NAME = "wallpaperSettings"; // // public static final String BACK1_URL = "back1.jpg"; // public static final String BACK2_URL = "back2.jpg"; // public static final String BACK_NONE = "none"; // public static final String BACK_IMG_CODE = "back"; // public static final String BACK_CCODE = "backcolor"; // // public static final String THEME_CODE = "theme"; // public static final int DEFAULT_THEME = 0xFF4CAF50; // // public static final String TRAILS_COUNT = "trails"; // public static final String TRAILS_CCODE = "tcolor"; // // public static final String WEATHER_DEFAULT = "2,35,94,68"; // public static final String WEATHER_VALUE = "weather_val"; // public static final String LAST_WEATHER_CHECK = "last_weather_check"; // public static final String WEATHER_NIGHT_MODE = "weather_night"; // // public static final String USE_FARENHIET = "weather_fahren"; // // public static final WidgetCode CLOCK = new WidgetCode("clock", "-92,17"); // public static final WidgetCode COMPASS = new WidgetCode("compass", "96,-176"); // public static final WidgetCode BATTERY = new WidgetCode("battery", "155,-48"); // public static final WidgetCode CPU = new WidgetCode("cpu", "113,84"); // public static final WidgetCode RAM = new WidgetCode("ram", "-41,192"); // public static final WidgetCode CALENDAR = new WidgetCode("calendar", "-110,-174"); // public static final WidgetCode WEATHER = new WidgetCode("weather", "125,265"); // // public static final class WidgetCode { // public final String code; // public final String prefix; // // public final String offset; // public final String offsetDefault; // // public final String color; // public final String zoom; // // private WidgetCode(String code, String defaultOffset) { // this.code = code + "Enabled"; // this.offset = code + "Offset"; // this.color = code + "color"; // this.zoom = code + "zoom"; // this.prefix = code + "_"; // // this.offsetDefault = defaultOffset; // } // // public int[] getOffset(SharedPreferences pref) { // final String[] values = pref.getString(offset, offsetDefault).split(","); // // final int[] offsets = new int[2]; // try { // offsets[0] = Integer.valueOf(values[0]); // offsets[1] = Integer.valueOf(values[1]); // } catch (final Exception e) { // offsets[0] = 0; // offsets[1] = 0; // } // return offsets; // } // // public float getZoom(SharedPreferences pref) { // return pref.getFloat(zoom, 1); // } // } // } // // Path: src/com/painless/glclock/Debug.java // public class Debug { // // private static final String TAG = "ClockGL"; // // public static void log(Object msg) { // Log.e(getTag(), msg + ""); // } // // public static void log(Throwable err) { // Log.e(getTag(), err.getMessage() + " "); // err.printStackTrace(); // } // // private static String getTag() { // boolean startFound = false; // String className = Debug.class.getName(); // // StackTraceElement[] trace = Thread.currentThread().getStackTrace(); // for(StackTraceElement item : trace){ // if (item.getClassName().equals(className)) { // startFound = true; // } else if (startFound) { // return String.format( // "[%s/%s/%s]", item.getFileName(), item.getMethodName(), item.getLineNumber()); // } // } // // return TAG; // } // } // // Path: src/com/painless/glclock/setting/ColorPickerView.java // public interface OnColorChangedListener{ // public void onColorChanged(int color); // }
import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.Toast; import com.painless.glclock.Constants; import com.painless.glclock.Debug; import com.painless.glclock.R; import com.painless.glclock.setting.ColorPickerView.OnColorChangedListener;
customColorClicked.onClick(null); customColorView.setBackgroundColor(color); } }; private CheckBox sameAsTheme; private ImageView customColorView; private ColorPickerView colorPickerView; SharedPreferences prefs; private String key; private int themeColor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.color_picker); final Bundle bundle = getIntent().getExtras(); setTitle(bundle.getString("title")); sameAsTheme = (CheckBox) findViewById(R.id.sameAsTheme); sameAsTheme.setOnClickListener(sameAsThemeClicked); customColorView = (ImageView) findViewById(R.id.customColorView); customColorView.setOnClickListener(customColorClicked); // Setting the type key = bundle.getString("key");
// Path: src/com/painless/glclock/Constants.java // public final class Constants { // // public static final String SHARED_PREFS_NAME = "wallpaperSettings"; // // public static final String BACK1_URL = "back1.jpg"; // public static final String BACK2_URL = "back2.jpg"; // public static final String BACK_NONE = "none"; // public static final String BACK_IMG_CODE = "back"; // public static final String BACK_CCODE = "backcolor"; // // public static final String THEME_CODE = "theme"; // public static final int DEFAULT_THEME = 0xFF4CAF50; // // public static final String TRAILS_COUNT = "trails"; // public static final String TRAILS_CCODE = "tcolor"; // // public static final String WEATHER_DEFAULT = "2,35,94,68"; // public static final String WEATHER_VALUE = "weather_val"; // public static final String LAST_WEATHER_CHECK = "last_weather_check"; // public static final String WEATHER_NIGHT_MODE = "weather_night"; // // public static final String USE_FARENHIET = "weather_fahren"; // // public static final WidgetCode CLOCK = new WidgetCode("clock", "-92,17"); // public static final WidgetCode COMPASS = new WidgetCode("compass", "96,-176"); // public static final WidgetCode BATTERY = new WidgetCode("battery", "155,-48"); // public static final WidgetCode CPU = new WidgetCode("cpu", "113,84"); // public static final WidgetCode RAM = new WidgetCode("ram", "-41,192"); // public static final WidgetCode CALENDAR = new WidgetCode("calendar", "-110,-174"); // public static final WidgetCode WEATHER = new WidgetCode("weather", "125,265"); // // public static final class WidgetCode { // public final String code; // public final String prefix; // // public final String offset; // public final String offsetDefault; // // public final String color; // public final String zoom; // // private WidgetCode(String code, String defaultOffset) { // this.code = code + "Enabled"; // this.offset = code + "Offset"; // this.color = code + "color"; // this.zoom = code + "zoom"; // this.prefix = code + "_"; // // this.offsetDefault = defaultOffset; // } // // public int[] getOffset(SharedPreferences pref) { // final String[] values = pref.getString(offset, offsetDefault).split(","); // // final int[] offsets = new int[2]; // try { // offsets[0] = Integer.valueOf(values[0]); // offsets[1] = Integer.valueOf(values[1]); // } catch (final Exception e) { // offsets[0] = 0; // offsets[1] = 0; // } // return offsets; // } // // public float getZoom(SharedPreferences pref) { // return pref.getFloat(zoom, 1); // } // } // } // // Path: src/com/painless/glclock/Debug.java // public class Debug { // // private static final String TAG = "ClockGL"; // // public static void log(Object msg) { // Log.e(getTag(), msg + ""); // } // // public static void log(Throwable err) { // Log.e(getTag(), err.getMessage() + " "); // err.printStackTrace(); // } // // private static String getTag() { // boolean startFound = false; // String className = Debug.class.getName(); // // StackTraceElement[] trace = Thread.currentThread().getStackTrace(); // for(StackTraceElement item : trace){ // if (item.getClassName().equals(className)) { // startFound = true; // } else if (startFound) { // return String.format( // "[%s/%s/%s]", item.getFileName(), item.getMethodName(), item.getLineNumber()); // } // } // // return TAG; // } // } // // Path: src/com/painless/glclock/setting/ColorPickerView.java // public interface OnColorChangedListener{ // public void onColorChanged(int color); // } // Path: src/com/painless/glclock/setting/ColorPicker.java import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.Toast; import com.painless.glclock.Constants; import com.painless.glclock.Debug; import com.painless.glclock.R; import com.painless.glclock.setting.ColorPickerView.OnColorChangedListener; customColorClicked.onClick(null); customColorView.setBackgroundColor(color); } }; private CheckBox sameAsTheme; private ImageView customColorView; private ColorPickerView colorPickerView; SharedPreferences prefs; private String key; private int themeColor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.color_picker); final Bundle bundle = getIntent().getExtras(); setTitle(bundle.getString("title")); sameAsTheme = (CheckBox) findViewById(R.id.sameAsTheme); sameAsTheme.setOnClickListener(sameAsThemeClicked); customColorView = (ImageView) findViewById(R.id.customColorView); customColorView.setOnClickListener(customColorClicked); // Setting the type key = bundle.getString("key");
Debug.log("Color picker key : " + key);
sunnygoyal/neon-clock-gl
src/com/painless/glclock/setting/ColorPicker.java
// Path: src/com/painless/glclock/Constants.java // public final class Constants { // // public static final String SHARED_PREFS_NAME = "wallpaperSettings"; // // public static final String BACK1_URL = "back1.jpg"; // public static final String BACK2_URL = "back2.jpg"; // public static final String BACK_NONE = "none"; // public static final String BACK_IMG_CODE = "back"; // public static final String BACK_CCODE = "backcolor"; // // public static final String THEME_CODE = "theme"; // public static final int DEFAULT_THEME = 0xFF4CAF50; // // public static final String TRAILS_COUNT = "trails"; // public static final String TRAILS_CCODE = "tcolor"; // // public static final String WEATHER_DEFAULT = "2,35,94,68"; // public static final String WEATHER_VALUE = "weather_val"; // public static final String LAST_WEATHER_CHECK = "last_weather_check"; // public static final String WEATHER_NIGHT_MODE = "weather_night"; // // public static final String USE_FARENHIET = "weather_fahren"; // // public static final WidgetCode CLOCK = new WidgetCode("clock", "-92,17"); // public static final WidgetCode COMPASS = new WidgetCode("compass", "96,-176"); // public static final WidgetCode BATTERY = new WidgetCode("battery", "155,-48"); // public static final WidgetCode CPU = new WidgetCode("cpu", "113,84"); // public static final WidgetCode RAM = new WidgetCode("ram", "-41,192"); // public static final WidgetCode CALENDAR = new WidgetCode("calendar", "-110,-174"); // public static final WidgetCode WEATHER = new WidgetCode("weather", "125,265"); // // public static final class WidgetCode { // public final String code; // public final String prefix; // // public final String offset; // public final String offsetDefault; // // public final String color; // public final String zoom; // // private WidgetCode(String code, String defaultOffset) { // this.code = code + "Enabled"; // this.offset = code + "Offset"; // this.color = code + "color"; // this.zoom = code + "zoom"; // this.prefix = code + "_"; // // this.offsetDefault = defaultOffset; // } // // public int[] getOffset(SharedPreferences pref) { // final String[] values = pref.getString(offset, offsetDefault).split(","); // // final int[] offsets = new int[2]; // try { // offsets[0] = Integer.valueOf(values[0]); // offsets[1] = Integer.valueOf(values[1]); // } catch (final Exception e) { // offsets[0] = 0; // offsets[1] = 0; // } // return offsets; // } // // public float getZoom(SharedPreferences pref) { // return pref.getFloat(zoom, 1); // } // } // } // // Path: src/com/painless/glclock/Debug.java // public class Debug { // // private static final String TAG = "ClockGL"; // // public static void log(Object msg) { // Log.e(getTag(), msg + ""); // } // // public static void log(Throwable err) { // Log.e(getTag(), err.getMessage() + " "); // err.printStackTrace(); // } // // private static String getTag() { // boolean startFound = false; // String className = Debug.class.getName(); // // StackTraceElement[] trace = Thread.currentThread().getStackTrace(); // for(StackTraceElement item : trace){ // if (item.getClassName().equals(className)) { // startFound = true; // } else if (startFound) { // return String.format( // "[%s/%s/%s]", item.getFileName(), item.getMethodName(), item.getLineNumber()); // } // } // // return TAG; // } // } // // Path: src/com/painless/glclock/setting/ColorPickerView.java // public interface OnColorChangedListener{ // public void onColorChanged(int color); // }
import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.Toast; import com.painless.glclock.Constants; import com.painless.glclock.Debug; import com.painless.glclock.R; import com.painless.glclock.setting.ColorPickerView.OnColorChangedListener;
customColorView.setBackgroundColor(color); } }; private CheckBox sameAsTheme; private ImageView customColorView; private ColorPickerView colorPickerView; SharedPreferences prefs; private String key; private int themeColor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.color_picker); final Bundle bundle = getIntent().getExtras(); setTitle(bundle.getString("title")); sameAsTheme = (CheckBox) findViewById(R.id.sameAsTheme); sameAsTheme.setOnClickListener(sameAsThemeClicked); customColorView = (ImageView) findViewById(R.id.customColorView); customColorView.setOnClickListener(customColorClicked); // Setting the type key = bundle.getString("key"); Debug.log("Color picker key : " + key);
// Path: src/com/painless/glclock/Constants.java // public final class Constants { // // public static final String SHARED_PREFS_NAME = "wallpaperSettings"; // // public static final String BACK1_URL = "back1.jpg"; // public static final String BACK2_URL = "back2.jpg"; // public static final String BACK_NONE = "none"; // public static final String BACK_IMG_CODE = "back"; // public static final String BACK_CCODE = "backcolor"; // // public static final String THEME_CODE = "theme"; // public static final int DEFAULT_THEME = 0xFF4CAF50; // // public static final String TRAILS_COUNT = "trails"; // public static final String TRAILS_CCODE = "tcolor"; // // public static final String WEATHER_DEFAULT = "2,35,94,68"; // public static final String WEATHER_VALUE = "weather_val"; // public static final String LAST_WEATHER_CHECK = "last_weather_check"; // public static final String WEATHER_NIGHT_MODE = "weather_night"; // // public static final String USE_FARENHIET = "weather_fahren"; // // public static final WidgetCode CLOCK = new WidgetCode("clock", "-92,17"); // public static final WidgetCode COMPASS = new WidgetCode("compass", "96,-176"); // public static final WidgetCode BATTERY = new WidgetCode("battery", "155,-48"); // public static final WidgetCode CPU = new WidgetCode("cpu", "113,84"); // public static final WidgetCode RAM = new WidgetCode("ram", "-41,192"); // public static final WidgetCode CALENDAR = new WidgetCode("calendar", "-110,-174"); // public static final WidgetCode WEATHER = new WidgetCode("weather", "125,265"); // // public static final class WidgetCode { // public final String code; // public final String prefix; // // public final String offset; // public final String offsetDefault; // // public final String color; // public final String zoom; // // private WidgetCode(String code, String defaultOffset) { // this.code = code + "Enabled"; // this.offset = code + "Offset"; // this.color = code + "color"; // this.zoom = code + "zoom"; // this.prefix = code + "_"; // // this.offsetDefault = defaultOffset; // } // // public int[] getOffset(SharedPreferences pref) { // final String[] values = pref.getString(offset, offsetDefault).split(","); // // final int[] offsets = new int[2]; // try { // offsets[0] = Integer.valueOf(values[0]); // offsets[1] = Integer.valueOf(values[1]); // } catch (final Exception e) { // offsets[0] = 0; // offsets[1] = 0; // } // return offsets; // } // // public float getZoom(SharedPreferences pref) { // return pref.getFloat(zoom, 1); // } // } // } // // Path: src/com/painless/glclock/Debug.java // public class Debug { // // private static final String TAG = "ClockGL"; // // public static void log(Object msg) { // Log.e(getTag(), msg + ""); // } // // public static void log(Throwable err) { // Log.e(getTag(), err.getMessage() + " "); // err.printStackTrace(); // } // // private static String getTag() { // boolean startFound = false; // String className = Debug.class.getName(); // // StackTraceElement[] trace = Thread.currentThread().getStackTrace(); // for(StackTraceElement item : trace){ // if (item.getClassName().equals(className)) { // startFound = true; // } else if (startFound) { // return String.format( // "[%s/%s/%s]", item.getFileName(), item.getMethodName(), item.getLineNumber()); // } // } // // return TAG; // } // } // // Path: src/com/painless/glclock/setting/ColorPickerView.java // public interface OnColorChangedListener{ // public void onColorChanged(int color); // } // Path: src/com/painless/glclock/setting/ColorPicker.java import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.Toast; import com.painless.glclock.Constants; import com.painless.glclock.Debug; import com.painless.glclock.R; import com.painless.glclock.setting.ColorPickerView.OnColorChangedListener; customColorView.setBackgroundColor(color); } }; private CheckBox sameAsTheme; private ImageView customColorView; private ColorPickerView colorPickerView; SharedPreferences prefs; private String key; private int themeColor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.color_picker); final Bundle bundle = getIntent().getExtras(); setTitle(bundle.getString("title")); sameAsTheme = (CheckBox) findViewById(R.id.sameAsTheme); sameAsTheme.setOnClickListener(sameAsThemeClicked); customColorView = (ImageView) findViewById(R.id.customColorView); customColorView.setOnClickListener(customColorClicked); // Setting the type key = bundle.getString("key"); Debug.log("Color picker key : " + key);
prefs = getSharedPreferences(Constants.SHARED_PREFS_NAME, 0);
sunnygoyal/neon-clock-gl
src/com/painless/glclock/service/CompassService.java
// Path: src/com/painless/glclock/Globals.java // public class Globals { // // public static float compassRotation = 0; // // public static int cpuUsage = 0; // public static int cpuUsageAngle = 0; // // public static int battery = 0; // public static int batteryCount = 0; // // public static int ramUsage = 0; // }
import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import com.painless.glclock.Globals;
package com.painless.glclock.service; public final class CompassService implements RService, SensorEventListener { private final SensorManager manager; public CompassService(Context context) { this.manager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); } @Override public void start() { Sensor s = manager.getDefaultSensor(Sensor.TYPE_ORIENTATION); manager.registerListener(this, s, SensorManager.SENSOR_DELAY_NORMAL); // Debug.log("CompassService started"); } @Override public void stop() { manager.unregisterListener(this); // Debug.log("CompassService stopped"); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } @Override public void onSensorChanged(SensorEvent event) {
// Path: src/com/painless/glclock/Globals.java // public class Globals { // // public static float compassRotation = 0; // // public static int cpuUsage = 0; // public static int cpuUsageAngle = 0; // // public static int battery = 0; // public static int batteryCount = 0; // // public static int ramUsage = 0; // } // Path: src/com/painless/glclock/service/CompassService.java import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import com.painless.glclock.Globals; package com.painless.glclock.service; public final class CompassService implements RService, SensorEventListener { private final SensorManager manager; public CompassService(Context context) { this.manager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); } @Override public void start() { Sensor s = manager.getDefaultSensor(Sensor.TYPE_ORIENTATION); manager.registerListener(this, s, SensorManager.SENSOR_DELAY_NORMAL); // Debug.log("CompassService started"); } @Override public void stop() { manager.unregisterListener(this); // Debug.log("CompassService stopped"); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } @Override public void onSensorChanged(SensorEvent event) {
Globals.compassRotation = event.values[0];
sunnygoyal/neon-clock-gl
src/com/painless/glclock/GLWallpaperService.java
// Path: src/com/painless/glclock/GLWallpaperService.java // public static class ComponentSizeChooser extends BaseConfigChooser { // public ComponentSizeChooser(int redSize, int greenSize, int blueSize, int alphaSize, int depthSize, // int stencilSize) { // super(new int[] { EGL10.EGL_RED_SIZE, redSize, EGL10.EGL_GREEN_SIZE, greenSize, EGL10.EGL_BLUE_SIZE, // blueSize, EGL10.EGL_ALPHA_SIZE, alphaSize, EGL10.EGL_DEPTH_SIZE, depthSize, EGL10.EGL_STENCIL_SIZE, // stencilSize, EGL10.EGL_NONE }); // mValue = new int[1]; // mRedSize = redSize; // mGreenSize = greenSize; // mBlueSize = blueSize; // mAlphaSize = alphaSize; // mDepthSize = depthSize; // mStencilSize = stencilSize; // } // // @Override // public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, EGLConfig[] configs) { // EGLConfig closestConfig = null; // int closestDistance = 1000; // for (final EGLConfig config : configs) { // final int d = findConfigAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0); // final int s = findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0); // if (d >= mDepthSize && s >= mStencilSize) { // final int r = findConfigAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0); // final int g = findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0); // final int b = findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0); // final int a = findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0); // final int distance = Math.abs(r - mRedSize) + Math.abs(g - mGreenSize) + Math.abs(b - mBlueSize) // + Math.abs(a - mAlphaSize); // if (distance < closestDistance) { // closestDistance = distance; // closestConfig = config; // } // } // } // return closestConfig; // } // // private int findConfigAttrib(EGL10 egl, EGLDisplay display, EGLConfig config, int attribute, int defaultValue) { // // if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) { // return mValue[0]; // } // return defaultValue; // } // // private final int[] mValue; // // Subclasses can adjust these values: // protected int mRedSize; // protected int mGreenSize; // protected int mBlueSize; // protected int mAlphaSize; // protected int mDepthSize; // protected int mStencilSize; // } // // Path: src/com/painless/glclock/GLWallpaperService.java // public static class SimpleEGLConfigChooser extends ComponentSizeChooser { // public SimpleEGLConfigChooser(boolean withDepthBuffer) { // super(4, 4, 4, 0, withDepthBuffer ? 16 : 0, 0); // // Adjust target values. This way we'll accept a 4444 or // // 555 buffer if there's no 565 buffer available. // mRedSize = 5; // mGreenSize = 6; // mBlueSize = 5; // } // }
import java.io.Writer; import java.util.ArrayList; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; import android.service.wallpaper.WallpaperService; import android.view.SurfaceHolder; import com.painless.glclock.BaseConfigChooser.ComponentSizeChooser; import com.painless.glclock.BaseConfigChooser.SimpleEGLConfigChooser;
Debug.log("onSurfaceCreated()"); mGLThread.surfaceCreated(holder); super.onSurfaceCreated(holder); } @Override public void onSurfaceDestroyed(SurfaceHolder holder) { Debug.log("onSurfaceDestroyed()"); mGLThread.surfaceDestroyed(); super.onSurfaceDestroyed(holder); } /** * An EGL helper class. */ public void setGLWrapper(GLWrapper glWrapper) { mGLWrapper = glWrapper; } public void setDebugFlags(int debugFlags) { mDebugFlags = debugFlags; } public int getDebugFlags() { return mDebugFlags; } public void setRenderer(Renderer renderer) { checkRenderThreadState(); if (mEGLConfigChooser == null) {
// Path: src/com/painless/glclock/GLWallpaperService.java // public static class ComponentSizeChooser extends BaseConfigChooser { // public ComponentSizeChooser(int redSize, int greenSize, int blueSize, int alphaSize, int depthSize, // int stencilSize) { // super(new int[] { EGL10.EGL_RED_SIZE, redSize, EGL10.EGL_GREEN_SIZE, greenSize, EGL10.EGL_BLUE_SIZE, // blueSize, EGL10.EGL_ALPHA_SIZE, alphaSize, EGL10.EGL_DEPTH_SIZE, depthSize, EGL10.EGL_STENCIL_SIZE, // stencilSize, EGL10.EGL_NONE }); // mValue = new int[1]; // mRedSize = redSize; // mGreenSize = greenSize; // mBlueSize = blueSize; // mAlphaSize = alphaSize; // mDepthSize = depthSize; // mStencilSize = stencilSize; // } // // @Override // public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, EGLConfig[] configs) { // EGLConfig closestConfig = null; // int closestDistance = 1000; // for (final EGLConfig config : configs) { // final int d = findConfigAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0); // final int s = findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0); // if (d >= mDepthSize && s >= mStencilSize) { // final int r = findConfigAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0); // final int g = findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0); // final int b = findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0); // final int a = findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0); // final int distance = Math.abs(r - mRedSize) + Math.abs(g - mGreenSize) + Math.abs(b - mBlueSize) // + Math.abs(a - mAlphaSize); // if (distance < closestDistance) { // closestDistance = distance; // closestConfig = config; // } // } // } // return closestConfig; // } // // private int findConfigAttrib(EGL10 egl, EGLDisplay display, EGLConfig config, int attribute, int defaultValue) { // // if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) { // return mValue[0]; // } // return defaultValue; // } // // private final int[] mValue; // // Subclasses can adjust these values: // protected int mRedSize; // protected int mGreenSize; // protected int mBlueSize; // protected int mAlphaSize; // protected int mDepthSize; // protected int mStencilSize; // } // // Path: src/com/painless/glclock/GLWallpaperService.java // public static class SimpleEGLConfigChooser extends ComponentSizeChooser { // public SimpleEGLConfigChooser(boolean withDepthBuffer) { // super(4, 4, 4, 0, withDepthBuffer ? 16 : 0, 0); // // Adjust target values. This way we'll accept a 4444 or // // 555 buffer if there's no 565 buffer available. // mRedSize = 5; // mGreenSize = 6; // mBlueSize = 5; // } // } // Path: src/com/painless/glclock/GLWallpaperService.java import java.io.Writer; import java.util.ArrayList; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; import android.service.wallpaper.WallpaperService; import android.view.SurfaceHolder; import com.painless.glclock.BaseConfigChooser.ComponentSizeChooser; import com.painless.glclock.BaseConfigChooser.SimpleEGLConfigChooser; Debug.log("onSurfaceCreated()"); mGLThread.surfaceCreated(holder); super.onSurfaceCreated(holder); } @Override public void onSurfaceDestroyed(SurfaceHolder holder) { Debug.log("onSurfaceDestroyed()"); mGLThread.surfaceDestroyed(); super.onSurfaceDestroyed(holder); } /** * An EGL helper class. */ public void setGLWrapper(GLWrapper glWrapper) { mGLWrapper = glWrapper; } public void setDebugFlags(int debugFlags) { mDebugFlags = debugFlags; } public int getDebugFlags() { return mDebugFlags; } public void setRenderer(Renderer renderer) { checkRenderThreadState(); if (mEGLConfigChooser == null) {
mEGLConfigChooser = new SimpleEGLConfigChooser(true);
sunnygoyal/neon-clock-gl
src/com/painless/glclock/GLWallpaperService.java
// Path: src/com/painless/glclock/GLWallpaperService.java // public static class ComponentSizeChooser extends BaseConfigChooser { // public ComponentSizeChooser(int redSize, int greenSize, int blueSize, int alphaSize, int depthSize, // int stencilSize) { // super(new int[] { EGL10.EGL_RED_SIZE, redSize, EGL10.EGL_GREEN_SIZE, greenSize, EGL10.EGL_BLUE_SIZE, // blueSize, EGL10.EGL_ALPHA_SIZE, alphaSize, EGL10.EGL_DEPTH_SIZE, depthSize, EGL10.EGL_STENCIL_SIZE, // stencilSize, EGL10.EGL_NONE }); // mValue = new int[1]; // mRedSize = redSize; // mGreenSize = greenSize; // mBlueSize = blueSize; // mAlphaSize = alphaSize; // mDepthSize = depthSize; // mStencilSize = stencilSize; // } // // @Override // public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, EGLConfig[] configs) { // EGLConfig closestConfig = null; // int closestDistance = 1000; // for (final EGLConfig config : configs) { // final int d = findConfigAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0); // final int s = findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0); // if (d >= mDepthSize && s >= mStencilSize) { // final int r = findConfigAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0); // final int g = findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0); // final int b = findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0); // final int a = findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0); // final int distance = Math.abs(r - mRedSize) + Math.abs(g - mGreenSize) + Math.abs(b - mBlueSize) // + Math.abs(a - mAlphaSize); // if (distance < closestDistance) { // closestDistance = distance; // closestConfig = config; // } // } // } // return closestConfig; // } // // private int findConfigAttrib(EGL10 egl, EGLDisplay display, EGLConfig config, int attribute, int defaultValue) { // // if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) { // return mValue[0]; // } // return defaultValue; // } // // private final int[] mValue; // // Subclasses can adjust these values: // protected int mRedSize; // protected int mGreenSize; // protected int mBlueSize; // protected int mAlphaSize; // protected int mDepthSize; // protected int mStencilSize; // } // // Path: src/com/painless/glclock/GLWallpaperService.java // public static class SimpleEGLConfigChooser extends ComponentSizeChooser { // public SimpleEGLConfigChooser(boolean withDepthBuffer) { // super(4, 4, 4, 0, withDepthBuffer ? 16 : 0, 0); // // Adjust target values. This way we'll accept a 4444 or // // 555 buffer if there's no 565 buffer available. // mRedSize = 5; // mGreenSize = 6; // mBlueSize = 5; // } // }
import java.io.Writer; import java.util.ArrayList; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; import android.service.wallpaper.WallpaperService; import android.view.SurfaceHolder; import com.painless.glclock.BaseConfigChooser.ComponentSizeChooser; import com.painless.glclock.BaseConfigChooser.SimpleEGLConfigChooser;
mEGLContextFactory = new DefaultContextFactory(); } if (mEGLWindowSurfaceFactory == null) { mEGLWindowSurfaceFactory = new DefaultWindowSurfaceFactory(); } mGLThread = new GLThread(renderer, mEGLConfigChooser, mEGLContextFactory, mEGLWindowSurfaceFactory, mGLWrapper); mGLThread.start(); } public void setEGLContextFactory(EGLContextFactory factory) { checkRenderThreadState(); mEGLContextFactory = factory; } public void setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory factory) { checkRenderThreadState(); mEGLWindowSurfaceFactory = factory; } public void setEGLConfigChooser(EGLConfigChooser configChooser) { checkRenderThreadState(); mEGLConfigChooser = configChooser; } public void setEGLConfigChooser(boolean needDepth) { setEGLConfigChooser(new SimpleEGLConfigChooser(needDepth)); } public void setEGLConfigChooser(int redSize, int greenSize, int blueSize, int alphaSize, int depthSize, int stencilSize) {
// Path: src/com/painless/glclock/GLWallpaperService.java // public static class ComponentSizeChooser extends BaseConfigChooser { // public ComponentSizeChooser(int redSize, int greenSize, int blueSize, int alphaSize, int depthSize, // int stencilSize) { // super(new int[] { EGL10.EGL_RED_SIZE, redSize, EGL10.EGL_GREEN_SIZE, greenSize, EGL10.EGL_BLUE_SIZE, // blueSize, EGL10.EGL_ALPHA_SIZE, alphaSize, EGL10.EGL_DEPTH_SIZE, depthSize, EGL10.EGL_STENCIL_SIZE, // stencilSize, EGL10.EGL_NONE }); // mValue = new int[1]; // mRedSize = redSize; // mGreenSize = greenSize; // mBlueSize = blueSize; // mAlphaSize = alphaSize; // mDepthSize = depthSize; // mStencilSize = stencilSize; // } // // @Override // public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, EGLConfig[] configs) { // EGLConfig closestConfig = null; // int closestDistance = 1000; // for (final EGLConfig config : configs) { // final int d = findConfigAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0); // final int s = findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0); // if (d >= mDepthSize && s >= mStencilSize) { // final int r = findConfigAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0); // final int g = findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0); // final int b = findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0); // final int a = findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0); // final int distance = Math.abs(r - mRedSize) + Math.abs(g - mGreenSize) + Math.abs(b - mBlueSize) // + Math.abs(a - mAlphaSize); // if (distance < closestDistance) { // closestDistance = distance; // closestConfig = config; // } // } // } // return closestConfig; // } // // private int findConfigAttrib(EGL10 egl, EGLDisplay display, EGLConfig config, int attribute, int defaultValue) { // // if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) { // return mValue[0]; // } // return defaultValue; // } // // private final int[] mValue; // // Subclasses can adjust these values: // protected int mRedSize; // protected int mGreenSize; // protected int mBlueSize; // protected int mAlphaSize; // protected int mDepthSize; // protected int mStencilSize; // } // // Path: src/com/painless/glclock/GLWallpaperService.java // public static class SimpleEGLConfigChooser extends ComponentSizeChooser { // public SimpleEGLConfigChooser(boolean withDepthBuffer) { // super(4, 4, 4, 0, withDepthBuffer ? 16 : 0, 0); // // Adjust target values. This way we'll accept a 4444 or // // 555 buffer if there's no 565 buffer available. // mRedSize = 5; // mGreenSize = 6; // mBlueSize = 5; // } // } // Path: src/com/painless/glclock/GLWallpaperService.java import java.io.Writer; import java.util.ArrayList; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; import android.service.wallpaper.WallpaperService; import android.view.SurfaceHolder; import com.painless.glclock.BaseConfigChooser.ComponentSizeChooser; import com.painless.glclock.BaseConfigChooser.SimpleEGLConfigChooser; mEGLContextFactory = new DefaultContextFactory(); } if (mEGLWindowSurfaceFactory == null) { mEGLWindowSurfaceFactory = new DefaultWindowSurfaceFactory(); } mGLThread = new GLThread(renderer, mEGLConfigChooser, mEGLContextFactory, mEGLWindowSurfaceFactory, mGLWrapper); mGLThread.start(); } public void setEGLContextFactory(EGLContextFactory factory) { checkRenderThreadState(); mEGLContextFactory = factory; } public void setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory factory) { checkRenderThreadState(); mEGLWindowSurfaceFactory = factory; } public void setEGLConfigChooser(EGLConfigChooser configChooser) { checkRenderThreadState(); mEGLConfigChooser = configChooser; } public void setEGLConfigChooser(boolean needDepth) { setEGLConfigChooser(new SimpleEGLConfigChooser(needDepth)); } public void setEGLConfigChooser(int redSize, int greenSize, int blueSize, int alphaSize, int depthSize, int stencilSize) {
setEGLConfigChooser(new ComponentSizeChooser(redSize, greenSize, blueSize, alphaSize, depthSize,
sunnygoyal/neon-clock-gl
src/com/painless/glclock/util/WeatherUtil.java
// Path: src/com/painless/glclock/Debug.java // public class Debug { // // private static final String TAG = "ClockGL"; // // public static void log(Object msg) { // Log.e(getTag(), msg + ""); // } // // public static void log(Throwable err) { // Log.e(getTag(), err.getMessage() + " "); // err.printStackTrace(); // } // // private static String getTag() { // boolean startFound = false; // String className = Debug.class.getName(); // // StackTraceElement[] trace = Thread.currentThread().getStackTrace(); // for(StackTraceElement item : trace){ // if (item.getClassName().equals(className)) { // startFound = true; // } else if (startFound) { // return String.format( // "[%s/%s/%s]", item.getFileName(), item.getMethodName(), item.getLineNumber()); // } // } // // return TAG; // } // }
import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import com.painless.glclock.Debug; import com.painless.glclock.R; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Calendar;
line = line.split("#")[0].trim(); final String[] parts = line.split(";"); final ArrayList<ArrayList<Rect>> ret = new ArrayList<ArrayList<Rect>>(); for (final String part : parts) { final ArrayList<Rect> lst = new ArrayList<Rect>(); String[] defs = part.split("-"); final Rect mainIcon = iconDefs.get(Integer.parseInt(defs[0])); defs = defs[1].split(":"); lst.add(mainIcon); for (final String def : defs) { final String[] points = def.split(","); if (points.length > 3) { lst.add(getRect(points)); } else { final Rect pos = new Rect(mainIcon); pos.offsetTo(Integer.parseInt(points[0]), Integer.parseInt(points[1])); lst.add(pos); } } ret.add(lst); } return ret; } catch (final Exception e) {
// Path: src/com/painless/glclock/Debug.java // public class Debug { // // private static final String TAG = "ClockGL"; // // public static void log(Object msg) { // Log.e(getTag(), msg + ""); // } // // public static void log(Throwable err) { // Log.e(getTag(), err.getMessage() + " "); // err.printStackTrace(); // } // // private static String getTag() { // boolean startFound = false; // String className = Debug.class.getName(); // // StackTraceElement[] trace = Thread.currentThread().getStackTrace(); // for(StackTraceElement item : trace){ // if (item.getClassName().equals(className)) { // startFound = true; // } else if (startFound) { // return String.format( // "[%s/%s/%s]", item.getFileName(), item.getMethodName(), item.getLineNumber()); // } // } // // return TAG; // } // } // Path: src/com/painless/glclock/util/WeatherUtil.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import com.painless.glclock.Debug; import com.painless.glclock.R; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Calendar; line = line.split("#")[0].trim(); final String[] parts = line.split(";"); final ArrayList<ArrayList<Rect>> ret = new ArrayList<ArrayList<Rect>>(); for (final String part : parts) { final ArrayList<Rect> lst = new ArrayList<Rect>(); String[] defs = part.split("-"); final Rect mainIcon = iconDefs.get(Integer.parseInt(defs[0])); defs = defs[1].split(":"); lst.add(mainIcon); for (final String def : defs) { final String[] points = def.split(","); if (points.length > 3) { lst.add(getRect(points)); } else { final Rect pos = new Rect(mainIcon); pos.offsetTo(Integer.parseInt(points[0]), Integer.parseInt(points[1])); lst.add(pos); } } ret.add(lst); } return ret; } catch (final Exception e) {
Debug.log(e);
sunnygoyal/neon-clock-gl
src/com/painless/glclock/spirit/BatterySpirit.java
// Path: src/com/painless/glclock/Globals.java // public class Globals { // // public static float compassRotation = 0; // // public static int cpuUsage = 0; // public static int cpuUsageAngle = 0; // // public static int battery = 0; // public static int batteryCount = 0; // // public static int ramUsage = 0; // } // // Path: src/com/painless/glclock/Grid.java // public final class Grid { // private final FloatBuffer mFloatVertexBuffer; // private final FloatBuffer mFloatTexCoordBuffer; // // private final CharBuffer mIndexBuffer; // // private final int mW; // private final int mH; // private final int mIndexCount; // // public Grid(int vertsAcross, int vertsDown) { // mW = vertsAcross; // mH = vertsDown; // final int size = vertsAcross * vertsDown; // final int FLOAT_SIZE = 4; // final int CHAR_SIZE = 2; // // mFloatVertexBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 3) // .order(ByteOrder.nativeOrder()).asFloatBuffer(); // mFloatTexCoordBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 2) // .order(ByteOrder.nativeOrder()).asFloatBuffer(); // // final int quadW = mW - 1; // final int quadH = mH - 1; // final int quadCount = quadW * quadH; // final int indexCount = quadCount * 6; // mIndexCount = indexCount; // mIndexBuffer = ByteBuffer.allocateDirect(CHAR_SIZE * indexCount) // .order(ByteOrder.nativeOrder()).asCharBuffer(); // // /* // * Initialize triangle list mesh. // * // * [0]-----[ 1] ... // * | / | // * | / | // * | / | // * [w]-----[w+1] ... // * | | // * // */ // // { // int i = 0; // for (int y = 0; y < quadH; y++) { // for (int x = 0; x < quadW; x++) { // final char a = (char) (y * mW + x); // final char b = (char) (y * mW + x + 1); // final char c = (char) ((y + 1) * mW + x); // final char d = (char) ((y + 1) * mW + x + 1); // // mIndexBuffer.put(i++, a); // mIndexBuffer.put(i++, b); // mIndexBuffer.put(i++, c); // // mIndexBuffer.put(i++, b); // mIndexBuffer.put(i++, c); // mIndexBuffer.put(i++, d); // } // } // } // } // // public void set(int i, int j, float x, float y, float z, float u, float v) { // if (i < 0 || i >= mW) { // throw new IllegalArgumentException("i"); // } // if (j < 0 || j >= mH) { // throw new IllegalArgumentException("j"); // } // // final int index = mW * j + i; // // final int posIndex = index * 3; // final int texIndex = index * 2; // // mFloatVertexBuffer.put(posIndex, x); // mFloatVertexBuffer.put(posIndex + 1, y); // mFloatVertexBuffer.put(posIndex + 2, z); // // mFloatTexCoordBuffer.put(texIndex, u); // mFloatTexCoordBuffer.put(texIndex + 1, v); // } // // public void draw(GL10 gl) { // gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFloatVertexBuffer); // // gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mFloatTexCoordBuffer); // // gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount, // GL10.GL_UNSIGNED_SHORT, mIndexBuffer); // } // // public static Grid getSimpleGrid(int width, int height) { // final Grid grid = new Grid(2, 2); // grid.set(0, 0, -width / 2, -height / 2, 0.0f, 0.0f, 1.0f); // grid.set(1, 0, width / 2, -height / 2, 0.0f, 1.0f, 1.0f); // grid.set(0, 1, -width / 2, height / 2, 0.0f, 0.0f, 0.0f); // grid.set(1, 1, width / 2, height / 2, 0.0f, 1.0f, 0.0f); // return grid; // } // }
import javax.microedition.khronos.opengles.GL10; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Rect; import com.painless.glclock.Globals; import com.painless.glclock.Grid; import com.painless.glclock.R;
package com.painless.glclock.spirit; final class BatterySpirit extends MovableSpirit { private final Bitmap batteryBitmap; private final DigitSpirit digit;
// Path: src/com/painless/glclock/Globals.java // public class Globals { // // public static float compassRotation = 0; // // public static int cpuUsage = 0; // public static int cpuUsageAngle = 0; // // public static int battery = 0; // public static int batteryCount = 0; // // public static int ramUsage = 0; // } // // Path: src/com/painless/glclock/Grid.java // public final class Grid { // private final FloatBuffer mFloatVertexBuffer; // private final FloatBuffer mFloatTexCoordBuffer; // // private final CharBuffer mIndexBuffer; // // private final int mW; // private final int mH; // private final int mIndexCount; // // public Grid(int vertsAcross, int vertsDown) { // mW = vertsAcross; // mH = vertsDown; // final int size = vertsAcross * vertsDown; // final int FLOAT_SIZE = 4; // final int CHAR_SIZE = 2; // // mFloatVertexBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 3) // .order(ByteOrder.nativeOrder()).asFloatBuffer(); // mFloatTexCoordBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 2) // .order(ByteOrder.nativeOrder()).asFloatBuffer(); // // final int quadW = mW - 1; // final int quadH = mH - 1; // final int quadCount = quadW * quadH; // final int indexCount = quadCount * 6; // mIndexCount = indexCount; // mIndexBuffer = ByteBuffer.allocateDirect(CHAR_SIZE * indexCount) // .order(ByteOrder.nativeOrder()).asCharBuffer(); // // /* // * Initialize triangle list mesh. // * // * [0]-----[ 1] ... // * | / | // * | / | // * | / | // * [w]-----[w+1] ... // * | | // * // */ // // { // int i = 0; // for (int y = 0; y < quadH; y++) { // for (int x = 0; x < quadW; x++) { // final char a = (char) (y * mW + x); // final char b = (char) (y * mW + x + 1); // final char c = (char) ((y + 1) * mW + x); // final char d = (char) ((y + 1) * mW + x + 1); // // mIndexBuffer.put(i++, a); // mIndexBuffer.put(i++, b); // mIndexBuffer.put(i++, c); // // mIndexBuffer.put(i++, b); // mIndexBuffer.put(i++, c); // mIndexBuffer.put(i++, d); // } // } // } // } // // public void set(int i, int j, float x, float y, float z, float u, float v) { // if (i < 0 || i >= mW) { // throw new IllegalArgumentException("i"); // } // if (j < 0 || j >= mH) { // throw new IllegalArgumentException("j"); // } // // final int index = mW * j + i; // // final int posIndex = index * 3; // final int texIndex = index * 2; // // mFloatVertexBuffer.put(posIndex, x); // mFloatVertexBuffer.put(posIndex + 1, y); // mFloatVertexBuffer.put(posIndex + 2, z); // // mFloatTexCoordBuffer.put(texIndex, u); // mFloatTexCoordBuffer.put(texIndex + 1, v); // } // // public void draw(GL10 gl) { // gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFloatVertexBuffer); // // gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mFloatTexCoordBuffer); // // gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount, // GL10.GL_UNSIGNED_SHORT, mIndexBuffer); // } // // public static Grid getSimpleGrid(int width, int height) { // final Grid grid = new Grid(2, 2); // grid.set(0, 0, -width / 2, -height / 2, 0.0f, 0.0f, 1.0f); // grid.set(1, 0, width / 2, -height / 2, 0.0f, 1.0f, 1.0f); // grid.set(0, 1, -width / 2, height / 2, 0.0f, 0.0f, 0.0f); // grid.set(1, 1, width / 2, height / 2, 0.0f, 1.0f, 0.0f); // return grid; // } // } // Path: src/com/painless/glclock/spirit/BatterySpirit.java import javax.microedition.khronos.opengles.GL10; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Rect; import com.painless.glclock.Globals; import com.painless.glclock.Grid; import com.painless.glclock.R; package com.painless.glclock.spirit; final class BatterySpirit extends MovableSpirit { private final Bitmap batteryBitmap; private final DigitSpirit digit;
private final Grid grid;
sunnygoyal/neon-clock-gl
src/com/painless/glclock/spirit/BatterySpirit.java
// Path: src/com/painless/glclock/Globals.java // public class Globals { // // public static float compassRotation = 0; // // public static int cpuUsage = 0; // public static int cpuUsageAngle = 0; // // public static int battery = 0; // public static int batteryCount = 0; // // public static int ramUsage = 0; // } // // Path: src/com/painless/glclock/Grid.java // public final class Grid { // private final FloatBuffer mFloatVertexBuffer; // private final FloatBuffer mFloatTexCoordBuffer; // // private final CharBuffer mIndexBuffer; // // private final int mW; // private final int mH; // private final int mIndexCount; // // public Grid(int vertsAcross, int vertsDown) { // mW = vertsAcross; // mH = vertsDown; // final int size = vertsAcross * vertsDown; // final int FLOAT_SIZE = 4; // final int CHAR_SIZE = 2; // // mFloatVertexBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 3) // .order(ByteOrder.nativeOrder()).asFloatBuffer(); // mFloatTexCoordBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 2) // .order(ByteOrder.nativeOrder()).asFloatBuffer(); // // final int quadW = mW - 1; // final int quadH = mH - 1; // final int quadCount = quadW * quadH; // final int indexCount = quadCount * 6; // mIndexCount = indexCount; // mIndexBuffer = ByteBuffer.allocateDirect(CHAR_SIZE * indexCount) // .order(ByteOrder.nativeOrder()).asCharBuffer(); // // /* // * Initialize triangle list mesh. // * // * [0]-----[ 1] ... // * | / | // * | / | // * | / | // * [w]-----[w+1] ... // * | | // * // */ // // { // int i = 0; // for (int y = 0; y < quadH; y++) { // for (int x = 0; x < quadW; x++) { // final char a = (char) (y * mW + x); // final char b = (char) (y * mW + x + 1); // final char c = (char) ((y + 1) * mW + x); // final char d = (char) ((y + 1) * mW + x + 1); // // mIndexBuffer.put(i++, a); // mIndexBuffer.put(i++, b); // mIndexBuffer.put(i++, c); // // mIndexBuffer.put(i++, b); // mIndexBuffer.put(i++, c); // mIndexBuffer.put(i++, d); // } // } // } // } // // public void set(int i, int j, float x, float y, float z, float u, float v) { // if (i < 0 || i >= mW) { // throw new IllegalArgumentException("i"); // } // if (j < 0 || j >= mH) { // throw new IllegalArgumentException("j"); // } // // final int index = mW * j + i; // // final int posIndex = index * 3; // final int texIndex = index * 2; // // mFloatVertexBuffer.put(posIndex, x); // mFloatVertexBuffer.put(posIndex + 1, y); // mFloatVertexBuffer.put(posIndex + 2, z); // // mFloatTexCoordBuffer.put(texIndex, u); // mFloatTexCoordBuffer.put(texIndex + 1, v); // } // // public void draw(GL10 gl) { // gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFloatVertexBuffer); // // gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mFloatTexCoordBuffer); // // gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount, // GL10.GL_UNSIGNED_SHORT, mIndexBuffer); // } // // public static Grid getSimpleGrid(int width, int height) { // final Grid grid = new Grid(2, 2); // grid.set(0, 0, -width / 2, -height / 2, 0.0f, 0.0f, 1.0f); // grid.set(1, 0, width / 2, -height / 2, 0.0f, 1.0f, 1.0f); // grid.set(0, 1, -width / 2, height / 2, 0.0f, 0.0f, 0.0f); // grid.set(1, 1, width / 2, height / 2, 0.0f, 1.0f, 0.0f); // return grid; // } // }
import javax.microedition.khronos.opengles.GL10; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Rect; import com.painless.glclock.Globals; import com.painless.glclock.Grid; import com.painless.glclock.R;
package com.painless.glclock.spirit; final class BatterySpirit extends MovableSpirit { private final Bitmap batteryBitmap; private final DigitSpirit digit; private final Grid grid; private int batteryCount = 0; double callerCount = 0; public BatterySpirit(Context context, SpiritManager spiritManager) { super(context, 1, SpiritManager.NO_SERVICE); batteryBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.battery); this.digit = spiritManager.digits; grid = Grid.getSimpleGrid(128, 128); } @Override int[] getResources() { return new int[]{ }; } @Override public void drawOnPos(GL10 gl) {
// Path: src/com/painless/glclock/Globals.java // public class Globals { // // public static float compassRotation = 0; // // public static int cpuUsage = 0; // public static int cpuUsageAngle = 0; // // public static int battery = 0; // public static int batteryCount = 0; // // public static int ramUsage = 0; // } // // Path: src/com/painless/glclock/Grid.java // public final class Grid { // private final FloatBuffer mFloatVertexBuffer; // private final FloatBuffer mFloatTexCoordBuffer; // // private final CharBuffer mIndexBuffer; // // private final int mW; // private final int mH; // private final int mIndexCount; // // public Grid(int vertsAcross, int vertsDown) { // mW = vertsAcross; // mH = vertsDown; // final int size = vertsAcross * vertsDown; // final int FLOAT_SIZE = 4; // final int CHAR_SIZE = 2; // // mFloatVertexBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 3) // .order(ByteOrder.nativeOrder()).asFloatBuffer(); // mFloatTexCoordBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 2) // .order(ByteOrder.nativeOrder()).asFloatBuffer(); // // final int quadW = mW - 1; // final int quadH = mH - 1; // final int quadCount = quadW * quadH; // final int indexCount = quadCount * 6; // mIndexCount = indexCount; // mIndexBuffer = ByteBuffer.allocateDirect(CHAR_SIZE * indexCount) // .order(ByteOrder.nativeOrder()).asCharBuffer(); // // /* // * Initialize triangle list mesh. // * // * [0]-----[ 1] ... // * | / | // * | / | // * | / | // * [w]-----[w+1] ... // * | | // * // */ // // { // int i = 0; // for (int y = 0; y < quadH; y++) { // for (int x = 0; x < quadW; x++) { // final char a = (char) (y * mW + x); // final char b = (char) (y * mW + x + 1); // final char c = (char) ((y + 1) * mW + x); // final char d = (char) ((y + 1) * mW + x + 1); // // mIndexBuffer.put(i++, a); // mIndexBuffer.put(i++, b); // mIndexBuffer.put(i++, c); // // mIndexBuffer.put(i++, b); // mIndexBuffer.put(i++, c); // mIndexBuffer.put(i++, d); // } // } // } // } // // public void set(int i, int j, float x, float y, float z, float u, float v) { // if (i < 0 || i >= mW) { // throw new IllegalArgumentException("i"); // } // if (j < 0 || j >= mH) { // throw new IllegalArgumentException("j"); // } // // final int index = mW * j + i; // // final int posIndex = index * 3; // final int texIndex = index * 2; // // mFloatVertexBuffer.put(posIndex, x); // mFloatVertexBuffer.put(posIndex + 1, y); // mFloatVertexBuffer.put(posIndex + 2, z); // // mFloatTexCoordBuffer.put(texIndex, u); // mFloatTexCoordBuffer.put(texIndex + 1, v); // } // // public void draw(GL10 gl) { // gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFloatVertexBuffer); // // gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mFloatTexCoordBuffer); // // gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount, // GL10.GL_UNSIGNED_SHORT, mIndexBuffer); // } // // public static Grid getSimpleGrid(int width, int height) { // final Grid grid = new Grid(2, 2); // grid.set(0, 0, -width / 2, -height / 2, 0.0f, 0.0f, 1.0f); // grid.set(1, 0, width / 2, -height / 2, 0.0f, 1.0f, 1.0f); // grid.set(0, 1, -width / 2, height / 2, 0.0f, 0.0f, 0.0f); // grid.set(1, 1, width / 2, height / 2, 0.0f, 1.0f, 0.0f); // return grid; // } // } // Path: src/com/painless/glclock/spirit/BatterySpirit.java import javax.microedition.khronos.opengles.GL10; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Rect; import com.painless.glclock.Globals; import com.painless.glclock.Grid; import com.painless.glclock.R; package com.painless.glclock.spirit; final class BatterySpirit extends MovableSpirit { private final Bitmap batteryBitmap; private final DigitSpirit digit; private final Grid grid; private int batteryCount = 0; double callerCount = 0; public BatterySpirit(Context context, SpiritManager spiritManager) { super(context, 1, SpiritManager.NO_SERVICE); batteryBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.battery); this.digit = spiritManager.digits; grid = Grid.getSimpleGrid(128, 128); } @Override int[] getResources() { return new int[]{ }; } @Override public void drawOnPos(GL10 gl) {
if (batteryCount != Globals.batteryCount) {
sunnygoyal/neon-clock-gl
src/com/painless/glclock/setting/DragImg.java
// Path: src/com/painless/glclock/Constants.java // public static final class WidgetCode { // public final String code; // public final String prefix; // // public final String offset; // public final String offsetDefault; // // public final String color; // public final String zoom; // // private WidgetCode(String code, String defaultOffset) { // this.code = code + "Enabled"; // this.offset = code + "Offset"; // this.color = code + "color"; // this.zoom = code + "zoom"; // this.prefix = code + "_"; // // this.offsetDefault = defaultOffset; // } // // public int[] getOffset(SharedPreferences pref) { // final String[] values = pref.getString(offset, offsetDefault).split(","); // // final int[] offsets = new int[2]; // try { // offsets[0] = Integer.valueOf(values[0]); // offsets[1] = Integer.valueOf(values[1]); // } catch (final Exception e) { // offsets[0] = 0; // offsets[1] = 0; // } // return offsets; // } // // public float getZoom(SharedPreferences pref) { // return pref.getFloat(zoom, 1); // } // } // // Path: src/com/painless/glclock/Debug.java // public class Debug { // // private static final String TAG = "ClockGL"; // // public static void log(Object msg) { // Log.e(getTag(), msg + ""); // } // // public static void log(Throwable err) { // Log.e(getTag(), err.getMessage() + " "); // err.printStackTrace(); // } // // private static String getTag() { // boolean startFound = false; // String className = Debug.class.getName(); // // StackTraceElement[] trace = Thread.currentThread().getStackTrace(); // for(StackTraceElement item : trace){ // if (item.getClassName().equals(className)) { // startFound = true; // } else if (startFound) { // return String.format( // "[%s/%s/%s]", item.getFileName(), item.getMethodName(), item.getLineNumber()); // } // } // // return TAG; // } // }
import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.Rect; import com.painless.glclock.Constants.WidgetCode; import com.painless.glclock.Debug;
setZoom(mMain.prefs.getFloat(widgetCode.zoom, 1)); } public void showDrag(int sx, int sy) { sx += offsetX; sy += offsetY; move(sx, sy); } public void finishMove(int endX, int endY) { offsetX += endX; offsetY += endY; dstRect.offsetTo(mMain.halfW + offsetX, mMain.halfH + offsetY); move(offsetX, offsetY); } private void move(int ox, int oy) { dstRect.offsetTo(mMain.halfW + ox + zoomOffsetX, mMain.halfH + oy + zoomOffsetY); } public boolean isIn(int pointX, int pointY) { return dstRect.contains(pointX, pointY); } public void saveSettings() { final int fx = offsetX + previewBitmap.getWidth() / 2; final int fy = offsetY + previewBitmap.getHeight() / 2; mMain.prefs.edit().putString(widgetCode.offset, fx + "," + fy).commit();
// Path: src/com/painless/glclock/Constants.java // public static final class WidgetCode { // public final String code; // public final String prefix; // // public final String offset; // public final String offsetDefault; // // public final String color; // public final String zoom; // // private WidgetCode(String code, String defaultOffset) { // this.code = code + "Enabled"; // this.offset = code + "Offset"; // this.color = code + "color"; // this.zoom = code + "zoom"; // this.prefix = code + "_"; // // this.offsetDefault = defaultOffset; // } // // public int[] getOffset(SharedPreferences pref) { // final String[] values = pref.getString(offset, offsetDefault).split(","); // // final int[] offsets = new int[2]; // try { // offsets[0] = Integer.valueOf(values[0]); // offsets[1] = Integer.valueOf(values[1]); // } catch (final Exception e) { // offsets[0] = 0; // offsets[1] = 0; // } // return offsets; // } // // public float getZoom(SharedPreferences pref) { // return pref.getFloat(zoom, 1); // } // } // // Path: src/com/painless/glclock/Debug.java // public class Debug { // // private static final String TAG = "ClockGL"; // // public static void log(Object msg) { // Log.e(getTag(), msg + ""); // } // // public static void log(Throwable err) { // Log.e(getTag(), err.getMessage() + " "); // err.printStackTrace(); // } // // private static String getTag() { // boolean startFound = false; // String className = Debug.class.getName(); // // StackTraceElement[] trace = Thread.currentThread().getStackTrace(); // for(StackTraceElement item : trace){ // if (item.getClassName().equals(className)) { // startFound = true; // } else if (startFound) { // return String.format( // "[%s/%s/%s]", item.getFileName(), item.getMethodName(), item.getLineNumber()); // } // } // // return TAG; // } // } // Path: src/com/painless/glclock/setting/DragImg.java import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.Rect; import com.painless.glclock.Constants.WidgetCode; import com.painless.glclock.Debug; setZoom(mMain.prefs.getFloat(widgetCode.zoom, 1)); } public void showDrag(int sx, int sy) { sx += offsetX; sy += offsetY; move(sx, sy); } public void finishMove(int endX, int endY) { offsetX += endX; offsetY += endY; dstRect.offsetTo(mMain.halfW + offsetX, mMain.halfH + offsetY); move(offsetX, offsetY); } private void move(int ox, int oy) { dstRect.offsetTo(mMain.halfW + ox + zoomOffsetX, mMain.halfH + oy + zoomOffsetY); } public boolean isIn(int pointX, int pointY) { return dstRect.contains(pointX, pointY); } public void saveSettings() { final int fx = offsetX + previewBitmap.getWidth() / 2; final int fy = offsetY + previewBitmap.getHeight() / 2; mMain.prefs.edit().putString(widgetCode.offset, fx + "," + fy).commit();
Debug.log("Save " + widgetCode.offset + " " + fx + "," + fy);
sunnygoyal/neon-clock-gl
src/com/painless/glclock/setting/WidgetSettingPopup.java
// Path: src/com/painless/glclock/Constants.java // public static final class WidgetCode { // public final String code; // public final String prefix; // // public final String offset; // public final String offsetDefault; // // public final String color; // public final String zoom; // // private WidgetCode(String code, String defaultOffset) { // this.code = code + "Enabled"; // this.offset = code + "Offset"; // this.color = code + "color"; // this.zoom = code + "zoom"; // this.prefix = code + "_"; // // this.offsetDefault = defaultOffset; // } // // public int[] getOffset(SharedPreferences pref) { // final String[] values = pref.getString(offset, offsetDefault).split(","); // // final int[] offsets = new int[2]; // try { // offsets[0] = Integer.valueOf(values[0]); // offsets[1] = Integer.valueOf(values[1]); // } catch (final Exception e) { // offsets[0] = 0; // offsets[1] = 0; // } // return offsets; // } // // public float getZoom(SharedPreferences pref) { // return pref.getFloat(zoom, 1); // } // } // // Path: src/com/painless/glclock/util/LayoutSlideAnim.java // public class LayoutSlideAnim extends Animation { // // private final View mtargetView; // private final LayoutParams mParams; // private final boolean mSlideIn; // // private final int mDelta; // private final boolean mIsVert; // // public LayoutSlideAnim(View target, boolean slideIn, boolean isVert) { // mSlideIn = slideIn; // mtargetView = target; // mParams = (LayoutParams) target.getLayoutParams(); // mDelta = (int) target.getResources().getDimension(R.dimen.info_margin); // mIsVert = isVert; // // setFillAfter(true); // setDuration(200); // } // // @Override // protected void applyTransformation(float interpolatedTime, Transformation t) { // if (mSlideIn) { // interpolatedTime = 1 - interpolatedTime; // } // // if (mIsVert) { // mParams.topMargin = (int) (-interpolatedTime * mtargetView.getHeight()); // } else { // mParams.leftMargin = (int) (-interpolatedTime * (mtargetView.getWidth() - mDelta)) - mDelta; // } // // mtargetView.setLayoutParams(mParams); // } // // }
import android.content.Intent; import android.content.SharedPreferences; import android.view.View; import android.view.View.OnClickListener; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import com.painless.glclock.Constants.WidgetCode; import com.painless.glclock.R; import com.painless.glclock.util.LayoutSlideAnim;
package com.painless.glclock.setting; public class WidgetSettingPopup implements OnClickListener, OnCheckedChangeListener, OnSeekBarChangeListener { private final OffsetPicker mMain; private final SharedPreferences mPrefs; private DragImg mImg;
// Path: src/com/painless/glclock/Constants.java // public static final class WidgetCode { // public final String code; // public final String prefix; // // public final String offset; // public final String offsetDefault; // // public final String color; // public final String zoom; // // private WidgetCode(String code, String defaultOffset) { // this.code = code + "Enabled"; // this.offset = code + "Offset"; // this.color = code + "color"; // this.zoom = code + "zoom"; // this.prefix = code + "_"; // // this.offsetDefault = defaultOffset; // } // // public int[] getOffset(SharedPreferences pref) { // final String[] values = pref.getString(offset, offsetDefault).split(","); // // final int[] offsets = new int[2]; // try { // offsets[0] = Integer.valueOf(values[0]); // offsets[1] = Integer.valueOf(values[1]); // } catch (final Exception e) { // offsets[0] = 0; // offsets[1] = 0; // } // return offsets; // } // // public float getZoom(SharedPreferences pref) { // return pref.getFloat(zoom, 1); // } // } // // Path: src/com/painless/glclock/util/LayoutSlideAnim.java // public class LayoutSlideAnim extends Animation { // // private final View mtargetView; // private final LayoutParams mParams; // private final boolean mSlideIn; // // private final int mDelta; // private final boolean mIsVert; // // public LayoutSlideAnim(View target, boolean slideIn, boolean isVert) { // mSlideIn = slideIn; // mtargetView = target; // mParams = (LayoutParams) target.getLayoutParams(); // mDelta = (int) target.getResources().getDimension(R.dimen.info_margin); // mIsVert = isVert; // // setFillAfter(true); // setDuration(200); // } // // @Override // protected void applyTransformation(float interpolatedTime, Transformation t) { // if (mSlideIn) { // interpolatedTime = 1 - interpolatedTime; // } // // if (mIsVert) { // mParams.topMargin = (int) (-interpolatedTime * mtargetView.getHeight()); // } else { // mParams.leftMargin = (int) (-interpolatedTime * (mtargetView.getWidth() - mDelta)) - mDelta; // } // // mtargetView.setLayoutParams(mParams); // } // // } // Path: src/com/painless/glclock/setting/WidgetSettingPopup.java import android.content.Intent; import android.content.SharedPreferences; import android.view.View; import android.view.View.OnClickListener; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import com.painless.glclock.Constants.WidgetCode; import com.painless.glclock.R; import com.painless.glclock.util.LayoutSlideAnim; package com.painless.glclock.setting; public class WidgetSettingPopup implements OnClickListener, OnCheckedChangeListener, OnSeekBarChangeListener { private final OffsetPicker mMain; private final SharedPreferences mPrefs; private DragImg mImg;
private WidgetCode mCode;
sunnygoyal/neon-clock-gl
src/com/painless/glclock/setting/WidgetSettingPopup.java
// Path: src/com/painless/glclock/Constants.java // public static final class WidgetCode { // public final String code; // public final String prefix; // // public final String offset; // public final String offsetDefault; // // public final String color; // public final String zoom; // // private WidgetCode(String code, String defaultOffset) { // this.code = code + "Enabled"; // this.offset = code + "Offset"; // this.color = code + "color"; // this.zoom = code + "zoom"; // this.prefix = code + "_"; // // this.offsetDefault = defaultOffset; // } // // public int[] getOffset(SharedPreferences pref) { // final String[] values = pref.getString(offset, offsetDefault).split(","); // // final int[] offsets = new int[2]; // try { // offsets[0] = Integer.valueOf(values[0]); // offsets[1] = Integer.valueOf(values[1]); // } catch (final Exception e) { // offsets[0] = 0; // offsets[1] = 0; // } // return offsets; // } // // public float getZoom(SharedPreferences pref) { // return pref.getFloat(zoom, 1); // } // } // // Path: src/com/painless/glclock/util/LayoutSlideAnim.java // public class LayoutSlideAnim extends Animation { // // private final View mtargetView; // private final LayoutParams mParams; // private final boolean mSlideIn; // // private final int mDelta; // private final boolean mIsVert; // // public LayoutSlideAnim(View target, boolean slideIn, boolean isVert) { // mSlideIn = slideIn; // mtargetView = target; // mParams = (LayoutParams) target.getLayoutParams(); // mDelta = (int) target.getResources().getDimension(R.dimen.info_margin); // mIsVert = isVert; // // setFillAfter(true); // setDuration(200); // } // // @Override // protected void applyTransformation(float interpolatedTime, Transformation t) { // if (mSlideIn) { // interpolatedTime = 1 - interpolatedTime; // } // // if (mIsVert) { // mParams.topMargin = (int) (-interpolatedTime * mtargetView.getHeight()); // } else { // mParams.leftMargin = (int) (-interpolatedTime * (mtargetView.getWidth() - mDelta)) - mDelta; // } // // mtargetView.setLayoutParams(mParams); // } // // }
import android.content.Intent; import android.content.SharedPreferences; import android.view.View; import android.view.View.OnClickListener; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import com.painless.glclock.Constants.WidgetCode; import com.painless.glclock.R; import com.painless.glclock.util.LayoutSlideAnim;
package com.painless.glclock.setting; public class WidgetSettingPopup implements OnClickListener, OnCheckedChangeListener, OnSeekBarChangeListener { private final OffsetPicker mMain; private final SharedPreferences mPrefs; private DragImg mImg; private WidgetCode mCode; private View mContent; private TextView mTitleText; private SeekBar mZoomSeek; private TextView mZoomText; private CompoundButton mEnabled; private boolean mIsShowing = false; public WidgetSettingPopup(OffsetPicker main) { mMain = main; mPrefs = main.prefs; } public void show(DragImg img) { mImg = img; mCode = img.widgetCode; if (mContent == null) { initContent(); } mEnabled.setOnCheckedChangeListener(null); mEnabled.setChecked(mPrefs.getBoolean(mCode.code, true)); mEnabled.setOnCheckedChangeListener(this); mZoomSeek.setProgress((int) (mPrefs.getFloat(mCode.zoom, 1) * 10) - 5); mTitleText.setText(mImg.titleRes); mTitleText.setCompoundDrawablesWithIntrinsicBounds(mImg.iconRes, 0, 0, 0); mIsShowing = true;
// Path: src/com/painless/glclock/Constants.java // public static final class WidgetCode { // public final String code; // public final String prefix; // // public final String offset; // public final String offsetDefault; // // public final String color; // public final String zoom; // // private WidgetCode(String code, String defaultOffset) { // this.code = code + "Enabled"; // this.offset = code + "Offset"; // this.color = code + "color"; // this.zoom = code + "zoom"; // this.prefix = code + "_"; // // this.offsetDefault = defaultOffset; // } // // public int[] getOffset(SharedPreferences pref) { // final String[] values = pref.getString(offset, offsetDefault).split(","); // // final int[] offsets = new int[2]; // try { // offsets[0] = Integer.valueOf(values[0]); // offsets[1] = Integer.valueOf(values[1]); // } catch (final Exception e) { // offsets[0] = 0; // offsets[1] = 0; // } // return offsets; // } // // public float getZoom(SharedPreferences pref) { // return pref.getFloat(zoom, 1); // } // } // // Path: src/com/painless/glclock/util/LayoutSlideAnim.java // public class LayoutSlideAnim extends Animation { // // private final View mtargetView; // private final LayoutParams mParams; // private final boolean mSlideIn; // // private final int mDelta; // private final boolean mIsVert; // // public LayoutSlideAnim(View target, boolean slideIn, boolean isVert) { // mSlideIn = slideIn; // mtargetView = target; // mParams = (LayoutParams) target.getLayoutParams(); // mDelta = (int) target.getResources().getDimension(R.dimen.info_margin); // mIsVert = isVert; // // setFillAfter(true); // setDuration(200); // } // // @Override // protected void applyTransformation(float interpolatedTime, Transformation t) { // if (mSlideIn) { // interpolatedTime = 1 - interpolatedTime; // } // // if (mIsVert) { // mParams.topMargin = (int) (-interpolatedTime * mtargetView.getHeight()); // } else { // mParams.leftMargin = (int) (-interpolatedTime * (mtargetView.getWidth() - mDelta)) - mDelta; // } // // mtargetView.setLayoutParams(mParams); // } // // } // Path: src/com/painless/glclock/setting/WidgetSettingPopup.java import android.content.Intent; import android.content.SharedPreferences; import android.view.View; import android.view.View.OnClickListener; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import com.painless.glclock.Constants.WidgetCode; import com.painless.glclock.R; import com.painless.glclock.util.LayoutSlideAnim; package com.painless.glclock.setting; public class WidgetSettingPopup implements OnClickListener, OnCheckedChangeListener, OnSeekBarChangeListener { private final OffsetPicker mMain; private final SharedPreferences mPrefs; private DragImg mImg; private WidgetCode mCode; private View mContent; private TextView mTitleText; private SeekBar mZoomSeek; private TextView mZoomText; private CompoundButton mEnabled; private boolean mIsShowing = false; public WidgetSettingPopup(OffsetPicker main) { mMain = main; mPrefs = main.prefs; } public void show(DragImg img) { mImg = img; mCode = img.widgetCode; if (mContent == null) { initContent(); } mEnabled.setOnCheckedChangeListener(null); mEnabled.setChecked(mPrefs.getBoolean(mCode.code, true)); mEnabled.setOnCheckedChangeListener(this); mZoomSeek.setProgress((int) (mPrefs.getFloat(mCode.zoom, 1) * 10) - 5); mTitleText.setText(mImg.titleRes); mTitleText.setCompoundDrawablesWithIntrinsicBounds(mImg.iconRes, 0, 0, 0); mIsShowing = true;
mContent.startAnimation(new LayoutSlideAnim(mContent, true, true));
sunnygoyal/neon-clock-gl
src/com/painless/glclock/service/CpuService.java
// Path: src/com/painless/glclock/Globals.java // public class Globals { // // public static float compassRotation = 0; // // public static int cpuUsage = 0; // public static int cpuUsageAngle = 0; // // public static int battery = 0; // public static int batteryCount = 0; // // public static int ramUsage = 0; // }
import android.os.Handler; import com.painless.glclock.Globals; import java.io.RandomAccessFile;
package com.painless.glclock.service; public final class CpuService implements Runnable, RService { private static final long REFRESH_RATE = 5000; // 5 seconds. private final Handler updateHandler; // keep these static to prevent restart private static long lastTotal = -1, lastIdle = -1; private boolean running = false; public CpuService() { updateHandler = new Handler(); } @Override public void run() { try { final RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r"); String line = reader.readLine(); reader.close(); line = line.split(" ", 2) [1]; final String values[] = line.trim().split(" "); final long idle = Long.parseLong(values[3]); long total = 0; for (int i=0; i<values.length; i++) { total += Long.parseLong(values[i]); } if (lastTotal > 0) { final long idleD = idle - lastIdle; final long totalD = total - lastTotal;
// Path: src/com/painless/glclock/Globals.java // public class Globals { // // public static float compassRotation = 0; // // public static int cpuUsage = 0; // public static int cpuUsageAngle = 0; // // public static int battery = 0; // public static int batteryCount = 0; // // public static int ramUsage = 0; // } // Path: src/com/painless/glclock/service/CpuService.java import android.os.Handler; import com.painless.glclock.Globals; import java.io.RandomAccessFile; package com.painless.glclock.service; public final class CpuService implements Runnable, RService { private static final long REFRESH_RATE = 5000; // 5 seconds. private final Handler updateHandler; // keep these static to prevent restart private static long lastTotal = -1, lastIdle = -1; private boolean running = false; public CpuService() { updateHandler = new Handler(); } @Override public void run() { try { final RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r"); String line = reader.readLine(); reader.close(); line = line.split(" ", 2) [1]; final String values[] = line.trim().split(" "); final long idle = Long.parseLong(values[3]); long total = 0; for (int i=0; i<values.length; i++) { total += Long.parseLong(values[i]); } if (lastTotal > 0) { final long idleD = idle - lastIdle; final long totalD = total - lastTotal;
Globals.cpuUsage = (int) (1000 * (totalD - idleD) / totalD + 5) / 10;
sunnygoyal/neon-clock-gl
src/com/painless/glclock/spirit/TrailSpirit.java
// Path: src/com/painless/glclock/Debug.java // public class Debug { // // private static final String TAG = "ClockGL"; // // public static void log(Object msg) { // Log.e(getTag(), msg + ""); // } // // public static void log(Throwable err) { // Log.e(getTag(), err.getMessage() + " "); // err.printStackTrace(); // } // // private static String getTag() { // boolean startFound = false; // String className = Debug.class.getName(); // // StackTraceElement[] trace = Thread.currentThread().getStackTrace(); // for(StackTraceElement item : trace){ // if (item.getClassName().equals(className)) { // startFound = true; // } else if (startFound) { // return String.format( // "[%s/%s/%s]", item.getFileName(), item.getMethodName(), item.getLineNumber()); // } // } // // return TAG; // } // }
import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Random; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import javax.microedition.khronos.opengles.GL11Ext; import android.content.Context; import com.painless.glclock.Debug;
trails.remove(0).clear(); } while(count > trails.size()) { final Trail t = new Trail(); if ((trailLimitX > 0) && (trailLimitY > 0)) { t.init(); } trails.add(t); } } @Override public void loadTextures(GL10 gl) { super.loadTextures(gl); if (textureW == 0 || textureH == 0) { return; } gl.glBindTexture(GL10.GL_TEXTURE_2D, textureNames[0]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST); // and init the GL texture with the pixels gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, GL10.GL_ALPHA, textureW, textureH, 0, GL10.GL_ALPHA, GL10.GL_UNSIGNED_BYTE, pixelBuffer); final int error = gl.glGetError(); if (error != GL10.GL_NO_ERROR) {
// Path: src/com/painless/glclock/Debug.java // public class Debug { // // private static final String TAG = "ClockGL"; // // public static void log(Object msg) { // Log.e(getTag(), msg + ""); // } // // public static void log(Throwable err) { // Log.e(getTag(), err.getMessage() + " "); // err.printStackTrace(); // } // // private static String getTag() { // boolean startFound = false; // String className = Debug.class.getName(); // // StackTraceElement[] trace = Thread.currentThread().getStackTrace(); // for(StackTraceElement item : trace){ // if (item.getClassName().equals(className)) { // startFound = true; // } else if (startFound) { // return String.format( // "[%s/%s/%s]", item.getFileName(), item.getMethodName(), item.getLineNumber()); // } // } // // return TAG; // } // } // Path: src/com/painless/glclock/spirit/TrailSpirit.java import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Random; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import javax.microedition.khronos.opengles.GL11Ext; import android.content.Context; import com.painless.glclock.Debug; trails.remove(0).clear(); } while(count > trails.size()) { final Trail t = new Trail(); if ((trailLimitX > 0) && (trailLimitY > 0)) { t.init(); } trails.add(t); } } @Override public void loadTextures(GL10 gl) { super.loadTextures(gl); if (textureW == 0 || textureH == 0) { return; } gl.glBindTexture(GL10.GL_TEXTURE_2D, textureNames[0]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST); // and init the GL texture with the pixels gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, GL10.GL_ALPHA, textureW, textureH, 0, GL10.GL_ALPHA, GL10.GL_UNSIGNED_BYTE, pixelBuffer); final int error = gl.glGetError(); if (error != GL10.GL_NO_ERROR) {
Debug.log("Trails Texture Load GLError: " + error);
Guichaguri/BetterFps
src/main/java/guichaguri/betterfps/gui/BetterFpsResourcePack.java
// Path: src/main/java/guichaguri/betterfps/tweaker/BetterFpsTweaker.java // public class BetterFpsTweaker implements ITweaker { // // public static InputStream getResourceStream(String path) { // return BetterFpsTweaker.class.getClassLoader().getResourceAsStream(path); // } // // public static URL getResource(String path) { // return BetterFpsTweaker.class.getClassLoader().getResource(path); // } // // private static final String[] TRANSFORMERS = new String[] { // "guichaguri.betterfps.transformers.PatcherTransformer", // "guichaguri.betterfps.transformers.MathTransformer" // }; // // private final String[] EXCLUDED = new String[] { // "guichaguri.betterfps.transformers", // "guichaguri.betterfps.tweaker", // "guichaguri.betterfps.patchers" // }; // // private final String[] LOAD_DISABLED = new String[] { // "guichaguri.betterfps.installer", // "guichaguri.betterfps.math", // "guichaguri.betterfps.patches" // }; // // private List<String> args; // // @Override // public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) { // this.args = new ArrayList<String>(args); // // this.args.add("--version"); // this.args.add(profile); // // if(assetsDir != null) { // this.args.add("--assetsDir"); // this.args.add(assetsDir.getAbsolutePath()); // } // if(gameDir != null) { // this.args.add("--gameDir"); // this.args.add(gameDir.getAbsolutePath()); // } // // BetterFps.GAME_DIR = gameDir; // } // // @Override // public void injectIntoClassLoader(LaunchClassLoader cl) { // loadMappings(); // // for(String transformer : TRANSFORMERS) { // cl.registerTransformer(transformer); // } // // for(String excluded : EXCLUDED) { // cl.addTransformerExclusion(excluded); // } // // for(String loadDisabled : LOAD_DISABLED) { // cl.addClassLoaderExclusion(loadDisabled); // } // } // // @Override // public String getLaunchTarget() { // return "net.minecraft.client.main.Main"; // } // // @Override // public String[] getLaunchArguments() { // // ArrayList args = (ArrayList)Launch.blackboard.get("ArgumentList"); // if(args.isEmpty()) args.addAll(this.args); // // this.args = null; // // // Just in case someone needs to know whether BetterFps is running // Launch.blackboard.put("BetterFpsVersion", BetterFps.VERSION); // // return new String[0]; // } // // private void loadMappings() { // BetterFpsHelper.LOG.debug("Loading Mappings..."); // try { // Mappings.loadMappings(getResourceStream("betterfps.srg")); // } catch(IOException ex) { // BetterFpsHelper.LOG.error("Could not load mappings. Things will not work!"); // } // } // }
import com.google.common.collect.ImmutableSet; import guichaguri.betterfps.tweaker.BetterFpsTweaker; import java.awt.image.BufferedImage; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Set; import net.minecraft.client.resources.IResourcePack; import net.minecraft.client.resources.data.IMetadataSection; import net.minecraft.client.resources.data.MetadataSerializer; import net.minecraft.util.ResourceLocation;
package guichaguri.betterfps.gui; /** * A resource pack that serves the purpose to provide lang files * @author Guilherme Chaguri */ public class BetterFpsResourcePack implements IResourcePack { private final Set<String> DOMAINS = ImmutableSet.of("betterfps"); public BetterFpsResourcePack() { } private String getPath(ResourceLocation location) { return String.format("assets/%s/%s", location.getResourceDomain(), location.getResourcePath()).toLowerCase(); } @Override public InputStream getInputStream(ResourceLocation location) throws IOException {
// Path: src/main/java/guichaguri/betterfps/tweaker/BetterFpsTweaker.java // public class BetterFpsTweaker implements ITweaker { // // public static InputStream getResourceStream(String path) { // return BetterFpsTweaker.class.getClassLoader().getResourceAsStream(path); // } // // public static URL getResource(String path) { // return BetterFpsTweaker.class.getClassLoader().getResource(path); // } // // private static final String[] TRANSFORMERS = new String[] { // "guichaguri.betterfps.transformers.PatcherTransformer", // "guichaguri.betterfps.transformers.MathTransformer" // }; // // private final String[] EXCLUDED = new String[] { // "guichaguri.betterfps.transformers", // "guichaguri.betterfps.tweaker", // "guichaguri.betterfps.patchers" // }; // // private final String[] LOAD_DISABLED = new String[] { // "guichaguri.betterfps.installer", // "guichaguri.betterfps.math", // "guichaguri.betterfps.patches" // }; // // private List<String> args; // // @Override // public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) { // this.args = new ArrayList<String>(args); // // this.args.add("--version"); // this.args.add(profile); // // if(assetsDir != null) { // this.args.add("--assetsDir"); // this.args.add(assetsDir.getAbsolutePath()); // } // if(gameDir != null) { // this.args.add("--gameDir"); // this.args.add(gameDir.getAbsolutePath()); // } // // BetterFps.GAME_DIR = gameDir; // } // // @Override // public void injectIntoClassLoader(LaunchClassLoader cl) { // loadMappings(); // // for(String transformer : TRANSFORMERS) { // cl.registerTransformer(transformer); // } // // for(String excluded : EXCLUDED) { // cl.addTransformerExclusion(excluded); // } // // for(String loadDisabled : LOAD_DISABLED) { // cl.addClassLoaderExclusion(loadDisabled); // } // } // // @Override // public String getLaunchTarget() { // return "net.minecraft.client.main.Main"; // } // // @Override // public String[] getLaunchArguments() { // // ArrayList args = (ArrayList)Launch.blackboard.get("ArgumentList"); // if(args.isEmpty()) args.addAll(this.args); // // this.args = null; // // // Just in case someone needs to know whether BetterFps is running // Launch.blackboard.put("BetterFpsVersion", BetterFps.VERSION); // // return new String[0]; // } // // private void loadMappings() { // BetterFpsHelper.LOG.debug("Loading Mappings..."); // try { // Mappings.loadMappings(getResourceStream("betterfps.srg")); // } catch(IOException ex) { // BetterFpsHelper.LOG.error("Could not load mappings. Things will not work!"); // } // } // } // Path: src/main/java/guichaguri/betterfps/gui/BetterFpsResourcePack.java import com.google.common.collect.ImmutableSet; import guichaguri.betterfps.tweaker.BetterFpsTweaker; import java.awt.image.BufferedImage; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Set; import net.minecraft.client.resources.IResourcePack; import net.minecraft.client.resources.data.IMetadataSection; import net.minecraft.client.resources.data.MetadataSerializer; import net.minecraft.util.ResourceLocation; package guichaguri.betterfps.gui; /** * A resource pack that serves the purpose to provide lang files * @author Guilherme Chaguri */ public class BetterFpsResourcePack implements IResourcePack { private final Set<String> DOMAINS = ImmutableSet.of("betterfps"); public BetterFpsResourcePack() { } private String getPath(ResourceLocation location) { return String.format("assets/%s/%s", location.getResourceDomain(), location.getResourcePath()).toLowerCase(); } @Override public InputStream getInputStream(ResourceLocation location) throws IOException {
InputStream stream = BetterFpsTweaker.getResourceStream(getPath(location));
Guichaguri/BetterFps
src/main/java/guichaguri/betterfps/patches/misc/ClientPlayerPatch.java
// Path: src/main/java/guichaguri/betterfps/UpdateChecker.java // public class UpdateChecker implements Runnable { // // private static boolean updateCheck = false; // private static boolean done = false; // private static String updateVersion = null; // private static String updateDownload = null; // // public static void check() { // if(!BetterFpsHelper.getConfig().updateChecker) { // done = true; // return; // } // if(!updateCheck) { // updateCheck = true; // checkForced(); // } // } // // public static void checkForced() { // done = false; // Thread thread = new Thread(new UpdateChecker(), "BetterFps Update Checker"); // thread.setDaemon(true); // thread.start(); // } // // public static void showChat(EntityPlayerSP player) { // if(!done) return; // if(updateVersion == null && updateDownload == null) return; // if(!BetterFps.CLIENT) return; // // TextComponentTranslation title = new TextComponentTranslation("betterfps.update.available", updateVersion); // title.setStyle(title.getStyle().setColor(TextFormatting.GREEN).setBold(true)); // // TextComponentString buttons = new TextComponentString(" "); // buttons.setStyle(buttons.getStyle().setColor(TextFormatting.YELLOW)); // buttons.appendSibling(createButton(updateDownload, "betterfps.update.button.download")); // buttons.appendText(" "); // buttons.appendSibling(createButton(BetterFps.URL, "betterfps.update.button.more")); // // int phrase = (int)(Math.random() * 12) + 1; // TextComponentTranslation desc = new TextComponentTranslation("betterfps.update.phrase." + phrase); // desc.setStyle(desc.getStyle().setColor(TextFormatting.GRAY)); // // if(updateVersion.length() < 8) { // title.appendSibling(buttons); // player.sendStatusMessage(title, false); // player.sendStatusMessage(desc, false); // } else { // player.sendStatusMessage(title, false); // player.sendStatusMessage(buttons, false); // player.sendStatusMessage(desc, false); // } // // updateVersion = null; // updateDownload = null; // } // // private static void showConsole() { // if(!done) return; // if(updateVersion == null && updateDownload == null) return; // // BetterFpsHelper.LOG.info("BetterFps " + updateVersion + " is available"); // BetterFpsHelper.LOG.info("Download: " + updateDownload); // BetterFpsHelper.LOG.info("More: " + BetterFps.URL); // // updateVersion = null; // updateDownload = null; // } // // private static TextComponentTranslation createButton(String link, String key) { // TextComponentTranslation sib = new TextComponentTranslation(key); // Style style = sib.getStyle(); // style.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, link)); // TextComponentTranslation h = new TextComponentTranslation(key + ".info"); // h.setStyle(h.getStyle().setColor(TextFormatting.RED)); // style.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, h)); // sib.setStyle(style); // return sib; // } // // @Override // public void run() { // try { // URL url = new URL(BetterFps.UPDATE_URL); // InputStream in = url.openStream(); // JsonParser parser = new JsonParser(); // JsonObject obj = parser.parse(new InputStreamReader(in)).getAsJsonObject(); // JsonObject versions = obj.getAsJsonObject("versions"); // // if(!versions.has(BetterFps.MC_VERSION)) return; // JsonArray array = versions.getAsJsonArray(BetterFps.MC_VERSION); // if(array.size() == 0) return; // // JsonObject latest = array.get(0).getAsJsonObject(); // String version = latest.get("name").getAsString(); // // if(!version.contains(BetterFps.VERSION)) { // updateVersion = version; // updateDownload = latest.get("url").getAsString(); // } // // done = true; // // if(!BetterFps.CLIENT) { // showConsole(); // } else { // if(Minecraft.getMinecraft().player != null) { // showChat(Minecraft.getMinecraft().player); // } // } // } catch(Exception ex) { // BetterFpsHelper.LOG.warn("Could not check for updates: " + ex.getMessage()); // } finally { // done = true; // } // } // }
import guichaguri.betterfps.UpdateChecker; import guichaguri.betterfps.transformers.annotations.Copy; import guichaguri.betterfps.transformers.annotations.Copy.Mode; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.stats.RecipeBook; import net.minecraft.stats.StatisticsManager; import net.minecraft.world.World;
package guichaguri.betterfps.patches.misc; /** * @author Guilherme Chaguri */ public abstract class ClientPlayerPatch extends EntityPlayerSP { public ClientPlayerPatch(Minecraft p_i47378_1_, World p_i47378_2_, NetHandlerPlayClient p_i47378_3_, StatisticsManager p_i47378_4_, RecipeBook p_i47378_5_) { super(p_i47378_1_, p_i47378_2_, p_i47378_3_, p_i47378_4_, p_i47378_5_); } @Copy(Mode.REPLACE) @Override public void preparePlayerToSpawn() {
// Path: src/main/java/guichaguri/betterfps/UpdateChecker.java // public class UpdateChecker implements Runnable { // // private static boolean updateCheck = false; // private static boolean done = false; // private static String updateVersion = null; // private static String updateDownload = null; // // public static void check() { // if(!BetterFpsHelper.getConfig().updateChecker) { // done = true; // return; // } // if(!updateCheck) { // updateCheck = true; // checkForced(); // } // } // // public static void checkForced() { // done = false; // Thread thread = new Thread(new UpdateChecker(), "BetterFps Update Checker"); // thread.setDaemon(true); // thread.start(); // } // // public static void showChat(EntityPlayerSP player) { // if(!done) return; // if(updateVersion == null && updateDownload == null) return; // if(!BetterFps.CLIENT) return; // // TextComponentTranslation title = new TextComponentTranslation("betterfps.update.available", updateVersion); // title.setStyle(title.getStyle().setColor(TextFormatting.GREEN).setBold(true)); // // TextComponentString buttons = new TextComponentString(" "); // buttons.setStyle(buttons.getStyle().setColor(TextFormatting.YELLOW)); // buttons.appendSibling(createButton(updateDownload, "betterfps.update.button.download")); // buttons.appendText(" "); // buttons.appendSibling(createButton(BetterFps.URL, "betterfps.update.button.more")); // // int phrase = (int)(Math.random() * 12) + 1; // TextComponentTranslation desc = new TextComponentTranslation("betterfps.update.phrase." + phrase); // desc.setStyle(desc.getStyle().setColor(TextFormatting.GRAY)); // // if(updateVersion.length() < 8) { // title.appendSibling(buttons); // player.sendStatusMessage(title, false); // player.sendStatusMessage(desc, false); // } else { // player.sendStatusMessage(title, false); // player.sendStatusMessage(buttons, false); // player.sendStatusMessage(desc, false); // } // // updateVersion = null; // updateDownload = null; // } // // private static void showConsole() { // if(!done) return; // if(updateVersion == null && updateDownload == null) return; // // BetterFpsHelper.LOG.info("BetterFps " + updateVersion + " is available"); // BetterFpsHelper.LOG.info("Download: " + updateDownload); // BetterFpsHelper.LOG.info("More: " + BetterFps.URL); // // updateVersion = null; // updateDownload = null; // } // // private static TextComponentTranslation createButton(String link, String key) { // TextComponentTranslation sib = new TextComponentTranslation(key); // Style style = sib.getStyle(); // style.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, link)); // TextComponentTranslation h = new TextComponentTranslation(key + ".info"); // h.setStyle(h.getStyle().setColor(TextFormatting.RED)); // style.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, h)); // sib.setStyle(style); // return sib; // } // // @Override // public void run() { // try { // URL url = new URL(BetterFps.UPDATE_URL); // InputStream in = url.openStream(); // JsonParser parser = new JsonParser(); // JsonObject obj = parser.parse(new InputStreamReader(in)).getAsJsonObject(); // JsonObject versions = obj.getAsJsonObject("versions"); // // if(!versions.has(BetterFps.MC_VERSION)) return; // JsonArray array = versions.getAsJsonArray(BetterFps.MC_VERSION); // if(array.size() == 0) return; // // JsonObject latest = array.get(0).getAsJsonObject(); // String version = latest.get("name").getAsString(); // // if(!version.contains(BetterFps.VERSION)) { // updateVersion = version; // updateDownload = latest.get("url").getAsString(); // } // // done = true; // // if(!BetterFps.CLIENT) { // showConsole(); // } else { // if(Minecraft.getMinecraft().player != null) { // showChat(Minecraft.getMinecraft().player); // } // } // } catch(Exception ex) { // BetterFpsHelper.LOG.warn("Could not check for updates: " + ex.getMessage()); // } finally { // done = true; // } // } // } // Path: src/main/java/guichaguri/betterfps/patches/misc/ClientPlayerPatch.java import guichaguri.betterfps.UpdateChecker; import guichaguri.betterfps.transformers.annotations.Copy; import guichaguri.betterfps.transformers.annotations.Copy.Mode; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.stats.RecipeBook; import net.minecraft.stats.StatisticsManager; import net.minecraft.world.World; package guichaguri.betterfps.patches.misc; /** * @author Guilherme Chaguri */ public abstract class ClientPlayerPatch extends EntityPlayerSP { public ClientPlayerPatch(Minecraft p_i47378_1_, World p_i47378_2_, NetHandlerPlayClient p_i47378_3_, StatisticsManager p_i47378_4_, RecipeBook p_i47378_5_) { super(p_i47378_1_, p_i47378_2_, p_i47378_3_, p_i47378_4_, p_i47378_5_); } @Copy(Mode.REPLACE) @Override public void preparePlayerToSpawn() {
UpdateChecker.showChat(this);
Guichaguri/BetterFps
src/main/java/guichaguri/betterfps/patches/block/FastBeacon.java
// Path: src/main/java/guichaguri/betterfps/api/IBlock.java // public interface IBlock { // // /** // * Method added by Forge. Reimplemented for compatibility with it. // */ // boolean isBeaconBase(IBlockAccess worldObj, BlockPos pos, BlockPos beacon); // // /** // * Method added by Forge. Reimplemented for compatibility with it. // */ // @Nullable // float[] getBeaconColorMultiplier(IBlockState state, World world, BlockPos pos, BlockPos beaconPos); // // } // // Path: src/main/java/guichaguri/betterfps/transformers/Conditions.java // public class Conditions { // // protected static final List<Mappings> patched = new ArrayList<Mappings>(); // // public static final String FAST_HOPPER = "fastHopper"; // public static final String FAST_BEACON = "fastBeacon"; // public static final String FAST_SEARCH = "fastSearch"; // public static final String FAST_BEAM_RENDER = "fastBeaconBeamRender"; // public static final String FOG_DISABLED = "fogDisabled"; // // /** // * Checks whether the condition identifier is met // */ // public static boolean shouldPatch(String condition) { // BetterFpsConfig config = BetterFpsHelper.getConfig(); // // if(condition.equals(FAST_HOPPER)) { // return config.fastHopper; // } else if(condition.equals(FAST_BEACON)) { // return config.fastBeacon; // } else if(condition.equals(FAST_SEARCH)) { // return config.fastSearch; // } else if(condition.equals(FAST_BEAM_RENDER)) { // return !config.beaconBeam; // } else if(condition.equals(FOG_DISABLED)) { // return !config.fog; // } // // return true; // } // // /** // * Checks whether the {@link Condition} annotation has its condition met // */ // public static boolean shouldPatch(List<AnnotationNode> annotations) { // AnnotationNode condition = ASMUtils.getAnnotation(annotations, Condition.class); // if(condition != null) { // String id = ASMUtils.getAnnotationValue(condition, "value", String.class); // return id == null || shouldPatch(id); // } // return true; // } // // public static boolean isPatched(Mappings name) { // return patched.contains(name); // } // // }
import guichaguri.betterfps.api.IBlock; import guichaguri.betterfps.transformers.Conditions; import guichaguri.betterfps.transformers.annotations.Condition; import guichaguri.betterfps.transformers.annotations.Copy; import guichaguri.betterfps.transformers.annotations.Copy.Mode; import java.util.Arrays; import net.minecraft.advancements.CriteriaTriggers; import net.minecraft.block.Block; import net.minecraft.block.BlockStainedGlass; import net.minecraft.block.BlockStainedGlassPane; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.passive.EntitySheep; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.item.EnumDyeColor; import net.minecraft.potion.PotionEffect; import net.minecraft.tileentity.TileEntityBeacon; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos;
*/ @Copy private void updateGlassLayers(int x, int y, int z) { BeamSegment beam = new BeamSegment(EntitySheep.getDyeRgb(EnumDyeColor.WHITE)); float[] oldColor = null; beamSegments.clear(); beamSegments.add(beam); isComplete = true; for(int blockY = y + 1; blockY < world.getActualHeight(); blockY++) { BlockPos blockPos = new BlockPos(x, blockY, z); IBlockState state = world.getBlockState(blockPos); Block b = state.getBlock(); float[] color = null; if(b == Blocks.STAINED_GLASS) { color = EntitySheep.getDyeRgb(state.getValue(BlockStainedGlass.COLOR)); } else if(b == Blocks.STAINED_GLASS_PANE) { color = EntitySheep.getDyeRgb(state.getValue(BlockStainedGlassPane.COLOR)); } else { if(b != Blocks.BEDROCK && state.getLightOpacity() >= 15) { isComplete = false; beamSegments.clear(); break; } // Forge Compatibility
// Path: src/main/java/guichaguri/betterfps/api/IBlock.java // public interface IBlock { // // /** // * Method added by Forge. Reimplemented for compatibility with it. // */ // boolean isBeaconBase(IBlockAccess worldObj, BlockPos pos, BlockPos beacon); // // /** // * Method added by Forge. Reimplemented for compatibility with it. // */ // @Nullable // float[] getBeaconColorMultiplier(IBlockState state, World world, BlockPos pos, BlockPos beaconPos); // // } // // Path: src/main/java/guichaguri/betterfps/transformers/Conditions.java // public class Conditions { // // protected static final List<Mappings> patched = new ArrayList<Mappings>(); // // public static final String FAST_HOPPER = "fastHopper"; // public static final String FAST_BEACON = "fastBeacon"; // public static final String FAST_SEARCH = "fastSearch"; // public static final String FAST_BEAM_RENDER = "fastBeaconBeamRender"; // public static final String FOG_DISABLED = "fogDisabled"; // // /** // * Checks whether the condition identifier is met // */ // public static boolean shouldPatch(String condition) { // BetterFpsConfig config = BetterFpsHelper.getConfig(); // // if(condition.equals(FAST_HOPPER)) { // return config.fastHopper; // } else if(condition.equals(FAST_BEACON)) { // return config.fastBeacon; // } else if(condition.equals(FAST_SEARCH)) { // return config.fastSearch; // } else if(condition.equals(FAST_BEAM_RENDER)) { // return !config.beaconBeam; // } else if(condition.equals(FOG_DISABLED)) { // return !config.fog; // } // // return true; // } // // /** // * Checks whether the {@link Condition} annotation has its condition met // */ // public static boolean shouldPatch(List<AnnotationNode> annotations) { // AnnotationNode condition = ASMUtils.getAnnotation(annotations, Condition.class); // if(condition != null) { // String id = ASMUtils.getAnnotationValue(condition, "value", String.class); // return id == null || shouldPatch(id); // } // return true; // } // // public static boolean isPatched(Mappings name) { // return patched.contains(name); // } // // } // Path: src/main/java/guichaguri/betterfps/patches/block/FastBeacon.java import guichaguri.betterfps.api.IBlock; import guichaguri.betterfps.transformers.Conditions; import guichaguri.betterfps.transformers.annotations.Condition; import guichaguri.betterfps.transformers.annotations.Copy; import guichaguri.betterfps.transformers.annotations.Copy.Mode; import java.util.Arrays; import net.minecraft.advancements.CriteriaTriggers; import net.minecraft.block.Block; import net.minecraft.block.BlockStainedGlass; import net.minecraft.block.BlockStainedGlassPane; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.passive.EntitySheep; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.item.EnumDyeColor; import net.minecraft.potion.PotionEffect; import net.minecraft.tileentity.TileEntityBeacon; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; */ @Copy private void updateGlassLayers(int x, int y, int z) { BeamSegment beam = new BeamSegment(EntitySheep.getDyeRgb(EnumDyeColor.WHITE)); float[] oldColor = null; beamSegments.clear(); beamSegments.add(beam); isComplete = true; for(int blockY = y + 1; blockY < world.getActualHeight(); blockY++) { BlockPos blockPos = new BlockPos(x, blockY, z); IBlockState state = world.getBlockState(blockPos); Block b = state.getBlock(); float[] color = null; if(b == Blocks.STAINED_GLASS) { color = EntitySheep.getDyeRgb(state.getValue(BlockStainedGlass.COLOR)); } else if(b == Blocks.STAINED_GLASS_PANE) { color = EntitySheep.getDyeRgb(state.getValue(BlockStainedGlassPane.COLOR)); } else { if(b != Blocks.BEDROCK && state.getLightOpacity() >= 15) { isComplete = false; beamSegments.clear(); break; } // Forge Compatibility
float[] customColor = ((IBlock)b).getBeaconColorMultiplier(state, world, blockPos, pos);
Guichaguri/BetterFps
src/main/java/guichaguri/betterfps/installer/BetterFpsInstaller.java
// Path: src/main/java/guichaguri/betterfps/BetterFps.java // public class BetterFps { // // public static final String MC_VERSION = "1.12"; // public static final String VERSION = "1.4.7"; // public static final String URL = "http://guichaguri.github.io/BetterFps/"; // public static final String UPDATE_URL = "http://widget.mcf.li/mc-mods/minecraft/229876-betterfps.json"; // // public static boolean CLIENT = false; // public static File GAME_DIR = null; // // }
import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonArray; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; import com.eclipsesource.json.WriterConfig; import guichaguri.betterfps.BetterFps; import java.awt.Desktop; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.UIManager;
package guichaguri.betterfps.installer; /** * @author Guilherme Chaguri */ public class BetterFpsInstaller { private static final String TWEAK_CLASS = "guichaguri.betterfps.tweaker.BetterFpsTweaker"; private static final String LIBRARY_IDENTIFIER = "betterfps";
// Path: src/main/java/guichaguri/betterfps/BetterFps.java // public class BetterFps { // // public static final String MC_VERSION = "1.12"; // public static final String VERSION = "1.4.7"; // public static final String URL = "http://guichaguri.github.io/BetterFps/"; // public static final String UPDATE_URL = "http://widget.mcf.li/mc-mods/minecraft/229876-betterfps.json"; // // public static boolean CLIENT = false; // public static File GAME_DIR = null; // // } // Path: src/main/java/guichaguri/betterfps/installer/BetterFpsInstaller.java import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonArray; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; import com.eclipsesource.json.WriterConfig; import guichaguri.betterfps.BetterFps; import java.awt.Desktop; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.UIManager; package guichaguri.betterfps.installer; /** * @author Guilherme Chaguri */ public class BetterFpsInstaller { private static final String TWEAK_CLASS = "guichaguri.betterfps.tweaker.BetterFpsTweaker"; private static final String LIBRARY_IDENTIFIER = "betterfps";
private static final String LIBRARY_NAME = "BetterFps";
Guichaguri/BetterFps
src/test/java/guichaguri/betterfps/test/math/JavaMathTest.java
// Path: src/main/java/guichaguri/betterfps/math/JavaMath.java // public class JavaMath { // // public static float sin(float radians) { // return (float)Math.sin(radians); // } // // public static float cos(float radians) { // return (float)Math.cos(radians); // } // }
import guichaguri.betterfps.math.JavaMath; import org.junit.Assert; import org.junit.Test;
package guichaguri.betterfps.test.math; /** * @author Guilherme Chaguri */ public class JavaMathTest { @Test public void testSine() {
// Path: src/main/java/guichaguri/betterfps/math/JavaMath.java // public class JavaMath { // // public static float sin(float radians) { // return (float)Math.sin(radians); // } // // public static float cos(float radians) { // return (float)Math.cos(radians); // } // } // Path: src/test/java/guichaguri/betterfps/test/math/JavaMathTest.java import guichaguri.betterfps.math.JavaMath; import org.junit.Assert; import org.junit.Test; package guichaguri.betterfps.test.math; /** * @author Guilherme Chaguri */ public class JavaMathTest { @Test public void testSine() {
float sine = JavaMath.sin(1);
Guichaguri/BetterFps
src/main/java/guichaguri/betterfps/tweaker/BetterFpsTweaker.java
// Path: src/main/java/guichaguri/betterfps/BetterFps.java // public class BetterFps { // // public static final String MC_VERSION = "1.12"; // public static final String VERSION = "1.4.7"; // public static final String URL = "http://guichaguri.github.io/BetterFps/"; // public static final String UPDATE_URL = "http://widget.mcf.li/mc-mods/minecraft/229876-betterfps.json"; // // public static boolean CLIENT = false; // public static File GAME_DIR = null; // // } // // Path: src/main/java/guichaguri/betterfps/BetterFpsHelper.java // public class BetterFpsHelper { // // public static final Logger LOG = LogManager.getLogger("BetterFps"); // // private static BetterFpsConfig INSTANCE = null; // private static File CONFIG_FILE = null; // // public static BetterFpsConfig getConfig() { // if(INSTANCE == null) loadConfig(); // return INSTANCE; // } // // public static void loadConfig() { // File configPath; // if(BetterFps.GAME_DIR == null) { // configPath = new File("config"); // } else { // configPath = new File(BetterFps.GAME_DIR, "config"); // } // // CONFIG_FILE = new File(configPath, "betterfps.json"); // // // Temporary code - Import old config file to the new one // File oldConfig; // if(BetterFps.GAME_DIR == null) { // oldConfig = new File("config" + File.pathSeparator + "betterfps.json"); // } else { // oldConfig = new File(BetterFps.GAME_DIR, "config" + File.pathSeparator + "betterfps.json"); // } // if(oldConfig.exists()) { // FileReader reader = null; // try { // reader = new FileReader(oldConfig); // INSTANCE = new Gson().fromJson(reader, BetterFpsConfig.class); // saveConfig(); // return; // } catch(Exception ex) { // LOG.error("Could not load the old config file. It will be deleted."); // } finally { // IOUtils.closeQuietly(reader); // oldConfig.deleteOnExit(); // } // } // // ------- // // FileReader reader = null; // try { // if(CONFIG_FILE.exists()) { // reader = new FileReader(CONFIG_FILE); // INSTANCE = new Gson().fromJson(reader, BetterFpsConfig.class); // } // } catch(Exception ex) { // LOG.error("Could not load the config file", ex); // } finally { // IOUtils.closeQuietly(reader); // } // // if(INSTANCE == null) INSTANCE = new BetterFpsConfig(); // // saveConfig(); // } // // public static void saveConfig() { // FileWriter writer = null; // try { // if(!CONFIG_FILE.exists()) CONFIG_FILE.getParentFile().mkdirs(); // writer = new FileWriter(CONFIG_FILE); // new Gson().toJson(INSTANCE, writer); // } catch(Exception ex) { // LOG.error("Could not save the config file", ex); // } finally { // IOUtils.closeQuietly(writer); // } // } // // }
import guichaguri.betterfps.BetterFps; import guichaguri.betterfps.BetterFpsHelper; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; import net.minecraft.launchwrapper.ITweaker; import net.minecraft.launchwrapper.Launch; import net.minecraft.launchwrapper.LaunchClassLoader;
private final String[] EXCLUDED = new String[] { "guichaguri.betterfps.transformers", "guichaguri.betterfps.tweaker", "guichaguri.betterfps.patchers" }; private final String[] LOAD_DISABLED = new String[] { "guichaguri.betterfps.installer", "guichaguri.betterfps.math", "guichaguri.betterfps.patches" }; private List<String> args; @Override public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) { this.args = new ArrayList<String>(args); this.args.add("--version"); this.args.add(profile); if(assetsDir != null) { this.args.add("--assetsDir"); this.args.add(assetsDir.getAbsolutePath()); } if(gameDir != null) { this.args.add("--gameDir"); this.args.add(gameDir.getAbsolutePath()); }
// Path: src/main/java/guichaguri/betterfps/BetterFps.java // public class BetterFps { // // public static final String MC_VERSION = "1.12"; // public static final String VERSION = "1.4.7"; // public static final String URL = "http://guichaguri.github.io/BetterFps/"; // public static final String UPDATE_URL = "http://widget.mcf.li/mc-mods/minecraft/229876-betterfps.json"; // // public static boolean CLIENT = false; // public static File GAME_DIR = null; // // } // // Path: src/main/java/guichaguri/betterfps/BetterFpsHelper.java // public class BetterFpsHelper { // // public static final Logger LOG = LogManager.getLogger("BetterFps"); // // private static BetterFpsConfig INSTANCE = null; // private static File CONFIG_FILE = null; // // public static BetterFpsConfig getConfig() { // if(INSTANCE == null) loadConfig(); // return INSTANCE; // } // // public static void loadConfig() { // File configPath; // if(BetterFps.GAME_DIR == null) { // configPath = new File("config"); // } else { // configPath = new File(BetterFps.GAME_DIR, "config"); // } // // CONFIG_FILE = new File(configPath, "betterfps.json"); // // // Temporary code - Import old config file to the new one // File oldConfig; // if(BetterFps.GAME_DIR == null) { // oldConfig = new File("config" + File.pathSeparator + "betterfps.json"); // } else { // oldConfig = new File(BetterFps.GAME_DIR, "config" + File.pathSeparator + "betterfps.json"); // } // if(oldConfig.exists()) { // FileReader reader = null; // try { // reader = new FileReader(oldConfig); // INSTANCE = new Gson().fromJson(reader, BetterFpsConfig.class); // saveConfig(); // return; // } catch(Exception ex) { // LOG.error("Could not load the old config file. It will be deleted."); // } finally { // IOUtils.closeQuietly(reader); // oldConfig.deleteOnExit(); // } // } // // ------- // // FileReader reader = null; // try { // if(CONFIG_FILE.exists()) { // reader = new FileReader(CONFIG_FILE); // INSTANCE = new Gson().fromJson(reader, BetterFpsConfig.class); // } // } catch(Exception ex) { // LOG.error("Could not load the config file", ex); // } finally { // IOUtils.closeQuietly(reader); // } // // if(INSTANCE == null) INSTANCE = new BetterFpsConfig(); // // saveConfig(); // } // // public static void saveConfig() { // FileWriter writer = null; // try { // if(!CONFIG_FILE.exists()) CONFIG_FILE.getParentFile().mkdirs(); // writer = new FileWriter(CONFIG_FILE); // new Gson().toJson(INSTANCE, writer); // } catch(Exception ex) { // LOG.error("Could not save the config file", ex); // } finally { // IOUtils.closeQuietly(writer); // } // } // // } // Path: src/main/java/guichaguri/betterfps/tweaker/BetterFpsTweaker.java import guichaguri.betterfps.BetterFps; import guichaguri.betterfps.BetterFpsHelper; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; import net.minecraft.launchwrapper.ITweaker; import net.minecraft.launchwrapper.Launch; import net.minecraft.launchwrapper.LaunchClassLoader; private final String[] EXCLUDED = new String[] { "guichaguri.betterfps.transformers", "guichaguri.betterfps.tweaker", "guichaguri.betterfps.patchers" }; private final String[] LOAD_DISABLED = new String[] { "guichaguri.betterfps.installer", "guichaguri.betterfps.math", "guichaguri.betterfps.patches" }; private List<String> args; @Override public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) { this.args = new ArrayList<String>(args); this.args.add("--version"); this.args.add(profile); if(assetsDir != null) { this.args.add("--assetsDir"); this.args.add(assetsDir.getAbsolutePath()); } if(gameDir != null) { this.args.add("--gameDir"); this.args.add(gameDir.getAbsolutePath()); }
BetterFps.GAME_DIR = gameDir;
Guichaguri/BetterFps
src/main/java/guichaguri/betterfps/tweaker/BetterFpsTweaker.java
// Path: src/main/java/guichaguri/betterfps/BetterFps.java // public class BetterFps { // // public static final String MC_VERSION = "1.12"; // public static final String VERSION = "1.4.7"; // public static final String URL = "http://guichaguri.github.io/BetterFps/"; // public static final String UPDATE_URL = "http://widget.mcf.li/mc-mods/minecraft/229876-betterfps.json"; // // public static boolean CLIENT = false; // public static File GAME_DIR = null; // // } // // Path: src/main/java/guichaguri/betterfps/BetterFpsHelper.java // public class BetterFpsHelper { // // public static final Logger LOG = LogManager.getLogger("BetterFps"); // // private static BetterFpsConfig INSTANCE = null; // private static File CONFIG_FILE = null; // // public static BetterFpsConfig getConfig() { // if(INSTANCE == null) loadConfig(); // return INSTANCE; // } // // public static void loadConfig() { // File configPath; // if(BetterFps.GAME_DIR == null) { // configPath = new File("config"); // } else { // configPath = new File(BetterFps.GAME_DIR, "config"); // } // // CONFIG_FILE = new File(configPath, "betterfps.json"); // // // Temporary code - Import old config file to the new one // File oldConfig; // if(BetterFps.GAME_DIR == null) { // oldConfig = new File("config" + File.pathSeparator + "betterfps.json"); // } else { // oldConfig = new File(BetterFps.GAME_DIR, "config" + File.pathSeparator + "betterfps.json"); // } // if(oldConfig.exists()) { // FileReader reader = null; // try { // reader = new FileReader(oldConfig); // INSTANCE = new Gson().fromJson(reader, BetterFpsConfig.class); // saveConfig(); // return; // } catch(Exception ex) { // LOG.error("Could not load the old config file. It will be deleted."); // } finally { // IOUtils.closeQuietly(reader); // oldConfig.deleteOnExit(); // } // } // // ------- // // FileReader reader = null; // try { // if(CONFIG_FILE.exists()) { // reader = new FileReader(CONFIG_FILE); // INSTANCE = new Gson().fromJson(reader, BetterFpsConfig.class); // } // } catch(Exception ex) { // LOG.error("Could not load the config file", ex); // } finally { // IOUtils.closeQuietly(reader); // } // // if(INSTANCE == null) INSTANCE = new BetterFpsConfig(); // // saveConfig(); // } // // public static void saveConfig() { // FileWriter writer = null; // try { // if(!CONFIG_FILE.exists()) CONFIG_FILE.getParentFile().mkdirs(); // writer = new FileWriter(CONFIG_FILE); // new Gson().toJson(INSTANCE, writer); // } catch(Exception ex) { // LOG.error("Could not save the config file", ex); // } finally { // IOUtils.closeQuietly(writer); // } // } // // }
import guichaguri.betterfps.BetterFps; import guichaguri.betterfps.BetterFpsHelper; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; import net.minecraft.launchwrapper.ITweaker; import net.minecraft.launchwrapper.Launch; import net.minecraft.launchwrapper.LaunchClassLoader;
for(String excluded : EXCLUDED) { cl.addTransformerExclusion(excluded); } for(String loadDisabled : LOAD_DISABLED) { cl.addClassLoaderExclusion(loadDisabled); } } @Override public String getLaunchTarget() { return "net.minecraft.client.main.Main"; } @Override public String[] getLaunchArguments() { ArrayList args = (ArrayList)Launch.blackboard.get("ArgumentList"); if(args.isEmpty()) args.addAll(this.args); this.args = null; // Just in case someone needs to know whether BetterFps is running Launch.blackboard.put("BetterFpsVersion", BetterFps.VERSION); return new String[0]; } private void loadMappings() {
// Path: src/main/java/guichaguri/betterfps/BetterFps.java // public class BetterFps { // // public static final String MC_VERSION = "1.12"; // public static final String VERSION = "1.4.7"; // public static final String URL = "http://guichaguri.github.io/BetterFps/"; // public static final String UPDATE_URL = "http://widget.mcf.li/mc-mods/minecraft/229876-betterfps.json"; // // public static boolean CLIENT = false; // public static File GAME_DIR = null; // // } // // Path: src/main/java/guichaguri/betterfps/BetterFpsHelper.java // public class BetterFpsHelper { // // public static final Logger LOG = LogManager.getLogger("BetterFps"); // // private static BetterFpsConfig INSTANCE = null; // private static File CONFIG_FILE = null; // // public static BetterFpsConfig getConfig() { // if(INSTANCE == null) loadConfig(); // return INSTANCE; // } // // public static void loadConfig() { // File configPath; // if(BetterFps.GAME_DIR == null) { // configPath = new File("config"); // } else { // configPath = new File(BetterFps.GAME_DIR, "config"); // } // // CONFIG_FILE = new File(configPath, "betterfps.json"); // // // Temporary code - Import old config file to the new one // File oldConfig; // if(BetterFps.GAME_DIR == null) { // oldConfig = new File("config" + File.pathSeparator + "betterfps.json"); // } else { // oldConfig = new File(BetterFps.GAME_DIR, "config" + File.pathSeparator + "betterfps.json"); // } // if(oldConfig.exists()) { // FileReader reader = null; // try { // reader = new FileReader(oldConfig); // INSTANCE = new Gson().fromJson(reader, BetterFpsConfig.class); // saveConfig(); // return; // } catch(Exception ex) { // LOG.error("Could not load the old config file. It will be deleted."); // } finally { // IOUtils.closeQuietly(reader); // oldConfig.deleteOnExit(); // } // } // // ------- // // FileReader reader = null; // try { // if(CONFIG_FILE.exists()) { // reader = new FileReader(CONFIG_FILE); // INSTANCE = new Gson().fromJson(reader, BetterFpsConfig.class); // } // } catch(Exception ex) { // LOG.error("Could not load the config file", ex); // } finally { // IOUtils.closeQuietly(reader); // } // // if(INSTANCE == null) INSTANCE = new BetterFpsConfig(); // // saveConfig(); // } // // public static void saveConfig() { // FileWriter writer = null; // try { // if(!CONFIG_FILE.exists()) CONFIG_FILE.getParentFile().mkdirs(); // writer = new FileWriter(CONFIG_FILE); // new Gson().toJson(INSTANCE, writer); // } catch(Exception ex) { // LOG.error("Could not save the config file", ex); // } finally { // IOUtils.closeQuietly(writer); // } // } // // } // Path: src/main/java/guichaguri/betterfps/tweaker/BetterFpsTweaker.java import guichaguri.betterfps.BetterFps; import guichaguri.betterfps.BetterFpsHelper; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; import net.minecraft.launchwrapper.ITweaker; import net.minecraft.launchwrapper.Launch; import net.minecraft.launchwrapper.LaunchClassLoader; for(String excluded : EXCLUDED) { cl.addTransformerExclusion(excluded); } for(String loadDisabled : LOAD_DISABLED) { cl.addClassLoaderExclusion(loadDisabled); } } @Override public String getLaunchTarget() { return "net.minecraft.client.main.Main"; } @Override public String[] getLaunchArguments() { ArrayList args = (ArrayList)Launch.blackboard.get("ArgumentList"); if(args.isEmpty()) args.addAll(this.args); this.args = null; // Just in case someone needs to know whether BetterFps is running Launch.blackboard.put("BetterFpsVersion", BetterFps.VERSION); return new String[0]; } private void loadMappings() {
BetterFpsHelper.LOG.debug("Loading Mappings...");
Guichaguri/BetterFps
src/main/java/guichaguri/betterfps/installer/GuiInstaller.java
// Path: src/main/java/guichaguri/betterfps/BetterFps.java // public class BetterFps { // // public static final String MC_VERSION = "1.12"; // public static final String VERSION = "1.4.7"; // public static final String URL = "http://guichaguri.github.io/BetterFps/"; // public static final String UPDATE_URL = "http://widget.mcf.li/mc-mods/minecraft/229876-betterfps.json"; // // public static boolean CLIENT = false; // public static File GAME_DIR = null; // // }
import guichaguri.betterfps.BetterFps; import java.awt.Desktop; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.concurrent.TimeUnit; import javax.swing.*;
package guichaguri.betterfps.installer; /** * @author Guilherme Chaguri */ public class GuiInstaller extends JFrame implements ActionListener { private final String INSTALL = "install"; private final String EXTRACT = "extract"; private final String TEST_ALGORITHMS = "algorithm_test"; private final String DOWNLOADS = "downloads"; private final String ISSUES = "issues"; private final String ISSUES_URL = "https://github.com/Guichaguri/BetterFps/issues"; public GuiInstaller() { setTitle(BetterFpsInstaller.i18n("betterfps.installer.title")); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel content = new JPanel(); content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS)); content.setBorder(BorderFactory.createEmptyBorder(25, 25, 25, 25));
// Path: src/main/java/guichaguri/betterfps/BetterFps.java // public class BetterFps { // // public static final String MC_VERSION = "1.12"; // public static final String VERSION = "1.4.7"; // public static final String URL = "http://guichaguri.github.io/BetterFps/"; // public static final String UPDATE_URL = "http://widget.mcf.li/mc-mods/minecraft/229876-betterfps.json"; // // public static boolean CLIENT = false; // public static File GAME_DIR = null; // // } // Path: src/main/java/guichaguri/betterfps/installer/GuiInstaller.java import guichaguri.betterfps.BetterFps; import java.awt.Desktop; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.concurrent.TimeUnit; import javax.swing.*; package guichaguri.betterfps.installer; /** * @author Guilherme Chaguri */ public class GuiInstaller extends JFrame implements ActionListener { private final String INSTALL = "install"; private final String EXTRACT = "extract"; private final String TEST_ALGORITHMS = "algorithm_test"; private final String DOWNLOADS = "downloads"; private final String ISSUES = "issues"; private final String ISSUES_URL = "https://github.com/Guichaguri/BetterFps/issues"; public GuiInstaller() { setTitle(BetterFpsInstaller.i18n("betterfps.installer.title")); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel content = new JPanel(); content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS)); content.setBorder(BorderFactory.createEmptyBorder(25, 25, 25, 25));
content.add(createLabel("betterfps.installer.versions", BetterFps.VERSION, BetterFps.MC_VERSION));
Guichaguri/BetterFps
src/test/java/guichaguri/betterfps/test/math/RivensHalfMathTest.java
// Path: src/main/java/guichaguri/betterfps/math/RivensHalfMath.java // public class RivensHalfMath { // // private static final float BF_SIN_TO_COS; // private static final int BF_SIN_BITS, BF_SIN_MASK, BF_SIN_MASK2, BF_SIN_COUNT, BF_SIN_COUNT2; // private static final float BF_radFull, BF_radToIndex; // private static final float[] BF_sinHalf; // // static { // BF_SIN_TO_COS = (float)(Math.PI * 0.5f); // // BF_SIN_BITS = 12; // BF_SIN_MASK = ~(-1 << BF_SIN_BITS); // BF_SIN_MASK2 = BF_SIN_MASK >> 1; // BF_SIN_COUNT = BF_SIN_MASK + 1; // BF_SIN_COUNT2 = BF_SIN_MASK2 + 1; // // BF_radFull = (float)(Math.PI * 2.0); // BF_radToIndex = BF_SIN_COUNT / BF_radFull; // // BF_sinHalf = new float[BF_SIN_COUNT2]; // for (int i = 0; i < BF_SIN_COUNT2; i++) { // BF_sinHalf[i] = (float) Math.sin((i + Math.min(1, i % (BF_SIN_COUNT / 4)) * 0.5) / BF_SIN_COUNT * BF_radFull); // } // // float[] hardcodedAngles = { // 90 * 0.017453292F, // getLook when looking up (sin) - Fixes Elytra // 90 * 0.017453292F + BF_SIN_TO_COS // getLook when looking up (cos) - Fixes Elytra // }; // for(float angle : hardcodedAngles) { // int index1 = (int)(angle * BF_radToIndex) & BF_SIN_MASK; // int index2 = index1 & BF_SIN_MASK2; // int mul = ((index1 == index2) ? +1 : -1); // BF_sinHalf[index2] = (float)(Math.sin(angle) / mul); // } // } // // public static float sin(float rad) { // int index1 = (int) (rad * BF_radToIndex) & BF_SIN_MASK; // int index2 = index1 & BF_SIN_MASK2; // // int mul = (((index1 - index2) >>> 31) << 1) + 1; // int mul = ((index1 == index2) ? +1 : -1); // return BF_sinHalf[index2] * mul; // } // // public static float cos(float rad) { // return sin(rad + BF_SIN_TO_COS); // } // }
import guichaguri.betterfps.math.RivensHalfMath; import org.junit.Assert; import org.junit.Test;
package guichaguri.betterfps.test.math; /** * @author Guilherme Chaguri */ public class RivensHalfMathTest { @Test public void testSine() {
// Path: src/main/java/guichaguri/betterfps/math/RivensHalfMath.java // public class RivensHalfMath { // // private static final float BF_SIN_TO_COS; // private static final int BF_SIN_BITS, BF_SIN_MASK, BF_SIN_MASK2, BF_SIN_COUNT, BF_SIN_COUNT2; // private static final float BF_radFull, BF_radToIndex; // private static final float[] BF_sinHalf; // // static { // BF_SIN_TO_COS = (float)(Math.PI * 0.5f); // // BF_SIN_BITS = 12; // BF_SIN_MASK = ~(-1 << BF_SIN_BITS); // BF_SIN_MASK2 = BF_SIN_MASK >> 1; // BF_SIN_COUNT = BF_SIN_MASK + 1; // BF_SIN_COUNT2 = BF_SIN_MASK2 + 1; // // BF_radFull = (float)(Math.PI * 2.0); // BF_radToIndex = BF_SIN_COUNT / BF_radFull; // // BF_sinHalf = new float[BF_SIN_COUNT2]; // for (int i = 0; i < BF_SIN_COUNT2; i++) { // BF_sinHalf[i] = (float) Math.sin((i + Math.min(1, i % (BF_SIN_COUNT / 4)) * 0.5) / BF_SIN_COUNT * BF_radFull); // } // // float[] hardcodedAngles = { // 90 * 0.017453292F, // getLook when looking up (sin) - Fixes Elytra // 90 * 0.017453292F + BF_SIN_TO_COS // getLook when looking up (cos) - Fixes Elytra // }; // for(float angle : hardcodedAngles) { // int index1 = (int)(angle * BF_radToIndex) & BF_SIN_MASK; // int index2 = index1 & BF_SIN_MASK2; // int mul = ((index1 == index2) ? +1 : -1); // BF_sinHalf[index2] = (float)(Math.sin(angle) / mul); // } // } // // public static float sin(float rad) { // int index1 = (int) (rad * BF_radToIndex) & BF_SIN_MASK; // int index2 = index1 & BF_SIN_MASK2; // // int mul = (((index1 - index2) >>> 31) << 1) + 1; // int mul = ((index1 == index2) ? +1 : -1); // return BF_sinHalf[index2] * mul; // } // // public static float cos(float rad) { // return sin(rad + BF_SIN_TO_COS); // } // } // Path: src/test/java/guichaguri/betterfps/test/math/RivensHalfMathTest.java import guichaguri.betterfps.math.RivensHalfMath; import org.junit.Assert; import org.junit.Test; package guichaguri.betterfps.test.math; /** * @author Guilherme Chaguri */ public class RivensHalfMathTest { @Test public void testSine() {
float sine = RivensHalfMath.sin(1);