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
|
---|---|---|---|---|---|---|
jinahya/bit-io | src/test/java/com/github/jinahya/bit/io/AbstractBitOutputSpyTest.java | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static char randomValueForChar(final int size) {
// return (char) (current().nextInt(Character.MAX_VALUE + 1) >> (Integer.SIZE - size));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomValueForInt(final boolean unsigned, final int size) {
// final int value;
// if (unsigned) {
// value = current().nextInt() >>> (Integer.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextInt() >> (Integer.SIZE - size);
// if (size < Integer.SIZE) {
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static long randomValueForLong(final boolean unsigned, final int size) {
// final long value;
// if (unsigned) {
// value = current().nextLong() >>> (Long.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextLong() >> (Long.SIZE - size);
// if (size < Long.SIZE) {
// assertEquals(value >> size, value >= 0L ? 0L : -1L);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static short randomValueForShort(final boolean unsigned, final int size) {
// final short value;
// if (unsigned) {
// value = (short) (current().nextInt() >>> (Integer.SIZE - size));
// assertTrue(value >= 0);
// } else {
// value = (short) (current().nextInt() >> (Integer.SIZE - size));
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// return value;
// }
| import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; | package com.github.jinahya.bit.io;
/*-
* #%L
* bit-io
* %%
* Copyright (C) 2014 - 2019 Jinahya, Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
/**
* A class for unit-testing {@link AbstractBitOutput} class.
*
* @author Jin Kwon <onacit_at_gmail.com>
* @see AbstractBitInputSpyTest
*/
@ExtendWith({MockitoExtension.class})
@Slf4j
final class AbstractBitOutputSpyTest {
// -----------------------------------------------------------------------------------------------------------------
@BeforeEach
void stubWrite() throws IOException {
//lenient().doNothing().when(bitOutput).write(anyInt());
}
// -----------------------------------------------------------------------------------------------------------------
@AfterEach
void alignAfterEach() throws IOException {
bitOutput.align(current().nextInt(1, 8));
}
// --------------------------------------------------------------------------------------------------------- boolean
@RepeatedTest(8)
void testWriteBoolean() throws IOException {
final boolean value = current().nextBoolean();
bitOutput.writeBoolean(value);
}
// ------------------------------------------------------------------------------------------------------------ byte
@RepeatedTest(8)
void testWriteByte() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = BitIoTests.randomSizeForByte(unsigned);
final byte value = BitIoTests.randomValueForByte(unsigned, size);
bitOutput.writeByte(unsigned, size, value);
}
// ----------------------------------------------------------------------------------------------------------- short
@RepeatedTest(8)
void testWriteShort() throws IOException {
final boolean unsigned = current().nextBoolean(); | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static char randomValueForChar(final int size) {
// return (char) (current().nextInt(Character.MAX_VALUE + 1) >> (Integer.SIZE - size));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomValueForInt(final boolean unsigned, final int size) {
// final int value;
// if (unsigned) {
// value = current().nextInt() >>> (Integer.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextInt() >> (Integer.SIZE - size);
// if (size < Integer.SIZE) {
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static long randomValueForLong(final boolean unsigned, final int size) {
// final long value;
// if (unsigned) {
// value = current().nextLong() >>> (Long.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextLong() >> (Long.SIZE - size);
// if (size < Long.SIZE) {
// assertEquals(value >> size, value >= 0L ? 0L : -1L);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static short randomValueForShort(final boolean unsigned, final int size) {
// final short value;
// if (unsigned) {
// value = (short) (current().nextInt() >>> (Integer.SIZE - size));
// assertTrue(value >= 0);
// } else {
// value = (short) (current().nextInt() >> (Integer.SIZE - size));
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// return value;
// }
// Path: src/test/java/com/github/jinahya/bit/io/AbstractBitOutputSpyTest.java
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
package com.github.jinahya.bit.io;
/*-
* #%L
* bit-io
* %%
* Copyright (C) 2014 - 2019 Jinahya, Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
/**
* A class for unit-testing {@link AbstractBitOutput} class.
*
* @author Jin Kwon <onacit_at_gmail.com>
* @see AbstractBitInputSpyTest
*/
@ExtendWith({MockitoExtension.class})
@Slf4j
final class AbstractBitOutputSpyTest {
// -----------------------------------------------------------------------------------------------------------------
@BeforeEach
void stubWrite() throws IOException {
//lenient().doNothing().when(bitOutput).write(anyInt());
}
// -----------------------------------------------------------------------------------------------------------------
@AfterEach
void alignAfterEach() throws IOException {
bitOutput.align(current().nextInt(1, 8));
}
// --------------------------------------------------------------------------------------------------------- boolean
@RepeatedTest(8)
void testWriteBoolean() throws IOException {
final boolean value = current().nextBoolean();
bitOutput.writeBoolean(value);
}
// ------------------------------------------------------------------------------------------------------------ byte
@RepeatedTest(8)
void testWriteByte() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = BitIoTests.randomSizeForByte(unsigned);
final byte value = BitIoTests.randomValueForByte(unsigned, size);
bitOutput.writeByte(unsigned, size, value);
}
// ----------------------------------------------------------------------------------------------------------- short
@RepeatedTest(8)
void testWriteShort() throws IOException {
final boolean unsigned = current().nextBoolean(); | final int size = randomSizeForShort(unsigned); |
jinahya/bit-io | src/test/java/com/github/jinahya/bit/io/AbstractBitOutputSpyTest.java | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static char randomValueForChar(final int size) {
// return (char) (current().nextInt(Character.MAX_VALUE + 1) >> (Integer.SIZE - size));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomValueForInt(final boolean unsigned, final int size) {
// final int value;
// if (unsigned) {
// value = current().nextInt() >>> (Integer.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextInt() >> (Integer.SIZE - size);
// if (size < Integer.SIZE) {
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static long randomValueForLong(final boolean unsigned, final int size) {
// final long value;
// if (unsigned) {
// value = current().nextLong() >>> (Long.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextLong() >> (Long.SIZE - size);
// if (size < Long.SIZE) {
// assertEquals(value >> size, value >= 0L ? 0L : -1L);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static short randomValueForShort(final boolean unsigned, final int size) {
// final short value;
// if (unsigned) {
// value = (short) (current().nextInt() >>> (Integer.SIZE - size));
// assertTrue(value >= 0);
// } else {
// value = (short) (current().nextInt() >> (Integer.SIZE - size));
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// return value;
// }
| import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; | package com.github.jinahya.bit.io;
/*-
* #%L
* bit-io
* %%
* Copyright (C) 2014 - 2019 Jinahya, Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
/**
* A class for unit-testing {@link AbstractBitOutput} class.
*
* @author Jin Kwon <onacit_at_gmail.com>
* @see AbstractBitInputSpyTest
*/
@ExtendWith({MockitoExtension.class})
@Slf4j
final class AbstractBitOutputSpyTest {
// -----------------------------------------------------------------------------------------------------------------
@BeforeEach
void stubWrite() throws IOException {
//lenient().doNothing().when(bitOutput).write(anyInt());
}
// -----------------------------------------------------------------------------------------------------------------
@AfterEach
void alignAfterEach() throws IOException {
bitOutput.align(current().nextInt(1, 8));
}
// --------------------------------------------------------------------------------------------------------- boolean
@RepeatedTest(8)
void testWriteBoolean() throws IOException {
final boolean value = current().nextBoolean();
bitOutput.writeBoolean(value);
}
// ------------------------------------------------------------------------------------------------------------ byte
@RepeatedTest(8)
void testWriteByte() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = BitIoTests.randomSizeForByte(unsigned);
final byte value = BitIoTests.randomValueForByte(unsigned, size);
bitOutput.writeByte(unsigned, size, value);
}
// ----------------------------------------------------------------------------------------------------------- short
@RepeatedTest(8)
void testWriteShort() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForShort(unsigned); | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static char randomValueForChar(final int size) {
// return (char) (current().nextInt(Character.MAX_VALUE + 1) >> (Integer.SIZE - size));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomValueForInt(final boolean unsigned, final int size) {
// final int value;
// if (unsigned) {
// value = current().nextInt() >>> (Integer.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextInt() >> (Integer.SIZE - size);
// if (size < Integer.SIZE) {
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static long randomValueForLong(final boolean unsigned, final int size) {
// final long value;
// if (unsigned) {
// value = current().nextLong() >>> (Long.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextLong() >> (Long.SIZE - size);
// if (size < Long.SIZE) {
// assertEquals(value >> size, value >= 0L ? 0L : -1L);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static short randomValueForShort(final boolean unsigned, final int size) {
// final short value;
// if (unsigned) {
// value = (short) (current().nextInt() >>> (Integer.SIZE - size));
// assertTrue(value >= 0);
// } else {
// value = (short) (current().nextInt() >> (Integer.SIZE - size));
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// return value;
// }
// Path: src/test/java/com/github/jinahya/bit/io/AbstractBitOutputSpyTest.java
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
package com.github.jinahya.bit.io;
/*-
* #%L
* bit-io
* %%
* Copyright (C) 2014 - 2019 Jinahya, Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
/**
* A class for unit-testing {@link AbstractBitOutput} class.
*
* @author Jin Kwon <onacit_at_gmail.com>
* @see AbstractBitInputSpyTest
*/
@ExtendWith({MockitoExtension.class})
@Slf4j
final class AbstractBitOutputSpyTest {
// -----------------------------------------------------------------------------------------------------------------
@BeforeEach
void stubWrite() throws IOException {
//lenient().doNothing().when(bitOutput).write(anyInt());
}
// -----------------------------------------------------------------------------------------------------------------
@AfterEach
void alignAfterEach() throws IOException {
bitOutput.align(current().nextInt(1, 8));
}
// --------------------------------------------------------------------------------------------------------- boolean
@RepeatedTest(8)
void testWriteBoolean() throws IOException {
final boolean value = current().nextBoolean();
bitOutput.writeBoolean(value);
}
// ------------------------------------------------------------------------------------------------------------ byte
@RepeatedTest(8)
void testWriteByte() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = BitIoTests.randomSizeForByte(unsigned);
final byte value = BitIoTests.randomValueForByte(unsigned, size);
bitOutput.writeByte(unsigned, size, value);
}
// ----------------------------------------------------------------------------------------------------------- short
@RepeatedTest(8)
void testWriteShort() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForShort(unsigned); | final short value = randomValueForShort(unsigned, size); |
jinahya/bit-io | src/test/java/com/github/jinahya/bit/io/AbstractBitOutputSpyTest.java | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static char randomValueForChar(final int size) {
// return (char) (current().nextInt(Character.MAX_VALUE + 1) >> (Integer.SIZE - size));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomValueForInt(final boolean unsigned, final int size) {
// final int value;
// if (unsigned) {
// value = current().nextInt() >>> (Integer.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextInt() >> (Integer.SIZE - size);
// if (size < Integer.SIZE) {
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static long randomValueForLong(final boolean unsigned, final int size) {
// final long value;
// if (unsigned) {
// value = current().nextLong() >>> (Long.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextLong() >> (Long.SIZE - size);
// if (size < Long.SIZE) {
// assertEquals(value >> size, value >= 0L ? 0L : -1L);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static short randomValueForShort(final boolean unsigned, final int size) {
// final short value;
// if (unsigned) {
// value = (short) (current().nextInt() >>> (Integer.SIZE - size));
// assertTrue(value >= 0);
// } else {
// value = (short) (current().nextInt() >> (Integer.SIZE - size));
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// return value;
// }
| import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; |
// --------------------------------------------------------------------------------------------------------- boolean
@RepeatedTest(8)
void testWriteBoolean() throws IOException {
final boolean value = current().nextBoolean();
bitOutput.writeBoolean(value);
}
// ------------------------------------------------------------------------------------------------------------ byte
@RepeatedTest(8)
void testWriteByte() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = BitIoTests.randomSizeForByte(unsigned);
final byte value = BitIoTests.randomValueForByte(unsigned, size);
bitOutput.writeByte(unsigned, size, value);
}
// ----------------------------------------------------------------------------------------------------------- short
@RepeatedTest(8)
void testWriteShort() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForShort(unsigned);
final short value = randomValueForShort(unsigned, size);
bitOutput.writeShort(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------- int
@RepeatedTest(8)
void testWriteInt() throws IOException {
final boolean unsigned = current().nextBoolean(); | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static char randomValueForChar(final int size) {
// return (char) (current().nextInt(Character.MAX_VALUE + 1) >> (Integer.SIZE - size));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomValueForInt(final boolean unsigned, final int size) {
// final int value;
// if (unsigned) {
// value = current().nextInt() >>> (Integer.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextInt() >> (Integer.SIZE - size);
// if (size < Integer.SIZE) {
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static long randomValueForLong(final boolean unsigned, final int size) {
// final long value;
// if (unsigned) {
// value = current().nextLong() >>> (Long.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextLong() >> (Long.SIZE - size);
// if (size < Long.SIZE) {
// assertEquals(value >> size, value >= 0L ? 0L : -1L);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static short randomValueForShort(final boolean unsigned, final int size) {
// final short value;
// if (unsigned) {
// value = (short) (current().nextInt() >>> (Integer.SIZE - size));
// assertTrue(value >= 0);
// } else {
// value = (short) (current().nextInt() >> (Integer.SIZE - size));
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// return value;
// }
// Path: src/test/java/com/github/jinahya/bit/io/AbstractBitOutputSpyTest.java
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
// --------------------------------------------------------------------------------------------------------- boolean
@RepeatedTest(8)
void testWriteBoolean() throws IOException {
final boolean value = current().nextBoolean();
bitOutput.writeBoolean(value);
}
// ------------------------------------------------------------------------------------------------------------ byte
@RepeatedTest(8)
void testWriteByte() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = BitIoTests.randomSizeForByte(unsigned);
final byte value = BitIoTests.randomValueForByte(unsigned, size);
bitOutput.writeByte(unsigned, size, value);
}
// ----------------------------------------------------------------------------------------------------------- short
@RepeatedTest(8)
void testWriteShort() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForShort(unsigned);
final short value = randomValueForShort(unsigned, size);
bitOutput.writeShort(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------- int
@RepeatedTest(8)
void testWriteInt() throws IOException {
final boolean unsigned = current().nextBoolean(); | final int size = randomSizeForInt(unsigned); |
jinahya/bit-io | src/test/java/com/github/jinahya/bit/io/AbstractBitOutputSpyTest.java | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static char randomValueForChar(final int size) {
// return (char) (current().nextInt(Character.MAX_VALUE + 1) >> (Integer.SIZE - size));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomValueForInt(final boolean unsigned, final int size) {
// final int value;
// if (unsigned) {
// value = current().nextInt() >>> (Integer.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextInt() >> (Integer.SIZE - size);
// if (size < Integer.SIZE) {
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static long randomValueForLong(final boolean unsigned, final int size) {
// final long value;
// if (unsigned) {
// value = current().nextLong() >>> (Long.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextLong() >> (Long.SIZE - size);
// if (size < Long.SIZE) {
// assertEquals(value >> size, value >= 0L ? 0L : -1L);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static short randomValueForShort(final boolean unsigned, final int size) {
// final short value;
// if (unsigned) {
// value = (short) (current().nextInt() >>> (Integer.SIZE - size));
// assertTrue(value >= 0);
// } else {
// value = (short) (current().nextInt() >> (Integer.SIZE - size));
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// return value;
// }
| import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; | // --------------------------------------------------------------------------------------------------------- boolean
@RepeatedTest(8)
void testWriteBoolean() throws IOException {
final boolean value = current().nextBoolean();
bitOutput.writeBoolean(value);
}
// ------------------------------------------------------------------------------------------------------------ byte
@RepeatedTest(8)
void testWriteByte() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = BitIoTests.randomSizeForByte(unsigned);
final byte value = BitIoTests.randomValueForByte(unsigned, size);
bitOutput.writeByte(unsigned, size, value);
}
// ----------------------------------------------------------------------------------------------------------- short
@RepeatedTest(8)
void testWriteShort() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForShort(unsigned);
final short value = randomValueForShort(unsigned, size);
bitOutput.writeShort(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------- int
@RepeatedTest(8)
void testWriteInt() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForInt(unsigned); | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static char randomValueForChar(final int size) {
// return (char) (current().nextInt(Character.MAX_VALUE + 1) >> (Integer.SIZE - size));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomValueForInt(final boolean unsigned, final int size) {
// final int value;
// if (unsigned) {
// value = current().nextInt() >>> (Integer.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextInt() >> (Integer.SIZE - size);
// if (size < Integer.SIZE) {
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static long randomValueForLong(final boolean unsigned, final int size) {
// final long value;
// if (unsigned) {
// value = current().nextLong() >>> (Long.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextLong() >> (Long.SIZE - size);
// if (size < Long.SIZE) {
// assertEquals(value >> size, value >= 0L ? 0L : -1L);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static short randomValueForShort(final boolean unsigned, final int size) {
// final short value;
// if (unsigned) {
// value = (short) (current().nextInt() >>> (Integer.SIZE - size));
// assertTrue(value >= 0);
// } else {
// value = (short) (current().nextInt() >> (Integer.SIZE - size));
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// return value;
// }
// Path: src/test/java/com/github/jinahya/bit/io/AbstractBitOutputSpyTest.java
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
// --------------------------------------------------------------------------------------------------------- boolean
@RepeatedTest(8)
void testWriteBoolean() throws IOException {
final boolean value = current().nextBoolean();
bitOutput.writeBoolean(value);
}
// ------------------------------------------------------------------------------------------------------------ byte
@RepeatedTest(8)
void testWriteByte() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = BitIoTests.randomSizeForByte(unsigned);
final byte value = BitIoTests.randomValueForByte(unsigned, size);
bitOutput.writeByte(unsigned, size, value);
}
// ----------------------------------------------------------------------------------------------------------- short
@RepeatedTest(8)
void testWriteShort() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForShort(unsigned);
final short value = randomValueForShort(unsigned, size);
bitOutput.writeShort(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------- int
@RepeatedTest(8)
void testWriteInt() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForInt(unsigned); | final int value = randomValueForInt(unsigned, size); |
jinahya/bit-io | src/test/java/com/github/jinahya/bit/io/AbstractBitOutputSpyTest.java | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static char randomValueForChar(final int size) {
// return (char) (current().nextInt(Character.MAX_VALUE + 1) >> (Integer.SIZE - size));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomValueForInt(final boolean unsigned, final int size) {
// final int value;
// if (unsigned) {
// value = current().nextInt() >>> (Integer.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextInt() >> (Integer.SIZE - size);
// if (size < Integer.SIZE) {
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static long randomValueForLong(final boolean unsigned, final int size) {
// final long value;
// if (unsigned) {
// value = current().nextLong() >>> (Long.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextLong() >> (Long.SIZE - size);
// if (size < Long.SIZE) {
// assertEquals(value >> size, value >= 0L ? 0L : -1L);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static short randomValueForShort(final boolean unsigned, final int size) {
// final short value;
// if (unsigned) {
// value = (short) (current().nextInt() >>> (Integer.SIZE - size));
// assertTrue(value >= 0);
// } else {
// value = (short) (current().nextInt() >> (Integer.SIZE - size));
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// return value;
// }
| import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; | @RepeatedTest(8)
void testWriteByte() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = BitIoTests.randomSizeForByte(unsigned);
final byte value = BitIoTests.randomValueForByte(unsigned, size);
bitOutput.writeByte(unsigned, size, value);
}
// ----------------------------------------------------------------------------------------------------------- short
@RepeatedTest(8)
void testWriteShort() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForShort(unsigned);
final short value = randomValueForShort(unsigned, size);
bitOutput.writeShort(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------- int
@RepeatedTest(8)
void testWriteInt() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForInt(unsigned);
final int value = randomValueForInt(unsigned, size);
bitOutput.writeInt(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------ long
@RepeatedTest(8)
void testWriteLong() throws IOException {
final boolean unsigned = current().nextBoolean(); | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static char randomValueForChar(final int size) {
// return (char) (current().nextInt(Character.MAX_VALUE + 1) >> (Integer.SIZE - size));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomValueForInt(final boolean unsigned, final int size) {
// final int value;
// if (unsigned) {
// value = current().nextInt() >>> (Integer.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextInt() >> (Integer.SIZE - size);
// if (size < Integer.SIZE) {
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static long randomValueForLong(final boolean unsigned, final int size) {
// final long value;
// if (unsigned) {
// value = current().nextLong() >>> (Long.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextLong() >> (Long.SIZE - size);
// if (size < Long.SIZE) {
// assertEquals(value >> size, value >= 0L ? 0L : -1L);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static short randomValueForShort(final boolean unsigned, final int size) {
// final short value;
// if (unsigned) {
// value = (short) (current().nextInt() >>> (Integer.SIZE - size));
// assertTrue(value >= 0);
// } else {
// value = (short) (current().nextInt() >> (Integer.SIZE - size));
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// return value;
// }
// Path: src/test/java/com/github/jinahya/bit/io/AbstractBitOutputSpyTest.java
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@RepeatedTest(8)
void testWriteByte() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = BitIoTests.randomSizeForByte(unsigned);
final byte value = BitIoTests.randomValueForByte(unsigned, size);
bitOutput.writeByte(unsigned, size, value);
}
// ----------------------------------------------------------------------------------------------------------- short
@RepeatedTest(8)
void testWriteShort() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForShort(unsigned);
final short value = randomValueForShort(unsigned, size);
bitOutput.writeShort(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------- int
@RepeatedTest(8)
void testWriteInt() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForInt(unsigned);
final int value = randomValueForInt(unsigned, size);
bitOutput.writeInt(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------ long
@RepeatedTest(8)
void testWriteLong() throws IOException {
final boolean unsigned = current().nextBoolean(); | final int size = randomSizeForLong(unsigned); |
jinahya/bit-io | src/test/java/com/github/jinahya/bit/io/AbstractBitOutputSpyTest.java | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static char randomValueForChar(final int size) {
// return (char) (current().nextInt(Character.MAX_VALUE + 1) >> (Integer.SIZE - size));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomValueForInt(final boolean unsigned, final int size) {
// final int value;
// if (unsigned) {
// value = current().nextInt() >>> (Integer.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextInt() >> (Integer.SIZE - size);
// if (size < Integer.SIZE) {
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static long randomValueForLong(final boolean unsigned, final int size) {
// final long value;
// if (unsigned) {
// value = current().nextLong() >>> (Long.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextLong() >> (Long.SIZE - size);
// if (size < Long.SIZE) {
// assertEquals(value >> size, value >= 0L ? 0L : -1L);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static short randomValueForShort(final boolean unsigned, final int size) {
// final short value;
// if (unsigned) {
// value = (short) (current().nextInt() >>> (Integer.SIZE - size));
// assertTrue(value >= 0);
// } else {
// value = (short) (current().nextInt() >> (Integer.SIZE - size));
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// return value;
// }
| import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; | void testWriteByte() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = BitIoTests.randomSizeForByte(unsigned);
final byte value = BitIoTests.randomValueForByte(unsigned, size);
bitOutput.writeByte(unsigned, size, value);
}
// ----------------------------------------------------------------------------------------------------------- short
@RepeatedTest(8)
void testWriteShort() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForShort(unsigned);
final short value = randomValueForShort(unsigned, size);
bitOutput.writeShort(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------- int
@RepeatedTest(8)
void testWriteInt() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForInt(unsigned);
final int value = randomValueForInt(unsigned, size);
bitOutput.writeInt(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------ long
@RepeatedTest(8)
void testWriteLong() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForLong(unsigned); | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static char randomValueForChar(final int size) {
// return (char) (current().nextInt(Character.MAX_VALUE + 1) >> (Integer.SIZE - size));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomValueForInt(final boolean unsigned, final int size) {
// final int value;
// if (unsigned) {
// value = current().nextInt() >>> (Integer.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextInt() >> (Integer.SIZE - size);
// if (size < Integer.SIZE) {
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static long randomValueForLong(final boolean unsigned, final int size) {
// final long value;
// if (unsigned) {
// value = current().nextLong() >>> (Long.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextLong() >> (Long.SIZE - size);
// if (size < Long.SIZE) {
// assertEquals(value >> size, value >= 0L ? 0L : -1L);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static short randomValueForShort(final boolean unsigned, final int size) {
// final short value;
// if (unsigned) {
// value = (short) (current().nextInt() >>> (Integer.SIZE - size));
// assertTrue(value >= 0);
// } else {
// value = (short) (current().nextInt() >> (Integer.SIZE - size));
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// return value;
// }
// Path: src/test/java/com/github/jinahya/bit/io/AbstractBitOutputSpyTest.java
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
void testWriteByte() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = BitIoTests.randomSizeForByte(unsigned);
final byte value = BitIoTests.randomValueForByte(unsigned, size);
bitOutput.writeByte(unsigned, size, value);
}
// ----------------------------------------------------------------------------------------------------------- short
@RepeatedTest(8)
void testWriteShort() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForShort(unsigned);
final short value = randomValueForShort(unsigned, size);
bitOutput.writeShort(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------- int
@RepeatedTest(8)
void testWriteInt() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForInt(unsigned);
final int value = randomValueForInt(unsigned, size);
bitOutput.writeInt(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------ long
@RepeatedTest(8)
void testWriteLong() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForLong(unsigned); | final long value = randomValueForLong(unsigned, size); |
jinahya/bit-io | src/test/java/com/github/jinahya/bit/io/AbstractBitOutputSpyTest.java | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static char randomValueForChar(final int size) {
// return (char) (current().nextInt(Character.MAX_VALUE + 1) >> (Integer.SIZE - size));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomValueForInt(final boolean unsigned, final int size) {
// final int value;
// if (unsigned) {
// value = current().nextInt() >>> (Integer.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextInt() >> (Integer.SIZE - size);
// if (size < Integer.SIZE) {
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static long randomValueForLong(final boolean unsigned, final int size) {
// final long value;
// if (unsigned) {
// value = current().nextLong() >>> (Long.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextLong() >> (Long.SIZE - size);
// if (size < Long.SIZE) {
// assertEquals(value >> size, value >= 0L ? 0L : -1L);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static short randomValueForShort(final boolean unsigned, final int size) {
// final short value;
// if (unsigned) {
// value = (short) (current().nextInt() >>> (Integer.SIZE - size));
// assertTrue(value >= 0);
// } else {
// value = (short) (current().nextInt() >> (Integer.SIZE - size));
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// return value;
// }
| import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; | // ----------------------------------------------------------------------------------------------------------- short
@RepeatedTest(8)
void testWriteShort() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForShort(unsigned);
final short value = randomValueForShort(unsigned, size);
bitOutput.writeShort(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------- int
@RepeatedTest(8)
void testWriteInt() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForInt(unsigned);
final int value = randomValueForInt(unsigned, size);
bitOutput.writeInt(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------ long
@RepeatedTest(8)
void testWriteLong() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForLong(unsigned);
final long value = randomValueForLong(unsigned, size);
bitOutput.writeLong(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------ char
@RepeatedTest(8)
void testWriteChar() throws IOException { | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static char randomValueForChar(final int size) {
// return (char) (current().nextInt(Character.MAX_VALUE + 1) >> (Integer.SIZE - size));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomValueForInt(final boolean unsigned, final int size) {
// final int value;
// if (unsigned) {
// value = current().nextInt() >>> (Integer.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextInt() >> (Integer.SIZE - size);
// if (size < Integer.SIZE) {
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static long randomValueForLong(final boolean unsigned, final int size) {
// final long value;
// if (unsigned) {
// value = current().nextLong() >>> (Long.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextLong() >> (Long.SIZE - size);
// if (size < Long.SIZE) {
// assertEquals(value >> size, value >= 0L ? 0L : -1L);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static short randomValueForShort(final boolean unsigned, final int size) {
// final short value;
// if (unsigned) {
// value = (short) (current().nextInt() >>> (Integer.SIZE - size));
// assertTrue(value >= 0);
// } else {
// value = (short) (current().nextInt() >> (Integer.SIZE - size));
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// return value;
// }
// Path: src/test/java/com/github/jinahya/bit/io/AbstractBitOutputSpyTest.java
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
// ----------------------------------------------------------------------------------------------------------- short
@RepeatedTest(8)
void testWriteShort() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForShort(unsigned);
final short value = randomValueForShort(unsigned, size);
bitOutput.writeShort(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------- int
@RepeatedTest(8)
void testWriteInt() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForInt(unsigned);
final int value = randomValueForInt(unsigned, size);
bitOutput.writeInt(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------ long
@RepeatedTest(8)
void testWriteLong() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForLong(unsigned);
final long value = randomValueForLong(unsigned, size);
bitOutput.writeLong(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------ char
@RepeatedTest(8)
void testWriteChar() throws IOException { | final int size = randomSizeForChar(); |
jinahya/bit-io | src/test/java/com/github/jinahya/bit/io/AbstractBitOutputSpyTest.java | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static char randomValueForChar(final int size) {
// return (char) (current().nextInt(Character.MAX_VALUE + 1) >> (Integer.SIZE - size));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomValueForInt(final boolean unsigned, final int size) {
// final int value;
// if (unsigned) {
// value = current().nextInt() >>> (Integer.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextInt() >> (Integer.SIZE - size);
// if (size < Integer.SIZE) {
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static long randomValueForLong(final boolean unsigned, final int size) {
// final long value;
// if (unsigned) {
// value = current().nextLong() >>> (Long.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextLong() >> (Long.SIZE - size);
// if (size < Long.SIZE) {
// assertEquals(value >> size, value >= 0L ? 0L : -1L);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static short randomValueForShort(final boolean unsigned, final int size) {
// final short value;
// if (unsigned) {
// value = (short) (current().nextInt() >>> (Integer.SIZE - size));
// assertTrue(value >= 0);
// } else {
// value = (short) (current().nextInt() >> (Integer.SIZE - size));
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// return value;
// }
| import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; | @RepeatedTest(8)
void testWriteShort() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForShort(unsigned);
final short value = randomValueForShort(unsigned, size);
bitOutput.writeShort(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------- int
@RepeatedTest(8)
void testWriteInt() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForInt(unsigned);
final int value = randomValueForInt(unsigned, size);
bitOutput.writeInt(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------ long
@RepeatedTest(8)
void testWriteLong() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForLong(unsigned);
final long value = randomValueForLong(unsigned, size);
bitOutput.writeLong(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------ char
@RepeatedTest(8)
void testWriteChar() throws IOException {
final int size = randomSizeForChar(); | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static char randomValueForChar(final int size) {
// return (char) (current().nextInt(Character.MAX_VALUE + 1) >> (Integer.SIZE - size));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomValueForInt(final boolean unsigned, final int size) {
// final int value;
// if (unsigned) {
// value = current().nextInt() >>> (Integer.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextInt() >> (Integer.SIZE - size);
// if (size < Integer.SIZE) {
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static long randomValueForLong(final boolean unsigned, final int size) {
// final long value;
// if (unsigned) {
// value = current().nextLong() >>> (Long.SIZE - size);
// assertTrue(value >= 0);
// } else {
// value = current().nextLong() >> (Long.SIZE - size);
// if (size < Long.SIZE) {
// assertEquals(value >> size, value >= 0L ? 0L : -1L);
// }
// }
// return value;
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static short randomValueForShort(final boolean unsigned, final int size) {
// final short value;
// if (unsigned) {
// value = (short) (current().nextInt() >>> (Integer.SIZE - size));
// assertTrue(value >= 0);
// } else {
// value = (short) (current().nextInt() >> (Integer.SIZE - size));
// assertEquals(value >> size, value >= 0 ? 0 : -1);
// }
// return value;
// }
// Path: src/test/java/com/github/jinahya/bit/io/AbstractBitOutputSpyTest.java
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomValueForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@RepeatedTest(8)
void testWriteShort() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForShort(unsigned);
final short value = randomValueForShort(unsigned, size);
bitOutput.writeShort(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------- int
@RepeatedTest(8)
void testWriteInt() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForInt(unsigned);
final int value = randomValueForInt(unsigned, size);
bitOutput.writeInt(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------ long
@RepeatedTest(8)
void testWriteLong() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForLong(unsigned);
final long value = randomValueForLong(unsigned, size);
bitOutput.writeLong(unsigned, size, value);
}
// ------------------------------------------------------------------------------------------------------------ char
@RepeatedTest(8)
void testWriteChar() throws IOException {
final int size = randomSizeForChar(); | final char value = randomValueForChar(size); |
jinahya/bit-io | src/main/java/com/github/jinahya/bit/io/AbstractBitInput.java | // Path: src/main/java/com/github/jinahya/bit/io/BitIoConstants.java
// static int mask(final int size) {
// return MASKS[size - 1];
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeByte(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Byte.SIZE);
// }
// if (unsigned && size == Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned byte");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeChar(final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Character.SIZE) {
// throw new IllegalArgumentException("size(" + size + ") > " + Character.SIZE);
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeInt(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Integer.SIZE);
// }
// if (unsigned && size == Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned integer");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeLong(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Long.SIZE);
// }
// if (unsigned && size == Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned long");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeShort(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Short.SIZE);
// }
// if (unsigned && size == Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned short");
// }
// return size;
// }
| import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoConstants.mask;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeByte;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeChar;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeInt;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeLong;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeShort; | package com.github.jinahya.bit.io;
/*-
* #%L
* bit-io
* %%
* Copyright (C) 2014 - 2019 Jinahya, Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
/**
* An abstract class for implementing {@link BitInput} interface.
*
* @author Jin Kwon <jinahya_at_gmail.com>
* @see AbstractBitOutput
* @see DefaultBitInput
*/
public abstract class AbstractBitInput implements BitInput {
// -----------------------------------------------------------------------------------------------------------------
/**
* Creates a new instance.
*/
protected AbstractBitInput() {
super();
}
// -----------------------------------------------------------------------------------------------------------------
/**
* Reads an {@value java.lang.Byte#SIZE}-bit unsigned integer.
*
* @return an {@value java.lang.Byte#SIZE}-bit unsigned integer.
* @throws IOException if an I/O error occurs.
* @see AbstractBitOutput#write(int)
*/
protected abstract int read() throws IOException;
// -----------------------------------------------------------------------------------------------------------------
/**
* Reads an unsigned {@code int} value of specified bit size which is, in maximum, {@value java.lang.Byte#SIZE}.
*
* @param size the number of bits for the value; between {@code 1} and {@value java.lang.Byte#SIZE}, both
* inclusive.
* @return an unsigned byte value.
* @throws IOException if an I/O error occurs.
* @see #read()
*/
private int unsigned8(final int size) throws IOException {
if (available == 0) {
octet = read();
assert octet >= 0 && octet < 256;
count++;
available = Byte.SIZE;
}
final int required = size - available;
if (required > 0) {
return (unsigned8(available) << required) | unsigned8(required);
}
available -= size; | // Path: src/main/java/com/github/jinahya/bit/io/BitIoConstants.java
// static int mask(final int size) {
// return MASKS[size - 1];
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeByte(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Byte.SIZE);
// }
// if (unsigned && size == Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned byte");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeChar(final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Character.SIZE) {
// throw new IllegalArgumentException("size(" + size + ") > " + Character.SIZE);
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeInt(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Integer.SIZE);
// }
// if (unsigned && size == Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned integer");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeLong(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Long.SIZE);
// }
// if (unsigned && size == Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned long");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeShort(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Short.SIZE);
// }
// if (unsigned && size == Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned short");
// }
// return size;
// }
// Path: src/main/java/com/github/jinahya/bit/io/AbstractBitInput.java
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoConstants.mask;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeByte;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeChar;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeInt;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeLong;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeShort;
package com.github.jinahya.bit.io;
/*-
* #%L
* bit-io
* %%
* Copyright (C) 2014 - 2019 Jinahya, Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
/**
* An abstract class for implementing {@link BitInput} interface.
*
* @author Jin Kwon <jinahya_at_gmail.com>
* @see AbstractBitOutput
* @see DefaultBitInput
*/
public abstract class AbstractBitInput implements BitInput {
// -----------------------------------------------------------------------------------------------------------------
/**
* Creates a new instance.
*/
protected AbstractBitInput() {
super();
}
// -----------------------------------------------------------------------------------------------------------------
/**
* Reads an {@value java.lang.Byte#SIZE}-bit unsigned integer.
*
* @return an {@value java.lang.Byte#SIZE}-bit unsigned integer.
* @throws IOException if an I/O error occurs.
* @see AbstractBitOutput#write(int)
*/
protected abstract int read() throws IOException;
// -----------------------------------------------------------------------------------------------------------------
/**
* Reads an unsigned {@code int} value of specified bit size which is, in maximum, {@value java.lang.Byte#SIZE}.
*
* @param size the number of bits for the value; between {@code 1} and {@value java.lang.Byte#SIZE}, both
* inclusive.
* @return an unsigned byte value.
* @throws IOException if an I/O error occurs.
* @see #read()
*/
private int unsigned8(final int size) throws IOException {
if (available == 0) {
octet = read();
assert octet >= 0 && octet < 256;
count++;
available = Byte.SIZE;
}
final int required = size - available;
if (required > 0) {
return (unsigned8(available) << required) | unsigned8(required);
}
available -= size; | return (octet >> available) & mask(size); |
jinahya/bit-io | src/main/java/com/github/jinahya/bit/io/AbstractBitInput.java | // Path: src/main/java/com/github/jinahya/bit/io/BitIoConstants.java
// static int mask(final int size) {
// return MASKS[size - 1];
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeByte(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Byte.SIZE);
// }
// if (unsigned && size == Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned byte");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeChar(final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Character.SIZE) {
// throw new IllegalArgumentException("size(" + size + ") > " + Character.SIZE);
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeInt(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Integer.SIZE);
// }
// if (unsigned && size == Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned integer");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeLong(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Long.SIZE);
// }
// if (unsigned && size == Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned long");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeShort(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Short.SIZE);
// }
// if (unsigned && size == Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned short");
// }
// return size;
// }
| import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoConstants.mask;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeByte;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeChar;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeInt;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeLong;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeShort; | package com.github.jinahya.bit.io;
/*-
* #%L
* bit-io
* %%
* Copyright (C) 2014 - 2019 Jinahya, Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
/**
* An abstract class for implementing {@link BitInput} interface.
*
* @author Jin Kwon <jinahya_at_gmail.com>
* @see AbstractBitOutput
* @see DefaultBitInput
*/
public abstract class AbstractBitInput implements BitInput {
// -----------------------------------------------------------------------------------------------------------------
/**
* Creates a new instance.
*/
protected AbstractBitInput() {
super();
}
// -----------------------------------------------------------------------------------------------------------------
/**
* Reads an {@value java.lang.Byte#SIZE}-bit unsigned integer.
*
* @return an {@value java.lang.Byte#SIZE}-bit unsigned integer.
* @throws IOException if an I/O error occurs.
* @see AbstractBitOutput#write(int)
*/
protected abstract int read() throws IOException;
// -----------------------------------------------------------------------------------------------------------------
/**
* Reads an unsigned {@code int} value of specified bit size which is, in maximum, {@value java.lang.Byte#SIZE}.
*
* @param size the number of bits for the value; between {@code 1} and {@value java.lang.Byte#SIZE}, both
* inclusive.
* @return an unsigned byte value.
* @throws IOException if an I/O error occurs.
* @see #read()
*/
private int unsigned8(final int size) throws IOException {
if (available == 0) {
octet = read();
assert octet >= 0 && octet < 256;
count++;
available = Byte.SIZE;
}
final int required = size - available;
if (required > 0) {
return (unsigned8(available) << required) | unsigned8(required);
}
available -= size;
return (octet >> available) & mask(size);
}
// --------------------------------------------------------------------------------------------------------- boolean
@Override
public boolean readBoolean() throws IOException {
return readInt(true, 1) == 1;
}
// ------------------------------------------------------------------------------------------------------------ byte
@Override
public byte readByte(final boolean unsigned, final int size) throws IOException { | // Path: src/main/java/com/github/jinahya/bit/io/BitIoConstants.java
// static int mask(final int size) {
// return MASKS[size - 1];
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeByte(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Byte.SIZE);
// }
// if (unsigned && size == Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned byte");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeChar(final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Character.SIZE) {
// throw new IllegalArgumentException("size(" + size + ") > " + Character.SIZE);
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeInt(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Integer.SIZE);
// }
// if (unsigned && size == Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned integer");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeLong(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Long.SIZE);
// }
// if (unsigned && size == Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned long");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeShort(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Short.SIZE);
// }
// if (unsigned && size == Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned short");
// }
// return size;
// }
// Path: src/main/java/com/github/jinahya/bit/io/AbstractBitInput.java
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoConstants.mask;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeByte;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeChar;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeInt;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeLong;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeShort;
package com.github.jinahya.bit.io;
/*-
* #%L
* bit-io
* %%
* Copyright (C) 2014 - 2019 Jinahya, Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
/**
* An abstract class for implementing {@link BitInput} interface.
*
* @author Jin Kwon <jinahya_at_gmail.com>
* @see AbstractBitOutput
* @see DefaultBitInput
*/
public abstract class AbstractBitInput implements BitInput {
// -----------------------------------------------------------------------------------------------------------------
/**
* Creates a new instance.
*/
protected AbstractBitInput() {
super();
}
// -----------------------------------------------------------------------------------------------------------------
/**
* Reads an {@value java.lang.Byte#SIZE}-bit unsigned integer.
*
* @return an {@value java.lang.Byte#SIZE}-bit unsigned integer.
* @throws IOException if an I/O error occurs.
* @see AbstractBitOutput#write(int)
*/
protected abstract int read() throws IOException;
// -----------------------------------------------------------------------------------------------------------------
/**
* Reads an unsigned {@code int} value of specified bit size which is, in maximum, {@value java.lang.Byte#SIZE}.
*
* @param size the number of bits for the value; between {@code 1} and {@value java.lang.Byte#SIZE}, both
* inclusive.
* @return an unsigned byte value.
* @throws IOException if an I/O error occurs.
* @see #read()
*/
private int unsigned8(final int size) throws IOException {
if (available == 0) {
octet = read();
assert octet >= 0 && octet < 256;
count++;
available = Byte.SIZE;
}
final int required = size - available;
if (required > 0) {
return (unsigned8(available) << required) | unsigned8(required);
}
available -= size;
return (octet >> available) & mask(size);
}
// --------------------------------------------------------------------------------------------------------- boolean
@Override
public boolean readBoolean() throws IOException {
return readInt(true, 1) == 1;
}
// ------------------------------------------------------------------------------------------------------------ byte
@Override
public byte readByte(final boolean unsigned, final int size) throws IOException { | return (byte) readInt(unsigned, requireValidSizeByte(unsigned, size)); |
jinahya/bit-io | src/main/java/com/github/jinahya/bit/io/AbstractBitInput.java | // Path: src/main/java/com/github/jinahya/bit/io/BitIoConstants.java
// static int mask(final int size) {
// return MASKS[size - 1];
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeByte(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Byte.SIZE);
// }
// if (unsigned && size == Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned byte");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeChar(final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Character.SIZE) {
// throw new IllegalArgumentException("size(" + size + ") > " + Character.SIZE);
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeInt(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Integer.SIZE);
// }
// if (unsigned && size == Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned integer");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeLong(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Long.SIZE);
// }
// if (unsigned && size == Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned long");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeShort(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Short.SIZE);
// }
// if (unsigned && size == Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned short");
// }
// return size;
// }
| import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoConstants.mask;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeByte;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeChar;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeInt;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeLong;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeShort; | available = Byte.SIZE;
}
final int required = size - available;
if (required > 0) {
return (unsigned8(available) << required) | unsigned8(required);
}
available -= size;
return (octet >> available) & mask(size);
}
// --------------------------------------------------------------------------------------------------------- boolean
@Override
public boolean readBoolean() throws IOException {
return readInt(true, 1) == 1;
}
// ------------------------------------------------------------------------------------------------------------ byte
@Override
public byte readByte(final boolean unsigned, final int size) throws IOException {
return (byte) readInt(unsigned, requireValidSizeByte(unsigned, size));
}
@Override
public byte readByte8() throws IOException {
return readByte(false, Byte.SIZE);
}
// ----------------------------------------------------------------------------------------------------------- short
@Override
public short readShort(final boolean unsigned, final int size) throws IOException { | // Path: src/main/java/com/github/jinahya/bit/io/BitIoConstants.java
// static int mask(final int size) {
// return MASKS[size - 1];
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeByte(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Byte.SIZE);
// }
// if (unsigned && size == Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned byte");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeChar(final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Character.SIZE) {
// throw new IllegalArgumentException("size(" + size + ") > " + Character.SIZE);
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeInt(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Integer.SIZE);
// }
// if (unsigned && size == Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned integer");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeLong(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Long.SIZE);
// }
// if (unsigned && size == Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned long");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeShort(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Short.SIZE);
// }
// if (unsigned && size == Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned short");
// }
// return size;
// }
// Path: src/main/java/com/github/jinahya/bit/io/AbstractBitInput.java
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoConstants.mask;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeByte;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeChar;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeInt;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeLong;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeShort;
available = Byte.SIZE;
}
final int required = size - available;
if (required > 0) {
return (unsigned8(available) << required) | unsigned8(required);
}
available -= size;
return (octet >> available) & mask(size);
}
// --------------------------------------------------------------------------------------------------------- boolean
@Override
public boolean readBoolean() throws IOException {
return readInt(true, 1) == 1;
}
// ------------------------------------------------------------------------------------------------------------ byte
@Override
public byte readByte(final boolean unsigned, final int size) throws IOException {
return (byte) readInt(unsigned, requireValidSizeByte(unsigned, size));
}
@Override
public byte readByte8() throws IOException {
return readByte(false, Byte.SIZE);
}
// ----------------------------------------------------------------------------------------------------------- short
@Override
public short readShort(final boolean unsigned, final int size) throws IOException { | return (short) readInt(unsigned, requireValidSizeShort(unsigned, size)); |
jinahya/bit-io | src/main/java/com/github/jinahya/bit/io/AbstractBitInput.java | // Path: src/main/java/com/github/jinahya/bit/io/BitIoConstants.java
// static int mask(final int size) {
// return MASKS[size - 1];
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeByte(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Byte.SIZE);
// }
// if (unsigned && size == Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned byte");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeChar(final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Character.SIZE) {
// throw new IllegalArgumentException("size(" + size + ") > " + Character.SIZE);
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeInt(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Integer.SIZE);
// }
// if (unsigned && size == Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned integer");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeLong(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Long.SIZE);
// }
// if (unsigned && size == Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned long");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeShort(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Short.SIZE);
// }
// if (unsigned && size == Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned short");
// }
// return size;
// }
| import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoConstants.mask;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeByte;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeChar;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeInt;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeLong;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeShort; | // ------------------------------------------------------------------------------------------------------------ byte
@Override
public byte readByte(final boolean unsigned, final int size) throws IOException {
return (byte) readInt(unsigned, requireValidSizeByte(unsigned, size));
}
@Override
public byte readByte8() throws IOException {
return readByte(false, Byte.SIZE);
}
// ----------------------------------------------------------------------------------------------------------- short
@Override
public short readShort(final boolean unsigned, final int size) throws IOException {
return (short) readInt(unsigned, requireValidSizeShort(unsigned, size));
}
@Override
public short readShort16() throws IOException {
return readShort(false, Short.SIZE);
}
@Override
public short readShort16Le() throws IOException {
return (short) (readByte8() & 0xFF | readByte8() << Byte.SIZE);
}
// ------------------------------------------------------------------------------------------------------------- int
@Override
public int readInt(final boolean unsigned, int size) throws IOException { | // Path: src/main/java/com/github/jinahya/bit/io/BitIoConstants.java
// static int mask(final int size) {
// return MASKS[size - 1];
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeByte(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Byte.SIZE);
// }
// if (unsigned && size == Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned byte");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeChar(final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Character.SIZE) {
// throw new IllegalArgumentException("size(" + size + ") > " + Character.SIZE);
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeInt(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Integer.SIZE);
// }
// if (unsigned && size == Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned integer");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeLong(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Long.SIZE);
// }
// if (unsigned && size == Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned long");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeShort(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Short.SIZE);
// }
// if (unsigned && size == Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned short");
// }
// return size;
// }
// Path: src/main/java/com/github/jinahya/bit/io/AbstractBitInput.java
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoConstants.mask;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeByte;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeChar;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeInt;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeLong;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeShort;
// ------------------------------------------------------------------------------------------------------------ byte
@Override
public byte readByte(final boolean unsigned, final int size) throws IOException {
return (byte) readInt(unsigned, requireValidSizeByte(unsigned, size));
}
@Override
public byte readByte8() throws IOException {
return readByte(false, Byte.SIZE);
}
// ----------------------------------------------------------------------------------------------------------- short
@Override
public short readShort(final boolean unsigned, final int size) throws IOException {
return (short) readInt(unsigned, requireValidSizeShort(unsigned, size));
}
@Override
public short readShort16() throws IOException {
return readShort(false, Short.SIZE);
}
@Override
public short readShort16Le() throws IOException {
return (short) (readByte8() & 0xFF | readByte8() << Byte.SIZE);
}
// ------------------------------------------------------------------------------------------------------------- int
@Override
public int readInt(final boolean unsigned, int size) throws IOException { | requireValidSizeInt(unsigned, size); |
jinahya/bit-io | src/main/java/com/github/jinahya/bit/io/AbstractBitInput.java | // Path: src/main/java/com/github/jinahya/bit/io/BitIoConstants.java
// static int mask(final int size) {
// return MASKS[size - 1];
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeByte(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Byte.SIZE);
// }
// if (unsigned && size == Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned byte");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeChar(final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Character.SIZE) {
// throw new IllegalArgumentException("size(" + size + ") > " + Character.SIZE);
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeInt(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Integer.SIZE);
// }
// if (unsigned && size == Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned integer");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeLong(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Long.SIZE);
// }
// if (unsigned && size == Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned long");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeShort(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Short.SIZE);
// }
// if (unsigned && size == Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned short");
// }
// return size;
// }
| import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoConstants.mask;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeByte;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeChar;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeInt;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeLong;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeShort; | if (--size > 0) {
value <<= size;
value |= readInt(true, size);
}
return value;
}
for (; size >= Byte.SIZE; size -= Byte.SIZE) {
value <<= Byte.SIZE;
value |= unsigned8(Byte.SIZE);
}
if (size > 0) {
value <<= size;
value |= unsigned8(size);
}
return value;
}
@Override
public int readInt32() throws IOException {
return readInt(false, Integer.SIZE);
}
@Override
public int readInt32Le() throws IOException {
return readShort16Le() & 0xFFFF | readShort16Le() << Short.SIZE;
}
// ------------------------------------------------------------------------------------------------------------ long
@Override
public long readLong(final boolean unsigned, int size) throws IOException { | // Path: src/main/java/com/github/jinahya/bit/io/BitIoConstants.java
// static int mask(final int size) {
// return MASKS[size - 1];
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeByte(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Byte.SIZE);
// }
// if (unsigned && size == Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned byte");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeChar(final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Character.SIZE) {
// throw new IllegalArgumentException("size(" + size + ") > " + Character.SIZE);
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeInt(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Integer.SIZE);
// }
// if (unsigned && size == Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned integer");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeLong(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Long.SIZE);
// }
// if (unsigned && size == Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned long");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeShort(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Short.SIZE);
// }
// if (unsigned && size == Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned short");
// }
// return size;
// }
// Path: src/main/java/com/github/jinahya/bit/io/AbstractBitInput.java
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoConstants.mask;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeByte;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeChar;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeInt;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeLong;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeShort;
if (--size > 0) {
value <<= size;
value |= readInt(true, size);
}
return value;
}
for (; size >= Byte.SIZE; size -= Byte.SIZE) {
value <<= Byte.SIZE;
value |= unsigned8(Byte.SIZE);
}
if (size > 0) {
value <<= size;
value |= unsigned8(size);
}
return value;
}
@Override
public int readInt32() throws IOException {
return readInt(false, Integer.SIZE);
}
@Override
public int readInt32Le() throws IOException {
return readShort16Le() & 0xFFFF | readShort16Le() << Short.SIZE;
}
// ------------------------------------------------------------------------------------------------------------ long
@Override
public long readLong(final boolean unsigned, int size) throws IOException { | requireValidSizeLong(unsigned, size); |
jinahya/bit-io | src/main/java/com/github/jinahya/bit/io/AbstractBitInput.java | // Path: src/main/java/com/github/jinahya/bit/io/BitIoConstants.java
// static int mask(final int size) {
// return MASKS[size - 1];
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeByte(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Byte.SIZE);
// }
// if (unsigned && size == Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned byte");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeChar(final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Character.SIZE) {
// throw new IllegalArgumentException("size(" + size + ") > " + Character.SIZE);
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeInt(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Integer.SIZE);
// }
// if (unsigned && size == Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned integer");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeLong(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Long.SIZE);
// }
// if (unsigned && size == Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned long");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeShort(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Short.SIZE);
// }
// if (unsigned && size == Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned short");
// }
// return size;
// }
| import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoConstants.mask;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeByte;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeChar;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeInt;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeLong;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeShort; | if (--size > 0) {
value <<= size;
value |= readLong(true, size);
}
return value;
}
if (size >= Integer.SIZE) {
value = (readInt(false, Integer.SIZE) & 0xFFFFFFFFL);
size -= Integer.SIZE;
}
if (size > 0) {
value <<= size;
value |= readInt(true, size);
}
return value;
}
@Override
public long readLong64() throws IOException {
return readLong(false, Long.SIZE);
}
@Override
public long readLong64Le() throws IOException {
return readInt32Le() & 0xFFFFFFFFL | ((long) readInt32Le()) << Integer.SIZE;
}
// ------------------------------------------------------------------------------------------------------------ char
@Override
public char readChar(final int size) throws IOException { | // Path: src/main/java/com/github/jinahya/bit/io/BitIoConstants.java
// static int mask(final int size) {
// return MASKS[size - 1];
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeByte(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Byte.SIZE);
// }
// if (unsigned && size == Byte.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned byte");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeChar(final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Character.SIZE) {
// throw new IllegalArgumentException("size(" + size + ") > " + Character.SIZE);
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeInt(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Integer.SIZE);
// }
// if (unsigned && size == Integer.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned integer");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeLong(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Long.SIZE);
// }
// if (unsigned && size == Long.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned long");
// }
// return size;
// }
//
// Path: src/main/java/com/github/jinahya/bit/io/BitIoConstraints.java
// static int requireValidSizeShort(final boolean unsigned, final int size) {
// if (size <= 0) {
// throw new IllegalArgumentException("size(" + size + ") <= 0");
// }
// if (size > Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") > " + Short.SIZE);
// }
// if (unsigned && size == Short.SIZE) {
// throw new IllegalArgumentException("invalid size(" + size + ") for unsigned short");
// }
// return size;
// }
// Path: src/main/java/com/github/jinahya/bit/io/AbstractBitInput.java
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoConstants.mask;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeByte;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeChar;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeInt;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeLong;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeShort;
if (--size > 0) {
value <<= size;
value |= readLong(true, size);
}
return value;
}
if (size >= Integer.SIZE) {
value = (readInt(false, Integer.SIZE) & 0xFFFFFFFFL);
size -= Integer.SIZE;
}
if (size > 0) {
value <<= size;
value |= readInt(true, size);
}
return value;
}
@Override
public long readLong64() throws IOException {
return readLong(false, Long.SIZE);
}
@Override
public long readLong64Le() throws IOException {
return readInt32Le() & 0xFFFFFFFFL | ((long) readInt32Le()) << Integer.SIZE;
}
// ------------------------------------------------------------------------------------------------------------ char
@Override
public char readChar(final int size) throws IOException { | return (char) readInt(true, requireValidSizeChar(size)); |
jinahya/bit-io | src/test/java/com/github/jinahya/bit/io/AbstractBitInputSpyTest.java | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForByte(final boolean unsigned) {
// return requireValidSizeByte(unsigned, current().nextInt(1, Byte.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
| import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForByte;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.lenient; | package com.github.jinahya.bit.io;
/*-
* #%L
* bit-io
* %%
* Copyright (C) 2014 - 2019 Jinahya, Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
/**
* A class for unit-testing {@link AbstractBitInput} with a spy.
*
* @author Jin Kwon <onacit_at_gmail.com>
* @see AbstractBitOutputSpyTest
*/
@ExtendWith({MockitoExtension.class})
@Slf4j
final class AbstractBitInputSpyTest {
// -----------------------------------------------------------------------------------------------------------------
@BeforeEach
void stubRead() throws IOException {
lenient().when(bitInput.read()).thenReturn(current().nextInt(0, 256));
}
// -----------------------------------------------------------------------------------------------------------------
@AfterEach
void alignAfterEach() throws IOException {
bitInput.align(current().nextInt(1, 8));
}
// ------------------------------------------------------------------------------------------------------------ byte
/**
* Tests {@link AbstractBitInput#readByte(boolean, int)} method.
*
* @throws IOException if an I/O error occurs.
*/
@RepeatedTest(8)
void testReadByte() throws IOException {
final boolean unsigned = current().nextBoolean(); | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForByte(final boolean unsigned) {
// return requireValidSizeByte(unsigned, current().nextInt(1, Byte.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
// Path: src/test/java/com/github/jinahya/bit/io/AbstractBitInputSpyTest.java
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForByte;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.lenient;
package com.github.jinahya.bit.io;
/*-
* #%L
* bit-io
* %%
* Copyright (C) 2014 - 2019 Jinahya, Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
/**
* A class for unit-testing {@link AbstractBitInput} with a spy.
*
* @author Jin Kwon <onacit_at_gmail.com>
* @see AbstractBitOutputSpyTest
*/
@ExtendWith({MockitoExtension.class})
@Slf4j
final class AbstractBitInputSpyTest {
// -----------------------------------------------------------------------------------------------------------------
@BeforeEach
void stubRead() throws IOException {
lenient().when(bitInput.read()).thenReturn(current().nextInt(0, 256));
}
// -----------------------------------------------------------------------------------------------------------------
@AfterEach
void alignAfterEach() throws IOException {
bitInput.align(current().nextInt(1, 8));
}
// ------------------------------------------------------------------------------------------------------------ byte
/**
* Tests {@link AbstractBitInput#readByte(boolean, int)} method.
*
* @throws IOException if an I/O error occurs.
*/
@RepeatedTest(8)
void testReadByte() throws IOException {
final boolean unsigned = current().nextBoolean(); | final int size = randomSizeForByte(unsigned); |
jinahya/bit-io | src/test/java/com/github/jinahya/bit/io/AbstractBitInputSpyTest.java | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForByte(final boolean unsigned) {
// return requireValidSizeByte(unsigned, current().nextInt(1, Byte.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
| import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForByte;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.lenient; | package com.github.jinahya.bit.io;
/*-
* #%L
* bit-io
* %%
* Copyright (C) 2014 - 2019 Jinahya, Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
/**
* A class for unit-testing {@link AbstractBitInput} with a spy.
*
* @author Jin Kwon <onacit_at_gmail.com>
* @see AbstractBitOutputSpyTest
*/
@ExtendWith({MockitoExtension.class})
@Slf4j
final class AbstractBitInputSpyTest {
// -----------------------------------------------------------------------------------------------------------------
@BeforeEach
void stubRead() throws IOException {
lenient().when(bitInput.read()).thenReturn(current().nextInt(0, 256));
}
// -----------------------------------------------------------------------------------------------------------------
@AfterEach
void alignAfterEach() throws IOException {
bitInput.align(current().nextInt(1, 8));
}
// ------------------------------------------------------------------------------------------------------------ byte
/**
* Tests {@link AbstractBitInput#readByte(boolean, int)} method.
*
* @throws IOException if an I/O error occurs.
*/
@RepeatedTest(8)
void testReadByte() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForByte(unsigned);
final byte value = bitInput.readByte(unsigned, size);
if (unsigned) {
assertEquals(0, value >> size);
} else {
if (value >= 0) {
assertEquals(0, value >> (size - 1));
} else {
assertEquals(-1, value >> (size - 1));
}
}
}
// ----------------------------------------------------------------------------------------------------------- short
@RepeatedTest(8)
void testReadShort() throws IOException {
final boolean unsigned = current().nextBoolean(); | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForByte(final boolean unsigned) {
// return requireValidSizeByte(unsigned, current().nextInt(1, Byte.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
// Path: src/test/java/com/github/jinahya/bit/io/AbstractBitInputSpyTest.java
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForByte;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.lenient;
package com.github.jinahya.bit.io;
/*-
* #%L
* bit-io
* %%
* Copyright (C) 2014 - 2019 Jinahya, Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
/**
* A class for unit-testing {@link AbstractBitInput} with a spy.
*
* @author Jin Kwon <onacit_at_gmail.com>
* @see AbstractBitOutputSpyTest
*/
@ExtendWith({MockitoExtension.class})
@Slf4j
final class AbstractBitInputSpyTest {
// -----------------------------------------------------------------------------------------------------------------
@BeforeEach
void stubRead() throws IOException {
lenient().when(bitInput.read()).thenReturn(current().nextInt(0, 256));
}
// -----------------------------------------------------------------------------------------------------------------
@AfterEach
void alignAfterEach() throws IOException {
bitInput.align(current().nextInt(1, 8));
}
// ------------------------------------------------------------------------------------------------------------ byte
/**
* Tests {@link AbstractBitInput#readByte(boolean, int)} method.
*
* @throws IOException if an I/O error occurs.
*/
@RepeatedTest(8)
void testReadByte() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForByte(unsigned);
final byte value = bitInput.readByte(unsigned, size);
if (unsigned) {
assertEquals(0, value >> size);
} else {
if (value >= 0) {
assertEquals(0, value >> (size - 1));
} else {
assertEquals(-1, value >> (size - 1));
}
}
}
// ----------------------------------------------------------------------------------------------------------- short
@RepeatedTest(8)
void testReadShort() throws IOException {
final boolean unsigned = current().nextBoolean(); | final int size = randomSizeForShort(unsigned); |
jinahya/bit-io | src/test/java/com/github/jinahya/bit/io/AbstractBitInputSpyTest.java | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForByte(final boolean unsigned) {
// return requireValidSizeByte(unsigned, current().nextInt(1, Byte.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
| import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForByte;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.lenient; | } else {
if (value >= 0) {
assertEquals(0, value >> (size - 1));
} else {
assertEquals(-1, value >> (size - 1));
}
}
}
// ----------------------------------------------------------------------------------------------------------- short
@RepeatedTest(8)
void testReadShort() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForShort(unsigned);
final short value = bitInput.readShort(unsigned, size);
if (unsigned) {
assertEquals(0, value >> size);
} else {
if (value >= 0) {
assertEquals(0, value >> (size - 1));
} else {
assertEquals(-1, value >> (size - 1));
}
}
}
// ------------------------------------------------------------------------------------------------------------- int
@RepeatedTest(8)
void testReadInt() throws IOException {
final boolean unsigned = current().nextBoolean(); | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForByte(final boolean unsigned) {
// return requireValidSizeByte(unsigned, current().nextInt(1, Byte.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
// Path: src/test/java/com/github/jinahya/bit/io/AbstractBitInputSpyTest.java
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForByte;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.lenient;
} else {
if (value >= 0) {
assertEquals(0, value >> (size - 1));
} else {
assertEquals(-1, value >> (size - 1));
}
}
}
// ----------------------------------------------------------------------------------------------------------- short
@RepeatedTest(8)
void testReadShort() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForShort(unsigned);
final short value = bitInput.readShort(unsigned, size);
if (unsigned) {
assertEquals(0, value >> size);
} else {
if (value >= 0) {
assertEquals(0, value >> (size - 1));
} else {
assertEquals(-1, value >> (size - 1));
}
}
}
// ------------------------------------------------------------------------------------------------------------- int
@RepeatedTest(8)
void testReadInt() throws IOException {
final boolean unsigned = current().nextBoolean(); | final int size = randomSizeForInt(unsigned); |
jinahya/bit-io | src/test/java/com/github/jinahya/bit/io/AbstractBitInputSpyTest.java | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForByte(final boolean unsigned) {
// return requireValidSizeByte(unsigned, current().nextInt(1, Byte.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
| import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForByte;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.lenient; | } else {
if (value >= 0) {
assertEquals(0, value >> (size - 1));
} else {
assertEquals(-1, value >> (size - 1));
}
}
}
// ------------------------------------------------------------------------------------------------------------- int
@RepeatedTest(8)
void testReadInt() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForInt(unsigned);
final int value = bitInput.readInt(unsigned, size);
if (unsigned) {
assertEquals(0, value >> size);
} else {
if (value >= 0) {
assertEquals(0, value >> (size - 1));
} else {
assertEquals(-1, value >> (size - 1));
}
}
}
// ------------------------------------------------------------------------------------------------------------ long
@RepeatedTest(8)
void testReadSignedLong() throws IOException {
final boolean unsigned = current().nextBoolean(); | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForByte(final boolean unsigned) {
// return requireValidSizeByte(unsigned, current().nextInt(1, Byte.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
// Path: src/test/java/com/github/jinahya/bit/io/AbstractBitInputSpyTest.java
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForByte;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.lenient;
} else {
if (value >= 0) {
assertEquals(0, value >> (size - 1));
} else {
assertEquals(-1, value >> (size - 1));
}
}
}
// ------------------------------------------------------------------------------------------------------------- int
@RepeatedTest(8)
void testReadInt() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForInt(unsigned);
final int value = bitInput.readInt(unsigned, size);
if (unsigned) {
assertEquals(0, value >> size);
} else {
if (value >= 0) {
assertEquals(0, value >> (size - 1));
} else {
assertEquals(-1, value >> (size - 1));
}
}
}
// ------------------------------------------------------------------------------------------------------------ long
@RepeatedTest(8)
void testReadSignedLong() throws IOException {
final boolean unsigned = current().nextBoolean(); | final int size = randomSizeForLong(unsigned); |
jinahya/bit-io | src/test/java/com/github/jinahya/bit/io/AbstractBitInputSpyTest.java | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForByte(final boolean unsigned) {
// return requireValidSizeByte(unsigned, current().nextInt(1, Byte.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
| import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForByte;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.lenient; | assertEquals(0, value >> size);
} else {
if (value >= 0) {
assertEquals(0, value >> (size - 1));
} else {
assertEquals(-1, value >> (size - 1));
}
}
}
// ------------------------------------------------------------------------------------------------------------ long
@RepeatedTest(8)
void testReadSignedLong() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForLong(unsigned);
final long value = bitInput.readLong(unsigned, size);
if (unsigned) {
assertEquals(0L, value >> size);
} else {
if (value >= 0L) {
assertEquals(0L, value >> (size - 1));
} else {
assertEquals(-1L, value >> (size - 1));
}
}
}
// ------------------------------------------------------------------------------------------------------------ char
@RepeatedTest(8)
void testReadChar() throws IOException { | // Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForByte(final boolean unsigned) {
// return requireValidSizeByte(unsigned, current().nextInt(1, Byte.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForChar() {
// return requireValidSizeChar(current().nextInt(1, Character.SIZE));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForInt(final boolean unsigned) {
// return requireValidSizeInt(unsigned, current().nextInt(1, Integer.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForLong(final boolean unsigned) {
// return requireValidSizeLong(unsigned, current().nextInt(1, Long.SIZE + (unsigned ? 0 : 1)));
// }
//
// Path: src/test/java/com/github/jinahya/bit/io/BitIoTests.java
// static int randomSizeForShort(final boolean unsigned) {
// return requireValidSizeShort(unsigned, current().nextInt(1, Short.SIZE + (unsigned ? 0 : 1)));
// }
// Path: src/test/java/com/github/jinahya/bit/io/AbstractBitInputSpyTest.java
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForByte;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForChar;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForInt;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForLong;
import static com.github.jinahya.bit.io.BitIoTests.randomSizeForShort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.lenient;
assertEquals(0, value >> size);
} else {
if (value >= 0) {
assertEquals(0, value >> (size - 1));
} else {
assertEquals(-1, value >> (size - 1));
}
}
}
// ------------------------------------------------------------------------------------------------------------ long
@RepeatedTest(8)
void testReadSignedLong() throws IOException {
final boolean unsigned = current().nextBoolean();
final int size = randomSizeForLong(unsigned);
final long value = bitInput.readLong(unsigned, size);
if (unsigned) {
assertEquals(0L, value >> size);
} else {
if (value >= 0L) {
assertEquals(0L, value >> (size - 1));
} else {
assertEquals(-1L, value >> (size - 1));
}
}
}
// ------------------------------------------------------------------------------------------------------------ char
@RepeatedTest(8)
void testReadChar() throws IOException { | final int size = randomSizeForChar(); |
forax/jigsaw-jrtfs | backport/src/rt/Enhancements.java | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/function/IntFunction.java
// public interface IntFunction<T> {
// public T apply(int value);
// }
//
// Path: backport/src/java/util/function/Predicate.java
// public interface Predicate<T> {
// boolean test(T element);
// }
//
// Path: backport/src/java/util/stream/Collector.java
// public interface Collector<T, A, R> {
// public R doCollect(Stream<T> stream);
// }
//
// Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: backport/src/java/util/stream/Stream.java
// public interface Stream<T> {
// public void forEach(Consumer<? super T> consumer);
// public Stream<T> filter(Predicate<? super T> predicate);
// public Stream<T> sorted();
// public <A> A[] toArray(IntFunction<A[]> generator);
// public <R, A> R collect(Collector<T, A, R> collector);
// public <U> Stream<U> map(Function<? super T, ? extends U> mapper);
// public Stream<T> distinct();
// public Stream<T> sorted(Comparator<? super T> comparator);
// }
| import java.lang.invoke.CallSite;
import java.lang.invoke.ConstantCallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandleProxies;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream; | package rt;
public class Enhancements {
// --- entry points
public static <T> Stream<T> stream(List<T> list) {
return streamImpl(list);
}
public static <T> Stream<T> stream(Set<T> list) {
return streamImpl(list);
} | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/function/IntFunction.java
// public interface IntFunction<T> {
// public T apply(int value);
// }
//
// Path: backport/src/java/util/function/Predicate.java
// public interface Predicate<T> {
// boolean test(T element);
// }
//
// Path: backport/src/java/util/stream/Collector.java
// public interface Collector<T, A, R> {
// public R doCollect(Stream<T> stream);
// }
//
// Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: backport/src/java/util/stream/Stream.java
// public interface Stream<T> {
// public void forEach(Consumer<? super T> consumer);
// public Stream<T> filter(Predicate<? super T> predicate);
// public Stream<T> sorted();
// public <A> A[] toArray(IntFunction<A[]> generator);
// public <R, A> R collect(Collector<T, A, R> collector);
// public <U> Stream<U> map(Function<? super T, ? extends U> mapper);
// public Stream<T> distinct();
// public Stream<T> sorted(Comparator<? super T> comparator);
// }
// Path: backport/src/rt/Enhancements.java
import java.lang.invoke.CallSite;
import java.lang.invoke.ConstantCallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandleProxies;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
package rt;
public class Enhancements {
// --- entry points
public static <T> Stream<T> stream(List<T> list) {
return streamImpl(list);
}
public static <T> Stream<T> stream(Set<T> list) {
return streamImpl(list);
} | public static <T> Function<T,T> identity() { |
forax/jigsaw-jrtfs | backport/src/rt/Enhancements.java | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/function/IntFunction.java
// public interface IntFunction<T> {
// public T apply(int value);
// }
//
// Path: backport/src/java/util/function/Predicate.java
// public interface Predicate<T> {
// boolean test(T element);
// }
//
// Path: backport/src/java/util/stream/Collector.java
// public interface Collector<T, A, R> {
// public R doCollect(Stream<T> stream);
// }
//
// Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: backport/src/java/util/stream/Stream.java
// public interface Stream<T> {
// public void forEach(Consumer<? super T> consumer);
// public Stream<T> filter(Predicate<? super T> predicate);
// public Stream<T> sorted();
// public <A> A[] toArray(IntFunction<A[]> generator);
// public <R, A> R collect(Collector<T, A, R> collector);
// public <U> Stream<U> map(Function<? super T, ? extends U> mapper);
// public Stream<T> distinct();
// public Stream<T> sorted(Comparator<? super T> comparator);
// }
| import java.lang.invoke.CallSite;
import java.lang.invoke.ConstantCallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandleProxies;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream; | package rt;
public class Enhancements {
// --- entry points
public static <T> Stream<T> stream(List<T> list) {
return streamImpl(list);
}
public static <T> Stream<T> stream(Set<T> list) {
return streamImpl(list);
}
public static <T> Function<T,T> identity() {
return x -> x;
}
// --- implementations
private static <T> StreamImpl<T> streamImpl(Iterable<? extends T> iterable) {
return new StreamImpl<T>() {
@Override | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/function/IntFunction.java
// public interface IntFunction<T> {
// public T apply(int value);
// }
//
// Path: backport/src/java/util/function/Predicate.java
// public interface Predicate<T> {
// boolean test(T element);
// }
//
// Path: backport/src/java/util/stream/Collector.java
// public interface Collector<T, A, R> {
// public R doCollect(Stream<T> stream);
// }
//
// Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: backport/src/java/util/stream/Stream.java
// public interface Stream<T> {
// public void forEach(Consumer<? super T> consumer);
// public Stream<T> filter(Predicate<? super T> predicate);
// public Stream<T> sorted();
// public <A> A[] toArray(IntFunction<A[]> generator);
// public <R, A> R collect(Collector<T, A, R> collector);
// public <U> Stream<U> map(Function<? super T, ? extends U> mapper);
// public Stream<T> distinct();
// public Stream<T> sorted(Comparator<? super T> comparator);
// }
// Path: backport/src/rt/Enhancements.java
import java.lang.invoke.CallSite;
import java.lang.invoke.ConstantCallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandleProxies;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
package rt;
public class Enhancements {
// --- entry points
public static <T> Stream<T> stream(List<T> list) {
return streamImpl(list);
}
public static <T> Stream<T> stream(Set<T> list) {
return streamImpl(list);
}
public static <T> Function<T,T> identity() {
return x -> x;
}
// --- implementations
private static <T> StreamImpl<T> streamImpl(Iterable<? extends T> iterable) {
return new StreamImpl<T>() {
@Override | public void forEach(Consumer<? super T> consumer) { |
forax/jigsaw-jrtfs | backport/src/rt/Enhancements.java | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/function/IntFunction.java
// public interface IntFunction<T> {
// public T apply(int value);
// }
//
// Path: backport/src/java/util/function/Predicate.java
// public interface Predicate<T> {
// boolean test(T element);
// }
//
// Path: backport/src/java/util/stream/Collector.java
// public interface Collector<T, A, R> {
// public R doCollect(Stream<T> stream);
// }
//
// Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: backport/src/java/util/stream/Stream.java
// public interface Stream<T> {
// public void forEach(Consumer<? super T> consumer);
// public Stream<T> filter(Predicate<? super T> predicate);
// public Stream<T> sorted();
// public <A> A[] toArray(IntFunction<A[]> generator);
// public <R, A> R collect(Collector<T, A, R> collector);
// public <U> Stream<U> map(Function<? super T, ? extends U> mapper);
// public Stream<T> distinct();
// public Stream<T> sorted(Comparator<? super T> comparator);
// }
| import java.lang.invoke.CallSite;
import java.lang.invoke.ConstantCallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandleProxies;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream; | package rt;
public class Enhancements {
// --- entry points
public static <T> Stream<T> stream(List<T> list) {
return streamImpl(list);
}
public static <T> Stream<T> stream(Set<T> list) {
return streamImpl(list);
}
public static <T> Function<T,T> identity() {
return x -> x;
}
// --- implementations
private static <T> StreamImpl<T> streamImpl(Iterable<? extends T> iterable) {
return new StreamImpl<T>() {
@Override
public void forEach(Consumer<? super T> consumer) {
for(T element: iterable) {
consumer.accept(element);
}
}
};
}
static abstract class StreamImpl<T> implements Stream<T> {
@Override
public abstract void forEach(Consumer<? super T> consumer);
@Override | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/function/IntFunction.java
// public interface IntFunction<T> {
// public T apply(int value);
// }
//
// Path: backport/src/java/util/function/Predicate.java
// public interface Predicate<T> {
// boolean test(T element);
// }
//
// Path: backport/src/java/util/stream/Collector.java
// public interface Collector<T, A, R> {
// public R doCollect(Stream<T> stream);
// }
//
// Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: backport/src/java/util/stream/Stream.java
// public interface Stream<T> {
// public void forEach(Consumer<? super T> consumer);
// public Stream<T> filter(Predicate<? super T> predicate);
// public Stream<T> sorted();
// public <A> A[] toArray(IntFunction<A[]> generator);
// public <R, A> R collect(Collector<T, A, R> collector);
// public <U> Stream<U> map(Function<? super T, ? extends U> mapper);
// public Stream<T> distinct();
// public Stream<T> sorted(Comparator<? super T> comparator);
// }
// Path: backport/src/rt/Enhancements.java
import java.lang.invoke.CallSite;
import java.lang.invoke.ConstantCallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandleProxies;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
package rt;
public class Enhancements {
// --- entry points
public static <T> Stream<T> stream(List<T> list) {
return streamImpl(list);
}
public static <T> Stream<T> stream(Set<T> list) {
return streamImpl(list);
}
public static <T> Function<T,T> identity() {
return x -> x;
}
// --- implementations
private static <T> StreamImpl<T> streamImpl(Iterable<? extends T> iterable) {
return new StreamImpl<T>() {
@Override
public void forEach(Consumer<? super T> consumer) {
for(T element: iterable) {
consumer.accept(element);
}
}
};
}
static abstract class StreamImpl<T> implements Stream<T> {
@Override
public abstract void forEach(Consumer<? super T> consumer);
@Override | public Stream<T> filter(Predicate<? super T> predicate) { |
forax/jigsaw-jrtfs | backport/src/rt/Enhancements.java | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/function/IntFunction.java
// public interface IntFunction<T> {
// public T apply(int value);
// }
//
// Path: backport/src/java/util/function/Predicate.java
// public interface Predicate<T> {
// boolean test(T element);
// }
//
// Path: backport/src/java/util/stream/Collector.java
// public interface Collector<T, A, R> {
// public R doCollect(Stream<T> stream);
// }
//
// Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: backport/src/java/util/stream/Stream.java
// public interface Stream<T> {
// public void forEach(Consumer<? super T> consumer);
// public Stream<T> filter(Predicate<? super T> predicate);
// public Stream<T> sorted();
// public <A> A[] toArray(IntFunction<A[]> generator);
// public <R, A> R collect(Collector<T, A, R> collector);
// public <U> Stream<U> map(Function<? super T, ? extends U> mapper);
// public Stream<T> distinct();
// public Stream<T> sorted(Comparator<? super T> comparator);
// }
| import java.lang.invoke.CallSite;
import java.lang.invoke.ConstantCallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandleProxies;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream; | };
}
static abstract class StreamImpl<T> implements Stream<T> {
@Override
public abstract void forEach(Consumer<? super T> consumer);
@Override
public Stream<T> filter(Predicate<? super T> predicate) {
return new StreamImpl<T>() {
@Override
public void forEach(Consumer<? super T> consumer) {
StreamImpl.this.forEach(element -> {
if (predicate.test(element)) {
consumer.accept(element);
}
});
}
};
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Stream<T> sorted() {
return sorted((e1, e2) -> ((Comparable)e1).compareTo(e2));
}
@Override
@SuppressWarnings("unchecked") | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/function/IntFunction.java
// public interface IntFunction<T> {
// public T apply(int value);
// }
//
// Path: backport/src/java/util/function/Predicate.java
// public interface Predicate<T> {
// boolean test(T element);
// }
//
// Path: backport/src/java/util/stream/Collector.java
// public interface Collector<T, A, R> {
// public R doCollect(Stream<T> stream);
// }
//
// Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: backport/src/java/util/stream/Stream.java
// public interface Stream<T> {
// public void forEach(Consumer<? super T> consumer);
// public Stream<T> filter(Predicate<? super T> predicate);
// public Stream<T> sorted();
// public <A> A[] toArray(IntFunction<A[]> generator);
// public <R, A> R collect(Collector<T, A, R> collector);
// public <U> Stream<U> map(Function<? super T, ? extends U> mapper);
// public Stream<T> distinct();
// public Stream<T> sorted(Comparator<? super T> comparator);
// }
// Path: backport/src/rt/Enhancements.java
import java.lang.invoke.CallSite;
import java.lang.invoke.ConstantCallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandleProxies;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
};
}
static abstract class StreamImpl<T> implements Stream<T> {
@Override
public abstract void forEach(Consumer<? super T> consumer);
@Override
public Stream<T> filter(Predicate<? super T> predicate) {
return new StreamImpl<T>() {
@Override
public void forEach(Consumer<? super T> consumer) {
StreamImpl.this.forEach(element -> {
if (predicate.test(element)) {
consumer.accept(element);
}
});
}
};
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Stream<T> sorted() {
return sorted((e1, e2) -> ((Comparable)e1).compareTo(e2));
}
@Override
@SuppressWarnings("unchecked") | public <A> A[] toArray(IntFunction<A[]> generator) { |
forax/jigsaw-jrtfs | backport/src/rt/Enhancements.java | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/function/IntFunction.java
// public interface IntFunction<T> {
// public T apply(int value);
// }
//
// Path: backport/src/java/util/function/Predicate.java
// public interface Predicate<T> {
// boolean test(T element);
// }
//
// Path: backport/src/java/util/stream/Collector.java
// public interface Collector<T, A, R> {
// public R doCollect(Stream<T> stream);
// }
//
// Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: backport/src/java/util/stream/Stream.java
// public interface Stream<T> {
// public void forEach(Consumer<? super T> consumer);
// public Stream<T> filter(Predicate<? super T> predicate);
// public Stream<T> sorted();
// public <A> A[] toArray(IntFunction<A[]> generator);
// public <R, A> R collect(Collector<T, A, R> collector);
// public <U> Stream<U> map(Function<? super T, ? extends U> mapper);
// public Stream<T> distinct();
// public Stream<T> sorted(Comparator<? super T> comparator);
// }
| import java.lang.invoke.CallSite;
import java.lang.invoke.ConstantCallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandleProxies;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream; | }
static abstract class StreamImpl<T> implements Stream<T> {
@Override
public abstract void forEach(Consumer<? super T> consumer);
@Override
public Stream<T> filter(Predicate<? super T> predicate) {
return new StreamImpl<T>() {
@Override
public void forEach(Consumer<? super T> consumer) {
StreamImpl.this.forEach(element -> {
if (predicate.test(element)) {
consumer.accept(element);
}
});
}
};
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Stream<T> sorted() {
return sorted((e1, e2) -> ((Comparable)e1).compareTo(e2));
}
@Override
@SuppressWarnings("unchecked")
public <A> A[] toArray(IntFunction<A[]> generator) { | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/function/IntFunction.java
// public interface IntFunction<T> {
// public T apply(int value);
// }
//
// Path: backport/src/java/util/function/Predicate.java
// public interface Predicate<T> {
// boolean test(T element);
// }
//
// Path: backport/src/java/util/stream/Collector.java
// public interface Collector<T, A, R> {
// public R doCollect(Stream<T> stream);
// }
//
// Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: backport/src/java/util/stream/Stream.java
// public interface Stream<T> {
// public void forEach(Consumer<? super T> consumer);
// public Stream<T> filter(Predicate<? super T> predicate);
// public Stream<T> sorted();
// public <A> A[] toArray(IntFunction<A[]> generator);
// public <R, A> R collect(Collector<T, A, R> collector);
// public <U> Stream<U> map(Function<? super T, ? extends U> mapper);
// public Stream<T> distinct();
// public Stream<T> sorted(Comparator<? super T> comparator);
// }
// Path: backport/src/rt/Enhancements.java
import java.lang.invoke.CallSite;
import java.lang.invoke.ConstantCallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandleProxies;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
}
static abstract class StreamImpl<T> implements Stream<T> {
@Override
public abstract void forEach(Consumer<? super T> consumer);
@Override
public Stream<T> filter(Predicate<? super T> predicate) {
return new StreamImpl<T>() {
@Override
public void forEach(Consumer<? super T> consumer) {
StreamImpl.this.forEach(element -> {
if (predicate.test(element)) {
consumer.accept(element);
}
});
}
};
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Stream<T> sorted() {
return sorted((e1, e2) -> ((Comparable)e1).compareTo(e2));
}
@Override
@SuppressWarnings("unchecked")
public <A> A[] toArray(IntFunction<A[]> generator) { | List<T> list = collect(Collectors.toList()); |
forax/jigsaw-jrtfs | backport/src/rt/Enhancements.java | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/function/IntFunction.java
// public interface IntFunction<T> {
// public T apply(int value);
// }
//
// Path: backport/src/java/util/function/Predicate.java
// public interface Predicate<T> {
// boolean test(T element);
// }
//
// Path: backport/src/java/util/stream/Collector.java
// public interface Collector<T, A, R> {
// public R doCollect(Stream<T> stream);
// }
//
// Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: backport/src/java/util/stream/Stream.java
// public interface Stream<T> {
// public void forEach(Consumer<? super T> consumer);
// public Stream<T> filter(Predicate<? super T> predicate);
// public Stream<T> sorted();
// public <A> A[] toArray(IntFunction<A[]> generator);
// public <R, A> R collect(Collector<T, A, R> collector);
// public <U> Stream<U> map(Function<? super T, ? extends U> mapper);
// public Stream<T> distinct();
// public Stream<T> sorted(Comparator<? super T> comparator);
// }
| import java.lang.invoke.CallSite;
import java.lang.invoke.ConstantCallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandleProxies;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream; | public void forEach(Consumer<? super T> consumer) {
StreamImpl.this.forEach(element -> {
if (predicate.test(element)) {
consumer.accept(element);
}
});
}
};
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Stream<T> sorted() {
return sorted((e1, e2) -> ((Comparable)e1).compareTo(e2));
}
@Override
@SuppressWarnings("unchecked")
public <A> A[] toArray(IntFunction<A[]> generator) {
List<T> list = collect(Collectors.toList());
A[] array = generator.apply(list.size());
Class<?> type = array.getClass().getComponentType();
for(int i = 0; i < list.size(); i++) {
array[i] = (A)type.cast(list.get(i));
}
return array;
}
@Override | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/function/IntFunction.java
// public interface IntFunction<T> {
// public T apply(int value);
// }
//
// Path: backport/src/java/util/function/Predicate.java
// public interface Predicate<T> {
// boolean test(T element);
// }
//
// Path: backport/src/java/util/stream/Collector.java
// public interface Collector<T, A, R> {
// public R doCollect(Stream<T> stream);
// }
//
// Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: backport/src/java/util/stream/Stream.java
// public interface Stream<T> {
// public void forEach(Consumer<? super T> consumer);
// public Stream<T> filter(Predicate<? super T> predicate);
// public Stream<T> sorted();
// public <A> A[] toArray(IntFunction<A[]> generator);
// public <R, A> R collect(Collector<T, A, R> collector);
// public <U> Stream<U> map(Function<? super T, ? extends U> mapper);
// public Stream<T> distinct();
// public Stream<T> sorted(Comparator<? super T> comparator);
// }
// Path: backport/src/rt/Enhancements.java
import java.lang.invoke.CallSite;
import java.lang.invoke.ConstantCallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandleProxies;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public void forEach(Consumer<? super T> consumer) {
StreamImpl.this.forEach(element -> {
if (predicate.test(element)) {
consumer.accept(element);
}
});
}
};
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Stream<T> sorted() {
return sorted((e1, e2) -> ((Comparable)e1).compareTo(e2));
}
@Override
@SuppressWarnings("unchecked")
public <A> A[] toArray(IntFunction<A[]> generator) {
List<T> list = collect(Collectors.toList());
A[] array = generator.apply(list.size());
Class<?> type = array.getClass().getComponentType();
for(int i = 0; i < list.size(); i++) {
array[i] = (A)type.cast(list.get(i));
}
return array;
}
@Override | public <R, A> R collect(Collector<T, A, R> collector) { |
forax/jigsaw-jrtfs | backport/src/java/util/stream/Stream.java | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/function/IntFunction.java
// public interface IntFunction<T> {
// public T apply(int value);
// }
//
// Path: backport/src/java/util/function/Predicate.java
// public interface Predicate<T> {
// boolean test(T element);
// }
| import java.util.Comparator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate; | package java.util.stream;
public interface Stream<T> {
public void forEach(Consumer<? super T> consumer); | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/function/IntFunction.java
// public interface IntFunction<T> {
// public T apply(int value);
// }
//
// Path: backport/src/java/util/function/Predicate.java
// public interface Predicate<T> {
// boolean test(T element);
// }
// Path: backport/src/java/util/stream/Stream.java
import java.util.Comparator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
package java.util.stream;
public interface Stream<T> {
public void forEach(Consumer<? super T> consumer); | public Stream<T> filter(Predicate<? super T> predicate); |
forax/jigsaw-jrtfs | backport/src/java/util/stream/Stream.java | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/function/IntFunction.java
// public interface IntFunction<T> {
// public T apply(int value);
// }
//
// Path: backport/src/java/util/function/Predicate.java
// public interface Predicate<T> {
// boolean test(T element);
// }
| import java.util.Comparator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate; | package java.util.stream;
public interface Stream<T> {
public void forEach(Consumer<? super T> consumer);
public Stream<T> filter(Predicate<? super T> predicate);
public Stream<T> sorted(); | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/function/IntFunction.java
// public interface IntFunction<T> {
// public T apply(int value);
// }
//
// Path: backport/src/java/util/function/Predicate.java
// public interface Predicate<T> {
// boolean test(T element);
// }
// Path: backport/src/java/util/stream/Stream.java
import java.util.Comparator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
package java.util.stream;
public interface Stream<T> {
public void forEach(Consumer<? super T> consumer);
public Stream<T> filter(Predicate<? super T> predicate);
public Stream<T> sorted(); | public <A> A[] toArray(IntFunction<A[]> generator); |
forax/jigsaw-jrtfs | backport/src/java/util/stream/Stream.java | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/function/IntFunction.java
// public interface IntFunction<T> {
// public T apply(int value);
// }
//
// Path: backport/src/java/util/function/Predicate.java
// public interface Predicate<T> {
// boolean test(T element);
// }
| import java.util.Comparator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate; | package java.util.stream;
public interface Stream<T> {
public void forEach(Consumer<? super T> consumer);
public Stream<T> filter(Predicate<? super T> predicate);
public Stream<T> sorted();
public <A> A[] toArray(IntFunction<A[]> generator);
public <R, A> R collect(Collector<T, A, R> collector); | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/function/IntFunction.java
// public interface IntFunction<T> {
// public T apply(int value);
// }
//
// Path: backport/src/java/util/function/Predicate.java
// public interface Predicate<T> {
// boolean test(T element);
// }
// Path: backport/src/java/util/stream/Stream.java
import java.util.Comparator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
package java.util.stream;
public interface Stream<T> {
public void forEach(Consumer<? super T> consumer);
public Stream<T> filter(Predicate<? super T> predicate);
public Stream<T> sorted();
public <A> A[] toArray(IntFunction<A[]> generator);
public <R, A> R collect(Collector<T, A, R> collector); | public <U> Stream<U> map(Function<? super T, ? extends U> mapper); |
forax/jigsaw-jrtfs | backport-build/src/com/github/forax/jrtfs/backport/Check.java | // Path: backport/src/java/io/UncheckedIOException.java
// public class UncheckedIOException extends RuntimeException {
// private static final long serialVersionUID = -5719611140800825697L;
//
// public UncheckedIOException(IOException cause) {
// super(cause);
// }
//
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.zip.GZIPInputStream;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes; | package com.github.forax.jrtfs.backport;
public class Check {
public static void main(String[] args) throws IOException {
Path sigPath = Paths.get("jdk7-sig.txt");
Path sigGzipPath = Paths.get("jdk7-sig.txt.gz");
HashSet<String> compatSignatures = new HashSet<>();
if (Files.exists(sigGzipPath)) {
try(InputStream input = Files.newInputStream(sigGzipPath);
GZIPInputStream gzipInput = new GZIPInputStream(input);
Reader r = new InputStreamReader(gzipInput);
BufferedReader reader = new BufferedReader(r)) {
reader.lines().forEach(compatSignatures::add);
}
} else {
Files.lines(sigPath).forEach(compatSignatures::add);
}
Files.walk(Paths.get("output/classes"))
.filter(path -> path.toString().endsWith(".class"))
.forEach(path -> {
ClassReader reader;
try {
reader = new ClassReader(Files.readAllBytes(path));
} catch (IOException e) { | // Path: backport/src/java/io/UncheckedIOException.java
// public class UncheckedIOException extends RuntimeException {
// private static final long serialVersionUID = -5719611140800825697L;
//
// public UncheckedIOException(IOException cause) {
// super(cause);
// }
//
// }
// Path: backport-build/src/com/github/forax/jrtfs/backport/Check.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.zip.GZIPInputStream;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
package com.github.forax.jrtfs.backport;
public class Check {
public static void main(String[] args) throws IOException {
Path sigPath = Paths.get("jdk7-sig.txt");
Path sigGzipPath = Paths.get("jdk7-sig.txt.gz");
HashSet<String> compatSignatures = new HashSet<>();
if (Files.exists(sigGzipPath)) {
try(InputStream input = Files.newInputStream(sigGzipPath);
GZIPInputStream gzipInput = new GZIPInputStream(input);
Reader r = new InputStreamReader(gzipInput);
BufferedReader reader = new BufferedReader(r)) {
reader.lines().forEach(compatSignatures::add);
}
} else {
Files.lines(sigPath).forEach(compatSignatures::add);
}
Files.walk(Paths.get("output/classes"))
.filter(path -> path.toString().endsWith(".class"))
.forEach(path -> {
ClassReader reader;
try {
reader = new ClassReader(Files.readAllBytes(path));
} catch (IOException e) { | throw new UncheckedIOException(e); |
forax/jigsaw-jrtfs | src/jdk/internal/jimage/Archive.java | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
| import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.function.Consumer; | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.internal.jimage;
/**
* An Archive of all content, classes, resources, configuration files, and
* other, for a module.
*/
public interface Archive {
/**
* The module name.
*/
String moduleName();
/**
* Visits all classes and resources.
*/ | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
// Path: src/jdk/internal/jimage/Archive.java
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.function.Consumer;
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.internal.jimage;
/**
* An Archive of all content, classes, resources, configuration files, and
* other, for a module.
*/
public interface Archive {
/**
* The module name.
*/
String moduleName();
/**
* Visits all classes and resources.
*/ | void visitResources(Consumer<Resource> consumer); |
forax/jigsaw-jrtfs | backport-build/src/com/github/forax/jrtfs/backport/Compatibility.java | // Path: backport/src/java/io/UncheckedIOException.java
// public class UncheckedIOException extends RuntimeException {
// private static final long serialVersionUID = -5719611140800825697L;
//
// public UncheckedIOException(IOException cause) {
// super(cause);
// }
//
// }
| import static org.objectweb.asm.Opcodes.*;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.jar.JarFile;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor; | /*
if (args.length == 3) {
Path jdkSig = Paths.get(args[2]);
Files.lines(jdkSig)
.forEach(line -> {
String[] parts = line.split("\\.");
if (parts.length != 2) {
throw new IllegalStateException("line " + line + " " + Arrays.toString(parts));
}
String className = parts[0];
String method = parts[1];
ClassMirror classMirror =
compatibility.classMirrorMap.computeIfAbsent(className,
key -> compatibility.new ClassMirror(key, true));
classMirror.methods.add(method);
});
}*/
try(JarFile jarInput = new JarFile(input.toFile());
BufferedWriter writer = Files.newBufferedWriter(output)) {
jarInput.stream()
.forEach(entry -> {
try(InputStream inputStream = jarInput.getInputStream(entry)) {
String name = entry.getName();
if (name.endsWith(".class")) {
ClassReader reader = new ClassReader(inputStream);
compatibility.parseClass(reader);
}
} catch (IOException e) { | // Path: backport/src/java/io/UncheckedIOException.java
// public class UncheckedIOException extends RuntimeException {
// private static final long serialVersionUID = -5719611140800825697L;
//
// public UncheckedIOException(IOException cause) {
// super(cause);
// }
//
// }
// Path: backport-build/src/com/github/forax/jrtfs/backport/Compatibility.java
import static org.objectweb.asm.Opcodes.*;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.jar.JarFile;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
/*
if (args.length == 3) {
Path jdkSig = Paths.get(args[2]);
Files.lines(jdkSig)
.forEach(line -> {
String[] parts = line.split("\\.");
if (parts.length != 2) {
throw new IllegalStateException("line " + line + " " + Arrays.toString(parts));
}
String className = parts[0];
String method = parts[1];
ClassMirror classMirror =
compatibility.classMirrorMap.computeIfAbsent(className,
key -> compatibility.new ClassMirror(key, true));
classMirror.methods.add(method);
});
}*/
try(JarFile jarInput = new JarFile(input.toFile());
BufferedWriter writer = Files.newBufferedWriter(output)) {
jarInput.stream()
.forEach(entry -> {
try(InputStream inputStream = jarInput.getInputStream(entry)) {
String name = entry.getName();
if (name.endsWith(".class")) {
ClassReader reader = new ClassReader(inputStream);
compatibility.parseClass(reader);
}
} catch (IOException e) { | throw new UncheckedIOException(e); |
forax/jigsaw-jrtfs | backport-build/src/com/github/forax/jrtfs/backport/RetroWeaver.java | // Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
| import static org.objectweb.asm.Opcodes.ASM5;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
import java.io.IOException;
import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.invoke.MethodType;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.stream.Collectors;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Handle;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.Remapper;
import org.objectweb.asm.commons.RemappingClassAdapter; | }
static Handle RETRO_BSM = new Handle(Opcodes.H_INVOKESTATIC,
"com/github/forax/jrtfs/backport/rt/Enhancements",
"metafactory",
MethodType.methodType(CallSite.class, Lookup.class, String.class, MethodType.class,
MethodType.class, MethodHandle.class, MethodType.class
).toMethodDescriptorString());
public static void main(String[] args) throws IOException {
Path backportClasses = Paths.get("output/backport/classes");
Path retroClasses = Paths.get("output/retro/classes");
Path outputClasses = Paths.get("output/classes");
RetroWeaver retroWeaver = new RetroWeaver();
// add classes
Files.walk(backportClasses)
.forEach(path -> {
Path localPath = backportClasses.relativize(path);
String filename = localPath.toString();
if (filename.endsWith(".class")) {
String internalName = filename.substring(0, filename.length() - 6);
System.out.println("need to repackage " + internalName);
retroWeaver.addNewClass(internalName);
}
});
// retro weave | // Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
// Path: backport-build/src/com/github/forax/jrtfs/backport/RetroWeaver.java
import static org.objectweb.asm.Opcodes.ASM5;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
import java.io.IOException;
import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.invoke.MethodType;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.stream.Collectors;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Handle;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.Remapper;
import org.objectweb.asm.commons.RemappingClassAdapter;
}
static Handle RETRO_BSM = new Handle(Opcodes.H_INVOKESTATIC,
"com/github/forax/jrtfs/backport/rt/Enhancements",
"metafactory",
MethodType.methodType(CallSite.class, Lookup.class, String.class, MethodType.class,
MethodType.class, MethodHandle.class, MethodType.class
).toMethodDescriptorString());
public static void main(String[] args) throws IOException {
Path backportClasses = Paths.get("output/backport/classes");
Path retroClasses = Paths.get("output/retro/classes");
Path outputClasses = Paths.get("output/classes");
RetroWeaver retroWeaver = new RetroWeaver();
// add classes
Files.walk(backportClasses)
.forEach(path -> {
Path localPath = backportClasses.relativize(path);
String filename = localPath.toString();
if (filename.endsWith(".class")) {
String internalName = filename.substring(0, filename.length() - 6);
System.out.println("need to repackage " + internalName);
retroWeaver.addNewClass(internalName);
}
});
// retro weave | for(Path path: Files.walk(retroClasses).filter(path -> !Files.isDirectory(path)).collect(Collectors.toList())) { |
forax/jigsaw-jrtfs | src/jdk/internal/jrtfs/JrtFileAttributes.java | // Path: src/jdk/internal/jimage/ImageReader.java
// public static abstract class Node {
// private static final int ROOT_DIR = 0b0000_0000_0000_0001;
// private static final int MODULE_DIR = 0b0000_0000_0000_0010;
// private static final int METAINF_DIR = 0b0000_0000_0000_0100;
// private static final int TOPLEVEL_PKG_DIR = 0b0000_0000_0000_1000;
//
// private int flags;
// private final UTF8String name;
// private final BasicFileAttributes fileAttrs;
//
// Node(UTF8String name, BasicFileAttributes fileAttrs) {
// assert name != null;
// assert fileAttrs != null;
// this.name = name;
// this.fileAttrs = fileAttrs;
// }
//
// public void setIsRootDir() {
// flags |= ROOT_DIR;
// }
//
// public boolean isRootDir() {
// return (flags & ROOT_DIR) != 0;
// }
//
// public void setIsModuleDir() {
// flags |= MODULE_DIR;
// }
//
// public boolean isModuleDir() {
// return (flags & MODULE_DIR) != 0;
// }
//
// public void setIsMetaInfDir() {
// flags |= METAINF_DIR;
// }
//
// public boolean isMetaInfDir() {
// return (flags & METAINF_DIR) != 0;
// }
//
// public void setIsTopLevelPackageDir() {
// flags |= TOPLEVEL_PKG_DIR;
// }
//
// public boolean isTopLevelPackageDir() {
// return (flags & TOPLEVEL_PKG_DIR) != 0;
// }
//
// public final UTF8String getName() {
// return name;
// }
//
// public final BasicFileAttributes getFileAttributes() {
// return fileAttrs;
// }
//
// public boolean isDirectory() {
// return false;
// }
//
// public List<Node> getChildren() {
// throw new IllegalArgumentException("not a directory: " + getNameString());
// }
//
// public boolean isResource() {
// return false;
// }
//
// public ImageLocation getLocation() {
// throw new IllegalArgumentException("not a resource: " + getNameString());
// }
//
// public long size() {
// return 0L;
// }
//
// public long compressedSize() {
// return 0L;
// }
//
// public String extension() {
// return null;
// }
//
// public long contentOffset() {
// return 0L;
// }
//
// public final FileTime creationTime() {
// return fileAttrs.creationTime();
// }
//
// public final FileTime lastAccessTime() {
// return fileAttrs.lastAccessTime();
// }
//
// public final FileTime lastModifiedTime() {
// return fileAttrs.lastModifiedTime();
// }
//
// public final String getNameString() {
// return name.toString();
// }
//
// @Override
// public final String toString() {
// return getNameString();
// }
//
// @Override
// public final int hashCode() {
// return name.hashCode();
// }
//
// @Override
// public final boolean equals(Object other) {
// if (this == other) {
// return true;
// }
//
// if (other instanceof Node) {
// return name.equals(((Node) other).name);
// }
//
// return false;
// }
// }
| import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.Formatter;
import jdk.internal.jimage.ImageReader.Node; | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.internal.jrtfs;
final class JrtFileAttributes implements BasicFileAttributes
{ | // Path: src/jdk/internal/jimage/ImageReader.java
// public static abstract class Node {
// private static final int ROOT_DIR = 0b0000_0000_0000_0001;
// private static final int MODULE_DIR = 0b0000_0000_0000_0010;
// private static final int METAINF_DIR = 0b0000_0000_0000_0100;
// private static final int TOPLEVEL_PKG_DIR = 0b0000_0000_0000_1000;
//
// private int flags;
// private final UTF8String name;
// private final BasicFileAttributes fileAttrs;
//
// Node(UTF8String name, BasicFileAttributes fileAttrs) {
// assert name != null;
// assert fileAttrs != null;
// this.name = name;
// this.fileAttrs = fileAttrs;
// }
//
// public void setIsRootDir() {
// flags |= ROOT_DIR;
// }
//
// public boolean isRootDir() {
// return (flags & ROOT_DIR) != 0;
// }
//
// public void setIsModuleDir() {
// flags |= MODULE_DIR;
// }
//
// public boolean isModuleDir() {
// return (flags & MODULE_DIR) != 0;
// }
//
// public void setIsMetaInfDir() {
// flags |= METAINF_DIR;
// }
//
// public boolean isMetaInfDir() {
// return (flags & METAINF_DIR) != 0;
// }
//
// public void setIsTopLevelPackageDir() {
// flags |= TOPLEVEL_PKG_DIR;
// }
//
// public boolean isTopLevelPackageDir() {
// return (flags & TOPLEVEL_PKG_DIR) != 0;
// }
//
// public final UTF8String getName() {
// return name;
// }
//
// public final BasicFileAttributes getFileAttributes() {
// return fileAttrs;
// }
//
// public boolean isDirectory() {
// return false;
// }
//
// public List<Node> getChildren() {
// throw new IllegalArgumentException("not a directory: " + getNameString());
// }
//
// public boolean isResource() {
// return false;
// }
//
// public ImageLocation getLocation() {
// throw new IllegalArgumentException("not a resource: " + getNameString());
// }
//
// public long size() {
// return 0L;
// }
//
// public long compressedSize() {
// return 0L;
// }
//
// public String extension() {
// return null;
// }
//
// public long contentOffset() {
// return 0L;
// }
//
// public final FileTime creationTime() {
// return fileAttrs.creationTime();
// }
//
// public final FileTime lastAccessTime() {
// return fileAttrs.lastAccessTime();
// }
//
// public final FileTime lastModifiedTime() {
// return fileAttrs.lastModifiedTime();
// }
//
// public final String getNameString() {
// return name.toString();
// }
//
// @Override
// public final String toString() {
// return getNameString();
// }
//
// @Override
// public final int hashCode() {
// return name.hashCode();
// }
//
// @Override
// public final boolean equals(Object other) {
// if (this == other) {
// return true;
// }
//
// if (other instanceof Node) {
// return name.equals(((Node) other).name);
// }
//
// return false;
// }
// }
// Path: src/jdk/internal/jrtfs/JrtFileAttributes.java
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.Formatter;
import jdk.internal.jimage.ImageReader.Node;
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.internal.jrtfs;
final class JrtFileAttributes implements BasicFileAttributes
{ | private final Node node; |
forax/jigsaw-jrtfs | src/jdk/internal/jimage/ImageFile.java | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: src/jdk/internal/jimage/ImageModules.java
// enum Loader {
// BOOT_LOADER(0, "bootmodules"),
// EXT_LOADER(1, "extmodules"),
// APP_LOADER(2, "appmodules"); // ## may be more than 1 loader
//
// final int id;
// final String name;
// Loader(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// String getName() {
// return name;
// }
// static Loader get(int id) {
// switch (id) {
// case 0: return BOOT_LOADER;
// case 1: return EXT_LOADER;
// case 2: return APP_LOADER;
// default:
// throw new IllegalArgumentException("invalid loader id: " + id);
// }
// }
// public int id() { return id; }
// }
//
// Path: src/jdk/internal/jimage/ImageModules.java
// public class ModuleIndex {
// final Map<String, Integer> moduleOffsets = new LinkedHashMap<>();
// final Map<String, List<Integer>> packageOffsets = new HashMap<>();
// final int size;
// public ModuleIndex(Set<String> mods, BasicImageWriter writer) {
// // module name offsets
// writer.addLocation(MODULES_ENTRY, 0, 0, mods.size() * 4);
// long offset = mods.size() * 4;
// for (String mn : mods) {
// moduleOffsets.put(mn, writer.addString(mn));
// List<Integer> poffsets = localPkgs.get(mn).stream()
// .map(pn -> pn.replace('.', '/'))
// .map(writer::addString)
// .collect(Collectors.toList());
// // package name offsets per module
// String entry = mn + "/" + PACKAGES_ENTRY;
// int bytes = poffsets.size() * 4;
// writer.addLocation(entry, offset, 0, bytes);
// offset += bytes;
// packageOffsets.put(mn, poffsets);
// }
// this.size = (int) offset;
// }
//
// void writeTo(DataOutputStream out) throws IOException {
// for (int moffset : moduleOffsets.values()) {
// out.writeInt(moffset);
// }
// for (String mn : moduleOffsets.keySet()) {
// for (int poffset : packageOffsets.get(mn)) {
// out.writeInt(poffset);
// }
// }
// }
//
// int size() {
// return size;
// }
// }
| import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteOrder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import jdk.internal.jimage.ImageModules.Loader;
import jdk.internal.jimage.ImageModules.ModuleIndex; | public static ImageFile create(Path output,
Set<Archive> archives,
ImageModules modules)
throws IOException
{
return ImageFile.create(output, archives, modules, ByteOrder.nativeOrder());
}
public static ImageFile create(Path output,
Set<Archive> archives,
ImageModules modules,
ByteOrder byteOrder)
throws IOException
{
ImageFile lib = new ImageFile(output);
// get all resources
lib.readModuleEntries(modules, archives);
// write to modular image
lib.writeImage(modules, archives, byteOrder);
return lib;
}
private void writeImage(ImageModules modules,
Set<Archive> archives,
ByteOrder byteOrder)
throws IOException
{
// name to Archive file
Map<String, Archive> nameToArchive =
archives.stream() | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: src/jdk/internal/jimage/ImageModules.java
// enum Loader {
// BOOT_LOADER(0, "bootmodules"),
// EXT_LOADER(1, "extmodules"),
// APP_LOADER(2, "appmodules"); // ## may be more than 1 loader
//
// final int id;
// final String name;
// Loader(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// String getName() {
// return name;
// }
// static Loader get(int id) {
// switch (id) {
// case 0: return BOOT_LOADER;
// case 1: return EXT_LOADER;
// case 2: return APP_LOADER;
// default:
// throw new IllegalArgumentException("invalid loader id: " + id);
// }
// }
// public int id() { return id; }
// }
//
// Path: src/jdk/internal/jimage/ImageModules.java
// public class ModuleIndex {
// final Map<String, Integer> moduleOffsets = new LinkedHashMap<>();
// final Map<String, List<Integer>> packageOffsets = new HashMap<>();
// final int size;
// public ModuleIndex(Set<String> mods, BasicImageWriter writer) {
// // module name offsets
// writer.addLocation(MODULES_ENTRY, 0, 0, mods.size() * 4);
// long offset = mods.size() * 4;
// for (String mn : mods) {
// moduleOffsets.put(mn, writer.addString(mn));
// List<Integer> poffsets = localPkgs.get(mn).stream()
// .map(pn -> pn.replace('.', '/'))
// .map(writer::addString)
// .collect(Collectors.toList());
// // package name offsets per module
// String entry = mn + "/" + PACKAGES_ENTRY;
// int bytes = poffsets.size() * 4;
// writer.addLocation(entry, offset, 0, bytes);
// offset += bytes;
// packageOffsets.put(mn, poffsets);
// }
// this.size = (int) offset;
// }
//
// void writeTo(DataOutputStream out) throws IOException {
// for (int moffset : moduleOffsets.values()) {
// out.writeInt(moffset);
// }
// for (String mn : moduleOffsets.keySet()) {
// for (int poffset : packageOffsets.get(mn)) {
// out.writeInt(poffset);
// }
// }
// }
//
// int size() {
// return size;
// }
// }
// Path: src/jdk/internal/jimage/ImageFile.java
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteOrder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import jdk.internal.jimage.ImageModules.Loader;
import jdk.internal.jimage.ImageModules.ModuleIndex;
public static ImageFile create(Path output,
Set<Archive> archives,
ImageModules modules)
throws IOException
{
return ImageFile.create(output, archives, modules, ByteOrder.nativeOrder());
}
public static ImageFile create(Path output,
Set<Archive> archives,
ImageModules modules,
ByteOrder byteOrder)
throws IOException
{
ImageFile lib = new ImageFile(output);
// get all resources
lib.readModuleEntries(modules, archives);
// write to modular image
lib.writeImage(modules, archives, byteOrder);
return lib;
}
private void writeImage(ImageModules modules,
Set<Archive> archives,
ByteOrder byteOrder)
throws IOException
{
// name to Archive file
Map<String, Archive> nameToArchive =
archives.stream() | .collect(Collectors.toMap(Archive::moduleName, Function.identity())); |
forax/jigsaw-jrtfs | src/jdk/internal/jimage/ImageFile.java | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: src/jdk/internal/jimage/ImageModules.java
// enum Loader {
// BOOT_LOADER(0, "bootmodules"),
// EXT_LOADER(1, "extmodules"),
// APP_LOADER(2, "appmodules"); // ## may be more than 1 loader
//
// final int id;
// final String name;
// Loader(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// String getName() {
// return name;
// }
// static Loader get(int id) {
// switch (id) {
// case 0: return BOOT_LOADER;
// case 1: return EXT_LOADER;
// case 2: return APP_LOADER;
// default:
// throw new IllegalArgumentException("invalid loader id: " + id);
// }
// }
// public int id() { return id; }
// }
//
// Path: src/jdk/internal/jimage/ImageModules.java
// public class ModuleIndex {
// final Map<String, Integer> moduleOffsets = new LinkedHashMap<>();
// final Map<String, List<Integer>> packageOffsets = new HashMap<>();
// final int size;
// public ModuleIndex(Set<String> mods, BasicImageWriter writer) {
// // module name offsets
// writer.addLocation(MODULES_ENTRY, 0, 0, mods.size() * 4);
// long offset = mods.size() * 4;
// for (String mn : mods) {
// moduleOffsets.put(mn, writer.addString(mn));
// List<Integer> poffsets = localPkgs.get(mn).stream()
// .map(pn -> pn.replace('.', '/'))
// .map(writer::addString)
// .collect(Collectors.toList());
// // package name offsets per module
// String entry = mn + "/" + PACKAGES_ENTRY;
// int bytes = poffsets.size() * 4;
// writer.addLocation(entry, offset, 0, bytes);
// offset += bytes;
// packageOffsets.put(mn, poffsets);
// }
// this.size = (int) offset;
// }
//
// void writeTo(DataOutputStream out) throws IOException {
// for (int moffset : moduleOffsets.values()) {
// out.writeInt(moffset);
// }
// for (String mn : moduleOffsets.keySet()) {
// for (int poffset : packageOffsets.get(mn)) {
// out.writeInt(poffset);
// }
// }
// }
//
// int size() {
// return size;
// }
// }
| import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteOrder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import jdk.internal.jimage.ImageModules.Loader;
import jdk.internal.jimage.ImageModules.ModuleIndex; | public static ImageFile create(Path output,
Set<Archive> archives,
ImageModules modules)
throws IOException
{
return ImageFile.create(output, archives, modules, ByteOrder.nativeOrder());
}
public static ImageFile create(Path output,
Set<Archive> archives,
ImageModules modules,
ByteOrder byteOrder)
throws IOException
{
ImageFile lib = new ImageFile(output);
// get all resources
lib.readModuleEntries(modules, archives);
// write to modular image
lib.writeImage(modules, archives, byteOrder);
return lib;
}
private void writeImage(ImageModules modules,
Set<Archive> archives,
ByteOrder byteOrder)
throws IOException
{
// name to Archive file
Map<String, Archive> nameToArchive =
archives.stream() | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: src/jdk/internal/jimage/ImageModules.java
// enum Loader {
// BOOT_LOADER(0, "bootmodules"),
// EXT_LOADER(1, "extmodules"),
// APP_LOADER(2, "appmodules"); // ## may be more than 1 loader
//
// final int id;
// final String name;
// Loader(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// String getName() {
// return name;
// }
// static Loader get(int id) {
// switch (id) {
// case 0: return BOOT_LOADER;
// case 1: return EXT_LOADER;
// case 2: return APP_LOADER;
// default:
// throw new IllegalArgumentException("invalid loader id: " + id);
// }
// }
// public int id() { return id; }
// }
//
// Path: src/jdk/internal/jimage/ImageModules.java
// public class ModuleIndex {
// final Map<String, Integer> moduleOffsets = new LinkedHashMap<>();
// final Map<String, List<Integer>> packageOffsets = new HashMap<>();
// final int size;
// public ModuleIndex(Set<String> mods, BasicImageWriter writer) {
// // module name offsets
// writer.addLocation(MODULES_ENTRY, 0, 0, mods.size() * 4);
// long offset = mods.size() * 4;
// for (String mn : mods) {
// moduleOffsets.put(mn, writer.addString(mn));
// List<Integer> poffsets = localPkgs.get(mn).stream()
// .map(pn -> pn.replace('.', '/'))
// .map(writer::addString)
// .collect(Collectors.toList());
// // package name offsets per module
// String entry = mn + "/" + PACKAGES_ENTRY;
// int bytes = poffsets.size() * 4;
// writer.addLocation(entry, offset, 0, bytes);
// offset += bytes;
// packageOffsets.put(mn, poffsets);
// }
// this.size = (int) offset;
// }
//
// void writeTo(DataOutputStream out) throws IOException {
// for (int moffset : moduleOffsets.values()) {
// out.writeInt(moffset);
// }
// for (String mn : moduleOffsets.keySet()) {
// for (int poffset : packageOffsets.get(mn)) {
// out.writeInt(poffset);
// }
// }
// }
//
// int size() {
// return size;
// }
// }
// Path: src/jdk/internal/jimage/ImageFile.java
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteOrder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import jdk.internal.jimage.ImageModules.Loader;
import jdk.internal.jimage.ImageModules.ModuleIndex;
public static ImageFile create(Path output,
Set<Archive> archives,
ImageModules modules)
throws IOException
{
return ImageFile.create(output, archives, modules, ByteOrder.nativeOrder());
}
public static ImageFile create(Path output,
Set<Archive> archives,
ImageModules modules,
ByteOrder byteOrder)
throws IOException
{
ImageFile lib = new ImageFile(output);
// get all resources
lib.readModuleEntries(modules, archives);
// write to modular image
lib.writeImage(modules, archives, byteOrder);
return lib;
}
private void writeImage(ImageModules modules,
Set<Archive> archives,
ByteOrder byteOrder)
throws IOException
{
// name to Archive file
Map<String, Archive> nameToArchive =
archives.stream() | .collect(Collectors.toMap(Archive::moduleName, Function.identity())); |
forax/jigsaw-jrtfs | src/jdk/internal/jimage/ImageFile.java | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: src/jdk/internal/jimage/ImageModules.java
// enum Loader {
// BOOT_LOADER(0, "bootmodules"),
// EXT_LOADER(1, "extmodules"),
// APP_LOADER(2, "appmodules"); // ## may be more than 1 loader
//
// final int id;
// final String name;
// Loader(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// String getName() {
// return name;
// }
// static Loader get(int id) {
// switch (id) {
// case 0: return BOOT_LOADER;
// case 1: return EXT_LOADER;
// case 2: return APP_LOADER;
// default:
// throw new IllegalArgumentException("invalid loader id: " + id);
// }
// }
// public int id() { return id; }
// }
//
// Path: src/jdk/internal/jimage/ImageModules.java
// public class ModuleIndex {
// final Map<String, Integer> moduleOffsets = new LinkedHashMap<>();
// final Map<String, List<Integer>> packageOffsets = new HashMap<>();
// final int size;
// public ModuleIndex(Set<String> mods, BasicImageWriter writer) {
// // module name offsets
// writer.addLocation(MODULES_ENTRY, 0, 0, mods.size() * 4);
// long offset = mods.size() * 4;
// for (String mn : mods) {
// moduleOffsets.put(mn, writer.addString(mn));
// List<Integer> poffsets = localPkgs.get(mn).stream()
// .map(pn -> pn.replace('.', '/'))
// .map(writer::addString)
// .collect(Collectors.toList());
// // package name offsets per module
// String entry = mn + "/" + PACKAGES_ENTRY;
// int bytes = poffsets.size() * 4;
// writer.addLocation(entry, offset, 0, bytes);
// offset += bytes;
// packageOffsets.put(mn, poffsets);
// }
// this.size = (int) offset;
// }
//
// void writeTo(DataOutputStream out) throws IOException {
// for (int moffset : moduleOffsets.values()) {
// out.writeInt(moffset);
// }
// for (String mn : moduleOffsets.keySet()) {
// for (int poffset : packageOffsets.get(mn)) {
// out.writeInt(poffset);
// }
// }
// }
//
// int size() {
// return size;
// }
// }
| import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteOrder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import jdk.internal.jimage.ImageModules.Loader;
import jdk.internal.jimage.ImageModules.ModuleIndex; | throws IOException
{
return ImageFile.create(output, archives, modules, ByteOrder.nativeOrder());
}
public static ImageFile create(Path output,
Set<Archive> archives,
ImageModules modules,
ByteOrder byteOrder)
throws IOException
{
ImageFile lib = new ImageFile(output);
// get all resources
lib.readModuleEntries(modules, archives);
// write to modular image
lib.writeImage(modules, archives, byteOrder);
return lib;
}
private void writeImage(ImageModules modules,
Set<Archive> archives,
ByteOrder byteOrder)
throws IOException
{
// name to Archive file
Map<String, Archive> nameToArchive =
archives.stream()
.collect(Collectors.toMap(Archive::moduleName, Function.identity()));
Files.createDirectories(mdir); | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: src/jdk/internal/jimage/ImageModules.java
// enum Loader {
// BOOT_LOADER(0, "bootmodules"),
// EXT_LOADER(1, "extmodules"),
// APP_LOADER(2, "appmodules"); // ## may be more than 1 loader
//
// final int id;
// final String name;
// Loader(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// String getName() {
// return name;
// }
// static Loader get(int id) {
// switch (id) {
// case 0: return BOOT_LOADER;
// case 1: return EXT_LOADER;
// case 2: return APP_LOADER;
// default:
// throw new IllegalArgumentException("invalid loader id: " + id);
// }
// }
// public int id() { return id; }
// }
//
// Path: src/jdk/internal/jimage/ImageModules.java
// public class ModuleIndex {
// final Map<String, Integer> moduleOffsets = new LinkedHashMap<>();
// final Map<String, List<Integer>> packageOffsets = new HashMap<>();
// final int size;
// public ModuleIndex(Set<String> mods, BasicImageWriter writer) {
// // module name offsets
// writer.addLocation(MODULES_ENTRY, 0, 0, mods.size() * 4);
// long offset = mods.size() * 4;
// for (String mn : mods) {
// moduleOffsets.put(mn, writer.addString(mn));
// List<Integer> poffsets = localPkgs.get(mn).stream()
// .map(pn -> pn.replace('.', '/'))
// .map(writer::addString)
// .collect(Collectors.toList());
// // package name offsets per module
// String entry = mn + "/" + PACKAGES_ENTRY;
// int bytes = poffsets.size() * 4;
// writer.addLocation(entry, offset, 0, bytes);
// offset += bytes;
// packageOffsets.put(mn, poffsets);
// }
// this.size = (int) offset;
// }
//
// void writeTo(DataOutputStream out) throws IOException {
// for (int moffset : moduleOffsets.values()) {
// out.writeInt(moffset);
// }
// for (String mn : moduleOffsets.keySet()) {
// for (int poffset : packageOffsets.get(mn)) {
// out.writeInt(poffset);
// }
// }
// }
//
// int size() {
// return size;
// }
// }
// Path: src/jdk/internal/jimage/ImageFile.java
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteOrder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import jdk.internal.jimage.ImageModules.Loader;
import jdk.internal.jimage.ImageModules.ModuleIndex;
throws IOException
{
return ImageFile.create(output, archives, modules, ByteOrder.nativeOrder());
}
public static ImageFile create(Path output,
Set<Archive> archives,
ImageModules modules,
ByteOrder byteOrder)
throws IOException
{
ImageFile lib = new ImageFile(output);
// get all resources
lib.readModuleEntries(modules, archives);
// write to modular image
lib.writeImage(modules, archives, byteOrder);
return lib;
}
private void writeImage(ImageModules modules,
Set<Archive> archives,
ByteOrder byteOrder)
throws IOException
{
// name to Archive file
Map<String, Archive> nameToArchive =
archives.stream()
.collect(Collectors.toMap(Archive::moduleName, Function.identity()));
Files.createDirectories(mdir); | for (Loader l : Loader.values()) { |
forax/jigsaw-jrtfs | src/jdk/internal/jimage/ImageFile.java | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: src/jdk/internal/jimage/ImageModules.java
// enum Loader {
// BOOT_LOADER(0, "bootmodules"),
// EXT_LOADER(1, "extmodules"),
// APP_LOADER(2, "appmodules"); // ## may be more than 1 loader
//
// final int id;
// final String name;
// Loader(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// String getName() {
// return name;
// }
// static Loader get(int id) {
// switch (id) {
// case 0: return BOOT_LOADER;
// case 1: return EXT_LOADER;
// case 2: return APP_LOADER;
// default:
// throw new IllegalArgumentException("invalid loader id: " + id);
// }
// }
// public int id() { return id; }
// }
//
// Path: src/jdk/internal/jimage/ImageModules.java
// public class ModuleIndex {
// final Map<String, Integer> moduleOffsets = new LinkedHashMap<>();
// final Map<String, List<Integer>> packageOffsets = new HashMap<>();
// final int size;
// public ModuleIndex(Set<String> mods, BasicImageWriter writer) {
// // module name offsets
// writer.addLocation(MODULES_ENTRY, 0, 0, mods.size() * 4);
// long offset = mods.size() * 4;
// for (String mn : mods) {
// moduleOffsets.put(mn, writer.addString(mn));
// List<Integer> poffsets = localPkgs.get(mn).stream()
// .map(pn -> pn.replace('.', '/'))
// .map(writer::addString)
// .collect(Collectors.toList());
// // package name offsets per module
// String entry = mn + "/" + PACKAGES_ENTRY;
// int bytes = poffsets.size() * 4;
// writer.addLocation(entry, offset, 0, bytes);
// offset += bytes;
// packageOffsets.put(mn, poffsets);
// }
// this.size = (int) offset;
// }
//
// void writeTo(DataOutputStream out) throws IOException {
// for (int moffset : moduleOffsets.values()) {
// out.writeInt(moffset);
// }
// for (String mn : moduleOffsets.keySet()) {
// for (int poffset : packageOffsets.get(mn)) {
// out.writeInt(poffset);
// }
// }
// }
//
// int size() {
// return size;
// }
// }
| import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteOrder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import jdk.internal.jimage.ImageModules.Loader;
import jdk.internal.jimage.ImageModules.ModuleIndex; | ImageFile lib = new ImageFile(output);
// get all resources
lib.readModuleEntries(modules, archives);
// write to modular image
lib.writeImage(modules, archives, byteOrder);
return lib;
}
private void writeImage(ImageModules modules,
Set<Archive> archives,
ByteOrder byteOrder)
throws IOException
{
// name to Archive file
Map<String, Archive> nameToArchive =
archives.stream()
.collect(Collectors.toMap(Archive::moduleName, Function.identity()));
Files.createDirectories(mdir);
for (Loader l : Loader.values()) {
Set<String> mods = modules.getModules(l);
try (OutputStream fos = Files.newOutputStream(mdir.resolve(l.getName() + IMAGE_EXT));
BufferedOutputStream bos = new BufferedOutputStream(fos);
DataOutputStream out = new DataOutputStream(bos)) {
// store index in addition of the class loader map for boot loader
BasicImageWriter writer = new BasicImageWriter(byteOrder);
Set<String> duplicates = new HashSet<>();
// build package map for modules and add as resources | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: src/jdk/internal/jimage/ImageModules.java
// enum Loader {
// BOOT_LOADER(0, "bootmodules"),
// EXT_LOADER(1, "extmodules"),
// APP_LOADER(2, "appmodules"); // ## may be more than 1 loader
//
// final int id;
// final String name;
// Loader(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// String getName() {
// return name;
// }
// static Loader get(int id) {
// switch (id) {
// case 0: return BOOT_LOADER;
// case 1: return EXT_LOADER;
// case 2: return APP_LOADER;
// default:
// throw new IllegalArgumentException("invalid loader id: " + id);
// }
// }
// public int id() { return id; }
// }
//
// Path: src/jdk/internal/jimage/ImageModules.java
// public class ModuleIndex {
// final Map<String, Integer> moduleOffsets = new LinkedHashMap<>();
// final Map<String, List<Integer>> packageOffsets = new HashMap<>();
// final int size;
// public ModuleIndex(Set<String> mods, BasicImageWriter writer) {
// // module name offsets
// writer.addLocation(MODULES_ENTRY, 0, 0, mods.size() * 4);
// long offset = mods.size() * 4;
// for (String mn : mods) {
// moduleOffsets.put(mn, writer.addString(mn));
// List<Integer> poffsets = localPkgs.get(mn).stream()
// .map(pn -> pn.replace('.', '/'))
// .map(writer::addString)
// .collect(Collectors.toList());
// // package name offsets per module
// String entry = mn + "/" + PACKAGES_ENTRY;
// int bytes = poffsets.size() * 4;
// writer.addLocation(entry, offset, 0, bytes);
// offset += bytes;
// packageOffsets.put(mn, poffsets);
// }
// this.size = (int) offset;
// }
//
// void writeTo(DataOutputStream out) throws IOException {
// for (int moffset : moduleOffsets.values()) {
// out.writeInt(moffset);
// }
// for (String mn : moduleOffsets.keySet()) {
// for (int poffset : packageOffsets.get(mn)) {
// out.writeInt(poffset);
// }
// }
// }
//
// int size() {
// return size;
// }
// }
// Path: src/jdk/internal/jimage/ImageFile.java
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteOrder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import jdk.internal.jimage.ImageModules.Loader;
import jdk.internal.jimage.ImageModules.ModuleIndex;
ImageFile lib = new ImageFile(output);
// get all resources
lib.readModuleEntries(modules, archives);
// write to modular image
lib.writeImage(modules, archives, byteOrder);
return lib;
}
private void writeImage(ImageModules modules,
Set<Archive> archives,
ByteOrder byteOrder)
throws IOException
{
// name to Archive file
Map<String, Archive> nameToArchive =
archives.stream()
.collect(Collectors.toMap(Archive::moduleName, Function.identity()));
Files.createDirectories(mdir);
for (Loader l : Loader.values()) {
Set<String> mods = modules.getModules(l);
try (OutputStream fos = Files.newOutputStream(mdir.resolve(l.getName() + IMAGE_EXT));
BufferedOutputStream bos = new BufferedOutputStream(fos);
DataOutputStream out = new DataOutputStream(bos)) {
// store index in addition of the class loader map for boot loader
BasicImageWriter writer = new BasicImageWriter(byteOrder);
Set<String> duplicates = new HashSet<>();
// build package map for modules and add as resources | ModuleIndex mindex = modules.buildModuleIndex(l, writer); |
forax/jigsaw-jrtfs | src/jdk/internal/jimage/ImageFile.java | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: src/jdk/internal/jimage/ImageModules.java
// enum Loader {
// BOOT_LOADER(0, "bootmodules"),
// EXT_LOADER(1, "extmodules"),
// APP_LOADER(2, "appmodules"); // ## may be more than 1 loader
//
// final int id;
// final String name;
// Loader(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// String getName() {
// return name;
// }
// static Loader get(int id) {
// switch (id) {
// case 0: return BOOT_LOADER;
// case 1: return EXT_LOADER;
// case 2: return APP_LOADER;
// default:
// throw new IllegalArgumentException("invalid loader id: " + id);
// }
// }
// public int id() { return id; }
// }
//
// Path: src/jdk/internal/jimage/ImageModules.java
// public class ModuleIndex {
// final Map<String, Integer> moduleOffsets = new LinkedHashMap<>();
// final Map<String, List<Integer>> packageOffsets = new HashMap<>();
// final int size;
// public ModuleIndex(Set<String> mods, BasicImageWriter writer) {
// // module name offsets
// writer.addLocation(MODULES_ENTRY, 0, 0, mods.size() * 4);
// long offset = mods.size() * 4;
// for (String mn : mods) {
// moduleOffsets.put(mn, writer.addString(mn));
// List<Integer> poffsets = localPkgs.get(mn).stream()
// .map(pn -> pn.replace('.', '/'))
// .map(writer::addString)
// .collect(Collectors.toList());
// // package name offsets per module
// String entry = mn + "/" + PACKAGES_ENTRY;
// int bytes = poffsets.size() * 4;
// writer.addLocation(entry, offset, 0, bytes);
// offset += bytes;
// packageOffsets.put(mn, poffsets);
// }
// this.size = (int) offset;
// }
//
// void writeTo(DataOutputStream out) throws IOException {
// for (int moffset : moduleOffsets.values()) {
// out.writeInt(moffset);
// }
// for (String mn : moduleOffsets.keySet()) {
// for (int poffset : packageOffsets.get(mn)) {
// out.writeInt(poffset);
// }
// }
// }
//
// int size() {
// return size;
// }
// }
| import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteOrder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import jdk.internal.jimage.ImageModules.Loader;
import jdk.internal.jimage.ImageModules.ModuleIndex; | List<Resource> res = new ArrayList<>();
archive.visitResources(x-> res.add(x));
String mn = archive.moduleName();
resourcesForModule.put(mn, res);
Set<String> pkgs = res.stream().map(Resource::name)
.filter(n -> n.endsWith(".class"))
.map(this::toPackage)
.distinct()
.collect(Collectors.toSet());
modules.setPackages(mn, pkgs);
}
}
private String toPackage(String name) {
int index = name.lastIndexOf('/');
if (index > 0) {
return name.substring(0, index).replace('/', '.');
} else {
// ## unnamed package
System.err.format("Warning: %s in unnamed package%n", name);
return "";
}
}
private void writeModule(Archive archive,
OutputStream out)
throws IOException
{ | // Path: backport/src/java/util/function/Consumer.java
// public interface Consumer<T> {
// public void accept(T element);
// }
//
// Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: src/jdk/internal/jimage/ImageModules.java
// enum Loader {
// BOOT_LOADER(0, "bootmodules"),
// EXT_LOADER(1, "extmodules"),
// APP_LOADER(2, "appmodules"); // ## may be more than 1 loader
//
// final int id;
// final String name;
// Loader(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// String getName() {
// return name;
// }
// static Loader get(int id) {
// switch (id) {
// case 0: return BOOT_LOADER;
// case 1: return EXT_LOADER;
// case 2: return APP_LOADER;
// default:
// throw new IllegalArgumentException("invalid loader id: " + id);
// }
// }
// public int id() { return id; }
// }
//
// Path: src/jdk/internal/jimage/ImageModules.java
// public class ModuleIndex {
// final Map<String, Integer> moduleOffsets = new LinkedHashMap<>();
// final Map<String, List<Integer>> packageOffsets = new HashMap<>();
// final int size;
// public ModuleIndex(Set<String> mods, BasicImageWriter writer) {
// // module name offsets
// writer.addLocation(MODULES_ENTRY, 0, 0, mods.size() * 4);
// long offset = mods.size() * 4;
// for (String mn : mods) {
// moduleOffsets.put(mn, writer.addString(mn));
// List<Integer> poffsets = localPkgs.get(mn).stream()
// .map(pn -> pn.replace('.', '/'))
// .map(writer::addString)
// .collect(Collectors.toList());
// // package name offsets per module
// String entry = mn + "/" + PACKAGES_ENTRY;
// int bytes = poffsets.size() * 4;
// writer.addLocation(entry, offset, 0, bytes);
// offset += bytes;
// packageOffsets.put(mn, poffsets);
// }
// this.size = (int) offset;
// }
//
// void writeTo(DataOutputStream out) throws IOException {
// for (int moffset : moduleOffsets.values()) {
// out.writeInt(moffset);
// }
// for (String mn : moduleOffsets.keySet()) {
// for (int poffset : packageOffsets.get(mn)) {
// out.writeInt(poffset);
// }
// }
// }
//
// int size() {
// return size;
// }
// }
// Path: src/jdk/internal/jimage/ImageFile.java
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteOrder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import jdk.internal.jimage.ImageModules.Loader;
import jdk.internal.jimage.ImageModules.ModuleIndex;
List<Resource> res = new ArrayList<>();
archive.visitResources(x-> res.add(x));
String mn = archive.moduleName();
resourcesForModule.put(mn, res);
Set<String> pkgs = res.stream().map(Resource::name)
.filter(n -> n.endsWith(".class"))
.map(this::toPackage)
.distinct()
.collect(Collectors.toSet());
modules.setPackages(mn, pkgs);
}
}
private String toPackage(String name) {
int index = name.lastIndexOf('/');
if (index > 0) {
return name.substring(0, index).replace('/', '.');
} else {
// ## unnamed package
System.err.format("Warning: %s in unnamed package%n", name);
return "";
}
}
private void writeModule(Archive archive,
OutputStream out)
throws IOException
{ | Consumer<Archive.Entry> consumer = archive.defaultImageWriter(root, out); |
forax/jigsaw-jrtfs | src/jdk/internal/jimage/ImageReader.java | // Path: backport/src/java/io/UncheckedIOException.java
// public class UncheckedIOException extends RuntimeException {
// private static final long serialVersionUID = -5719611140800825697L;
//
// public UncheckedIOException(IOException cause) {
// super(cause);
// }
//
// }
//
// Path: backport/src/java/util/function/Supplier.java
// public interface Supplier<T> {
// public T get();
// }
| import java.nio.file.Files;
import java.nio.file.FileSystem;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer; | }
public Node findNode(String name) {
return findNode(new UTF8String(name));
}
public Node findNode(byte[] name) {
return findNode(new UTF8String(name));
}
public synchronized Node findNode(UTF8String name) {
buildRootDirectory();
return nodes.get(name);
}
private synchronized void clearNodes() {
nodes.clear();
rootDir = null;
}
/**
* Returns the file attributes of the image file.
*/
private BasicFileAttributes imageFileAttributes() {
BasicFileAttributes attrs = imageFileAttributes;
if (attrs == null) {
try {
Path file = Paths.get(imagePath());
attrs = Files.readAttributes(file, BasicFileAttributes.class);
} catch (IOException ioe) { | // Path: backport/src/java/io/UncheckedIOException.java
// public class UncheckedIOException extends RuntimeException {
// private static final long serialVersionUID = -5719611140800825697L;
//
// public UncheckedIOException(IOException cause) {
// super(cause);
// }
//
// }
//
// Path: backport/src/java/util/function/Supplier.java
// public interface Supplier<T> {
// public T get();
// }
// Path: src/jdk/internal/jimage/ImageReader.java
import java.nio.file.Files;
import java.nio.file.FileSystem;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
}
public Node findNode(String name) {
return findNode(new UTF8String(name));
}
public Node findNode(byte[] name) {
return findNode(new UTF8String(name));
}
public synchronized Node findNode(UTF8String name) {
buildRootDirectory();
return nodes.get(name);
}
private synchronized void clearNodes() {
nodes.clear();
rootDir = null;
}
/**
* Returns the file attributes of the image file.
*/
private BasicFileAttributes imageFileAttributes() {
BasicFileAttributes attrs = imageFileAttributes;
if (attrs == null) {
try {
Path file = Paths.get(imagePath());
attrs = Files.readAttributes(file, BasicFileAttributes.class);
} catch (IOException ioe) { | throw new UncheckedIOException(ioe); |
forax/jigsaw-jrtfs | backport/src/java/util/stream/Collectors.java | // Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/function/Supplier.java
// public interface Supplier<T> {
// public T get();
// }
| import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier; | package java.util.stream;
public class Collectors {
public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends V> valueMapper) {
return stream -> {
HashMap<K, V> map = new HashMap<>();
stream.forEach(element -> {
map.put(keyMapper.apply(element), valueMapper.apply(element));
});
return map;
};
}
public static <T> Collector<T, ?, Set<T>> toSet() {
return toCollection(HashSet::new);
}
public static <T> Collector<T, ?, List<T>> toList() {
return toCollection(ArrayList::new);
}
| // Path: backport/src/java/util/function/Function.java
// public interface Function<T, U> {
// public U apply(T element);
// }
//
// Path: backport/src/java/util/function/Supplier.java
// public interface Supplier<T> {
// public T get();
// }
// Path: backport/src/java/util/stream/Collectors.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
package java.util.stream;
public class Collectors {
public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends V> valueMapper) {
return stream -> {
HashMap<K, V> map = new HashMap<>();
stream.forEach(element -> {
map.put(keyMapper.apply(element), valueMapper.apply(element));
});
return map;
};
}
public static <T> Collector<T, ?, Set<T>> toSet() {
return toCollection(HashSet::new);
}
public static <T> Collector<T, ?, List<T>> toList() {
return toCollection(ArrayList::new);
}
| private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) { |
forax/jigsaw-jrtfs | src/jdk/internal/jimage/ImageModules.java | // Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: src/jdk/internal/jimage/PackageModuleMap.java
// public final class PackageModuleMap {
// private PackageModuleMap() {}
//
// public static final String MODULES_ENTRY = "module/modules.offsets";
// public static final String PACKAGES_ENTRY = "packages.offsets";
//
// /*
// * Returns a package-to-module map.
// *
// * The package name is in binary name format.
// */
// static Map<String,String> readFrom(ImageReader reader) throws IOException {
// Map<String,String> result = new HashMap<>();
// List<String> moduleNames = reader.getNames(MODULES_ENTRY);
//
// for (String moduleName : moduleNames) {
// List<String> packageNames = reader.getNames(moduleName + "/" + PACKAGES_ENTRY);
//
// for (String packageName : packageNames) {
// result.put(packageName, moduleName);
// }
// }
// return result;
// }
// }
| import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static jdk.internal.jimage.PackageModuleMap.*;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap; | this.modules = Collections.unmodifiableSet(modules);
}
Set<String> modules() {
return modules;
}
Loader loader() { return loader; }
}
ModuleIndex buildModuleIndex(Loader type, BasicImageWriter writer) {
return new ModuleIndex(getModules(type), writer);
}
/*
* Generate module name table and the package map as resources
* in the modular image
*/
public class ModuleIndex {
final Map<String, Integer> moduleOffsets = new LinkedHashMap<>();
final Map<String, List<Integer>> packageOffsets = new HashMap<>();
final int size;
public ModuleIndex(Set<String> mods, BasicImageWriter writer) {
// module name offsets
writer.addLocation(MODULES_ENTRY, 0, 0, mods.size() * 4);
long offset = mods.size() * 4;
for (String mn : mods) {
moduleOffsets.put(mn, writer.addString(mn));
List<Integer> poffsets = localPkgs.get(mn).stream()
.map(pn -> pn.replace('.', '/'))
.map(writer::addString) | // Path: backport/src/java/util/stream/Collectors.java
// public class Collectors {
// public static <T, K, V> Collector<T, ?, Map<K,V>> toMap(Function<? super T, ? extends K> keyMapper,
// Function<? super T, ? extends V> valueMapper) {
// return stream -> {
// HashMap<K, V> map = new HashMap<>();
// stream.forEach(element -> {
// map.put(keyMapper.apply(element), valueMapper.apply(element));
// });
// return map;
// };
// }
//
// public static <T> Collector<T, ?, Set<T>> toSet() {
// return toCollection(HashSet::new);
// }
//
// public static <T> Collector<T, ?, List<T>> toList() {
// return toCollection(ArrayList::new);
// }
//
// private static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
// return stream -> {
// C collection = collectionFactory.get();
// stream.forEach(collection::add);
// return collection;
// };
// }
// }
//
// Path: src/jdk/internal/jimage/PackageModuleMap.java
// public final class PackageModuleMap {
// private PackageModuleMap() {}
//
// public static final String MODULES_ENTRY = "module/modules.offsets";
// public static final String PACKAGES_ENTRY = "packages.offsets";
//
// /*
// * Returns a package-to-module map.
// *
// * The package name is in binary name format.
// */
// static Map<String,String> readFrom(ImageReader reader) throws IOException {
// Map<String,String> result = new HashMap<>();
// List<String> moduleNames = reader.getNames(MODULES_ENTRY);
//
// for (String moduleName : moduleNames) {
// List<String> packageNames = reader.getNames(moduleName + "/" + PACKAGES_ENTRY);
//
// for (String packageName : packageNames) {
// result.put(packageName, moduleName);
// }
// }
// return result;
// }
// }
// Path: src/jdk/internal/jimage/ImageModules.java
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static jdk.internal.jimage.PackageModuleMap.*;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
this.modules = Collections.unmodifiableSet(modules);
}
Set<String> modules() {
return modules;
}
Loader loader() { return loader; }
}
ModuleIndex buildModuleIndex(Loader type, BasicImageWriter writer) {
return new ModuleIndex(getModules(type), writer);
}
/*
* Generate module name table and the package map as resources
* in the modular image
*/
public class ModuleIndex {
final Map<String, Integer> moduleOffsets = new LinkedHashMap<>();
final Map<String, List<Integer>> packageOffsets = new HashMap<>();
final int size;
public ModuleIndex(Set<String> mods, BasicImageWriter writer) {
// module name offsets
writer.addLocation(MODULES_ENTRY, 0, 0, mods.size() * 4);
long offset = mods.size() * 4;
for (String mn : mods) {
moduleOffsets.put(mn, writer.addString(mn));
List<Integer> poffsets = localPkgs.get(mn).stream()
.map(pn -> pn.replace('.', '/'))
.map(writer::addString) | .collect(Collectors.toList()); |
ushahidi/SMSSync | smssync/src/main/java/org/addhen/smssync/presentation/view/ui/widget/TimePreferenceFragmentDialog.java | // Path: smssync/src/main/java/org/addhen/smssync/presentation/App.java
// public class App extends BaseApplication {
//
// private static AppComponent mAppComponent;
//
// private static TwitterClient mTwitter;
//
// private static App mApp;
//
//
// public static synchronized TwitterClient getTwitterInstance() {
// if (mTwitter == null) {
// mTwitter = new TwitterBuilder(mApp,
// BuildConfig.TWITTER_CONSUMER_KEY,
// BuildConfig.TWITTER_CONSUMER_SECRET)
// .build();
// }
// return mTwitter;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// initializeInjector();
// mApp = this;
// Timber.plant(new FirebaseCrashTree());
// }
//
// private void initializeInjector() {
// mAppComponent = AppComponent.Initializer.init(this);
// }
//
// public static AppComponent getAppComponent() {
// return mAppComponent;
// }
//
// /**
// * Return the application tracker
// */
// public static AppTracker getInstance() {
// return TrackerResolver.getInstance();
// }
// }
| import org.addhen.smssync.R;
import org.addhen.smssync.data.PrefsFactory;
import org.addhen.smssync.presentation.App;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.preference.DialogPreference.TargetFragment;
import android.support.v7.preference.ListPreferenceDialogFragmentCompat;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceDialogFragmentCompat;
import android.view.View;
import android.widget.TimePicker; | /*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.presentation.view.ui.widget;
/**
* @author Ushahidi Team <[email protected]>
*/
public class TimePreferenceFragmentDialog extends PreferenceDialogFragmentCompat implements
TargetFragment {
public static final String DIALOG_FRAGMENT_TAG
= "android.support.v7.preference.PreferenceFragment.DIALOG";
// Fist picker field
private int lastHour = 0;
// Second picker field
private int lastMinute = 0;
private TimePicker picker = null;
private PrefsFactory prefs;
private ListPreferenceDialogFragmentCompat mListPreferenceDialogFragmentCompat;
public TimePreferenceFragmentDialog() {
}
public static TimePreferenceFragmentDialog newInstance(String key) {
TimePreferenceFragmentDialog fragment = new TimePreferenceFragmentDialog();
Bundle bundle = new Bundle(1);
bundle.putString("key", key);
fragment.setArguments(bundle);
return fragment;
}
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
super.onPrepareDialogBuilder(builder);
TimePreference preference = this.getTimePreference();
builder.setPositiveButton(R.string.ok, (dialog, which) -> {
saveSelectedTime(preference);
dialog.dismiss();
});
}
@Override
protected View onCreateDialogView(Context context) { | // Path: smssync/src/main/java/org/addhen/smssync/presentation/App.java
// public class App extends BaseApplication {
//
// private static AppComponent mAppComponent;
//
// private static TwitterClient mTwitter;
//
// private static App mApp;
//
//
// public static synchronized TwitterClient getTwitterInstance() {
// if (mTwitter == null) {
// mTwitter = new TwitterBuilder(mApp,
// BuildConfig.TWITTER_CONSUMER_KEY,
// BuildConfig.TWITTER_CONSUMER_SECRET)
// .build();
// }
// return mTwitter;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// initializeInjector();
// mApp = this;
// Timber.plant(new FirebaseCrashTree());
// }
//
// private void initializeInjector() {
// mAppComponent = AppComponent.Initializer.init(this);
// }
//
// public static AppComponent getAppComponent() {
// return mAppComponent;
// }
//
// /**
// * Return the application tracker
// */
// public static AppTracker getInstance() {
// return TrackerResolver.getInstance();
// }
// }
// Path: smssync/src/main/java/org/addhen/smssync/presentation/view/ui/widget/TimePreferenceFragmentDialog.java
import org.addhen.smssync.R;
import org.addhen.smssync.data.PrefsFactory;
import org.addhen.smssync.presentation.App;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.preference.DialogPreference.TargetFragment;
import android.support.v7.preference.ListPreferenceDialogFragmentCompat;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceDialogFragmentCompat;
import android.view.View;
import android.widget.TimePicker;
/*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.presentation.view.ui.widget;
/**
* @author Ushahidi Team <[email protected]>
*/
public class TimePreferenceFragmentDialog extends PreferenceDialogFragmentCompat implements
TargetFragment {
public static final String DIALOG_FRAGMENT_TAG
= "android.support.v7.preference.PreferenceFragment.DIALOG";
// Fist picker field
private int lastHour = 0;
// Second picker field
private int lastMinute = 0;
private TimePicker picker = null;
private PrefsFactory prefs;
private ListPreferenceDialogFragmentCompat mListPreferenceDialogFragmentCompat;
public TimePreferenceFragmentDialog() {
}
public static TimePreferenceFragmentDialog newInstance(String key) {
TimePreferenceFragmentDialog fragment = new TimePreferenceFragmentDialog();
Bundle bundle = new Bundle(1);
bundle.putString("key", key);
fragment.setArguments(bundle);
return fragment;
}
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
super.onPrepareDialogBuilder(builder);
TimePreference preference = this.getTimePreference();
builder.setPositiveButton(R.string.ok, (dialog, which) -> {
saveSelectedTime(preference);
dialog.dismiss();
});
}
@Override
protected View onCreateDialogView(Context context) { | prefs = App.getAppComponent().prefsFactory(); |
ushahidi/SMSSync | smssync/src/main/java/org/addhen/smssync/presentation/view/ui/fragment/TaskSettingsFragment.java | // Path: smssync/src/main/java/org/addhen/smssync/presentation/view/ui/widget/TimePreferenceFragmentDialog.java
// public class TimePreferenceFragmentDialog extends PreferenceDialogFragmentCompat implements
// TargetFragment {
//
// public static final String DIALOG_FRAGMENT_TAG
// = "android.support.v7.preference.PreferenceFragment.DIALOG";
//
// // Fist picker field
// private int lastHour = 0;
//
// // Second picker field
// private int lastMinute = 0;
//
// private TimePicker picker = null;
//
// private PrefsFactory prefs;
//
// private ListPreferenceDialogFragmentCompat mListPreferenceDialogFragmentCompat;
//
// public TimePreferenceFragmentDialog() {
//
// }
//
// public static TimePreferenceFragmentDialog newInstance(String key) {
// TimePreferenceFragmentDialog fragment = new TimePreferenceFragmentDialog();
// Bundle bundle = new Bundle(1);
// bundle.putString("key", key);
// fragment.setArguments(bundle);
// return fragment;
// }
//
// protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
// super.onPrepareDialogBuilder(builder);
// TimePreference preference = this.getTimePreference();
// builder.setPositiveButton(R.string.ok, (dialog, which) -> {
// saveSelectedTime(preference);
// dialog.dismiss();
// });
// }
//
//
// @Override
// protected View onCreateDialogView(Context context) {
// prefs = App.getAppComponent().prefsFactory();
// picker = new TimePicker(context);
// return (picker);
// }
//
// @Override
// protected void onBindDialogView(View v) {
// super.onBindDialogView(v);
// picker.setIs24HourView(true);
// TimePreference timePreference = this.getTimePreference();
// picker.setCurrentHour(timePreference.getLastHour());
// picker.setCurrentMinute(timePreference.getLastMinute());
// }
//
// @Override
// public void onDialogClosed(boolean positiveResult) {
// TimePreference timePreference = this.getTimePreference();
// if (positiveResult) {
// saveSelectedTime(timePreference);
// }
// }
//
// private void saveSelectedTime(TimePreference timePreference) {
// timePreference.setLastHour(picker.getCurrentHour());
// timePreference.setLastMinute(picker.getCurrentMinute());
// if (timePreference.callChangeListener(timePreference.getTimeValueAsString())) {
// timePreference.persistStringValue(timePreference.getTimeValueAsString());
// timePreference.saveTimeFrequency();
// }
// }
//
// private TimePreference getTimePreference() {
// return (TimePreference) this.getPreference();
// }
//
// @Override
// public Preference findPreference(CharSequence charSequence) {
// return getTimePreference();
// }
// }
| import org.addhen.smssync.R;
import org.addhen.smssync.presentation.view.ui.widget.TimePreference;
import org.addhen.smssync.presentation.view.ui.widget.TimePreferenceFragmentDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.preference.Preference;
import android.support.v7.preference.SwitchPreferenceCompat; | /*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.presentation.view.ui.fragment;
/**
* @author Ushahidi Team <[email protected]>
*/
public class TaskSettingsFragment extends BasePreferenceFragmentCompat implements
SharedPreferences.OnSharedPreferenceChangeListener {
public static final String TASK_SETTINGS_FRAGMENT = "task_settings_fragment";
public static final String TASK_CHECK = "task_check_preference";
public static final String TASK_CHECK_TIMES = "task_check_times";
public static final String MESSAGE_RESULTS_API = "message_results_api_preference";
private SwitchPreferenceCompat mTaskCheck;
private TimePreference mTaskCheckTimes;
private SwitchPreferenceCompat mEnableMessageResultsAPI;
public TaskSettingsFragment() {
// Do nothing
}
@Override
public void onCreatePreferences(Bundle bundle, String key) {
addPreferencesFromResource(R.xml.task_preferences);
}
@Override
public void onDisplayPreferenceDialog(Preference preference) {
if (preference instanceof TimePreference) { | // Path: smssync/src/main/java/org/addhen/smssync/presentation/view/ui/widget/TimePreferenceFragmentDialog.java
// public class TimePreferenceFragmentDialog extends PreferenceDialogFragmentCompat implements
// TargetFragment {
//
// public static final String DIALOG_FRAGMENT_TAG
// = "android.support.v7.preference.PreferenceFragment.DIALOG";
//
// // Fist picker field
// private int lastHour = 0;
//
// // Second picker field
// private int lastMinute = 0;
//
// private TimePicker picker = null;
//
// private PrefsFactory prefs;
//
// private ListPreferenceDialogFragmentCompat mListPreferenceDialogFragmentCompat;
//
// public TimePreferenceFragmentDialog() {
//
// }
//
// public static TimePreferenceFragmentDialog newInstance(String key) {
// TimePreferenceFragmentDialog fragment = new TimePreferenceFragmentDialog();
// Bundle bundle = new Bundle(1);
// bundle.putString("key", key);
// fragment.setArguments(bundle);
// return fragment;
// }
//
// protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
// super.onPrepareDialogBuilder(builder);
// TimePreference preference = this.getTimePreference();
// builder.setPositiveButton(R.string.ok, (dialog, which) -> {
// saveSelectedTime(preference);
// dialog.dismiss();
// });
// }
//
//
// @Override
// protected View onCreateDialogView(Context context) {
// prefs = App.getAppComponent().prefsFactory();
// picker = new TimePicker(context);
// return (picker);
// }
//
// @Override
// protected void onBindDialogView(View v) {
// super.onBindDialogView(v);
// picker.setIs24HourView(true);
// TimePreference timePreference = this.getTimePreference();
// picker.setCurrentHour(timePreference.getLastHour());
// picker.setCurrentMinute(timePreference.getLastMinute());
// }
//
// @Override
// public void onDialogClosed(boolean positiveResult) {
// TimePreference timePreference = this.getTimePreference();
// if (positiveResult) {
// saveSelectedTime(timePreference);
// }
// }
//
// private void saveSelectedTime(TimePreference timePreference) {
// timePreference.setLastHour(picker.getCurrentHour());
// timePreference.setLastMinute(picker.getCurrentMinute());
// if (timePreference.callChangeListener(timePreference.getTimeValueAsString())) {
// timePreference.persistStringValue(timePreference.getTimeValueAsString());
// timePreference.saveTimeFrequency();
// }
// }
//
// private TimePreference getTimePreference() {
// return (TimePreference) this.getPreference();
// }
//
// @Override
// public Preference findPreference(CharSequence charSequence) {
// return getTimePreference();
// }
// }
// Path: smssync/src/main/java/org/addhen/smssync/presentation/view/ui/fragment/TaskSettingsFragment.java
import org.addhen.smssync.R;
import org.addhen.smssync.presentation.view.ui.widget.TimePreference;
import org.addhen.smssync.presentation.view.ui.widget.TimePreferenceFragmentDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.preference.Preference;
import android.support.v7.preference.SwitchPreferenceCompat;
/*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.presentation.view.ui.fragment;
/**
* @author Ushahidi Team <[email protected]>
*/
public class TaskSettingsFragment extends BasePreferenceFragmentCompat implements
SharedPreferences.OnSharedPreferenceChangeListener {
public static final String TASK_SETTINGS_FRAGMENT = "task_settings_fragment";
public static final String TASK_CHECK = "task_check_preference";
public static final String TASK_CHECK_TIMES = "task_check_times";
public static final String MESSAGE_RESULTS_API = "message_results_api_preference";
private SwitchPreferenceCompat mTaskCheck;
private TimePreference mTaskCheckTimes;
private SwitchPreferenceCompat mEnableMessageResultsAPI;
public TaskSettingsFragment() {
// Do nothing
}
@Override
public void onCreatePreferences(Bundle bundle, String key) {
addPreferencesFromResource(R.xml.task_preferences);
}
@Override
public void onDisplayPreferenceDialog(Preference preference) {
if (preference instanceof TimePreference) { | DialogFragment dialogFragment = TimePreferenceFragmentDialog.newInstance( |
ushahidi/SMSSync | smssync/src/main/java/org/addhen/smssync/presentation/view/ui/activity/QrcodeReaderActivity.java | // Path: smssync/src/main/java/org/addhen/smssync/presentation/model/WebServiceModel.java
// public class WebServiceModel extends Model implements Parcelable {
//
// private String title;
//
// private String url;
//
// private String secret;
//
// private String syncScheme;
//
// private Status status;
//
// private KeywordStatus keywordStatus;
//
// private String keywords;
//
// public WebServiceModel() {
// }
//
// public Long getId() {
// return _id;
// }
//
// public void setId(Long id) {
// _id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getSecret() {
// return secret;
// }
//
// public void setSecret(String secret) {
// this.secret = secret;
// }
//
// public SyncSchemeModel getSyncScheme() {
// return new SyncSchemeModel(syncScheme);
// }
//
// public void setSyncScheme(SyncSchemeModel syncScheme) {
// this.syncScheme = syncScheme.toJSONString();
// }
//
// public Status getStatus() {
// return status;
// }
//
// public void setStatus(Status status) {
// this.status = status;
// }
//
// public void setKeywords(String keywords) {
// this.keywords = keywords;
// }
//
// public String getKeywords() {
// return keywords;
// }
//
// public KeywordStatus getKeywordStatus() {
// return keywordStatus;
// }
//
// public void setKeywordStatus(
// KeywordStatus keywordStatus) {
// this.keywordStatus = keywordStatus;
// }
//
// @Override
// public String toString() {
// return "SyncUrl{" +
// "id=" + _id +
// "title='" + title + '\'' +
// ", url='" + url + '\'' +
// ", secret='" + secret + '\'' +
// ", syncScheme=" + syncScheme +
// ", keywords=" + keywords +
// ", keywordStatus=" + keywordStatus +
// ", status=" + status +
// '}';
// }
//
// public enum Status {
// ENABLED, DISABLED
// }
//
// public enum KeywordStatus {
// ENABLED, DISABLED
// }
//
// protected WebServiceModel(Parcel in) {
// _id = in.readByte() == 0x00 ? null : in.readLong();
// title = in.readString();
// url = in.readString();
// secret = in.readString();
// syncScheme = in.readString();
// status = (Status) in.readValue(Status.class.getClassLoader());
// keywords = in.readString();
// keywordStatus = (KeywordStatus) in.readValue(KeywordStatus.class.getClassLoader());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// if (_id == null) {
// dest.writeByte((byte) (0x00));
// } else {
// dest.writeByte((byte) (0x01));
// dest.writeLong(_id);
// }
// dest.writeString(title);
// dest.writeString(url);
// dest.writeString(secret);
// dest.writeString(syncScheme);
// dest.writeValue(status);
// dest.writeString(keywords);
// dest.writeValue(keywordStatus);
// }
//
// @SuppressWarnings("unused")
// public static final Parcelable.Creator<WebServiceModel> CREATOR
// = new Parcelable.Creator<WebServiceModel>() {
// @Override
// public WebServiceModel createFromParcel(Parcel in) {
// return new WebServiceModel(in);
// }
//
// @Override
// public WebServiceModel[] newArray(int size) {
// return new WebServiceModel[size];
// }
// };
// }
| import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.addhen.android.raiburari.presentation.ui.activity.BaseActivity;
import org.addhen.smssync.R;
import org.addhen.smssync.presentation.model.WebServiceModel;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import me.dm7.barcodescanner.zxing.ZXingScannerView; | mUnbinder = ButterKnife.bind(this);
}
@Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this);
mScannerView.startCamera();
mScannerView.setFlash(false);
mScannerView.setAutoFocus(true);
}
@Override
public void onPause() {
super.onPause();
mScannerView.stopCamera();
}
@Override
public void handleResult(Result result) {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
if (!TextUtils.isEmpty(result.getText())) {
Gson gson = new Gson(); | // Path: smssync/src/main/java/org/addhen/smssync/presentation/model/WebServiceModel.java
// public class WebServiceModel extends Model implements Parcelable {
//
// private String title;
//
// private String url;
//
// private String secret;
//
// private String syncScheme;
//
// private Status status;
//
// private KeywordStatus keywordStatus;
//
// private String keywords;
//
// public WebServiceModel() {
// }
//
// public Long getId() {
// return _id;
// }
//
// public void setId(Long id) {
// _id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getSecret() {
// return secret;
// }
//
// public void setSecret(String secret) {
// this.secret = secret;
// }
//
// public SyncSchemeModel getSyncScheme() {
// return new SyncSchemeModel(syncScheme);
// }
//
// public void setSyncScheme(SyncSchemeModel syncScheme) {
// this.syncScheme = syncScheme.toJSONString();
// }
//
// public Status getStatus() {
// return status;
// }
//
// public void setStatus(Status status) {
// this.status = status;
// }
//
// public void setKeywords(String keywords) {
// this.keywords = keywords;
// }
//
// public String getKeywords() {
// return keywords;
// }
//
// public KeywordStatus getKeywordStatus() {
// return keywordStatus;
// }
//
// public void setKeywordStatus(
// KeywordStatus keywordStatus) {
// this.keywordStatus = keywordStatus;
// }
//
// @Override
// public String toString() {
// return "SyncUrl{" +
// "id=" + _id +
// "title='" + title + '\'' +
// ", url='" + url + '\'' +
// ", secret='" + secret + '\'' +
// ", syncScheme=" + syncScheme +
// ", keywords=" + keywords +
// ", keywordStatus=" + keywordStatus +
// ", status=" + status +
// '}';
// }
//
// public enum Status {
// ENABLED, DISABLED
// }
//
// public enum KeywordStatus {
// ENABLED, DISABLED
// }
//
// protected WebServiceModel(Parcel in) {
// _id = in.readByte() == 0x00 ? null : in.readLong();
// title = in.readString();
// url = in.readString();
// secret = in.readString();
// syncScheme = in.readString();
// status = (Status) in.readValue(Status.class.getClassLoader());
// keywords = in.readString();
// keywordStatus = (KeywordStatus) in.readValue(KeywordStatus.class.getClassLoader());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// if (_id == null) {
// dest.writeByte((byte) (0x00));
// } else {
// dest.writeByte((byte) (0x01));
// dest.writeLong(_id);
// }
// dest.writeString(title);
// dest.writeString(url);
// dest.writeString(secret);
// dest.writeString(syncScheme);
// dest.writeValue(status);
// dest.writeString(keywords);
// dest.writeValue(keywordStatus);
// }
//
// @SuppressWarnings("unused")
// public static final Parcelable.Creator<WebServiceModel> CREATOR
// = new Parcelable.Creator<WebServiceModel>() {
// @Override
// public WebServiceModel createFromParcel(Parcel in) {
// return new WebServiceModel(in);
// }
//
// @Override
// public WebServiceModel[] newArray(int size) {
// return new WebServiceModel[size];
// }
// };
// }
// Path: smssync/src/main/java/org/addhen/smssync/presentation/view/ui/activity/QrcodeReaderActivity.java
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.addhen.android.raiburari.presentation.ui.activity.BaseActivity;
import org.addhen.smssync.R;
import org.addhen.smssync.presentation.model.WebServiceModel;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
mUnbinder = ButterKnife.bind(this);
}
@Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this);
mScannerView.startCamera();
mScannerView.setFlash(false);
mScannerView.setAutoFocus(true);
}
@Override
public void onPause() {
super.onPause();
mScannerView.stopCamera();
}
@Override
public void handleResult(Result result) {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
if (!TextUtils.isEmpty(result.getText())) {
Gson gson = new Gson(); | WebServiceModel webServiceModel = null; |
ushahidi/SMSSync | smssync/src/main/java/org/addhen/smssync/data/cache/FileManager.java | // Path: smssync/src/main/java/org/addhen/smssync/data/util/Logger.java
// public class Logger {
//
// public static final boolean LOGGING_MODE = BuildConfig.DEBUG;
//
// public Logger() {
//
// }
//
// public static void log(String tag, String message) {
// if (LOGGING_MODE) {
// Timber.tag(tag).i(message);
// }
// }
//
// public static void log(String tag, String format, Object... args) {
// if (LOGGING_MODE) {
// Timber.tag(tag).i(String.format(format, args));
// }
// }
//
// public static void log(String tag, String message, Exception ex) {
// if (LOGGING_MODE) {
// Timber.tag(tag).e(ex, message);
// }
// }
// }
| import org.addhen.smssync.data.PrefsFactory;
import org.addhen.smssync.data.entity.Log;
import org.addhen.smssync.data.exception.LogNotFoundException;
import org.addhen.smssync.data.util.Logger;
import android.content.Context;
import android.os.Environment;
import android.text.format.DateFormat;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import rx.Observable; | private String mName;
PrefsFactory mPrefsFactory;
@Inject
public FileManager(Context context, PrefsFactory prefsFactory) {
this(LOG_NAME);
mPrefsFactory = prefsFactory;
}
public FileManager(String name) {
mName = name;
mDateFormat = "dd-MM kk:mm";
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
final File logFile = getFile(name);
if (logFile.isFile() && logFile.exists()) {
rotate(logFile);
}
try {
mWriter = new PrintWriter(new FileWriter(logFile, true));
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void rotate(final File logFile) {
if (logFile.length() > MAX_SIZE) { | // Path: smssync/src/main/java/org/addhen/smssync/data/util/Logger.java
// public class Logger {
//
// public static final boolean LOGGING_MODE = BuildConfig.DEBUG;
//
// public Logger() {
//
// }
//
// public static void log(String tag, String message) {
// if (LOGGING_MODE) {
// Timber.tag(tag).i(message);
// }
// }
//
// public static void log(String tag, String format, Object... args) {
// if (LOGGING_MODE) {
// Timber.tag(tag).i(String.format(format, args));
// }
// }
//
// public static void log(String tag, String message, Exception ex) {
// if (LOGGING_MODE) {
// Timber.tag(tag).e(ex, message);
// }
// }
// }
// Path: smssync/src/main/java/org/addhen/smssync/data/cache/FileManager.java
import org.addhen.smssync.data.PrefsFactory;
import org.addhen.smssync.data.entity.Log;
import org.addhen.smssync.data.exception.LogNotFoundException;
import org.addhen.smssync.data.util.Logger;
import android.content.Context;
import android.os.Environment;
import android.text.format.DateFormat;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import rx.Observable;
private String mName;
PrefsFactory mPrefsFactory;
@Inject
public FileManager(Context context, PrefsFactory prefsFactory) {
this(LOG_NAME);
mPrefsFactory = prefsFactory;
}
public FileManager(String name) {
mName = name;
mDateFormat = "dd-MM kk:mm";
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
final File logFile = getFile(name);
if (logFile.isFile() && logFile.exists()) {
rotate(logFile);
}
try {
mWriter = new PrintWriter(new FileWriter(logFile, true));
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void rotate(final File logFile) {
if (logFile.length() > MAX_SIZE) { | Logger.log(TAG, "rotating logfile " + logFile); |
ushahidi/SMSSync | smssync/src/main/java/org/addhen/smssync/presentation/presenter/webservice/UpdateWebServicePresenter.java | // Path: smssync/src/main/java/org/addhen/smssync/presentation/model/WebServiceModel.java
// public class WebServiceModel extends Model implements Parcelable {
//
// private String title;
//
// private String url;
//
// private String secret;
//
// private String syncScheme;
//
// private Status status;
//
// private KeywordStatus keywordStatus;
//
// private String keywords;
//
// public WebServiceModel() {
// }
//
// public Long getId() {
// return _id;
// }
//
// public void setId(Long id) {
// _id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getSecret() {
// return secret;
// }
//
// public void setSecret(String secret) {
// this.secret = secret;
// }
//
// public SyncSchemeModel getSyncScheme() {
// return new SyncSchemeModel(syncScheme);
// }
//
// public void setSyncScheme(SyncSchemeModel syncScheme) {
// this.syncScheme = syncScheme.toJSONString();
// }
//
// public Status getStatus() {
// return status;
// }
//
// public void setStatus(Status status) {
// this.status = status;
// }
//
// public void setKeywords(String keywords) {
// this.keywords = keywords;
// }
//
// public String getKeywords() {
// return keywords;
// }
//
// public KeywordStatus getKeywordStatus() {
// return keywordStatus;
// }
//
// public void setKeywordStatus(
// KeywordStatus keywordStatus) {
// this.keywordStatus = keywordStatus;
// }
//
// @Override
// public String toString() {
// return "SyncUrl{" +
// "id=" + _id +
// "title='" + title + '\'' +
// ", url='" + url + '\'' +
// ", secret='" + secret + '\'' +
// ", syncScheme=" + syncScheme +
// ", keywords=" + keywords +
// ", keywordStatus=" + keywordStatus +
// ", status=" + status +
// '}';
// }
//
// public enum Status {
// ENABLED, DISABLED
// }
//
// public enum KeywordStatus {
// ENABLED, DISABLED
// }
//
// protected WebServiceModel(Parcel in) {
// _id = in.readByte() == 0x00 ? null : in.readLong();
// title = in.readString();
// url = in.readString();
// secret = in.readString();
// syncScheme = in.readString();
// status = (Status) in.readValue(Status.class.getClassLoader());
// keywords = in.readString();
// keywordStatus = (KeywordStatus) in.readValue(KeywordStatus.class.getClassLoader());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// if (_id == null) {
// dest.writeByte((byte) (0x00));
// } else {
// dest.writeByte((byte) (0x01));
// dest.writeLong(_id);
// }
// dest.writeString(title);
// dest.writeString(url);
// dest.writeString(secret);
// dest.writeString(syncScheme);
// dest.writeValue(status);
// dest.writeString(keywords);
// dest.writeValue(keywordStatus);
// }
//
// @SuppressWarnings("unused")
// public static final Parcelable.Creator<WebServiceModel> CREATOR
// = new Parcelable.Creator<WebServiceModel>() {
// @Override
// public WebServiceModel createFromParcel(Parcel in) {
// return new WebServiceModel(in);
// }
//
// @Override
// public WebServiceModel[] newArray(int size) {
// return new WebServiceModel[size];
// }
// };
// }
| import android.support.annotation.NonNull;
import javax.inject.Inject;
import javax.inject.Named;
import com.addhen.android.raiburari.domain.exception.DefaultErrorHandler;
import com.addhen.android.raiburari.domain.exception.ErrorHandler;
import com.addhen.android.raiburari.domain.usecase.DefaultSubscriber;
import com.addhen.android.raiburari.presentation.presenter.Presenter;
import org.addhen.smssync.domain.usecase.webservice.TestWebServiceUsecase;
import org.addhen.smssync.domain.usecase.webservice.UpdateWebServiceUsecase;
import org.addhen.smssync.presentation.exception.ErrorMessageFactory;
import org.addhen.smssync.presentation.model.WebServiceModel;
import org.addhen.smssync.presentation.model.mapper.WebServiceModelDataMapper;
import org.addhen.smssync.presentation.view.webservice.TestWebServiceView;
import org.addhen.smssync.presentation.view.webservice.UpdateWebServiceView; |
@Override
public void resume() {
// Do nothing
}
@Override
public void pause() {
// Do nothing
}
@Override
public void destroy() {
mUpdateWebServiceUsecase.unsubscribe();
mTestWebServiceUsecase.unsubscribe();
}
public void setView(@NonNull UpdateWebServiceView addWebServiceView) {
mUpdateWebServiceView = addWebServiceView;
}
public void setTestWebServiceView(@NonNull TestWebServiceView testWebServiceView) {
mTestWebServiceView = testWebServiceView;
}
/**
* Updates {@link WebServiceModel}
*
* @param deploymentModel The deployment model to be updated
*/ | // Path: smssync/src/main/java/org/addhen/smssync/presentation/model/WebServiceModel.java
// public class WebServiceModel extends Model implements Parcelable {
//
// private String title;
//
// private String url;
//
// private String secret;
//
// private String syncScheme;
//
// private Status status;
//
// private KeywordStatus keywordStatus;
//
// private String keywords;
//
// public WebServiceModel() {
// }
//
// public Long getId() {
// return _id;
// }
//
// public void setId(Long id) {
// _id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getSecret() {
// return secret;
// }
//
// public void setSecret(String secret) {
// this.secret = secret;
// }
//
// public SyncSchemeModel getSyncScheme() {
// return new SyncSchemeModel(syncScheme);
// }
//
// public void setSyncScheme(SyncSchemeModel syncScheme) {
// this.syncScheme = syncScheme.toJSONString();
// }
//
// public Status getStatus() {
// return status;
// }
//
// public void setStatus(Status status) {
// this.status = status;
// }
//
// public void setKeywords(String keywords) {
// this.keywords = keywords;
// }
//
// public String getKeywords() {
// return keywords;
// }
//
// public KeywordStatus getKeywordStatus() {
// return keywordStatus;
// }
//
// public void setKeywordStatus(
// KeywordStatus keywordStatus) {
// this.keywordStatus = keywordStatus;
// }
//
// @Override
// public String toString() {
// return "SyncUrl{" +
// "id=" + _id +
// "title='" + title + '\'' +
// ", url='" + url + '\'' +
// ", secret='" + secret + '\'' +
// ", syncScheme=" + syncScheme +
// ", keywords=" + keywords +
// ", keywordStatus=" + keywordStatus +
// ", status=" + status +
// '}';
// }
//
// public enum Status {
// ENABLED, DISABLED
// }
//
// public enum KeywordStatus {
// ENABLED, DISABLED
// }
//
// protected WebServiceModel(Parcel in) {
// _id = in.readByte() == 0x00 ? null : in.readLong();
// title = in.readString();
// url = in.readString();
// secret = in.readString();
// syncScheme = in.readString();
// status = (Status) in.readValue(Status.class.getClassLoader());
// keywords = in.readString();
// keywordStatus = (KeywordStatus) in.readValue(KeywordStatus.class.getClassLoader());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// if (_id == null) {
// dest.writeByte((byte) (0x00));
// } else {
// dest.writeByte((byte) (0x01));
// dest.writeLong(_id);
// }
// dest.writeString(title);
// dest.writeString(url);
// dest.writeString(secret);
// dest.writeString(syncScheme);
// dest.writeValue(status);
// dest.writeString(keywords);
// dest.writeValue(keywordStatus);
// }
//
// @SuppressWarnings("unused")
// public static final Parcelable.Creator<WebServiceModel> CREATOR
// = new Parcelable.Creator<WebServiceModel>() {
// @Override
// public WebServiceModel createFromParcel(Parcel in) {
// return new WebServiceModel(in);
// }
//
// @Override
// public WebServiceModel[] newArray(int size) {
// return new WebServiceModel[size];
// }
// };
// }
// Path: smssync/src/main/java/org/addhen/smssync/presentation/presenter/webservice/UpdateWebServicePresenter.java
import android.support.annotation.NonNull;
import javax.inject.Inject;
import javax.inject.Named;
import com.addhen.android.raiburari.domain.exception.DefaultErrorHandler;
import com.addhen.android.raiburari.domain.exception.ErrorHandler;
import com.addhen.android.raiburari.domain.usecase.DefaultSubscriber;
import com.addhen.android.raiburari.presentation.presenter.Presenter;
import org.addhen.smssync.domain.usecase.webservice.TestWebServiceUsecase;
import org.addhen.smssync.domain.usecase.webservice.UpdateWebServiceUsecase;
import org.addhen.smssync.presentation.exception.ErrorMessageFactory;
import org.addhen.smssync.presentation.model.WebServiceModel;
import org.addhen.smssync.presentation.model.mapper.WebServiceModelDataMapper;
import org.addhen.smssync.presentation.view.webservice.TestWebServiceView;
import org.addhen.smssync.presentation.view.webservice.UpdateWebServiceView;
@Override
public void resume() {
// Do nothing
}
@Override
public void pause() {
// Do nothing
}
@Override
public void destroy() {
mUpdateWebServiceUsecase.unsubscribe();
mTestWebServiceUsecase.unsubscribe();
}
public void setView(@NonNull UpdateWebServiceView addWebServiceView) {
mUpdateWebServiceView = addWebServiceView;
}
public void setTestWebServiceView(@NonNull TestWebServiceView testWebServiceView) {
mTestWebServiceView = testWebServiceView;
}
/**
* Updates {@link WebServiceModel}
*
* @param deploymentModel The deployment model to be updated
*/ | public void updateWebService(WebServiceModel deploymentModel) { |
ushahidi/SMSSync | smssync/src/main/java/org/addhen/smssync/presentation/model/mapper/FilterModelDataMapper.java | // Path: smssync/src/main/java/org/addhen/smssync/domain/entity/FilterEntity.java
// public class FilterEntity extends Entity {
//
// private String phoneNumber;
//
// private Status status;
//
// public Long getId() {
// return _id;
// }
//
// public void setId(Long id) {
// _id = id;
// }
//
// public String getPhoneNumber() {
// return phoneNumber;
// }
//
// public void setPhoneNumber(String phoneNumber) {
// this.phoneNumber = phoneNumber;
// }
//
// public Status getStatus() {
// return status;
// }
//
// public void setStatus(Status status) {
// this.status = status;
// }
//
// /**
// * The status of the filtered phone number.
// */
// public enum Status {
// WHITELIST, BLACKLIST
// }
// }
| import com.addhen.android.raiburari.presentation.di.qualifier.ActivityScope;
import org.addhen.smssync.domain.entity.FilterEntity;
import org.addhen.smssync.presentation.model.FilterModel;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject; | /*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.presentation.model.mapper;
/**
* @author Henry Addo
*/
@ActivityScope
public class FilterModelDataMapper {
@Inject
public FilterModelDataMapper() {
// Do nothing
}
/**
* Maps {@link FilterModel} to {@link FilterEntity}
*
* @param filter The {@link FilterModel} to be
* mapped
* @return The {@link FilterModel} entity
*/ | // Path: smssync/src/main/java/org/addhen/smssync/domain/entity/FilterEntity.java
// public class FilterEntity extends Entity {
//
// private String phoneNumber;
//
// private Status status;
//
// public Long getId() {
// return _id;
// }
//
// public void setId(Long id) {
// _id = id;
// }
//
// public String getPhoneNumber() {
// return phoneNumber;
// }
//
// public void setPhoneNumber(String phoneNumber) {
// this.phoneNumber = phoneNumber;
// }
//
// public Status getStatus() {
// return status;
// }
//
// public void setStatus(Status status) {
// this.status = status;
// }
//
// /**
// * The status of the filtered phone number.
// */
// public enum Status {
// WHITELIST, BLACKLIST
// }
// }
// Path: smssync/src/main/java/org/addhen/smssync/presentation/model/mapper/FilterModelDataMapper.java
import com.addhen.android.raiburari.presentation.di.qualifier.ActivityScope;
import org.addhen.smssync.domain.entity.FilterEntity;
import org.addhen.smssync.presentation.model.FilterModel;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
/*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.presentation.model.mapper;
/**
* @author Henry Addo
*/
@ActivityScope
public class FilterModelDataMapper {
@Inject
public FilterModelDataMapper() {
// Do nothing
}
/**
* Maps {@link FilterModel} to {@link FilterEntity}
*
* @param filter The {@link FilterModel} to be
* mapped
* @return The {@link FilterModel} entity
*/ | public FilterEntity map(FilterModel filter) { |
ushahidi/SMSSync | smssync/src/main/java/org/addhen/smssync/data/net/BaseHttpClient.java | // Path: smssync/src/main/java/org/addhen/smssync/data/util/Logger.java
// public class Logger {
//
// public static final boolean LOGGING_MODE = BuildConfig.DEBUG;
//
// public Logger() {
//
// }
//
// public static void log(String tag, String message) {
// if (LOGGING_MODE) {
// Timber.tag(tag).i(message);
// }
// }
//
// public static void log(String tag, String format, Object... args) {
// if (LOGGING_MODE) {
// Timber.tag(tag).i(String.format(format, args));
// }
// }
//
// public static void log(String tag, String message, Exception ex) {
// if (LOGGING_MODE) {
// Timber.tag(tag).e(ex, message);
// }
// }
// }
| import org.addhen.smssync.BuildConfig;
import org.addhen.smssync.data.util.Logger;
import org.addhen.smssync.domain.entity.HttpNameValuePair;
import android.content.Context;
import android.content.pm.PackageManager;
import android.util.Base64;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import timber.log.Timber; | }
}
return combinedParams;
}
public Response getResponse() {
return mResponse;
}
public void setResponse(Response response) {
mResponse = response;
}
public enum HttpMethod {
POST("POST"),
GET("GET"),
PUT("PUT");
private final String mMethod;
HttpMethod(String method) {
mMethod = method;
}
public String value() {
return mMethod;
}
}
protected void log(String message) { | // Path: smssync/src/main/java/org/addhen/smssync/data/util/Logger.java
// public class Logger {
//
// public static final boolean LOGGING_MODE = BuildConfig.DEBUG;
//
// public Logger() {
//
// }
//
// public static void log(String tag, String message) {
// if (LOGGING_MODE) {
// Timber.tag(tag).i(message);
// }
// }
//
// public static void log(String tag, String format, Object... args) {
// if (LOGGING_MODE) {
// Timber.tag(tag).i(String.format(format, args));
// }
// }
//
// public static void log(String tag, String message, Exception ex) {
// if (LOGGING_MODE) {
// Timber.tag(tag).e(ex, message);
// }
// }
// }
// Path: smssync/src/main/java/org/addhen/smssync/data/net/BaseHttpClient.java
import org.addhen.smssync.BuildConfig;
import org.addhen.smssync.data.util.Logger;
import org.addhen.smssync.domain.entity.HttpNameValuePair;
import android.content.Context;
import android.content.pm.PackageManager;
import android.util.Base64;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import timber.log.Timber;
}
}
return combinedParams;
}
public Response getResponse() {
return mResponse;
}
public void setResponse(Response response) {
mResponse = response;
}
public enum HttpMethod {
POST("POST"),
GET("GET"),
PUT("PUT");
private final String mMethod;
HttpMethod(String method) {
mMethod = method;
}
public String value() {
return mMethod;
}
}
protected void log(String message) { | Logger.log(getClass().getName(), message); |
ushahidi/SMSSync | smssync/src/main/java/org/addhen/smssync/presentation/presenter/message/PublishAllMessagesPresenter.java | // Path: smssync/src/main/java/org/addhen/smssync/presentation/model/mapper/MessageModelDataMapper.java
// public class MessageModelDataMapper {
//
// @Inject
// public MessageModelDataMapper() {
// // Do nothing
// }
//
// public MessageEntity map(MessageModel message) {
// MessageEntity messageEntity = null;
// if (message != null) {
// messageEntity = new MessageEntity();
// messageEntity.setId(message.getId());
// messageEntity.setMessageBody(message.getMessageBody());
// messageEntity.setMessageDate(message.getMessageDate());
// messageEntity.setMessageFrom(message.getMessageFrom());
// messageEntity.setMessageUuid(message.getMessageUuid());
// messageEntity.setSentResultMessage(message.getSentResultMessage());
// messageEntity.setSentResultCode(message.getSentResultCode());
// messageEntity.setMessageType(map(message.getMessageType()));
// messageEntity.setStatus(map(message.getStatus()));
// messageEntity.setDeliveryResultCode(message.getDeliveryResultCode());
// messageEntity.setDeliveryResultMessage(message.getDeliveryResultMessage());
// }
// return messageEntity;
// }
//
// public MessageModel map(MessageEntity messageEntity) {
// MessageModel message = null;
// if (messageEntity != null) {
// message = new MessageModel();
// message.setId(messageEntity.getId());
// message.setMessageBody(messageEntity.getMessageBody());
// message.setMessageDate(messageEntity.getMessageDate());
// message.setMessageFrom(messageEntity.getMessageFrom());
// message.setMessageUuid(messageEntity.getMessageUuid());
// message.setSentResultMessage(messageEntity.getSentResultMessage());
// message.setSentResultCode(messageEntity.getSentResultCode());
// message.setMessageType(map(messageEntity.getMessageType()));
// message.setStatus(map(messageEntity.getStatus()));
// message.setDeliveryResultCode(messageEntity.getDeliveryResultCode());
// message.setDeliveryResultMessage(messageEntity.getDeliveryResultMessage());
// }
// return message;
// }
//
// public List<MessageModel> map(List<MessageEntity> messageList) {
// List<MessageModel> messageEntityList = new ArrayList<>();
// MessageModel messageEntity;
// for (MessageEntity message : messageList) {
// messageEntity = map(message);
// if (messageEntity != null) {
// messageEntityList.add(messageEntity);
// }
// }
// return messageEntityList;
// }
//
// public List<MessageEntity> unmap(List<MessageModel> messageModels) {
// List<MessageEntity> messageList = new ArrayList<>();
// MessageEntity messageEntity;
// for (MessageModel messageModel : messageModels) {
// messageEntity = map(messageModel);
// if (messageEntity != null) {
// messageList.add(messageEntity);
// }
// }
// return messageList;
// }
//
// public MessageEntity.Status map(MessageModel.Status status) {
// return status != null ? MessageEntity.Status.valueOf(status.name())
// : MessageEntity.Status.FAILED;
// }
//
// public MessageModel.Status map(MessageEntity.Status status) {
// return status != null ? MessageModel.Status.valueOf(status.name())
// : MessageModel.Status.FAILED;
// }
//
// public MessageEntity.Type map(MessageModel.Type type) {
// return type != null ? MessageEntity.Type.valueOf(type.name()) : MessageEntity.Type.PENDING;
// }
//
// public MessageModel.Type map(MessageEntity.Type type) {
// return type != null ? MessageModel.Type.valueOf(type.name()) : MessageModel.Type.PENDING;
// }
// }
//
// Path: smssync/src/main/java/org/addhen/smssync/presentation/view/message/PublishAllMessagesView.java
// public interface PublishAllMessagesView extends LoadDataView {
//
// void successfullyPublished(boolean status);
//
// void showEnableServiceMessage(String s);
// }
| import javax.inject.Inject;
import javax.inject.Named;
import com.addhen.android.raiburari.domain.exception.DefaultErrorHandler;
import com.addhen.android.raiburari.domain.exception.ErrorHandler;
import com.addhen.android.raiburari.domain.usecase.DefaultSubscriber;
import com.addhen.android.raiburari.domain.usecase.Usecase;
import com.addhen.android.raiburari.presentation.presenter.Presenter;
import org.addhen.smssync.R;
import org.addhen.smssync.data.PrefsFactory;
import org.addhen.smssync.presentation.exception.ErrorMessageFactory;
import org.addhen.smssync.presentation.model.mapper.MessageModelDataMapper;
import org.addhen.smssync.presentation.view.message.PublishAllMessagesView;
import android.support.annotation.NonNull; | /*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.presentation.presenter.message;
/**
* @author Ushahidi Team <[email protected]>
*/
public class PublishAllMessagesPresenter implements Presenter {
private final Usecase mPublishAllMessagesUsecase;
| // Path: smssync/src/main/java/org/addhen/smssync/presentation/model/mapper/MessageModelDataMapper.java
// public class MessageModelDataMapper {
//
// @Inject
// public MessageModelDataMapper() {
// // Do nothing
// }
//
// public MessageEntity map(MessageModel message) {
// MessageEntity messageEntity = null;
// if (message != null) {
// messageEntity = new MessageEntity();
// messageEntity.setId(message.getId());
// messageEntity.setMessageBody(message.getMessageBody());
// messageEntity.setMessageDate(message.getMessageDate());
// messageEntity.setMessageFrom(message.getMessageFrom());
// messageEntity.setMessageUuid(message.getMessageUuid());
// messageEntity.setSentResultMessage(message.getSentResultMessage());
// messageEntity.setSentResultCode(message.getSentResultCode());
// messageEntity.setMessageType(map(message.getMessageType()));
// messageEntity.setStatus(map(message.getStatus()));
// messageEntity.setDeliveryResultCode(message.getDeliveryResultCode());
// messageEntity.setDeliveryResultMessage(message.getDeliveryResultMessage());
// }
// return messageEntity;
// }
//
// public MessageModel map(MessageEntity messageEntity) {
// MessageModel message = null;
// if (messageEntity != null) {
// message = new MessageModel();
// message.setId(messageEntity.getId());
// message.setMessageBody(messageEntity.getMessageBody());
// message.setMessageDate(messageEntity.getMessageDate());
// message.setMessageFrom(messageEntity.getMessageFrom());
// message.setMessageUuid(messageEntity.getMessageUuid());
// message.setSentResultMessage(messageEntity.getSentResultMessage());
// message.setSentResultCode(messageEntity.getSentResultCode());
// message.setMessageType(map(messageEntity.getMessageType()));
// message.setStatus(map(messageEntity.getStatus()));
// message.setDeliveryResultCode(messageEntity.getDeliveryResultCode());
// message.setDeliveryResultMessage(messageEntity.getDeliveryResultMessage());
// }
// return message;
// }
//
// public List<MessageModel> map(List<MessageEntity> messageList) {
// List<MessageModel> messageEntityList = new ArrayList<>();
// MessageModel messageEntity;
// for (MessageEntity message : messageList) {
// messageEntity = map(message);
// if (messageEntity != null) {
// messageEntityList.add(messageEntity);
// }
// }
// return messageEntityList;
// }
//
// public List<MessageEntity> unmap(List<MessageModel> messageModels) {
// List<MessageEntity> messageList = new ArrayList<>();
// MessageEntity messageEntity;
// for (MessageModel messageModel : messageModels) {
// messageEntity = map(messageModel);
// if (messageEntity != null) {
// messageList.add(messageEntity);
// }
// }
// return messageList;
// }
//
// public MessageEntity.Status map(MessageModel.Status status) {
// return status != null ? MessageEntity.Status.valueOf(status.name())
// : MessageEntity.Status.FAILED;
// }
//
// public MessageModel.Status map(MessageEntity.Status status) {
// return status != null ? MessageModel.Status.valueOf(status.name())
// : MessageModel.Status.FAILED;
// }
//
// public MessageEntity.Type map(MessageModel.Type type) {
// return type != null ? MessageEntity.Type.valueOf(type.name()) : MessageEntity.Type.PENDING;
// }
//
// public MessageModel.Type map(MessageEntity.Type type) {
// return type != null ? MessageModel.Type.valueOf(type.name()) : MessageModel.Type.PENDING;
// }
// }
//
// Path: smssync/src/main/java/org/addhen/smssync/presentation/view/message/PublishAllMessagesView.java
// public interface PublishAllMessagesView extends LoadDataView {
//
// void successfullyPublished(boolean status);
//
// void showEnableServiceMessage(String s);
// }
// Path: smssync/src/main/java/org/addhen/smssync/presentation/presenter/message/PublishAllMessagesPresenter.java
import javax.inject.Inject;
import javax.inject.Named;
import com.addhen.android.raiburari.domain.exception.DefaultErrorHandler;
import com.addhen.android.raiburari.domain.exception.ErrorHandler;
import com.addhen.android.raiburari.domain.usecase.DefaultSubscriber;
import com.addhen.android.raiburari.domain.usecase.Usecase;
import com.addhen.android.raiburari.presentation.presenter.Presenter;
import org.addhen.smssync.R;
import org.addhen.smssync.data.PrefsFactory;
import org.addhen.smssync.presentation.exception.ErrorMessageFactory;
import org.addhen.smssync.presentation.model.mapper.MessageModelDataMapper;
import org.addhen.smssync.presentation.view.message.PublishAllMessagesView;
import android.support.annotation.NonNull;
/*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.presentation.presenter.message;
/**
* @author Ushahidi Team <[email protected]>
*/
public class PublishAllMessagesPresenter implements Presenter {
private final Usecase mPublishAllMessagesUsecase;
| private final MessageModelDataMapper mMessageModelDataMapper; |
ushahidi/SMSSync | smssync/src/main/java/org/addhen/smssync/presentation/presenter/message/PublishAllMessagesPresenter.java | // Path: smssync/src/main/java/org/addhen/smssync/presentation/model/mapper/MessageModelDataMapper.java
// public class MessageModelDataMapper {
//
// @Inject
// public MessageModelDataMapper() {
// // Do nothing
// }
//
// public MessageEntity map(MessageModel message) {
// MessageEntity messageEntity = null;
// if (message != null) {
// messageEntity = new MessageEntity();
// messageEntity.setId(message.getId());
// messageEntity.setMessageBody(message.getMessageBody());
// messageEntity.setMessageDate(message.getMessageDate());
// messageEntity.setMessageFrom(message.getMessageFrom());
// messageEntity.setMessageUuid(message.getMessageUuid());
// messageEntity.setSentResultMessage(message.getSentResultMessage());
// messageEntity.setSentResultCode(message.getSentResultCode());
// messageEntity.setMessageType(map(message.getMessageType()));
// messageEntity.setStatus(map(message.getStatus()));
// messageEntity.setDeliveryResultCode(message.getDeliveryResultCode());
// messageEntity.setDeliveryResultMessage(message.getDeliveryResultMessage());
// }
// return messageEntity;
// }
//
// public MessageModel map(MessageEntity messageEntity) {
// MessageModel message = null;
// if (messageEntity != null) {
// message = new MessageModel();
// message.setId(messageEntity.getId());
// message.setMessageBody(messageEntity.getMessageBody());
// message.setMessageDate(messageEntity.getMessageDate());
// message.setMessageFrom(messageEntity.getMessageFrom());
// message.setMessageUuid(messageEntity.getMessageUuid());
// message.setSentResultMessage(messageEntity.getSentResultMessage());
// message.setSentResultCode(messageEntity.getSentResultCode());
// message.setMessageType(map(messageEntity.getMessageType()));
// message.setStatus(map(messageEntity.getStatus()));
// message.setDeliveryResultCode(messageEntity.getDeliveryResultCode());
// message.setDeliveryResultMessage(messageEntity.getDeliveryResultMessage());
// }
// return message;
// }
//
// public List<MessageModel> map(List<MessageEntity> messageList) {
// List<MessageModel> messageEntityList = new ArrayList<>();
// MessageModel messageEntity;
// for (MessageEntity message : messageList) {
// messageEntity = map(message);
// if (messageEntity != null) {
// messageEntityList.add(messageEntity);
// }
// }
// return messageEntityList;
// }
//
// public List<MessageEntity> unmap(List<MessageModel> messageModels) {
// List<MessageEntity> messageList = new ArrayList<>();
// MessageEntity messageEntity;
// for (MessageModel messageModel : messageModels) {
// messageEntity = map(messageModel);
// if (messageEntity != null) {
// messageList.add(messageEntity);
// }
// }
// return messageList;
// }
//
// public MessageEntity.Status map(MessageModel.Status status) {
// return status != null ? MessageEntity.Status.valueOf(status.name())
// : MessageEntity.Status.FAILED;
// }
//
// public MessageModel.Status map(MessageEntity.Status status) {
// return status != null ? MessageModel.Status.valueOf(status.name())
// : MessageModel.Status.FAILED;
// }
//
// public MessageEntity.Type map(MessageModel.Type type) {
// return type != null ? MessageEntity.Type.valueOf(type.name()) : MessageEntity.Type.PENDING;
// }
//
// public MessageModel.Type map(MessageEntity.Type type) {
// return type != null ? MessageModel.Type.valueOf(type.name()) : MessageModel.Type.PENDING;
// }
// }
//
// Path: smssync/src/main/java/org/addhen/smssync/presentation/view/message/PublishAllMessagesView.java
// public interface PublishAllMessagesView extends LoadDataView {
//
// void successfullyPublished(boolean status);
//
// void showEnableServiceMessage(String s);
// }
| import javax.inject.Inject;
import javax.inject.Named;
import com.addhen.android.raiburari.domain.exception.DefaultErrorHandler;
import com.addhen.android.raiburari.domain.exception.ErrorHandler;
import com.addhen.android.raiburari.domain.usecase.DefaultSubscriber;
import com.addhen.android.raiburari.domain.usecase.Usecase;
import com.addhen.android.raiburari.presentation.presenter.Presenter;
import org.addhen.smssync.R;
import org.addhen.smssync.data.PrefsFactory;
import org.addhen.smssync.presentation.exception.ErrorMessageFactory;
import org.addhen.smssync.presentation.model.mapper.MessageModelDataMapper;
import org.addhen.smssync.presentation.view.message.PublishAllMessagesView;
import android.support.annotation.NonNull; | /*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.presentation.presenter.message;
/**
* @author Ushahidi Team <[email protected]>
*/
public class PublishAllMessagesPresenter implements Presenter {
private final Usecase mPublishAllMessagesUsecase;
private final MessageModelDataMapper mMessageModelDataMapper;
| // Path: smssync/src/main/java/org/addhen/smssync/presentation/model/mapper/MessageModelDataMapper.java
// public class MessageModelDataMapper {
//
// @Inject
// public MessageModelDataMapper() {
// // Do nothing
// }
//
// public MessageEntity map(MessageModel message) {
// MessageEntity messageEntity = null;
// if (message != null) {
// messageEntity = new MessageEntity();
// messageEntity.setId(message.getId());
// messageEntity.setMessageBody(message.getMessageBody());
// messageEntity.setMessageDate(message.getMessageDate());
// messageEntity.setMessageFrom(message.getMessageFrom());
// messageEntity.setMessageUuid(message.getMessageUuid());
// messageEntity.setSentResultMessage(message.getSentResultMessage());
// messageEntity.setSentResultCode(message.getSentResultCode());
// messageEntity.setMessageType(map(message.getMessageType()));
// messageEntity.setStatus(map(message.getStatus()));
// messageEntity.setDeliveryResultCode(message.getDeliveryResultCode());
// messageEntity.setDeliveryResultMessage(message.getDeliveryResultMessage());
// }
// return messageEntity;
// }
//
// public MessageModel map(MessageEntity messageEntity) {
// MessageModel message = null;
// if (messageEntity != null) {
// message = new MessageModel();
// message.setId(messageEntity.getId());
// message.setMessageBody(messageEntity.getMessageBody());
// message.setMessageDate(messageEntity.getMessageDate());
// message.setMessageFrom(messageEntity.getMessageFrom());
// message.setMessageUuid(messageEntity.getMessageUuid());
// message.setSentResultMessage(messageEntity.getSentResultMessage());
// message.setSentResultCode(messageEntity.getSentResultCode());
// message.setMessageType(map(messageEntity.getMessageType()));
// message.setStatus(map(messageEntity.getStatus()));
// message.setDeliveryResultCode(messageEntity.getDeliveryResultCode());
// message.setDeliveryResultMessage(messageEntity.getDeliveryResultMessage());
// }
// return message;
// }
//
// public List<MessageModel> map(List<MessageEntity> messageList) {
// List<MessageModel> messageEntityList = new ArrayList<>();
// MessageModel messageEntity;
// for (MessageEntity message : messageList) {
// messageEntity = map(message);
// if (messageEntity != null) {
// messageEntityList.add(messageEntity);
// }
// }
// return messageEntityList;
// }
//
// public List<MessageEntity> unmap(List<MessageModel> messageModels) {
// List<MessageEntity> messageList = new ArrayList<>();
// MessageEntity messageEntity;
// for (MessageModel messageModel : messageModels) {
// messageEntity = map(messageModel);
// if (messageEntity != null) {
// messageList.add(messageEntity);
// }
// }
// return messageList;
// }
//
// public MessageEntity.Status map(MessageModel.Status status) {
// return status != null ? MessageEntity.Status.valueOf(status.name())
// : MessageEntity.Status.FAILED;
// }
//
// public MessageModel.Status map(MessageEntity.Status status) {
// return status != null ? MessageModel.Status.valueOf(status.name())
// : MessageModel.Status.FAILED;
// }
//
// public MessageEntity.Type map(MessageModel.Type type) {
// return type != null ? MessageEntity.Type.valueOf(type.name()) : MessageEntity.Type.PENDING;
// }
//
// public MessageModel.Type map(MessageEntity.Type type) {
// return type != null ? MessageModel.Type.valueOf(type.name()) : MessageModel.Type.PENDING;
// }
// }
//
// Path: smssync/src/main/java/org/addhen/smssync/presentation/view/message/PublishAllMessagesView.java
// public interface PublishAllMessagesView extends LoadDataView {
//
// void successfullyPublished(boolean status);
//
// void showEnableServiceMessage(String s);
// }
// Path: smssync/src/main/java/org/addhen/smssync/presentation/presenter/message/PublishAllMessagesPresenter.java
import javax.inject.Inject;
import javax.inject.Named;
import com.addhen.android.raiburari.domain.exception.DefaultErrorHandler;
import com.addhen.android.raiburari.domain.exception.ErrorHandler;
import com.addhen.android.raiburari.domain.usecase.DefaultSubscriber;
import com.addhen.android.raiburari.domain.usecase.Usecase;
import com.addhen.android.raiburari.presentation.presenter.Presenter;
import org.addhen.smssync.R;
import org.addhen.smssync.data.PrefsFactory;
import org.addhen.smssync.presentation.exception.ErrorMessageFactory;
import org.addhen.smssync.presentation.model.mapper.MessageModelDataMapper;
import org.addhen.smssync.presentation.view.message.PublishAllMessagesView;
import android.support.annotation.NonNull;
/*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.presentation.presenter.message;
/**
* @author Ushahidi Team <[email protected]>
*/
public class PublishAllMessagesPresenter implements Presenter {
private final Usecase mPublishAllMessagesUsecase;
private final MessageModelDataMapper mMessageModelDataMapper;
| private PublishAllMessagesView mPublishMessagesView; |
ushahidi/SMSSync | smssync/src/main/java/org/addhen/smssync/domain/usecase/log/ListLogUsecase.java | // Path: smssync/src/main/java/org/addhen/smssync/domain/entity/LogEntity.java
// public class LogEntity extends Entity {
//
// private String message;
//
// public Long getId() {
// return _id;
// }
//
// public void setId(Long id) {
// _id = id;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public String toString() {
// return "LogEntity{"
// + "message='" + message + '\''
// + '}';
// }
// }
| import rx.Observable;
import com.addhen.android.raiburari.domain.executor.PostExecutionThread;
import com.addhen.android.raiburari.domain.executor.ThreadExecutor;
import com.addhen.android.raiburari.domain.usecase.Usecase;
import org.addhen.smssync.domain.entity.LogEntity;
import org.addhen.smssync.domain.repository.LogRepository;
import android.support.annotation.NonNull;
import java.util.List;
import javax.inject.Inject; | /*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.domain.usecase.log;
/**
* @author Ushahidi Team <[email protected]>
*/
public class ListLogUsecase extends Usecase {
private final LogRepository mLogRepository;
@Inject
public ListLogUsecase(@NonNull LogRepository logRepository,
ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread) {
super(threadExecutor, postExecutionThread);
mLogRepository = logRepository;
}
@Override | // Path: smssync/src/main/java/org/addhen/smssync/domain/entity/LogEntity.java
// public class LogEntity extends Entity {
//
// private String message;
//
// public Long getId() {
// return _id;
// }
//
// public void setId(Long id) {
// _id = id;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public String toString() {
// return "LogEntity{"
// + "message='" + message + '\''
// + '}';
// }
// }
// Path: smssync/src/main/java/org/addhen/smssync/domain/usecase/log/ListLogUsecase.java
import rx.Observable;
import com.addhen.android.raiburari.domain.executor.PostExecutionThread;
import com.addhen.android.raiburari.domain.executor.ThreadExecutor;
import com.addhen.android.raiburari.domain.usecase.Usecase;
import org.addhen.smssync.domain.entity.LogEntity;
import org.addhen.smssync.domain.repository.LogRepository;
import android.support.annotation.NonNull;
import java.util.List;
import javax.inject.Inject;
/*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.domain.usecase.log;
/**
* @author Ushahidi Team <[email protected]>
*/
public class ListLogUsecase extends Usecase {
private final LogRepository mLogRepository;
@Inject
public ListLogUsecase(@NonNull LogRepository logRepository,
ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread) {
super(threadExecutor, postExecutionThread);
mLogRepository = logRepository;
}
@Override | protected Observable<List<LogEntity>> buildUseCaseObservable() { |
ushahidi/SMSSync | smssync/src/main/java/org/addhen/smssync/data/entity/mapper/FilterDataMapper.java | // Path: smssync/src/main/java/org/addhen/smssync/domain/entity/FilterEntity.java
// public class FilterEntity extends Entity {
//
// private String phoneNumber;
//
// private Status status;
//
// public Long getId() {
// return _id;
// }
//
// public void setId(Long id) {
// _id = id;
// }
//
// public String getPhoneNumber() {
// return phoneNumber;
// }
//
// public void setPhoneNumber(String phoneNumber) {
// this.phoneNumber = phoneNumber;
// }
//
// public Status getStatus() {
// return status;
// }
//
// public void setStatus(Status status) {
// this.status = status;
// }
//
// /**
// * The status of the filtered phone number.
// */
// public enum Status {
// WHITELIST, BLACKLIST
// }
// }
| import org.addhen.smssync.data.entity.Filter;
import org.addhen.smssync.domain.entity.FilterEntity;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject; | /*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.data.entity.mapper;
/**
* @author Henry Addo
*/
public class FilterDataMapper {
@Inject
public FilterDataMapper() {
// Do nothing
}
/**
* Maps {@link org.addhen.smssync.data.entity.Filter} to {@link FilterEntity}
*
* @param filter The {@link Filter} to be
* mapped
* @return The {@link Filter} entity
*/ | // Path: smssync/src/main/java/org/addhen/smssync/domain/entity/FilterEntity.java
// public class FilterEntity extends Entity {
//
// private String phoneNumber;
//
// private Status status;
//
// public Long getId() {
// return _id;
// }
//
// public void setId(Long id) {
// _id = id;
// }
//
// public String getPhoneNumber() {
// return phoneNumber;
// }
//
// public void setPhoneNumber(String phoneNumber) {
// this.phoneNumber = phoneNumber;
// }
//
// public Status getStatus() {
// return status;
// }
//
// public void setStatus(Status status) {
// this.status = status;
// }
//
// /**
// * The status of the filtered phone number.
// */
// public enum Status {
// WHITELIST, BLACKLIST
// }
// }
// Path: smssync/src/main/java/org/addhen/smssync/data/entity/mapper/FilterDataMapper.java
import org.addhen.smssync.data.entity.Filter;
import org.addhen.smssync.domain.entity.FilterEntity;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
/*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.data.entity.mapper;
/**
* @author Henry Addo
*/
public class FilterDataMapper {
@Inject
public FilterDataMapper() {
// Do nothing
}
/**
* Maps {@link org.addhen.smssync.data.entity.Filter} to {@link FilterEntity}
*
* @param filter The {@link Filter} to be
* mapped
* @return The {@link Filter} entity
*/ | public FilterEntity map(Filter filter) { |
ushahidi/SMSSync | smssync/src/main/java/org/addhen/smssync/presentation/di/module/MessageModule.java | // Path: smssync/src/main/java/org/addhen/smssync/domain/usecase/message/PublishAllMessagesUsecase.java
// public class PublishAllMessagesUsecase extends Usecase {
//
// private final MessageRepository mMessageRepository;
//
// @Inject
// protected PublishAllMessagesUsecase(@NonNull MessageRepository messageRepository,
// @NonNull ThreadExecutor threadExecutor,
// @NonNull PostExecutionThread postExecutionThread) {
// super(threadExecutor, postExecutionThread);
// mMessageRepository = messageRepository;
// }
//
// @Override
// protected Observable buildUseCaseObservable() {
// return mMessageRepository.publishMessages();
// }
//
// }
//
// Path: smssync/src/main/java/org/addhen/smssync/domain/usecase/message/PublishMessageUsecase.java
// public class PublishMessageUsecase extends Usecase {
//
// private final MessageRepository mMessageRepository;
//
// public MessageEntity mMessageEntity;
//
// @Inject
// protected PublishMessageUsecase(@NonNull MessageRepository messageRepository,
// @NonNull ThreadExecutor threadExecutor,
// @NonNull PostExecutionThread postExecutionThread) {
// super(threadExecutor, postExecutionThread);
// mMessageRepository = messageRepository;
// }
//
// public void setMessageEntity(MessageEntity messageEntity) {
// mMessageEntity = messageEntity;
// }
//
// @Override
// protected Observable buildUseCaseObservable() {
// if (mMessageEntity == null) {
// throw new RuntimeException(
// "MessageEntity is null. You must call setMessageEntity(...)");
// }
// return mMessageRepository.publishMessage(mMessageEntity);
// }
//
// }
| import dagger.Module;
import dagger.Provides;
import com.addhen.android.raiburari.domain.usecase.Usecase;
import com.addhen.android.raiburari.presentation.di.qualifier.ActivityScope;
import org.addhen.smssync.domain.usecase.message.DeleteMessageUsecase;
import org.addhen.smssync.domain.usecase.message.ImportMessagesUsecase;
import org.addhen.smssync.domain.usecase.message.ListMessageUsecase;
import org.addhen.smssync.domain.usecase.message.ListPublishedMessageUsecase;
import org.addhen.smssync.domain.usecase.message.PublishAllMessagesUsecase;
import org.addhen.smssync.domain.usecase.message.PublishMessageUsecase;
import org.addhen.smssync.domain.usecase.message.UpdateMessageUsecase;
import javax.inject.Named; | /*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.presentation.di.module;
/**
* @author Ushahidi Team <[email protected]>
*/
@Module
public class MessageModule {
@Provides
@ActivityScope
@Named("messageList")
Usecase provideListMessageUseCase(ListMessageUsecase listMessageUsecase) {
return listMessageUsecase;
}
@Provides
@ActivityScope
@Named("messagePublishList")
ListPublishedMessageUsecase provideListPublishedMessageUsecase(
ListPublishedMessageUsecase listPublishedMessageUsecase) {
return listPublishedMessageUsecase;
}
@Provides
@ActivityScope
@Named("messagePublish") | // Path: smssync/src/main/java/org/addhen/smssync/domain/usecase/message/PublishAllMessagesUsecase.java
// public class PublishAllMessagesUsecase extends Usecase {
//
// private final MessageRepository mMessageRepository;
//
// @Inject
// protected PublishAllMessagesUsecase(@NonNull MessageRepository messageRepository,
// @NonNull ThreadExecutor threadExecutor,
// @NonNull PostExecutionThread postExecutionThread) {
// super(threadExecutor, postExecutionThread);
// mMessageRepository = messageRepository;
// }
//
// @Override
// protected Observable buildUseCaseObservable() {
// return mMessageRepository.publishMessages();
// }
//
// }
//
// Path: smssync/src/main/java/org/addhen/smssync/domain/usecase/message/PublishMessageUsecase.java
// public class PublishMessageUsecase extends Usecase {
//
// private final MessageRepository mMessageRepository;
//
// public MessageEntity mMessageEntity;
//
// @Inject
// protected PublishMessageUsecase(@NonNull MessageRepository messageRepository,
// @NonNull ThreadExecutor threadExecutor,
// @NonNull PostExecutionThread postExecutionThread) {
// super(threadExecutor, postExecutionThread);
// mMessageRepository = messageRepository;
// }
//
// public void setMessageEntity(MessageEntity messageEntity) {
// mMessageEntity = messageEntity;
// }
//
// @Override
// protected Observable buildUseCaseObservable() {
// if (mMessageEntity == null) {
// throw new RuntimeException(
// "MessageEntity is null. You must call setMessageEntity(...)");
// }
// return mMessageRepository.publishMessage(mMessageEntity);
// }
//
// }
// Path: smssync/src/main/java/org/addhen/smssync/presentation/di/module/MessageModule.java
import dagger.Module;
import dagger.Provides;
import com.addhen.android.raiburari.domain.usecase.Usecase;
import com.addhen.android.raiburari.presentation.di.qualifier.ActivityScope;
import org.addhen.smssync.domain.usecase.message.DeleteMessageUsecase;
import org.addhen.smssync.domain.usecase.message.ImportMessagesUsecase;
import org.addhen.smssync.domain.usecase.message.ListMessageUsecase;
import org.addhen.smssync.domain.usecase.message.ListPublishedMessageUsecase;
import org.addhen.smssync.domain.usecase.message.PublishAllMessagesUsecase;
import org.addhen.smssync.domain.usecase.message.PublishMessageUsecase;
import org.addhen.smssync.domain.usecase.message.UpdateMessageUsecase;
import javax.inject.Named;
/*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.presentation.di.module;
/**
* @author Ushahidi Team <[email protected]>
*/
@Module
public class MessageModule {
@Provides
@ActivityScope
@Named("messageList")
Usecase provideListMessageUseCase(ListMessageUsecase listMessageUsecase) {
return listMessageUsecase;
}
@Provides
@ActivityScope
@Named("messagePublishList")
ListPublishedMessageUsecase provideListPublishedMessageUsecase(
ListPublishedMessageUsecase listPublishedMessageUsecase) {
return listPublishedMessageUsecase;
}
@Provides
@ActivityScope
@Named("messagePublish") | PublishMessageUsecase providePublishedMessageUsecase( |
ushahidi/SMSSync | smssync/src/main/java/org/addhen/smssync/presentation/di/module/MessageModule.java | // Path: smssync/src/main/java/org/addhen/smssync/domain/usecase/message/PublishAllMessagesUsecase.java
// public class PublishAllMessagesUsecase extends Usecase {
//
// private final MessageRepository mMessageRepository;
//
// @Inject
// protected PublishAllMessagesUsecase(@NonNull MessageRepository messageRepository,
// @NonNull ThreadExecutor threadExecutor,
// @NonNull PostExecutionThread postExecutionThread) {
// super(threadExecutor, postExecutionThread);
// mMessageRepository = messageRepository;
// }
//
// @Override
// protected Observable buildUseCaseObservable() {
// return mMessageRepository.publishMessages();
// }
//
// }
//
// Path: smssync/src/main/java/org/addhen/smssync/domain/usecase/message/PublishMessageUsecase.java
// public class PublishMessageUsecase extends Usecase {
//
// private final MessageRepository mMessageRepository;
//
// public MessageEntity mMessageEntity;
//
// @Inject
// protected PublishMessageUsecase(@NonNull MessageRepository messageRepository,
// @NonNull ThreadExecutor threadExecutor,
// @NonNull PostExecutionThread postExecutionThread) {
// super(threadExecutor, postExecutionThread);
// mMessageRepository = messageRepository;
// }
//
// public void setMessageEntity(MessageEntity messageEntity) {
// mMessageEntity = messageEntity;
// }
//
// @Override
// protected Observable buildUseCaseObservable() {
// if (mMessageEntity == null) {
// throw new RuntimeException(
// "MessageEntity is null. You must call setMessageEntity(...)");
// }
// return mMessageRepository.publishMessage(mMessageEntity);
// }
//
// }
| import dagger.Module;
import dagger.Provides;
import com.addhen.android.raiburari.domain.usecase.Usecase;
import com.addhen.android.raiburari.presentation.di.qualifier.ActivityScope;
import org.addhen.smssync.domain.usecase.message.DeleteMessageUsecase;
import org.addhen.smssync.domain.usecase.message.ImportMessagesUsecase;
import org.addhen.smssync.domain.usecase.message.ListMessageUsecase;
import org.addhen.smssync.domain.usecase.message.ListPublishedMessageUsecase;
import org.addhen.smssync.domain.usecase.message.PublishAllMessagesUsecase;
import org.addhen.smssync.domain.usecase.message.PublishMessageUsecase;
import org.addhen.smssync.domain.usecase.message.UpdateMessageUsecase;
import javax.inject.Named; | /*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.presentation.di.module;
/**
* @author Ushahidi Team <[email protected]>
*/
@Module
public class MessageModule {
@Provides
@ActivityScope
@Named("messageList")
Usecase provideListMessageUseCase(ListMessageUsecase listMessageUsecase) {
return listMessageUsecase;
}
@Provides
@ActivityScope
@Named("messagePublishList")
ListPublishedMessageUsecase provideListPublishedMessageUsecase(
ListPublishedMessageUsecase listPublishedMessageUsecase) {
return listPublishedMessageUsecase;
}
@Provides
@ActivityScope
@Named("messagePublish")
PublishMessageUsecase providePublishedMessageUsecase(
PublishMessageUsecase publishMessageUsecase) {
return publishMessageUsecase;
}
@Provides
@ActivityScope
@Named("publishAllMessages")
Usecase providePublishedMessagesUsecase( | // Path: smssync/src/main/java/org/addhen/smssync/domain/usecase/message/PublishAllMessagesUsecase.java
// public class PublishAllMessagesUsecase extends Usecase {
//
// private final MessageRepository mMessageRepository;
//
// @Inject
// protected PublishAllMessagesUsecase(@NonNull MessageRepository messageRepository,
// @NonNull ThreadExecutor threadExecutor,
// @NonNull PostExecutionThread postExecutionThread) {
// super(threadExecutor, postExecutionThread);
// mMessageRepository = messageRepository;
// }
//
// @Override
// protected Observable buildUseCaseObservable() {
// return mMessageRepository.publishMessages();
// }
//
// }
//
// Path: smssync/src/main/java/org/addhen/smssync/domain/usecase/message/PublishMessageUsecase.java
// public class PublishMessageUsecase extends Usecase {
//
// private final MessageRepository mMessageRepository;
//
// public MessageEntity mMessageEntity;
//
// @Inject
// protected PublishMessageUsecase(@NonNull MessageRepository messageRepository,
// @NonNull ThreadExecutor threadExecutor,
// @NonNull PostExecutionThread postExecutionThread) {
// super(threadExecutor, postExecutionThread);
// mMessageRepository = messageRepository;
// }
//
// public void setMessageEntity(MessageEntity messageEntity) {
// mMessageEntity = messageEntity;
// }
//
// @Override
// protected Observable buildUseCaseObservable() {
// if (mMessageEntity == null) {
// throw new RuntimeException(
// "MessageEntity is null. You must call setMessageEntity(...)");
// }
// return mMessageRepository.publishMessage(mMessageEntity);
// }
//
// }
// Path: smssync/src/main/java/org/addhen/smssync/presentation/di/module/MessageModule.java
import dagger.Module;
import dagger.Provides;
import com.addhen.android.raiburari.domain.usecase.Usecase;
import com.addhen.android.raiburari.presentation.di.qualifier.ActivityScope;
import org.addhen.smssync.domain.usecase.message.DeleteMessageUsecase;
import org.addhen.smssync.domain.usecase.message.ImportMessagesUsecase;
import org.addhen.smssync.domain.usecase.message.ListMessageUsecase;
import org.addhen.smssync.domain.usecase.message.ListPublishedMessageUsecase;
import org.addhen.smssync.domain.usecase.message.PublishAllMessagesUsecase;
import org.addhen.smssync.domain.usecase.message.PublishMessageUsecase;
import org.addhen.smssync.domain.usecase.message.UpdateMessageUsecase;
import javax.inject.Named;
/*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.presentation.di.module;
/**
* @author Ushahidi Team <[email protected]>
*/
@Module
public class MessageModule {
@Provides
@ActivityScope
@Named("messageList")
Usecase provideListMessageUseCase(ListMessageUsecase listMessageUsecase) {
return listMessageUsecase;
}
@Provides
@ActivityScope
@Named("messagePublishList")
ListPublishedMessageUsecase provideListPublishedMessageUsecase(
ListPublishedMessageUsecase listPublishedMessageUsecase) {
return listPublishedMessageUsecase;
}
@Provides
@ActivityScope
@Named("messagePublish")
PublishMessageUsecase providePublishedMessageUsecase(
PublishMessageUsecase publishMessageUsecase) {
return publishMessageUsecase;
}
@Provides
@ActivityScope
@Named("publishAllMessages")
Usecase providePublishedMessagesUsecase( | PublishAllMessagesUsecase publishMessagesUsecase) { |
ushahidi/SMSSync | smssync/src/main/java/org/addhen/smssync/data/database/WebServiceDatabaseHelper.java | // Path: smssync/src/main/java/org/addhen/smssync/data/exception/WebServiceNotFoundException.java
// public class WebServiceNotFoundException extends Exception {
//
// /**
// * Default exception
// */
// public WebServiceNotFoundException() {
// super();
// }
//
// /**
// * Initialize the exception with a custom message
// *
// * @param message The message be shown when the exception is thrown
// */
// public WebServiceNotFoundException(final String message) {
// super(message);
// }
//
// /**
// * Initialize the exception with a custom message and the cause of the exception
// *
// * @param message The message to be shown when the exception is thrown
// * @param cause The cause of the exception
// */
// public WebServiceNotFoundException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * Initialize the exception with a the cause of the exception
// *
// * @param cause The cause of the exception
// */
// public WebServiceNotFoundException(final Throwable cause) {
// super(cause);
// }
// }
| import static nl.qbusict.cupboard.CupboardFactory.cupboard;
import org.addhen.smssync.data.entity.SyncUrl;
import org.addhen.smssync.data.exception.WebServiceNotFoundException;
import android.content.Context;
import android.support.annotation.NonNull;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import rx.Observable; | /*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.data.database;
/**
* @author Ushahidi Team <[email protected]>
*/
@Singleton
public class WebServiceDatabaseHelper extends BaseDatabaseHelper {
/**
* Default constructor
*
* @param context The calling context. Cannot be a null value
*/
@Inject
public WebServiceDatabaseHelper(@NonNull Context context) {
super(context);
}
/**
* Gets webServices by it's status
*
* @param status The status to use to query for the webService
* @return An Observable that emits a {@link SyncUrl}
*/
public Observable<List<SyncUrl>> getByStatus(final SyncUrl.Status status) {
return Observable.create((subscriber) -> {
final List<SyncUrl> syncUrlEntity = get(status);
if (syncUrlEntity != null) {
subscriber.onNext(syncUrlEntity);
subscriber.onCompleted();
} else { | // Path: smssync/src/main/java/org/addhen/smssync/data/exception/WebServiceNotFoundException.java
// public class WebServiceNotFoundException extends Exception {
//
// /**
// * Default exception
// */
// public WebServiceNotFoundException() {
// super();
// }
//
// /**
// * Initialize the exception with a custom message
// *
// * @param message The message be shown when the exception is thrown
// */
// public WebServiceNotFoundException(final String message) {
// super(message);
// }
//
// /**
// * Initialize the exception with a custom message and the cause of the exception
// *
// * @param message The message to be shown when the exception is thrown
// * @param cause The cause of the exception
// */
// public WebServiceNotFoundException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// /**
// * Initialize the exception with a the cause of the exception
// *
// * @param cause The cause of the exception
// */
// public WebServiceNotFoundException(final Throwable cause) {
// super(cause);
// }
// }
// Path: smssync/src/main/java/org/addhen/smssync/data/database/WebServiceDatabaseHelper.java
import static nl.qbusict.cupboard.CupboardFactory.cupboard;
import org.addhen.smssync.data.entity.SyncUrl;
import org.addhen.smssync.data.exception.WebServiceNotFoundException;
import android.content.Context;
import android.support.annotation.NonNull;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import rx.Observable;
/*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.data.database;
/**
* @author Ushahidi Team <[email protected]>
*/
@Singleton
public class WebServiceDatabaseHelper extends BaseDatabaseHelper {
/**
* Default constructor
*
* @param context The calling context. Cannot be a null value
*/
@Inject
public WebServiceDatabaseHelper(@NonNull Context context) {
super(context);
}
/**
* Gets webServices by it's status
*
* @param status The status to use to query for the webService
* @return An Observable that emits a {@link SyncUrl}
*/
public Observable<List<SyncUrl>> getByStatus(final SyncUrl.Status status) {
return Observable.create((subscriber) -> {
final List<SyncUrl> syncUrlEntity = get(status);
if (syncUrlEntity != null) {
subscriber.onNext(syncUrlEntity);
subscriber.onCompleted();
} else { | subscriber.onError(new WebServiceNotFoundException()); |
ushahidi/SMSSync | smssync/src/main/java/org/addhen/smssync/presentation/di/module/ServiceModule.java | // Path: smssync/src/main/java/org/addhen/smssync/domain/usecase/message/PublishMessageUsecase.java
// public class PublishMessageUsecase extends Usecase {
//
// private final MessageRepository mMessageRepository;
//
// public MessageEntity mMessageEntity;
//
// @Inject
// protected PublishMessageUsecase(@NonNull MessageRepository messageRepository,
// @NonNull ThreadExecutor threadExecutor,
// @NonNull PostExecutionThread postExecutionThread) {
// super(threadExecutor, postExecutionThread);
// mMessageRepository = messageRepository;
// }
//
// public void setMessageEntity(MessageEntity messageEntity) {
// mMessageEntity = messageEntity;
// }
//
// @Override
// protected Observable buildUseCaseObservable() {
// if (mMessageEntity == null) {
// throw new RuntimeException(
// "MessageEntity is null. You must call setMessageEntity(...)");
// }
// return mMessageRepository.publishMessage(mMessageEntity);
// }
//
// }
| import org.addhen.smssync.domain.usecase.message.DeleteMessageUsecase;
import org.addhen.smssync.domain.usecase.message.PublishMessageUsecase;
import org.addhen.smssync.domain.usecase.message.UpdateMessageUsecase;
import org.addhen.smssync.presentation.di.qualifier.ServiceScope;
import android.app.Service;
import javax.inject.Named;
import dagger.Module;
import dagger.Provides; | /*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.presentation.di.module;
/**
* @author Ushahidi Team <[email protected]>
*/
@Module
public class ServiceModule {
private final Service mService;
public ServiceModule(Service service) {
mService = service;
}
/**
* Expose the activity to dependents in the graph.
*/
@Provides
@ServiceScope
Service service() {
return mService;
}
@Provides
@ServiceScope
@Named("messageUpdate")
UpdateMessageUsecase provideUpdateMessageUsecase(UpdateMessageUsecase updateMessageUsecase) {
return updateMessageUsecase;
}
@Provides
@ServiceScope
@Named("messageDelete")
DeleteMessageUsecase providesDeleteMessageUsecase(DeleteMessageUsecase deleteMessageUsecase) {
return deleteMessageUsecase;
}
@Provides
@ServiceScope
@Named("messagePublish") | // Path: smssync/src/main/java/org/addhen/smssync/domain/usecase/message/PublishMessageUsecase.java
// public class PublishMessageUsecase extends Usecase {
//
// private final MessageRepository mMessageRepository;
//
// public MessageEntity mMessageEntity;
//
// @Inject
// protected PublishMessageUsecase(@NonNull MessageRepository messageRepository,
// @NonNull ThreadExecutor threadExecutor,
// @NonNull PostExecutionThread postExecutionThread) {
// super(threadExecutor, postExecutionThread);
// mMessageRepository = messageRepository;
// }
//
// public void setMessageEntity(MessageEntity messageEntity) {
// mMessageEntity = messageEntity;
// }
//
// @Override
// protected Observable buildUseCaseObservable() {
// if (mMessageEntity == null) {
// throw new RuntimeException(
// "MessageEntity is null. You must call setMessageEntity(...)");
// }
// return mMessageRepository.publishMessage(mMessageEntity);
// }
//
// }
// Path: smssync/src/main/java/org/addhen/smssync/presentation/di/module/ServiceModule.java
import org.addhen.smssync.domain.usecase.message.DeleteMessageUsecase;
import org.addhen.smssync.domain.usecase.message.PublishMessageUsecase;
import org.addhen.smssync.domain.usecase.message.UpdateMessageUsecase;
import org.addhen.smssync.presentation.di.qualifier.ServiceScope;
import android.app.Service;
import javax.inject.Named;
import dagger.Module;
import dagger.Provides;
/*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.presentation.di.module;
/**
* @author Ushahidi Team <[email protected]>
*/
@Module
public class ServiceModule {
private final Service mService;
public ServiceModule(Service service) {
mService = service;
}
/**
* Expose the activity to dependents in the graph.
*/
@Provides
@ServiceScope
Service service() {
return mService;
}
@Provides
@ServiceScope
@Named("messageUpdate")
UpdateMessageUsecase provideUpdateMessageUsecase(UpdateMessageUsecase updateMessageUsecase) {
return updateMessageUsecase;
}
@Provides
@ServiceScope
@Named("messageDelete")
DeleteMessageUsecase providesDeleteMessageUsecase(DeleteMessageUsecase deleteMessageUsecase) {
return deleteMessageUsecase;
}
@Provides
@ServiceScope
@Named("messagePublish") | PublishMessageUsecase providePublishedMessageUsecase( |
ushahidi/SMSSync | smssync/src/main/java/org/addhen/smssync/presentation/view/ui/fragment/TwitterProfileFragment.java | // Path: smssync/src/main/java/org/addhen/smssync/presentation/App.java
// public class App extends BaseApplication {
//
// private static AppComponent mAppComponent;
//
// private static TwitterClient mTwitter;
//
// private static App mApp;
//
//
// public static synchronized TwitterClient getTwitterInstance() {
// if (mTwitter == null) {
// mTwitter = new TwitterBuilder(mApp,
// BuildConfig.TWITTER_CONSUMER_KEY,
// BuildConfig.TWITTER_CONSUMER_SECRET)
// .build();
// }
// return mTwitter;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// initializeInjector();
// mApp = this;
// Timber.plant(new FirebaseCrashTree());
// }
//
// private void initializeInjector() {
// mAppComponent = AppComponent.Initializer.init(this);
// }
//
// public static AppComponent getAppComponent() {
// return mAppComponent;
// }
//
// /**
// * Return the application tracker
// */
// public static AppTracker getInstance() {
// return TrackerResolver.getInstance();
// }
// }
| import com.addhen.android.raiburari.presentation.ui.fragment.BaseFragment;
import org.addhen.smssync.R;
import org.addhen.smssync.presentation.App;
import android.os.Bundle;
import android.support.v7.widget.AppCompatTextView;
import android.view.View;
import butterknife.BindView;
import butterknife.OnClick; | /*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.presentation.view.ui.fragment;
/**
* Fragment for showing logged in user
*
* @author Ushahidi Team <[email protected]>
*/
public class TwitterProfileFragment extends BaseFragment {
@BindView(R.id.twitter_logged_user)
AppCompatTextView mLoggedInUser;
public TwitterProfileFragment() {
super(R.layout.fragment_twitter_profile, 0);
}
public static TwitterProfileFragment newInstance() {
return new TwitterProfileFragment();
}
public void onViewCreated(View view, Bundle savedInstance) {
super.onViewCreated(view, savedInstance); | // Path: smssync/src/main/java/org/addhen/smssync/presentation/App.java
// public class App extends BaseApplication {
//
// private static AppComponent mAppComponent;
//
// private static TwitterClient mTwitter;
//
// private static App mApp;
//
//
// public static synchronized TwitterClient getTwitterInstance() {
// if (mTwitter == null) {
// mTwitter = new TwitterBuilder(mApp,
// BuildConfig.TWITTER_CONSUMER_KEY,
// BuildConfig.TWITTER_CONSUMER_SECRET)
// .build();
// }
// return mTwitter;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// initializeInjector();
// mApp = this;
// Timber.plant(new FirebaseCrashTree());
// }
//
// private void initializeInjector() {
// mAppComponent = AppComponent.Initializer.init(this);
// }
//
// public static AppComponent getAppComponent() {
// return mAppComponent;
// }
//
// /**
// * Return the application tracker
// */
// public static AppTracker getInstance() {
// return TrackerResolver.getInstance();
// }
// }
// Path: smssync/src/main/java/org/addhen/smssync/presentation/view/ui/fragment/TwitterProfileFragment.java
import com.addhen.android.raiburari.presentation.ui.fragment.BaseFragment;
import org.addhen.smssync.R;
import org.addhen.smssync.presentation.App;
import android.os.Bundle;
import android.support.v7.widget.AppCompatTextView;
import android.view.View;
import butterknife.BindView;
import butterknife.OnClick;
/*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.presentation.view.ui.fragment;
/**
* Fragment for showing logged in user
*
* @author Ushahidi Team <[email protected]>
*/
public class TwitterProfileFragment extends BaseFragment {
@BindView(R.id.twitter_logged_user)
AppCompatTextView mLoggedInUser;
public TwitterProfileFragment() {
super(R.layout.fragment_twitter_profile, 0);
}
public static TwitterProfileFragment newInstance() {
return new TwitterProfileFragment();
}
public void onViewCreated(View view, Bundle savedInstance) {
super.onViewCreated(view, savedInstance); | final String username = "@" + App.getTwitterInstance().getSessionManager() |
ushahidi/SMSSync | smssync/src/test/java/org/addhen/smssync/domain/usecase/filter/DeleteFilterUsecaseTest.java | // Path: smssync/src/test/java/org/addhen/smssync/domain/entity/DomainEntityFixture.java
// public final class DomainEntityFixture {
//
// public static final Long ID = 2l;
//
// private static Date mDate = new Date();
//
// public static FilterEntity getFilterEntity() {
// FilterEntity filterEntity = new FilterEntity();
// filterEntity._id = ID;
// filterEntity.setPhoneNumber("000000000");
// filterEntity.setStatus(FilterEntity.Status.WHITELIST);
// return filterEntity;
// }
//
// public static HttpNameValuePair getHttpNameValuePair() {
// return new HttpNameValuePair("key", "value");
// }
//
// public static LogEntity getLogEntity() {
// LogEntity logEntity = new LogEntity();
// logEntity._id = ID;
// logEntity.setMessage("Log message");
// return logEntity;
// }
//
// public static MessageEntity getMessageEntity() {
// MessageEntity messageEntity = new MessageEntity();
// messageEntity.setId(ID);
// messageEntity.setDeliveredMessageDate(mDate);
// messageEntity.setDeliveryResultCode(1);
// messageEntity.setDeliveryResultMessage("delivered");
// messageEntity.setMessageBody("Message body");
// messageEntity.setMessageDate(mDate);
// messageEntity.setMessageType(MessageEntity.Type.PENDING);
// messageEntity.setMessageFrom("000000000");
// messageEntity.setMessageUuid("uuid0123456");
// messageEntity.setSentResultCode(1);
// messageEntity.setStatus(MessageEntity.Status.SENT);
// messageEntity.setRetries(3);
// return messageEntity;
// }
//
// public static WebServiceEntity getWebServiceEntity() {
// WebServiceEntity webServiceEntity = new WebServiceEntity();
// webServiceEntity.setId(ID);
// webServiceEntity.setSecret("secret");
// webServiceEntity.setKeywords("keywords");
// webServiceEntity.setTitle("title");
// webServiceEntity.setSyncScheme(new SyncSchemeEntity());
// webServiceEntity.setUrl("url");
// return webServiceEntity;
// }
// }
//
// Path: smssync/src/main/java/org/addhen/smssync/domain/entity/FilterEntity.java
// public class FilterEntity extends Entity {
//
// private String phoneNumber;
//
// private Status status;
//
// public Long getId() {
// return _id;
// }
//
// public void setId(Long id) {
// _id = id;
// }
//
// public String getPhoneNumber() {
// return phoneNumber;
// }
//
// public void setPhoneNumber(String phoneNumber) {
// this.phoneNumber = phoneNumber;
// }
//
// public Status getStatus() {
// return status;
// }
//
// public void setStatus(Status status) {
// this.status = status;
// }
//
// /**
// * The status of the filtered phone number.
// */
// public enum Status {
// WHITELIST, BLACKLIST
// }
// }
| import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import com.addhen.android.raiburari.domain.executor.PostExecutionThread;
import com.addhen.android.raiburari.domain.executor.ThreadExecutor;
import org.addhen.smssync.domain.entity.DomainEntityFixture;
import org.addhen.smssync.domain.entity.FilterEntity;
import org.addhen.smssync.domain.repository.FilterRepository;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.verify; | /*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.domain.usecase.filter;
/**
* @author Ushahidi Team <[email protected]>
*/
public class DeleteFilterUsecaseTest {
private DeleteFilterUsecase mDeleteFilterUsecase;
@Mock
private ThreadExecutor mMockThreadExecutor;
@Mock
private PostExecutionThread mMockPostExecutionThread;
@Mock
private FilterRepository mMockFilterRepository;
@Mock | // Path: smssync/src/test/java/org/addhen/smssync/domain/entity/DomainEntityFixture.java
// public final class DomainEntityFixture {
//
// public static final Long ID = 2l;
//
// private static Date mDate = new Date();
//
// public static FilterEntity getFilterEntity() {
// FilterEntity filterEntity = new FilterEntity();
// filterEntity._id = ID;
// filterEntity.setPhoneNumber("000000000");
// filterEntity.setStatus(FilterEntity.Status.WHITELIST);
// return filterEntity;
// }
//
// public static HttpNameValuePair getHttpNameValuePair() {
// return new HttpNameValuePair("key", "value");
// }
//
// public static LogEntity getLogEntity() {
// LogEntity logEntity = new LogEntity();
// logEntity._id = ID;
// logEntity.setMessage("Log message");
// return logEntity;
// }
//
// public static MessageEntity getMessageEntity() {
// MessageEntity messageEntity = new MessageEntity();
// messageEntity.setId(ID);
// messageEntity.setDeliveredMessageDate(mDate);
// messageEntity.setDeliveryResultCode(1);
// messageEntity.setDeliveryResultMessage("delivered");
// messageEntity.setMessageBody("Message body");
// messageEntity.setMessageDate(mDate);
// messageEntity.setMessageType(MessageEntity.Type.PENDING);
// messageEntity.setMessageFrom("000000000");
// messageEntity.setMessageUuid("uuid0123456");
// messageEntity.setSentResultCode(1);
// messageEntity.setStatus(MessageEntity.Status.SENT);
// messageEntity.setRetries(3);
// return messageEntity;
// }
//
// public static WebServiceEntity getWebServiceEntity() {
// WebServiceEntity webServiceEntity = new WebServiceEntity();
// webServiceEntity.setId(ID);
// webServiceEntity.setSecret("secret");
// webServiceEntity.setKeywords("keywords");
// webServiceEntity.setTitle("title");
// webServiceEntity.setSyncScheme(new SyncSchemeEntity());
// webServiceEntity.setUrl("url");
// return webServiceEntity;
// }
// }
//
// Path: smssync/src/main/java/org/addhen/smssync/domain/entity/FilterEntity.java
// public class FilterEntity extends Entity {
//
// private String phoneNumber;
//
// private Status status;
//
// public Long getId() {
// return _id;
// }
//
// public void setId(Long id) {
// _id = id;
// }
//
// public String getPhoneNumber() {
// return phoneNumber;
// }
//
// public void setPhoneNumber(String phoneNumber) {
// this.phoneNumber = phoneNumber;
// }
//
// public Status getStatus() {
// return status;
// }
//
// public void setStatus(Status status) {
// this.status = status;
// }
//
// /**
// * The status of the filtered phone number.
// */
// public enum Status {
// WHITELIST, BLACKLIST
// }
// }
// Path: smssync/src/test/java/org/addhen/smssync/domain/usecase/filter/DeleteFilterUsecaseTest.java
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import com.addhen.android.raiburari.domain.executor.PostExecutionThread;
import com.addhen.android.raiburari.domain.executor.ThreadExecutor;
import org.addhen.smssync.domain.entity.DomainEntityFixture;
import org.addhen.smssync.domain.entity.FilterEntity;
import org.addhen.smssync.domain.repository.FilterRepository;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.verify;
/*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.domain.usecase.filter;
/**
* @author Ushahidi Team <[email protected]>
*/
public class DeleteFilterUsecaseTest {
private DeleteFilterUsecase mDeleteFilterUsecase;
@Mock
private ThreadExecutor mMockThreadExecutor;
@Mock
private PostExecutionThread mMockPostExecutionThread;
@Mock
private FilterRepository mMockFilterRepository;
@Mock | private FilterEntity mFilterEntity; |
ushahidi/SMSSync | smssync/src/test/java/org/addhen/smssync/domain/usecase/filter/DeleteFilterUsecaseTest.java | // Path: smssync/src/test/java/org/addhen/smssync/domain/entity/DomainEntityFixture.java
// public final class DomainEntityFixture {
//
// public static final Long ID = 2l;
//
// private static Date mDate = new Date();
//
// public static FilterEntity getFilterEntity() {
// FilterEntity filterEntity = new FilterEntity();
// filterEntity._id = ID;
// filterEntity.setPhoneNumber("000000000");
// filterEntity.setStatus(FilterEntity.Status.WHITELIST);
// return filterEntity;
// }
//
// public static HttpNameValuePair getHttpNameValuePair() {
// return new HttpNameValuePair("key", "value");
// }
//
// public static LogEntity getLogEntity() {
// LogEntity logEntity = new LogEntity();
// logEntity._id = ID;
// logEntity.setMessage("Log message");
// return logEntity;
// }
//
// public static MessageEntity getMessageEntity() {
// MessageEntity messageEntity = new MessageEntity();
// messageEntity.setId(ID);
// messageEntity.setDeliveredMessageDate(mDate);
// messageEntity.setDeliveryResultCode(1);
// messageEntity.setDeliveryResultMessage("delivered");
// messageEntity.setMessageBody("Message body");
// messageEntity.setMessageDate(mDate);
// messageEntity.setMessageType(MessageEntity.Type.PENDING);
// messageEntity.setMessageFrom("000000000");
// messageEntity.setMessageUuid("uuid0123456");
// messageEntity.setSentResultCode(1);
// messageEntity.setStatus(MessageEntity.Status.SENT);
// messageEntity.setRetries(3);
// return messageEntity;
// }
//
// public static WebServiceEntity getWebServiceEntity() {
// WebServiceEntity webServiceEntity = new WebServiceEntity();
// webServiceEntity.setId(ID);
// webServiceEntity.setSecret("secret");
// webServiceEntity.setKeywords("keywords");
// webServiceEntity.setTitle("title");
// webServiceEntity.setSyncScheme(new SyncSchemeEntity());
// webServiceEntity.setUrl("url");
// return webServiceEntity;
// }
// }
//
// Path: smssync/src/main/java/org/addhen/smssync/domain/entity/FilterEntity.java
// public class FilterEntity extends Entity {
//
// private String phoneNumber;
//
// private Status status;
//
// public Long getId() {
// return _id;
// }
//
// public void setId(Long id) {
// _id = id;
// }
//
// public String getPhoneNumber() {
// return phoneNumber;
// }
//
// public void setPhoneNumber(String phoneNumber) {
// this.phoneNumber = phoneNumber;
// }
//
// public Status getStatus() {
// return status;
// }
//
// public void setStatus(Status status) {
// this.status = status;
// }
//
// /**
// * The status of the filtered phone number.
// */
// public enum Status {
// WHITELIST, BLACKLIST
// }
// }
| import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import com.addhen.android.raiburari.domain.executor.PostExecutionThread;
import com.addhen.android.raiburari.domain.executor.ThreadExecutor;
import org.addhen.smssync.domain.entity.DomainEntityFixture;
import org.addhen.smssync.domain.entity.FilterEntity;
import org.addhen.smssync.domain.repository.FilterRepository;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.verify; | /*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.domain.usecase.filter;
/**
* @author Ushahidi Team <[email protected]>
*/
public class DeleteFilterUsecaseTest {
private DeleteFilterUsecase mDeleteFilterUsecase;
@Mock
private ThreadExecutor mMockThreadExecutor;
@Mock
private PostExecutionThread mMockPostExecutionThread;
@Mock
private FilterRepository mMockFilterRepository;
@Mock
private FilterEntity mFilterEntity;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mDeleteFilterUsecase = new DeleteFilterUsecase(mMockFilterRepository, mMockThreadExecutor,
mMockPostExecutionThread);
}
@Test
public void shouldSuccessfullyDeleteAFilter() { | // Path: smssync/src/test/java/org/addhen/smssync/domain/entity/DomainEntityFixture.java
// public final class DomainEntityFixture {
//
// public static final Long ID = 2l;
//
// private static Date mDate = new Date();
//
// public static FilterEntity getFilterEntity() {
// FilterEntity filterEntity = new FilterEntity();
// filterEntity._id = ID;
// filterEntity.setPhoneNumber("000000000");
// filterEntity.setStatus(FilterEntity.Status.WHITELIST);
// return filterEntity;
// }
//
// public static HttpNameValuePair getHttpNameValuePair() {
// return new HttpNameValuePair("key", "value");
// }
//
// public static LogEntity getLogEntity() {
// LogEntity logEntity = new LogEntity();
// logEntity._id = ID;
// logEntity.setMessage("Log message");
// return logEntity;
// }
//
// public static MessageEntity getMessageEntity() {
// MessageEntity messageEntity = new MessageEntity();
// messageEntity.setId(ID);
// messageEntity.setDeliveredMessageDate(mDate);
// messageEntity.setDeliveryResultCode(1);
// messageEntity.setDeliveryResultMessage("delivered");
// messageEntity.setMessageBody("Message body");
// messageEntity.setMessageDate(mDate);
// messageEntity.setMessageType(MessageEntity.Type.PENDING);
// messageEntity.setMessageFrom("000000000");
// messageEntity.setMessageUuid("uuid0123456");
// messageEntity.setSentResultCode(1);
// messageEntity.setStatus(MessageEntity.Status.SENT);
// messageEntity.setRetries(3);
// return messageEntity;
// }
//
// public static WebServiceEntity getWebServiceEntity() {
// WebServiceEntity webServiceEntity = new WebServiceEntity();
// webServiceEntity.setId(ID);
// webServiceEntity.setSecret("secret");
// webServiceEntity.setKeywords("keywords");
// webServiceEntity.setTitle("title");
// webServiceEntity.setSyncScheme(new SyncSchemeEntity());
// webServiceEntity.setUrl("url");
// return webServiceEntity;
// }
// }
//
// Path: smssync/src/main/java/org/addhen/smssync/domain/entity/FilterEntity.java
// public class FilterEntity extends Entity {
//
// private String phoneNumber;
//
// private Status status;
//
// public Long getId() {
// return _id;
// }
//
// public void setId(Long id) {
// _id = id;
// }
//
// public String getPhoneNumber() {
// return phoneNumber;
// }
//
// public void setPhoneNumber(String phoneNumber) {
// this.phoneNumber = phoneNumber;
// }
//
// public Status getStatus() {
// return status;
// }
//
// public void setStatus(Status status) {
// this.status = status;
// }
//
// /**
// * The status of the filtered phone number.
// */
// public enum Status {
// WHITELIST, BLACKLIST
// }
// }
// Path: smssync/src/test/java/org/addhen/smssync/domain/usecase/filter/DeleteFilterUsecaseTest.java
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import com.addhen.android.raiburari.domain.executor.PostExecutionThread;
import com.addhen.android.raiburari.domain.executor.ThreadExecutor;
import org.addhen.smssync.domain.entity.DomainEntityFixture;
import org.addhen.smssync.domain.entity.FilterEntity;
import org.addhen.smssync.domain.repository.FilterRepository;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.verify;
/*
* Copyright (c) 2010 - 2015 Ushahidi Inc
* All rights reserved
* Contact: [email protected]
* Website: http://www.ushahidi.com
* GNU Lesser General Public License Usage
* This file may be used under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 3 requirements
* will be met: http://www.gnu.org/licenses/lgpl.html.
*
* If you have questions regarding the use of this file, please contact
* Ushahidi developers at [email protected].
*/
package org.addhen.smssync.domain.usecase.filter;
/**
* @author Ushahidi Team <[email protected]>
*/
public class DeleteFilterUsecaseTest {
private DeleteFilterUsecase mDeleteFilterUsecase;
@Mock
private ThreadExecutor mMockThreadExecutor;
@Mock
private PostExecutionThread mMockPostExecutionThread;
@Mock
private FilterRepository mMockFilterRepository;
@Mock
private FilterEntity mFilterEntity;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mDeleteFilterUsecase = new DeleteFilterUsecase(mMockFilterRepository, mMockThreadExecutor,
mMockPostExecutionThread);
}
@Test
public void shouldSuccessfullyDeleteAFilter() { | mDeleteFilterUsecase.setFilterId(DomainEntityFixture.ID); |
ewolff/user-registration | user-registration-application/src/main/java/com/ewolff/user_registration/web/RegistrationController.java | // Path: user-registration-application/src/main/java/com/ewolff/user_registration/domain/User.java
// public class User {
//
// private String name;
//
// private String firstname;
//
// private String email;
//
// private User() {
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public void setFirstname(String firstname) {
// this.firstname = firstname;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public User(String firstname, String name, String email) {
// super();
// this.firstname = firstname;
// this.name = name;
// this.email = email;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFirstname() {
// return firstname;
// }
//
// public String getEmail() {
// return email;
// }
//
//
// }
| import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.ewolff.user_registration.domain.User;
import com.ewolff.user_registration.service.RegistrationService; | package com.ewolff.user_registration.web;
@Controller
public class RegistrationController {
private Log log = LogFactory.getLog(RegistrationController.class);
@Autowired
private RegistrationController(RegistrationService registrationService) {
this.registrationService = registrationService;
}
private RegistrationService registrationService;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String homepage() {
return "index";
}
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView createForm() { | // Path: user-registration-application/src/main/java/com/ewolff/user_registration/domain/User.java
// public class User {
//
// private String name;
//
// private String firstname;
//
// private String email;
//
// private User() {
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public void setFirstname(String firstname) {
// this.firstname = firstname;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public User(String firstname, String name, String email) {
// super();
// this.firstname = firstname;
// this.name = name;
// this.email = email;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFirstname() {
// return firstname;
// }
//
// public String getEmail() {
// return email;
// }
//
//
// }
// Path: user-registration-application/src/main/java/com/ewolff/user_registration/web/RegistrationController.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.ewolff.user_registration.domain.User;
import com.ewolff.user_registration.service.RegistrationService;
package com.ewolff.user_registration.web;
@Controller
public class RegistrationController {
private Log log = LogFactory.getLog(RegistrationController.class);
@Autowired
private RegistrationController(RegistrationService registrationService) {
this.registrationService = registrationService;
}
private RegistrationService registrationService;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String homepage() {
return "index";
}
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView createForm() { | return new ModelAndView("user/form", "user", new User("", "", "")); |
ewolff/user-registration | user-registration-acceptancetest-selenium/src/test/java/com/ewolff/user_registration/selenium/RegisterierungTest.java | // Path: user-registration-application/src/main/java/com/ewolff/user_registration/RegistrationApplication.java
// @ComponentScan
// @EnableAutoConfiguration
// public class RegistrationApplication {
//
// public static void main(String[] args) {
// SpringApplication.run(RegistrationApplication.class, args);
// }
// }
| import static org.junit.Assert.assertTrue;
import java.net.URL;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.springframework.boot.SpringApplication;
import org.springframework.web.client.RestTemplate;
import com.ewolff.user_registration.RegistrationApplication; | package com.ewolff.user_registration.selenium;
public class RegisterierungTest {
private WebDriver driver;
private String baseUrl;
@BeforeClass
public static void startWebApplication() { | // Path: user-registration-application/src/main/java/com/ewolff/user_registration/RegistrationApplication.java
// @ComponentScan
// @EnableAutoConfiguration
// public class RegistrationApplication {
//
// public static void main(String[] args) {
// SpringApplication.run(RegistrationApplication.class, args);
// }
// }
// Path: user-registration-acceptancetest-selenium/src/test/java/com/ewolff/user_registration/selenium/RegisterierungTest.java
import static org.junit.Assert.assertTrue;
import java.net.URL;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.springframework.boot.SpringApplication;
import org.springframework.web.client.RestTemplate;
import com.ewolff.user_registration.RegistrationApplication;
package com.ewolff.user_registration.selenium;
public class RegisterierungTest {
private WebDriver driver;
private String baseUrl;
@BeforeClass
public static void startWebApplication() { | SpringApplication.run(RegistrationApplication.class); |
ewolff/user-registration | user-registration-application/src/test/java/com/ewolff/user_registration/service/RegistrationServiceUnitTest.java | // Path: user-registration-application/src/main/java/com/ewolff/user_registration/domain/User.java
// public class User {
//
// private String name;
//
// private String firstname;
//
// private String email;
//
// private User() {
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public void setFirstname(String firstname) {
// this.firstname = firstname;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public User(String firstname, String name, String email) {
// super();
// this.firstname = firstname;
// this.name = name;
// this.email = email;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFirstname() {
// return firstname;
// }
//
// public String getEmail() {
// return email;
// }
//
//
// }
| import com.ewolff.user_registration.domain.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package com.ewolff.user_registration.service;
@RunWith(MockitoJUnitRunner.class)
public class RegistrationServiceUnitTest {
@Mock
private JdbcTemplate jdbcTemplateMock;
@InjectMocks
private RegistrationService service;
@Test
public void registerNewUser() {
// arrange | // Path: user-registration-application/src/main/java/com/ewolff/user_registration/domain/User.java
// public class User {
//
// private String name;
//
// private String firstname;
//
// private String email;
//
// private User() {
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public void setFirstname(String firstname) {
// this.firstname = firstname;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public User(String firstname, String name, String email) {
// super();
// this.firstname = firstname;
// this.name = name;
// this.email = email;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFirstname() {
// return firstname;
// }
//
// public String getEmail() {
// return email;
// }
//
//
// }
// Path: user-registration-application/src/test/java/com/ewolff/user_registration/service/RegistrationServiceUnitTest.java
import com.ewolff.user_registration.domain.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package com.ewolff.user_registration.service;
@RunWith(MockitoJUnitRunner.class)
public class RegistrationServiceUnitTest {
@Mock
private JdbcTemplate jdbcTemplateMock;
@InjectMocks
private RegistrationService service;
@Test
public void registerNewUser() {
// arrange | User user = new User("Eberhard","Wolff","[email protected]"); |
ewolff/user-registration | user-registration-application/src/test/java/com/ewolff/user_registration/service/RegistrationServiceTest.java | // Path: user-registration-application/src/main/java/com/ewolff/user_registration/RegistrationApplication.java
// @ComponentScan
// @EnableAutoConfiguration
// public class RegistrationApplication {
//
// public static void main(String[] args) {
// SpringApplication.run(RegistrationApplication.class, args);
// }
// }
//
// Path: user-registration-application/src/main/java/com/ewolff/user_registration/domain/User.java
// public class User {
//
// private String name;
//
// private String firstname;
//
// private String email;
//
// private User() {
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public void setFirstname(String firstname) {
// this.firstname = firstname;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public User(String firstname, String name, String email) {
// super();
// this.firstname = firstname;
// this.name = name;
// this.email = email;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFirstname() {
// return firstname;
// }
//
// public String getEmail() {
// return email;
// }
//
//
// }
| import static org.junit.Assert.*;
import javax.sql.DataSource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationContextLoader;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import com.ewolff.user_registration.RegistrationApplication;
import com.ewolff.user_registration.domain.User; | package com.ewolff.user_registration.service;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=RegistrationApplication.class, loader=SpringApplicationContextLoader.class)
@Transactional
public class RegistrationServiceTest {
@Autowired
private RegistrationService registrationService;
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void simpleRegistration() { | // Path: user-registration-application/src/main/java/com/ewolff/user_registration/RegistrationApplication.java
// @ComponentScan
// @EnableAutoConfiguration
// public class RegistrationApplication {
//
// public static void main(String[] args) {
// SpringApplication.run(RegistrationApplication.class, args);
// }
// }
//
// Path: user-registration-application/src/main/java/com/ewolff/user_registration/domain/User.java
// public class User {
//
// private String name;
//
// private String firstname;
//
// private String email;
//
// private User() {
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public void setFirstname(String firstname) {
// this.firstname = firstname;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public User(String firstname, String name, String email) {
// super();
// this.firstname = firstname;
// this.name = name;
// this.email = email;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFirstname() {
// return firstname;
// }
//
// public String getEmail() {
// return email;
// }
//
//
// }
// Path: user-registration-application/src/test/java/com/ewolff/user_registration/service/RegistrationServiceTest.java
import static org.junit.Assert.*;
import javax.sql.DataSource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationContextLoader;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import com.ewolff.user_registration.RegistrationApplication;
import com.ewolff.user_registration.domain.User;
package com.ewolff.user_registration.service;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=RegistrationApplication.class, loader=SpringApplicationContextLoader.class)
@Transactional
public class RegistrationServiceTest {
@Autowired
private RegistrationService registrationService;
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void simpleRegistration() { | User user = new User("Eberhard","Wolff","[email protected]"); |
ChiralBehaviors/Kramer | kramer-ql/src/test/java/com/chiralbehaviors/layout/graphql/TestGraphQlUtil.java | // Path: kramer/src/main/java/com/chiralbehaviors/layout/schema/Relation.java
// public class Relation extends SchemaNode {
// private boolean autoFold = true;
// private final List<SchemaNode> children = new ArrayList<>();
// private Relation fold;
//
// public Relation(String label) {
// super(label);
// }
//
// public void addChild(SchemaNode child) {
// children.add(child);
// }
//
// public Relation getAutoFoldable() {
// if (fold != null) {
// return fold;
// }
// return autoFold && children.size() == 1
// && children.get(children.size() - 1) instanceof Relation
// ? (Relation) children.get(0)
// : null;
// }
//
// public SchemaNode getChild(String field) {
// for (SchemaNode child : children) {
// if (child.getField()
// .equals(field)) {
// return child;
// }
// }
// return null;
// }
//
// public List<SchemaNode> getChildren() {
// return children;
// }
//
// public Relation getFold() {
// return fold;
// }
//
// @JsonProperty
// public boolean isFold() {
// return fold != null;
// }
//
// @Override
// public boolean isRelation() {
// return true;
// }
//
// public void setFold(boolean fold) {
// this.fold = (fold && children.size() == 1 && children.get(0)
// .isRelation()) ? (Relation) children.get(0)
// : null;
// }
//
// @Override
// public String toString() {
// return toString(0);
// }
//
// @Override
// public String toString(int indent) {
// StringBuffer buf = new StringBuffer();
// buf.append(String.format("Relation [%s]", label));
// buf.append('\n');
// children.forEach(c -> {
// for (int i = 0; i < indent; i++) {
// buf.append(" ");
// }
// buf.append(" - ");
// buf.append(c.toString(indent + 1));
// if (!c.equals(children.get(children.size() - 1))) {
// buf.append('\n');
// }
// });
// return buf.toString();
// }
// }
| import com.chiralbehaviors.layout.schema.Relation;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.junit.Test; | /**
* Copyright (c) 2017 Chiral Behaviors, LLC, all rights reserved.
*
* This file is part of Ultrastructure.
*
* Ultrastructure is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ULtrastructure 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Ultrastructure. If not, see <http://www.gnu.org/licenses/>.
*/
package com.chiralbehaviors.layout.graphql;
/**
* @author halhildebrand
*
*/
public class TestGraphQlUtil {
@Test
public void testFragments() throws Exception {
| // Path: kramer/src/main/java/com/chiralbehaviors/layout/schema/Relation.java
// public class Relation extends SchemaNode {
// private boolean autoFold = true;
// private final List<SchemaNode> children = new ArrayList<>();
// private Relation fold;
//
// public Relation(String label) {
// super(label);
// }
//
// public void addChild(SchemaNode child) {
// children.add(child);
// }
//
// public Relation getAutoFoldable() {
// if (fold != null) {
// return fold;
// }
// return autoFold && children.size() == 1
// && children.get(children.size() - 1) instanceof Relation
// ? (Relation) children.get(0)
// : null;
// }
//
// public SchemaNode getChild(String field) {
// for (SchemaNode child : children) {
// if (child.getField()
// .equals(field)) {
// return child;
// }
// }
// return null;
// }
//
// public List<SchemaNode> getChildren() {
// return children;
// }
//
// public Relation getFold() {
// return fold;
// }
//
// @JsonProperty
// public boolean isFold() {
// return fold != null;
// }
//
// @Override
// public boolean isRelation() {
// return true;
// }
//
// public void setFold(boolean fold) {
// this.fold = (fold && children.size() == 1 && children.get(0)
// .isRelation()) ? (Relation) children.get(0)
// : null;
// }
//
// @Override
// public String toString() {
// return toString(0);
// }
//
// @Override
// public String toString(int indent) {
// StringBuffer buf = new StringBuffer();
// buf.append(String.format("Relation [%s]", label));
// buf.append('\n');
// children.forEach(c -> {
// for (int i = 0; i < indent; i++) {
// buf.append(" ");
// }
// buf.append(" - ");
// buf.append(c.toString(indent + 1));
// if (!c.equals(children.get(children.size() - 1))) {
// buf.append('\n');
// }
// });
// return buf.toString();
// }
// }
// Path: kramer-ql/src/test/java/com/chiralbehaviors/layout/graphql/TestGraphQlUtil.java
import com.chiralbehaviors.layout.schema.Relation;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.junit.Test;
/**
* Copyright (c) 2017 Chiral Behaviors, LLC, all rights reserved.
*
* This file is part of Ultrastructure.
*
* Ultrastructure is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ULtrastructure 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Ultrastructure. If not, see <http://www.gnu.org/licenses/>.
*/
package com.chiralbehaviors.layout.graphql;
/**
* @author halhildebrand
*
*/
public class TestGraphQlUtil {
@Test
public void testFragments() throws Exception {
| Relation relation = GraphQlUtil.buildSchema(readFile("target/test-classes/fragment.query")); |
ChiralBehaviors/Kramer | toy-app/src/main/java/com/chiralbehaviors/layout/toy/Page.java | // Path: kramer/src/main/java/com/chiralbehaviors/layout/schema/Relation.java
// public class Relation extends SchemaNode {
// private boolean autoFold = true;
// private final List<SchemaNode> children = new ArrayList<>();
// private Relation fold;
//
// public Relation(String label) {
// super(label);
// }
//
// public void addChild(SchemaNode child) {
// children.add(child);
// }
//
// public Relation getAutoFoldable() {
// if (fold != null) {
// return fold;
// }
// return autoFold && children.size() == 1
// && children.get(children.size() - 1) instanceof Relation
// ? (Relation) children.get(0)
// : null;
// }
//
// public SchemaNode getChild(String field) {
// for (SchemaNode child : children) {
// if (child.getField()
// .equals(field)) {
// return child;
// }
// }
// return null;
// }
//
// public List<SchemaNode> getChildren() {
// return children;
// }
//
// public Relation getFold() {
// return fold;
// }
//
// @JsonProperty
// public boolean isFold() {
// return fold != null;
// }
//
// @Override
// public boolean isRelation() {
// return true;
// }
//
// public void setFold(boolean fold) {
// this.fold = (fold && children.size() == 1 && children.get(0)
// .isRelation()) ? (Relation) children.get(0)
// : null;
// }
//
// @Override
// public String toString() {
// return toString(0);
// }
//
// @Override
// public String toString(int indent) {
// StringBuffer buf = new StringBuffer();
// buf.append(String.format("Relation [%s]", label));
// buf.append('\n');
// children.forEach(c -> {
// for (int i = 0; i < indent; i++) {
// buf.append(" ");
// }
// buf.append(" - ");
// buf.append(c.toString(indent + 1));
// if (!c.equals(children.get(children.size() - 1))) {
// buf.append('\n');
// }
// });
// return buf.toString();
// }
// }
| import java.util.Map;
import com.chiralbehaviors.layout.schema.Relation;
import com.fasterxml.jackson.annotation.JsonProperty; | /**
* Copyright (c) 2016 Chiral Behaviors, LLC, all rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.chiralbehaviors.layout.toy;
/**
*
* @author hhildebrand
*
*/
public class Page {
public static class Route {
@JsonProperty
private String path;
@JsonProperty
private Map<String, String> extract;
public String getPath() {
return path;
}
public Map<String, String> getExtract() {
return extract;
}
}
@JsonProperty
private String endpoint;
@JsonProperty
private String query;
@JsonProperty
private Map<String, Route> routing;
@JsonProperty
private String title;
public String getQuery() {
return query;
}
| // Path: kramer/src/main/java/com/chiralbehaviors/layout/schema/Relation.java
// public class Relation extends SchemaNode {
// private boolean autoFold = true;
// private final List<SchemaNode> children = new ArrayList<>();
// private Relation fold;
//
// public Relation(String label) {
// super(label);
// }
//
// public void addChild(SchemaNode child) {
// children.add(child);
// }
//
// public Relation getAutoFoldable() {
// if (fold != null) {
// return fold;
// }
// return autoFold && children.size() == 1
// && children.get(children.size() - 1) instanceof Relation
// ? (Relation) children.get(0)
// : null;
// }
//
// public SchemaNode getChild(String field) {
// for (SchemaNode child : children) {
// if (child.getField()
// .equals(field)) {
// return child;
// }
// }
// return null;
// }
//
// public List<SchemaNode> getChildren() {
// return children;
// }
//
// public Relation getFold() {
// return fold;
// }
//
// @JsonProperty
// public boolean isFold() {
// return fold != null;
// }
//
// @Override
// public boolean isRelation() {
// return true;
// }
//
// public void setFold(boolean fold) {
// this.fold = (fold && children.size() == 1 && children.get(0)
// .isRelation()) ? (Relation) children.get(0)
// : null;
// }
//
// @Override
// public String toString() {
// return toString(0);
// }
//
// @Override
// public String toString(int indent) {
// StringBuffer buf = new StringBuffer();
// buf.append(String.format("Relation [%s]", label));
// buf.append('\n');
// children.forEach(c -> {
// for (int i = 0; i < indent; i++) {
// buf.append(" ");
// }
// buf.append(" - ");
// buf.append(c.toString(indent + 1));
// if (!c.equals(children.get(children.size() - 1))) {
// buf.append('\n');
// }
// });
// return buf.toString();
// }
// }
// Path: toy-app/src/main/java/com/chiralbehaviors/layout/toy/Page.java
import java.util.Map;
import com.chiralbehaviors.layout.schema.Relation;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Copyright (c) 2016 Chiral Behaviors, LLC, all rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.chiralbehaviors.layout.toy;
/**
*
* @author hhildebrand
*
*/
public class Page {
public static class Route {
@JsonProperty
private String path;
@JsonProperty
private Map<String, String> extract;
public String getPath() {
return path;
}
public Map<String, String> getExtract() {
return extract;
}
}
@JsonProperty
private String endpoint;
@JsonProperty
private String query;
@JsonProperty
private Map<String, Route> routing;
@JsonProperty
private String title;
public String getQuery() {
return query;
}
| public Route getRoute(Relation relation) { |
ChiralBehaviors/Kramer | kramer/src/main/java/com/chiralbehaviors/layout/style/LabelStyle.java | // Path: kramer/src/main/java/com/chiralbehaviors/layout/LayoutLabel.java
// public class LayoutLabel extends Label {
// private static final String LAYOUT_LABEL = "layout-label";
// private static final String STYLE_SHEET = "layout-label.css";
// private final String stylesheet;
//
// public LayoutLabel() {
// URL url = getClass().getResource(STYLE_SHEET);
// stylesheet = url == null ? null : url.toExternalForm();
// getStyleClass().clear();
// getStyleClass().add(LAYOUT_LABEL);
// }
//
// public LayoutLabel(String arg0) {
// super(arg0);
// URL url = getClass().getResource(STYLE_SHEET);
// stylesheet = url == null ? null : url.toExternalForm();
// getStyleClass().clear();
// getStyleClass().add(LAYOUT_LABEL);
// }
//
// public LayoutLabel(String arg0, Node arg1) {
// super(arg0, arg1);
// URL url = getClass().getResource(STYLE_SHEET);
// stylesheet = url == null ? null : url.toExternalForm();
// getStyleClass().clear();
// getStyleClass().add(LAYOUT_LABEL);
// }
//
// @Override
// public String getUserAgentStylesheet() {
// return stylesheet;
// }
// }
| import com.chiralbehaviors.layout.LayoutLabel;
import javafx.geometry.Bounds;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextBoundsType; | tb.getWidth(), tb.getHeight()))
.getBoundsInLocal()
.getHeight();
}
private final Font font;
private final Insets insets;
private final double lineHeight;
public LabelStyle(Label label) {
Insets lInsets = Style.add(label.getInsets() , label.getPadding());
insets = lInsets;
lineHeight = getLineHeight(label.getFont(),
TextBoundsType.LOGICAL_VERTICAL_CENTER);
font = label.getFont();
}
public double getHeight() {
return lineHeight + insets.getTop() + insets.getBottom();
}
public double getHeight(double rows) {
return (lineHeight * rows) + insets.getTop() + insets.getBottom();
}
public double getHorizontalInset() {
return insets.getLeft() + insets.getRight();
}
public Label label(double width, String text, double height) { | // Path: kramer/src/main/java/com/chiralbehaviors/layout/LayoutLabel.java
// public class LayoutLabel extends Label {
// private static final String LAYOUT_LABEL = "layout-label";
// private static final String STYLE_SHEET = "layout-label.css";
// private final String stylesheet;
//
// public LayoutLabel() {
// URL url = getClass().getResource(STYLE_SHEET);
// stylesheet = url == null ? null : url.toExternalForm();
// getStyleClass().clear();
// getStyleClass().add(LAYOUT_LABEL);
// }
//
// public LayoutLabel(String arg0) {
// super(arg0);
// URL url = getClass().getResource(STYLE_SHEET);
// stylesheet = url == null ? null : url.toExternalForm();
// getStyleClass().clear();
// getStyleClass().add(LAYOUT_LABEL);
// }
//
// public LayoutLabel(String arg0, Node arg1) {
// super(arg0, arg1);
// URL url = getClass().getResource(STYLE_SHEET);
// stylesheet = url == null ? null : url.toExternalForm();
// getStyleClass().clear();
// getStyleClass().add(LAYOUT_LABEL);
// }
//
// @Override
// public String getUserAgentStylesheet() {
// return stylesheet;
// }
// }
// Path: kramer/src/main/java/com/chiralbehaviors/layout/style/LabelStyle.java
import com.chiralbehaviors.layout.LayoutLabel;
import javafx.geometry.Bounds;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextBoundsType;
tb.getWidth(), tb.getHeight()))
.getBoundsInLocal()
.getHeight();
}
private final Font font;
private final Insets insets;
private final double lineHeight;
public LabelStyle(Label label) {
Insets lInsets = Style.add(label.getInsets() , label.getPadding());
insets = lInsets;
lineHeight = getLineHeight(label.getFont(),
TextBoundsType.LOGICAL_VERTICAL_CENTER);
font = label.getFont();
}
public double getHeight() {
return lineHeight + insets.getTop() + insets.getBottom();
}
public double getHeight(double rows) {
return (lineHeight * rows) + insets.getTop() + insets.getBottom();
}
public double getHorizontalInset() {
return insets.getLeft() + insets.getRight();
}
public Label label(double width, String text, double height) { | LayoutLabel label = new LayoutLabel(text); |
ChiralBehaviors/Kramer | kramer/src/main/java/com/chiralbehaviors/layout/cell/control/SelectionEvent.java | // Path: kramer/src/main/java/com/chiralbehaviors/layout/flowless/Cell.java
// @FunctionalInterface
// public interface Cell<T, N extends Node> {
// static <T, N extends Node> Cell<T, N> wrapNode(N node) {
// return new Cell<T, N>() {
//
// @Override
// public N getNode() {
// return node;
// }
//
// @Override
// public String toString() {
// return node.toString();
// }
// };
// }
//
// default Cell<T, N> afterDispose(Runnable action) {
// return CellWrapper.afterDispose(this, action);
// }
//
// default Cell<T, N> afterReset(Runnable action) {
// return CellWrapper.afterReset(this, action);
// }
//
// default Cell<T, N> afterUpdateIndex(IntConsumer action) {
// return CellWrapper.afterUpdateIndex(this, action);
// }
//
// default Cell<T, N> afterUpdateItem(Consumer<? super T> action) {
// return CellWrapper.afterUpdateItem(this, action);
// }
//
// default Cell<T, N> beforeDispose(Runnable action) {
// return CellWrapper.beforeDispose(this, action);
// }
//
// default Cell<T, N> beforeReset(Runnable action) {
// return CellWrapper.beforeReset(this, action);
// }
//
// default Cell<T, N> beforeUpdateIndex(IntConsumer action) {
// return CellWrapper.beforeUpdateIndex(this, action);
// }
//
// default Cell<T, N> beforeUpdateItem(Consumer<? super T> action) {
// return CellWrapper.beforeUpdateItem(this, action);
// }
//
// /**
// * Called when this cell is no longer going to be used at all.
// * {@link #reset()} will have been called before this method is invoked.
// *
// * <p>
// * Default implementation does nothing.
// */
// default void dispose() {
// // do nothing by default
// }
//
// N getNode();
//
// /**
// * Indicates whether this cell can be reused to display different items.
// *
// * <p>
// * Default implementation returns {@code false}.
// */
// default boolean isReusable() {
// return false;
// }
//
// /**
// * Called when this cell is no longer used to display its item. If this cell
// * is reusable, it may later be asked to display a different item by a call
// * to {@link #updateItem(Object)}.
// *
// * <p>
// * Default implementation does nothing.
// */
// default void reset() {
// // do nothing by default
// }
//
// default void setFocus() {
// getNode().requestFocus();
// }
//
// default int getIndex() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Called to update index of a visible cell.
// *
// * <p>
// * Default implementation does nothing.
// */
// default void updateIndex(int index) {
// // do nothing by default
// }
//
// /**
// * If this cell is reusable (as indicated by {@link #isReusable()}), this
// * method is called to display a different item. {@link #reset()} will have
// * been called before a call to this method.
// *
// * <p>
// * The default implementation throws {@link UnsupportedOperationException}.
// *
// * @param item
// * the new item to display
// */
// default void updateItem(T item) {
// throw new UnsupportedOperationException();
// }
//
// default void updateSelection(boolean selected) {
// // do nothing
// }
// }
| import com.chiralbehaviors.layout.flowless.Cell;
import javafx.event.Event;
import javafx.event.EventType; | /**
* Copyright (c) 2017 Chiral Behaviors, LLC, all rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.chiralbehaviors.layout.cell.control;
/**
* @author halhildebrand
*
*/
public class SelectionEvent extends Event {
public static final EventType<SelectionEvent> ALL = new EventType<SelectionEvent>("SELECT");
public static final EventType<SelectionEvent> DOUBLE_SELECT;
public static final EventType<SelectionEvent> SINGLE_SELECT;
public static final EventType<SelectionEvent> TRIPLE_SELECT;
private static final long serialVersionUID = 1L;
static {
SINGLE_SELECT = new EventType<>(ALL, "SINGLE_SELECT");
DOUBLE_SELECT = new EventType<>(SINGLE_SELECT, "DOUBLE_SELECT");
TRIPLE_SELECT = new EventType<>(DOUBLE_SELECT, "TRIPLE_SELECT");
}
| // Path: kramer/src/main/java/com/chiralbehaviors/layout/flowless/Cell.java
// @FunctionalInterface
// public interface Cell<T, N extends Node> {
// static <T, N extends Node> Cell<T, N> wrapNode(N node) {
// return new Cell<T, N>() {
//
// @Override
// public N getNode() {
// return node;
// }
//
// @Override
// public String toString() {
// return node.toString();
// }
// };
// }
//
// default Cell<T, N> afterDispose(Runnable action) {
// return CellWrapper.afterDispose(this, action);
// }
//
// default Cell<T, N> afterReset(Runnable action) {
// return CellWrapper.afterReset(this, action);
// }
//
// default Cell<T, N> afterUpdateIndex(IntConsumer action) {
// return CellWrapper.afterUpdateIndex(this, action);
// }
//
// default Cell<T, N> afterUpdateItem(Consumer<? super T> action) {
// return CellWrapper.afterUpdateItem(this, action);
// }
//
// default Cell<T, N> beforeDispose(Runnable action) {
// return CellWrapper.beforeDispose(this, action);
// }
//
// default Cell<T, N> beforeReset(Runnable action) {
// return CellWrapper.beforeReset(this, action);
// }
//
// default Cell<T, N> beforeUpdateIndex(IntConsumer action) {
// return CellWrapper.beforeUpdateIndex(this, action);
// }
//
// default Cell<T, N> beforeUpdateItem(Consumer<? super T> action) {
// return CellWrapper.beforeUpdateItem(this, action);
// }
//
// /**
// * Called when this cell is no longer going to be used at all.
// * {@link #reset()} will have been called before this method is invoked.
// *
// * <p>
// * Default implementation does nothing.
// */
// default void dispose() {
// // do nothing by default
// }
//
// N getNode();
//
// /**
// * Indicates whether this cell can be reused to display different items.
// *
// * <p>
// * Default implementation returns {@code false}.
// */
// default boolean isReusable() {
// return false;
// }
//
// /**
// * Called when this cell is no longer used to display its item. If this cell
// * is reusable, it may later be asked to display a different item by a call
// * to {@link #updateItem(Object)}.
// *
// * <p>
// * Default implementation does nothing.
// */
// default void reset() {
// // do nothing by default
// }
//
// default void setFocus() {
// getNode().requestFocus();
// }
//
// default int getIndex() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Called to update index of a visible cell.
// *
// * <p>
// * Default implementation does nothing.
// */
// default void updateIndex(int index) {
// // do nothing by default
// }
//
// /**
// * If this cell is reusable (as indicated by {@link #isReusable()}), this
// * method is called to display a different item. {@link #reset()} will have
// * been called before a call to this method.
// *
// * <p>
// * The default implementation throws {@link UnsupportedOperationException}.
// *
// * @param item
// * the new item to display
// */
// default void updateItem(T item) {
// throw new UnsupportedOperationException();
// }
//
// default void updateSelection(boolean selected) {
// // do nothing
// }
// }
// Path: kramer/src/main/java/com/chiralbehaviors/layout/cell/control/SelectionEvent.java
import com.chiralbehaviors.layout.flowless.Cell;
import javafx.event.Event;
import javafx.event.EventType;
/**
* Copyright (c) 2017 Chiral Behaviors, LLC, all rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.chiralbehaviors.layout.cell.control;
/**
* @author halhildebrand
*
*/
public class SelectionEvent extends Event {
public static final EventType<SelectionEvent> ALL = new EventType<SelectionEvent>("SELECT");
public static final EventType<SelectionEvent> DOUBLE_SELECT;
public static final EventType<SelectionEvent> SINGLE_SELECT;
public static final EventType<SelectionEvent> TRIPLE_SELECT;
private static final long serialVersionUID = 1L;
static {
SINGLE_SELECT = new EventType<>(ALL, "SINGLE_SELECT");
DOUBLE_SELECT = new EventType<>(SINGLE_SELECT, "DOUBLE_SELECT");
TRIPLE_SELECT = new EventType<>(DOUBLE_SELECT, "TRIPLE_SELECT");
}
| private final Cell<?, ?> selected; |
ChiralBehaviors/Kramer | kramer-ql/src/main/java/com/chiralbehaviors/layout/graphql/GraphQlUtil.java | // Path: kramer/src/main/java/com/chiralbehaviors/layout/schema/Primitive.java
// public class Primitive extends SchemaNode {
//
// private double defaultWidth = 0;
//
// public Primitive() {
// super();
// }
//
// public Primitive(String field) {
// super(field);
// }
//
// public double getDefaultWidth() {
// return defaultWidth;
// }
//
// @Override
// public String toString() {
// return String.format("Primitive [%s]", label);
// }
//
// @Override
// public String toString(int indent) {
// return toString();
// }
// }
//
// Path: kramer/src/main/java/com/chiralbehaviors/layout/schema/Relation.java
// public class Relation extends SchemaNode {
// private boolean autoFold = true;
// private final List<SchemaNode> children = new ArrayList<>();
// private Relation fold;
//
// public Relation(String label) {
// super(label);
// }
//
// public void addChild(SchemaNode child) {
// children.add(child);
// }
//
// public Relation getAutoFoldable() {
// if (fold != null) {
// return fold;
// }
// return autoFold && children.size() == 1
// && children.get(children.size() - 1) instanceof Relation
// ? (Relation) children.get(0)
// : null;
// }
//
// public SchemaNode getChild(String field) {
// for (SchemaNode child : children) {
// if (child.getField()
// .equals(field)) {
// return child;
// }
// }
// return null;
// }
//
// public List<SchemaNode> getChildren() {
// return children;
// }
//
// public Relation getFold() {
// return fold;
// }
//
// @JsonProperty
// public boolean isFold() {
// return fold != null;
// }
//
// @Override
// public boolean isRelation() {
// return true;
// }
//
// public void setFold(boolean fold) {
// this.fold = (fold && children.size() == 1 && children.get(0)
// .isRelation()) ? (Relation) children.get(0)
// : null;
// }
//
// @Override
// public String toString() {
// return toString(0);
// }
//
// @Override
// public String toString(int indent) {
// StringBuffer buf = new StringBuffer();
// buf.append(String.format("Relation [%s]", label));
// buf.append('\n');
// children.forEach(c -> {
// for (int i = 0; i < indent; i++) {
// buf.append(" ");
// }
// buf.append(" - ");
// buf.append(c.toString(indent + 1));
// if (!c.equals(children.get(children.size() - 1))) {
// buf.append('\n');
// }
// });
// return buf.toString();
// }
// }
| import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import com.chiralbehaviors.layout.schema.Primitive;
import com.chiralbehaviors.layout.schema.Relation;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import graphql.language.Definition;
import graphql.language.Field;
import graphql.language.FragmentSpread;
import graphql.language.InlineFragment;
import graphql.language.OperationDefinition;
import graphql.language.OperationDefinition.Operation;
import graphql.language.Selection;
import graphql.parser.Parser; | /**
* Copyright (c) 2016 Chiral Behaviors, LLC, all rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.chiralbehaviors.layout.graphql;
/**
*
* @author halhildebrand
*
*/
public interface GraphQlUtil {
static class QueryException extends Exception {
private static final long serialVersionUID = 1L;
private final ArrayNode errors;
public QueryException(ArrayNode errors) {
super(errors.toString());
this.errors = errors;
}
public ArrayNode getErrors() {
return errors;
}
}
static class QueryRequest {
public String operationName;
public String query;
public Map<String, Object> variables = Collections.emptyMap();
public QueryRequest() {
}
public QueryRequest(String query, Map<String, Object> variables) {
this.query = query;
this.variables = variables;
}
@Override
public String toString() {
return "QueryRequest [query=" + query + ", variables=" + variables
+ "]";
}
}
| // Path: kramer/src/main/java/com/chiralbehaviors/layout/schema/Primitive.java
// public class Primitive extends SchemaNode {
//
// private double defaultWidth = 0;
//
// public Primitive() {
// super();
// }
//
// public Primitive(String field) {
// super(field);
// }
//
// public double getDefaultWidth() {
// return defaultWidth;
// }
//
// @Override
// public String toString() {
// return String.format("Primitive [%s]", label);
// }
//
// @Override
// public String toString(int indent) {
// return toString();
// }
// }
//
// Path: kramer/src/main/java/com/chiralbehaviors/layout/schema/Relation.java
// public class Relation extends SchemaNode {
// private boolean autoFold = true;
// private final List<SchemaNode> children = new ArrayList<>();
// private Relation fold;
//
// public Relation(String label) {
// super(label);
// }
//
// public void addChild(SchemaNode child) {
// children.add(child);
// }
//
// public Relation getAutoFoldable() {
// if (fold != null) {
// return fold;
// }
// return autoFold && children.size() == 1
// && children.get(children.size() - 1) instanceof Relation
// ? (Relation) children.get(0)
// : null;
// }
//
// public SchemaNode getChild(String field) {
// for (SchemaNode child : children) {
// if (child.getField()
// .equals(field)) {
// return child;
// }
// }
// return null;
// }
//
// public List<SchemaNode> getChildren() {
// return children;
// }
//
// public Relation getFold() {
// return fold;
// }
//
// @JsonProperty
// public boolean isFold() {
// return fold != null;
// }
//
// @Override
// public boolean isRelation() {
// return true;
// }
//
// public void setFold(boolean fold) {
// this.fold = (fold && children.size() == 1 && children.get(0)
// .isRelation()) ? (Relation) children.get(0)
// : null;
// }
//
// @Override
// public String toString() {
// return toString(0);
// }
//
// @Override
// public String toString(int indent) {
// StringBuffer buf = new StringBuffer();
// buf.append(String.format("Relation [%s]", label));
// buf.append('\n');
// children.forEach(c -> {
// for (int i = 0; i < indent; i++) {
// buf.append(" ");
// }
// buf.append(" - ");
// buf.append(c.toString(indent + 1));
// if (!c.equals(children.get(children.size() - 1))) {
// buf.append('\n');
// }
// });
// return buf.toString();
// }
// }
// Path: kramer-ql/src/main/java/com/chiralbehaviors/layout/graphql/GraphQlUtil.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import com.chiralbehaviors.layout.schema.Primitive;
import com.chiralbehaviors.layout.schema.Relation;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import graphql.language.Definition;
import graphql.language.Field;
import graphql.language.FragmentSpread;
import graphql.language.InlineFragment;
import graphql.language.OperationDefinition;
import graphql.language.OperationDefinition.Operation;
import graphql.language.Selection;
import graphql.parser.Parser;
/**
* Copyright (c) 2016 Chiral Behaviors, LLC, all rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.chiralbehaviors.layout.graphql;
/**
*
* @author halhildebrand
*
*/
public interface GraphQlUtil {
static class QueryException extends Exception {
private static final long serialVersionUID = 1L;
private final ArrayNode errors;
public QueryException(ArrayNode errors) {
super(errors.toString());
this.errors = errors;
}
public ArrayNode getErrors() {
return errors;
}
}
static class QueryRequest {
public String operationName;
public String query;
public Map<String, Object> variables = Collections.emptyMap();
public QueryRequest() {
}
public QueryRequest(String query, Map<String, Object> variables) {
this.query = query;
this.variables = variables;
}
@Override
public String toString() {
return "QueryRequest [query=" + query + ", variables=" + variables
+ "]";
}
}
| static Relation buildSchema(Field parentField) { |
ChiralBehaviors/Kramer | kramer-ql/src/main/java/com/chiralbehaviors/layout/graphql/GraphQlUtil.java | // Path: kramer/src/main/java/com/chiralbehaviors/layout/schema/Primitive.java
// public class Primitive extends SchemaNode {
//
// private double defaultWidth = 0;
//
// public Primitive() {
// super();
// }
//
// public Primitive(String field) {
// super(field);
// }
//
// public double getDefaultWidth() {
// return defaultWidth;
// }
//
// @Override
// public String toString() {
// return String.format("Primitive [%s]", label);
// }
//
// @Override
// public String toString(int indent) {
// return toString();
// }
// }
//
// Path: kramer/src/main/java/com/chiralbehaviors/layout/schema/Relation.java
// public class Relation extends SchemaNode {
// private boolean autoFold = true;
// private final List<SchemaNode> children = new ArrayList<>();
// private Relation fold;
//
// public Relation(String label) {
// super(label);
// }
//
// public void addChild(SchemaNode child) {
// children.add(child);
// }
//
// public Relation getAutoFoldable() {
// if (fold != null) {
// return fold;
// }
// return autoFold && children.size() == 1
// && children.get(children.size() - 1) instanceof Relation
// ? (Relation) children.get(0)
// : null;
// }
//
// public SchemaNode getChild(String field) {
// for (SchemaNode child : children) {
// if (child.getField()
// .equals(field)) {
// return child;
// }
// }
// return null;
// }
//
// public List<SchemaNode> getChildren() {
// return children;
// }
//
// public Relation getFold() {
// return fold;
// }
//
// @JsonProperty
// public boolean isFold() {
// return fold != null;
// }
//
// @Override
// public boolean isRelation() {
// return true;
// }
//
// public void setFold(boolean fold) {
// this.fold = (fold && children.size() == 1 && children.get(0)
// .isRelation()) ? (Relation) children.get(0)
// : null;
// }
//
// @Override
// public String toString() {
// return toString(0);
// }
//
// @Override
// public String toString(int indent) {
// StringBuffer buf = new StringBuffer();
// buf.append(String.format("Relation [%s]", label));
// buf.append('\n');
// children.forEach(c -> {
// for (int i = 0; i < indent; i++) {
// buf.append(" ");
// }
// buf.append(" - ");
// buf.append(c.toString(indent + 1));
// if (!c.equals(children.get(children.size() - 1))) {
// buf.append('\n');
// }
// });
// return buf.toString();
// }
// }
| import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import com.chiralbehaviors.layout.schema.Primitive;
import com.chiralbehaviors.layout.schema.Relation;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import graphql.language.Definition;
import graphql.language.Field;
import graphql.language.FragmentSpread;
import graphql.language.InlineFragment;
import graphql.language.OperationDefinition;
import graphql.language.OperationDefinition.Operation;
import graphql.language.Selection;
import graphql.parser.Parser; |
static class QueryRequest {
public String operationName;
public String query;
public Map<String, Object> variables = Collections.emptyMap();
public QueryRequest() {
}
public QueryRequest(String query, Map<String, Object> variables) {
this.query = query;
this.variables = variables;
}
@Override
public String toString() {
return "QueryRequest [query=" + query + ", variables=" + variables
+ "]";
}
}
static Relation buildSchema(Field parentField) {
Relation parent = new Relation(parentField.getName());
for (Selection selection : parentField.getSelectionSet()
.getSelections()) {
if (selection instanceof Field) {
Field field = (Field) selection;
if (field.getSelectionSet() == null) {
if (!field.getName()
.equals("id")) { | // Path: kramer/src/main/java/com/chiralbehaviors/layout/schema/Primitive.java
// public class Primitive extends SchemaNode {
//
// private double defaultWidth = 0;
//
// public Primitive() {
// super();
// }
//
// public Primitive(String field) {
// super(field);
// }
//
// public double getDefaultWidth() {
// return defaultWidth;
// }
//
// @Override
// public String toString() {
// return String.format("Primitive [%s]", label);
// }
//
// @Override
// public String toString(int indent) {
// return toString();
// }
// }
//
// Path: kramer/src/main/java/com/chiralbehaviors/layout/schema/Relation.java
// public class Relation extends SchemaNode {
// private boolean autoFold = true;
// private final List<SchemaNode> children = new ArrayList<>();
// private Relation fold;
//
// public Relation(String label) {
// super(label);
// }
//
// public void addChild(SchemaNode child) {
// children.add(child);
// }
//
// public Relation getAutoFoldable() {
// if (fold != null) {
// return fold;
// }
// return autoFold && children.size() == 1
// && children.get(children.size() - 1) instanceof Relation
// ? (Relation) children.get(0)
// : null;
// }
//
// public SchemaNode getChild(String field) {
// for (SchemaNode child : children) {
// if (child.getField()
// .equals(field)) {
// return child;
// }
// }
// return null;
// }
//
// public List<SchemaNode> getChildren() {
// return children;
// }
//
// public Relation getFold() {
// return fold;
// }
//
// @JsonProperty
// public boolean isFold() {
// return fold != null;
// }
//
// @Override
// public boolean isRelation() {
// return true;
// }
//
// public void setFold(boolean fold) {
// this.fold = (fold && children.size() == 1 && children.get(0)
// .isRelation()) ? (Relation) children.get(0)
// : null;
// }
//
// @Override
// public String toString() {
// return toString(0);
// }
//
// @Override
// public String toString(int indent) {
// StringBuffer buf = new StringBuffer();
// buf.append(String.format("Relation [%s]", label));
// buf.append('\n');
// children.forEach(c -> {
// for (int i = 0; i < indent; i++) {
// buf.append(" ");
// }
// buf.append(" - ");
// buf.append(c.toString(indent + 1));
// if (!c.equals(children.get(children.size() - 1))) {
// buf.append('\n');
// }
// });
// return buf.toString();
// }
// }
// Path: kramer-ql/src/main/java/com/chiralbehaviors/layout/graphql/GraphQlUtil.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import com.chiralbehaviors.layout.schema.Primitive;
import com.chiralbehaviors.layout.schema.Relation;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import graphql.language.Definition;
import graphql.language.Field;
import graphql.language.FragmentSpread;
import graphql.language.InlineFragment;
import graphql.language.OperationDefinition;
import graphql.language.OperationDefinition.Operation;
import graphql.language.Selection;
import graphql.parser.Parser;
static class QueryRequest {
public String operationName;
public String query;
public Map<String, Object> variables = Collections.emptyMap();
public QueryRequest() {
}
public QueryRequest(String query, Map<String, Object> variables) {
this.query = query;
this.variables = variables;
}
@Override
public String toString() {
return "QueryRequest [query=" + query + ", variables=" + variables
+ "]";
}
}
static Relation buildSchema(Field parentField) {
Relation parent = new Relation(parentField.getName());
for (Selection selection : parentField.getSelectionSet()
.getSelections()) {
if (selection instanceof Field) {
Field field = (Field) selection;
if (field.getSelectionSet() == null) {
if (!field.getName()
.equals("id")) { | parent.addChild(new Primitive(field.getName())); |
SpoonLabs/spoon-maven-plugin | src/main/java/fr/inria/gforge/spoon/logging/ReportDaoImpl.java | // Path: src/main/java/fr/inria/gforge/spoon/logging/ReportBuilderImpl.java
// enum ReportKey {
// PROJECT_NAME, FRAGMENT_MODE, PROCESSORS, MODULE_NAME, INPUT, OUTPUT, SOURCE_CLASSPATH, PERFORMANCE
// }
//
// Path: src/main/java/fr/inria/gforge/spoon/logging/ReportBuilderImpl.java
// enum ReportKey {
// PROJECT_NAME, FRAGMENT_MODE, PROCESSORS, MODULE_NAME, INPUT, OUTPUT, SOURCE_CLASSPATH, PERFORMANCE
// }
| import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.util.Map;
import static fr.inria.gforge.spoon.logging.ReportBuilderImpl.ReportKey;
import static fr.inria.gforge.spoon.logging.ReportBuilderImpl.ReportKey.*; | package fr.inria.gforge.spoon.logging;
class ReportDaoImpl implements ReportDao {
private final File resultFile;
ReportDaoImpl(File resultFile) {
this.resultFile = resultFile;
}
@Override | // Path: src/main/java/fr/inria/gforge/spoon/logging/ReportBuilderImpl.java
// enum ReportKey {
// PROJECT_NAME, FRAGMENT_MODE, PROCESSORS, MODULE_NAME, INPUT, OUTPUT, SOURCE_CLASSPATH, PERFORMANCE
// }
//
// Path: src/main/java/fr/inria/gforge/spoon/logging/ReportBuilderImpl.java
// enum ReportKey {
// PROJECT_NAME, FRAGMENT_MODE, PROCESSORS, MODULE_NAME, INPUT, OUTPUT, SOURCE_CLASSPATH, PERFORMANCE
// }
// Path: src/main/java/fr/inria/gforge/spoon/logging/ReportDaoImpl.java
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.util.Map;
import static fr.inria.gforge.spoon.logging.ReportBuilderImpl.ReportKey;
import static fr.inria.gforge.spoon.logging.ReportBuilderImpl.ReportKey.*;
package fr.inria.gforge.spoon.logging;
class ReportDaoImpl implements ReportDao {
private final File resultFile;
ReportDaoImpl(File resultFile) {
this.resultFile = resultFile;
}
@Override | public void save(Map<ReportBuilderImpl.ReportKey, Object> reportsData) { |
SpoonLabs/spoon-maven-plugin | src/test/java/fr/inria/gforge/spoon/unit/XMLLoaderTest.java | // Path: src/main/java/fr/inria/gforge/spoon/util/XMLLoader.java
// public final class XMLLoader {
// private XMLLoader() {
// }
//
// public static SpoonModel load(InputStream inputStream) throws Exception {
// JAXBContext jaxbContext = JAXBContext.newInstance(SpoonModel.class);
// Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
// return (SpoonModel) jaxbUnmarshaller.unmarshal(inputStream);
// }
// }
| import fr.inria.gforge.spoon.SpoonModel;
import fr.inria.gforge.spoon.util.XMLLoader;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat; | package fr.inria.gforge.spoon.unit;
/**
* Created at 19/11/2013 10:14.<br>
*
* @author Christophe DUFOUR
*/
public class XMLLoaderTest {
@Test
public void simpleTest() throws Exception { | // Path: src/main/java/fr/inria/gforge/spoon/util/XMLLoader.java
// public final class XMLLoader {
// private XMLLoader() {
// }
//
// public static SpoonModel load(InputStream inputStream) throws Exception {
// JAXBContext jaxbContext = JAXBContext.newInstance(SpoonModel.class);
// Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
// return (SpoonModel) jaxbUnmarshaller.unmarshal(inputStream);
// }
// }
// Path: src/test/java/fr/inria/gforge/spoon/unit/XMLLoaderTest.java
import fr.inria.gforge.spoon.SpoonModel;
import fr.inria.gforge.spoon.util.XMLLoader;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
package fr.inria.gforge.spoon.unit;
/**
* Created at 19/11/2013 10:14.<br>
*
* @author Christophe DUFOUR
*/
public class XMLLoaderTest {
@Test
public void simpleTest() throws Exception { | final SpoonModel model = XMLLoader.load(XMLLoaderTest.class.getResourceAsStream("spoon.xml")); |
SpoonLabs/spoon-maven-plugin | src/main/java/fr/inria/gforge/spoon/metrics/PerformanceDecorator.java | // Path: src/main/java/fr/inria/gforge/spoon/logging/ReportBuilder.java
// public interface ReportBuilder {
//
// /**
// * Sets project name.
// */
// ReportBuilder setProjectName(String name);
//
// /**
// * Sets processors.
// */
// ReportBuilder setProcessors(String[] processors);
//
// /**
// * Sets name of the module.
// */
// ReportBuilder setModuleName(String name);
//
// /**
// * Sets input directory.
// */
// ReportBuilder setInput(String input);
//
// /**
// * Sets output directory.
// */
// ReportBuilder setOutput(String output);
//
// /**
// * Sets source classpath.
// */
// ReportBuilder setSourceClasspath(String sourceClasspath);
//
// /**
// * Sets performance metric.
// */
// ReportBuilder setPerformance(long performance);
//
// /**
// * Builds the report in a XML file.
// */
// void buildReport();
// }
| import fr.inria.gforge.spoon.logging.ReportBuilder;
import org.apache.maven.plugin.MojoExecutionException;
import spoon.Launcher; | package fr.inria.gforge.spoon.metrics;
public class PerformanceDecorator implements SpoonLauncherDecorator {
private final Launcher launcher; | // Path: src/main/java/fr/inria/gforge/spoon/logging/ReportBuilder.java
// public interface ReportBuilder {
//
// /**
// * Sets project name.
// */
// ReportBuilder setProjectName(String name);
//
// /**
// * Sets processors.
// */
// ReportBuilder setProcessors(String[] processors);
//
// /**
// * Sets name of the module.
// */
// ReportBuilder setModuleName(String name);
//
// /**
// * Sets input directory.
// */
// ReportBuilder setInput(String input);
//
// /**
// * Sets output directory.
// */
// ReportBuilder setOutput(String output);
//
// /**
// * Sets source classpath.
// */
// ReportBuilder setSourceClasspath(String sourceClasspath);
//
// /**
// * Sets performance metric.
// */
// ReportBuilder setPerformance(long performance);
//
// /**
// * Builds the report in a XML file.
// */
// void buildReport();
// }
// Path: src/main/java/fr/inria/gforge/spoon/metrics/PerformanceDecorator.java
import fr.inria.gforge.spoon.logging.ReportBuilder;
import org.apache.maven.plugin.MojoExecutionException;
import spoon.Launcher;
package fr.inria.gforge.spoon.metrics;
public class PerformanceDecorator implements SpoonLauncherDecorator {
private final Launcher launcher; | private final ReportBuilder reportBuilder; |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/SharedPreferenceVault.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/storage/KeyStorageType.java
// public enum KeyStorageType {
// ANDROID_KEYSTORE,
// ANDROID_KEYSTORE_AUTHENTICATED,
// OBFUSCATED,
// NOT_PERSISTENT
// }
| import android.content.SharedPreferences;
import com.bottlerocketstudios.vault.keys.storage.KeyStorageType;
import javax.crypto.SecretKey; | /*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault;
/**
* Shared Preferences backed vault for storing sensitive information.
*/
public interface SharedPreferenceVault extends SharedPreferences {
/**
* Remove all stored values and destroy cryptographic keys associated with the vault instance.
* <strong>This will permanently destroy all data in the preference file.</strong>
*/
void clearStorage();
/**
* Remove all stored values and destroy cryptographic keys associated with the vault instance.
* Configure the vault to use the newly provided key for future data.
* <strong>This will permanently destroy all data in the preference file.</strong>
*/
void rekeyStorage(SecretKey secretKey);
/**
* Arbitrarily set the secret key to a specific value without removing any stored values. This is primarily
* designed for {@link com.bottlerocketstudios.vault.keys.storage.MemoryOnlyKeyStorage} and typical
* usage would be through the {@link #rekeyStorage(SecretKey)} method.
* <strong>If this key is not the right key, existing data may become permanently unreadable.</strong>
*/
void setKey(SecretKey secretKey);
/**
* Determine if this instance of storage currently has a valid key with which to encrypt values.
*/
boolean isKeyAvailable();
/**
* Enable or disable logging operations.
*/
void setDebugEnabled(boolean enabled);
/**
* Determine if logging is enabled.
*/
boolean isDebugEnabled();
/**
* Method to find out expected security level of KeyStorage implementation being used.
*/ | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/storage/KeyStorageType.java
// public enum KeyStorageType {
// ANDROID_KEYSTORE,
// ANDROID_KEYSTORE_AUTHENTICATED,
// OBFUSCATED,
// NOT_PERSISTENT
// }
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/SharedPreferenceVault.java
import android.content.SharedPreferences;
import com.bottlerocketstudios.vault.keys.storage.KeyStorageType;
import javax.crypto.SecretKey;
/*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault;
/**
* Shared Preferences backed vault for storing sensitive information.
*/
public interface SharedPreferenceVault extends SharedPreferences {
/**
* Remove all stored values and destroy cryptographic keys associated with the vault instance.
* <strong>This will permanently destroy all data in the preference file.</strong>
*/
void clearStorage();
/**
* Remove all stored values and destroy cryptographic keys associated with the vault instance.
* Configure the vault to use the newly provided key for future data.
* <strong>This will permanently destroy all data in the preference file.</strong>
*/
void rekeyStorage(SecretKey secretKey);
/**
* Arbitrarily set the secret key to a specific value without removing any stored values. This is primarily
* designed for {@link com.bottlerocketstudios.vault.keys.storage.MemoryOnlyKeyStorage} and typical
* usage would be through the {@link #rekeyStorage(SecretKey)} method.
* <strong>If this key is not the right key, existing data may become permanently unreadable.</strong>
*/
void setKey(SecretKey secretKey);
/**
* Determine if this instance of storage currently has a valid key with which to encrypt values.
*/
boolean isKeyAvailable();
/**
* Enable or disable logging operations.
*/
void setDebugEnabled(boolean enabled);
/**
* Determine if logging is enabled.
*/
boolean isDebugEnabled();
/**
* Method to find out expected security level of KeyStorage implementation being used.
*/ | KeyStorageType getKeyStorageType(); |
BottleRocketStudios/Android-Vault | SampleApplication/app/src/main/java/com/bottlerocketstudios/vaultsampleapplication/ui/BaseSecretActivity.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/SharedPreferenceVault.java
// public interface SharedPreferenceVault extends SharedPreferences {
// /**
// * Remove all stored values and destroy cryptographic keys associated with the vault instance.
// * <strong>This will permanently destroy all data in the preference file.</strong>
// */
// void clearStorage();
//
// /**
// * Remove all stored values and destroy cryptographic keys associated with the vault instance.
// * Configure the vault to use the newly provided key for future data.
// * <strong>This will permanently destroy all data in the preference file.</strong>
// */
// void rekeyStorage(SecretKey secretKey);
//
// /**
// * Arbitrarily set the secret key to a specific value without removing any stored values. This is primarily
// * designed for {@link com.bottlerocketstudios.vault.keys.storage.MemoryOnlyKeyStorage} and typical
// * usage would be through the {@link #rekeyStorage(SecretKey)} method.
// * <strong>If this key is not the right key, existing data may become permanently unreadable.</strong>
// */
// void setKey(SecretKey secretKey);
//
// /**
// * Determine if this instance of storage currently has a valid key with which to encrypt values.
// */
// boolean isKeyAvailable();
//
// /**
// * Enable or disable logging operations.
// */
// void setDebugEnabled(boolean enabled);
//
// /**
// * Determine if logging is enabled.
// */
// boolean isDebugEnabled();
//
// /**
// * Method to find out expected security level of KeyStorage implementation being used.
// */
// KeyStorageType getKeyStorageType();
// }
| import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import com.bottlerocketstudios.vault.SharedPreferenceVault;
import com.bottlerocketstudios.vaultsampleapplication.R; | package com.bottlerocketstudios.vaultsampleapplication.ui;
/**
* Basis for every activity that contains a secret text field.
*/
public abstract class BaseSecretActivity extends AppCompatActivity {
private static final String TAG = BaseSecretActivity.class.getSimpleName();
protected static final int REQUEST_CODE_FIX_LOAD = 123;
protected static final int REQUEST_CODE_FIX_SAVE = 124;
private static final String PREF_SECRET = "theSecret";
protected EditText mSecretText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentViewLayoutId());
mSecretText = (EditText) findViewById(R.id.secret_text);
wireClick(R.id.load_secret, mClickListener);
wireClick(R.id.save_secret, mClickListener);
}
protected abstract int getContentViewLayoutId();
| // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/SharedPreferenceVault.java
// public interface SharedPreferenceVault extends SharedPreferences {
// /**
// * Remove all stored values and destroy cryptographic keys associated with the vault instance.
// * <strong>This will permanently destroy all data in the preference file.</strong>
// */
// void clearStorage();
//
// /**
// * Remove all stored values and destroy cryptographic keys associated with the vault instance.
// * Configure the vault to use the newly provided key for future data.
// * <strong>This will permanently destroy all data in the preference file.</strong>
// */
// void rekeyStorage(SecretKey secretKey);
//
// /**
// * Arbitrarily set the secret key to a specific value without removing any stored values. This is primarily
// * designed for {@link com.bottlerocketstudios.vault.keys.storage.MemoryOnlyKeyStorage} and typical
// * usage would be through the {@link #rekeyStorage(SecretKey)} method.
// * <strong>If this key is not the right key, existing data may become permanently unreadable.</strong>
// */
// void setKey(SecretKey secretKey);
//
// /**
// * Determine if this instance of storage currently has a valid key with which to encrypt values.
// */
// boolean isKeyAvailable();
//
// /**
// * Enable or disable logging operations.
// */
// void setDebugEnabled(boolean enabled);
//
// /**
// * Determine if logging is enabled.
// */
// boolean isDebugEnabled();
//
// /**
// * Method to find out expected security level of KeyStorage implementation being used.
// */
// KeyStorageType getKeyStorageType();
// }
// Path: SampleApplication/app/src/main/java/com/bottlerocketstudios/vaultsampleapplication/ui/BaseSecretActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import com.bottlerocketstudios.vault.SharedPreferenceVault;
import com.bottlerocketstudios.vaultsampleapplication.R;
package com.bottlerocketstudios.vaultsampleapplication.ui;
/**
* Basis for every activity that contains a secret text field.
*/
public abstract class BaseSecretActivity extends AppCompatActivity {
private static final String TAG = BaseSecretActivity.class.getSimpleName();
protected static final int REQUEST_CODE_FIX_LOAD = 123;
protected static final int REQUEST_CODE_FIX_SAVE = 124;
private static final String PREF_SECRET = "theSecret";
protected EditText mSecretText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentViewLayoutId());
mSecretText = (EditText) findViewById(R.id.secret_text);
wireClick(R.id.load_secret, mClickListener);
wireClick(R.id.save_secret, mClickListener);
}
protected abstract int getContentViewLayoutId();
| protected abstract SharedPreferenceVault getVault(); |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/wrapper/AbstractAndroidKeystoreSecretKeyWrapper.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/storage/KeyStorageType.java
// public enum KeyStorageType {
// ANDROID_KEYSTORE,
// ANDROID_KEYSTORE_AUTHENTICATED,
// OBFUSCATED,
// NOT_PERSISTENT
// }
| import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.security.KeyPairGeneratorSpec;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.keys.storage.KeyStorageType;
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.security.auth.x500.X500Principal; | /*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.wrapper;
/**
* Created on 9/20/16.
*/
public abstract class AbstractAndroidKeystoreSecretKeyWrapper implements SecretKeyWrapper {
protected static final String ALGORITHM = "RSA";
protected static final int START_OFFSET = -5; /* -5 mins */
protected static final int CERTIFICATE_LIFE_YEARS = 100;
private final Cipher mCipher;
private final Context mContext;
private KeyPair mKeyPair;
private final String mAlias;
/**
* Create a wrapper using the public/private key pair with the given alias.
* If no pair with that alias exists, it will be generated.
*/
@SuppressLint("GetInstance") //Suppressing ECB mode warning because we use RSA algorithm.
public AbstractAndroidKeystoreSecretKeyWrapper(Context context, String alias)
throws GeneralSecurityException {
mAlias = alias;
mCipher = Cipher.getInstance(getTransformation());
mContext = context.getApplicationContext();
}
protected abstract String getTransformation();
private KeyPair getKeyPair() throws GeneralSecurityException, IOException {
synchronized (mAlias) {
if (mKeyPair == null) { | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/storage/KeyStorageType.java
// public enum KeyStorageType {
// ANDROID_KEYSTORE,
// ANDROID_KEYSTORE_AUTHENTICATED,
// OBFUSCATED,
// NOT_PERSISTENT
// }
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/wrapper/AbstractAndroidKeystoreSecretKeyWrapper.java
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.security.KeyPairGeneratorSpec;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.keys.storage.KeyStorageType;
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.security.auth.x500.X500Principal;
/*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.wrapper;
/**
* Created on 9/20/16.
*/
public abstract class AbstractAndroidKeystoreSecretKeyWrapper implements SecretKeyWrapper {
protected static final String ALGORITHM = "RSA";
protected static final int START_OFFSET = -5; /* -5 mins */
protected static final int CERTIFICATE_LIFE_YEARS = 100;
private final Cipher mCipher;
private final Context mContext;
private KeyPair mKeyPair;
private final String mAlias;
/**
* Create a wrapper using the public/private key pair with the given alias.
* If no pair with that alias exists, it will be generated.
*/
@SuppressLint("GetInstance") //Suppressing ECB mode warning because we use RSA algorithm.
public AbstractAndroidKeystoreSecretKeyWrapper(Context context, String alias)
throws GeneralSecurityException {
mAlias = alias;
mCipher = Cipher.getInstance(getTransformation());
mContext = context.getApplicationContext();
}
protected abstract String getTransformation();
private KeyPair getKeyPair() throws GeneralSecurityException, IOException {
synchronized (mAlias) {
if (mKeyPair == null) { | final KeyStore keyStore = KeyStore.getInstance(EncryptionConstants.ANDROID_KEY_STORE); |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/wrapper/AbstractAndroidKeystoreSecretKeyWrapper.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/storage/KeyStorageType.java
// public enum KeyStorageType {
// ANDROID_KEYSTORE,
// ANDROID_KEYSTORE_AUTHENTICATED,
// OBFUSCATED,
// NOT_PERSISTENT
// }
| import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.security.KeyPairGeneratorSpec;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.keys.storage.KeyStorageType;
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.security.auth.x500.X500Principal; | public synchronized SecretKey unwrap(byte[] blob, String wrappedKeyAlgorithm) throws GeneralSecurityException, IOException {
AlgorithmParameterSpec spec = buildCipherAlgorithmParameterSpec();
if (spec == null) {
mCipher.init(Cipher.UNWRAP_MODE, getKeyPair().getPrivate());
} else {
mCipher.init(Cipher.UNWRAP_MODE, getKeyPair().getPrivate(), spec);
}
return (SecretKey) mCipher.unwrap(blob, wrappedKeyAlgorithm, Cipher.SECRET_KEY);
}
@Override
public synchronized void clearKey(Context context) throws GeneralSecurityException, IOException {
mKeyPair = null;
final KeyStore keyStore = KeyStore.getInstance(EncryptionConstants.ANDROID_KEY_STORE);
keyStore.load(null);
keyStore.deleteEntry(mAlias);
}
public AlgorithmParameterSpec buildCipherAlgorithmParameterSpec() {
return null;
}
public boolean testKey() throws GeneralSecurityException, IOException {
KeyPair keyPair = getKeyPair();
if (keyPair == null) return false;
//Create a throwaway AES key to ensure that both wrap and unwrap operations work properly. | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/storage/KeyStorageType.java
// public enum KeyStorageType {
// ANDROID_KEYSTORE,
// ANDROID_KEYSTORE_AUTHENTICATED,
// OBFUSCATED,
// NOT_PERSISTENT
// }
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/wrapper/AbstractAndroidKeystoreSecretKeyWrapper.java
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.security.KeyPairGeneratorSpec;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.keys.storage.KeyStorageType;
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.security.auth.x500.X500Principal;
public synchronized SecretKey unwrap(byte[] blob, String wrappedKeyAlgorithm) throws GeneralSecurityException, IOException {
AlgorithmParameterSpec spec = buildCipherAlgorithmParameterSpec();
if (spec == null) {
mCipher.init(Cipher.UNWRAP_MODE, getKeyPair().getPrivate());
} else {
mCipher.init(Cipher.UNWRAP_MODE, getKeyPair().getPrivate(), spec);
}
return (SecretKey) mCipher.unwrap(blob, wrappedKeyAlgorithm, Cipher.SECRET_KEY);
}
@Override
public synchronized void clearKey(Context context) throws GeneralSecurityException, IOException {
mKeyPair = null;
final KeyStore keyStore = KeyStore.getInstance(EncryptionConstants.ANDROID_KEY_STORE);
keyStore.load(null);
keyStore.deleteEntry(mAlias);
}
public AlgorithmParameterSpec buildCipherAlgorithmParameterSpec() {
return null;
}
public boolean testKey() throws GeneralSecurityException, IOException {
KeyPair keyPair = getKeyPair();
if (keyPair == null) return false;
//Create a throwaway AES key to ensure that both wrap and unwrap operations work properly. | SecretKey secretKey = Aes256RandomKeyFactory.createKey(); |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/wrapper/AbstractAndroidKeystoreSecretKeyWrapper.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/storage/KeyStorageType.java
// public enum KeyStorageType {
// ANDROID_KEYSTORE,
// ANDROID_KEYSTORE_AUTHENTICATED,
// OBFUSCATED,
// NOT_PERSISTENT
// }
| import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.security.KeyPairGeneratorSpec;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.keys.storage.KeyStorageType;
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.security.auth.x500.X500Principal; | }
return (SecretKey) mCipher.unwrap(blob, wrappedKeyAlgorithm, Cipher.SECRET_KEY);
}
@Override
public synchronized void clearKey(Context context) throws GeneralSecurityException, IOException {
mKeyPair = null;
final KeyStore keyStore = KeyStore.getInstance(EncryptionConstants.ANDROID_KEY_STORE);
keyStore.load(null);
keyStore.deleteEntry(mAlias);
}
public AlgorithmParameterSpec buildCipherAlgorithmParameterSpec() {
return null;
}
public boolean testKey() throws GeneralSecurityException, IOException {
KeyPair keyPair = getKeyPair();
if (keyPair == null) return false;
//Create a throwaway AES key to ensure that both wrap and unwrap operations work properly.
SecretKey secretKey = Aes256RandomKeyFactory.createKey();
byte[] wrapped = wrap(secretKey);
SecretKey unwrapped = unwrap(wrapped, EncryptionConstants.AES_CIPHER);
return unwrapped != null && Arrays.equals(unwrapped.getEncoded(), secretKey.getEncoded());
}
@Override | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/storage/KeyStorageType.java
// public enum KeyStorageType {
// ANDROID_KEYSTORE,
// ANDROID_KEYSTORE_AUTHENTICATED,
// OBFUSCATED,
// NOT_PERSISTENT
// }
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/wrapper/AbstractAndroidKeystoreSecretKeyWrapper.java
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.security.KeyPairGeneratorSpec;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.keys.storage.KeyStorageType;
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.security.auth.x500.X500Principal;
}
return (SecretKey) mCipher.unwrap(blob, wrappedKeyAlgorithm, Cipher.SECRET_KEY);
}
@Override
public synchronized void clearKey(Context context) throws GeneralSecurityException, IOException {
mKeyPair = null;
final KeyStore keyStore = KeyStore.getInstance(EncryptionConstants.ANDROID_KEY_STORE);
keyStore.load(null);
keyStore.deleteEntry(mAlias);
}
public AlgorithmParameterSpec buildCipherAlgorithmParameterSpec() {
return null;
}
public boolean testKey() throws GeneralSecurityException, IOException {
KeyPair keyPair = getKeyPair();
if (keyPair == null) return false;
//Create a throwaway AES key to ensure that both wrap and unwrap operations work properly.
SecretKey secretKey = Aes256RandomKeyFactory.createKey();
byte[] wrapped = wrap(secretKey);
SecretKey unwrapped = unwrap(wrapped, EncryptionConstants.AES_CIPHER);
return unwrapped != null && Arrays.equals(unwrapped.getEncoded(), secretKey.getEncoded());
}
@Override | public KeyStorageType getKeyStorageType() { |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/storage/SharedPrefKeyStorage.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/wrapper/SecretKeyWrapper.java
// public interface SecretKeyWrapper {
// /**
// * Wrap a {@link javax.crypto.SecretKey} using the public key assigned to this wrapper.
// * Use {@link #unwrap(byte[], String)} to later recover the original
// * {@link javax.crypto.SecretKey}.
// *
// * @return a wrapped version of the given {@link javax.crypto.SecretKey} that can be
// * safely stored on untrusted storage.
// */
// byte[] wrap(SecretKey key) throws GeneralSecurityException, IOException;
//
// /**
// * Unwrap a {@link javax.crypto.SecretKey} using the private key assigned to this
// * wrapper.
// *
// * @param blob a wrapped {@link javax.crypto.SecretKey} as previously returned by
// * {@link #wrap(javax.crypto.SecretKey)}.
// */
// SecretKey unwrap(byte[] blob, String wrappedKeyAlgorithm) throws GeneralSecurityException, IOException;
//
// /**
// * Change key material so that next wrapping will use a different key pair.
// * @throws GeneralSecurityException
// */
// void clearKey(Context context) throws GeneralSecurityException, IOException;
//
// public KeyStorageType getKeyStorageType();
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;
import android.util.Log;
import com.bottlerocketstudios.vault.keys.wrapper.SecretKeyWrapper;
import java.io.IOException;
import java.security.GeneralSecurityException;
import javax.crypto.SecretKey; | /*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.storage;
/**
* Storage system using SharedPreference file to retain SecretKeys.
*/
public class SharedPrefKeyStorage implements KeyStorage {
private static final String TAG = SharedPrefKeyStorage.class.getSimpleName();
private static final String PREF_ROOT = "vaultedBlobV2.";
| // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/wrapper/SecretKeyWrapper.java
// public interface SecretKeyWrapper {
// /**
// * Wrap a {@link javax.crypto.SecretKey} using the public key assigned to this wrapper.
// * Use {@link #unwrap(byte[], String)} to later recover the original
// * {@link javax.crypto.SecretKey}.
// *
// * @return a wrapped version of the given {@link javax.crypto.SecretKey} that can be
// * safely stored on untrusted storage.
// */
// byte[] wrap(SecretKey key) throws GeneralSecurityException, IOException;
//
// /**
// * Unwrap a {@link javax.crypto.SecretKey} using the private key assigned to this
// * wrapper.
// *
// * @param blob a wrapped {@link javax.crypto.SecretKey} as previously returned by
// * {@link #wrap(javax.crypto.SecretKey)}.
// */
// SecretKey unwrap(byte[] blob, String wrappedKeyAlgorithm) throws GeneralSecurityException, IOException;
//
// /**
// * Change key material so that next wrapping will use a different key pair.
// * @throws GeneralSecurityException
// */
// void clearKey(Context context) throws GeneralSecurityException, IOException;
//
// public KeyStorageType getKeyStorageType();
// }
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/storage/SharedPrefKeyStorage.java
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;
import android.util.Log;
import com.bottlerocketstudios.vault.keys.wrapper.SecretKeyWrapper;
import java.io.IOException;
import java.security.GeneralSecurityException;
import javax.crypto.SecretKey;
/*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.storage;
/**
* Storage system using SharedPreference file to retain SecretKeys.
*/
public class SharedPrefKeyStorage implements KeyStorage {
private static final String TAG = SharedPrefKeyStorage.class.getSimpleName();
private static final String PREF_ROOT = "vaultedBlobV2.";
| private final SecretKeyWrapper mSecretKeyWrapper; |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256KeyFromPasswordFactory.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/SaltGenerator.java
// public interface SaltGenerator {
// byte[] createSaltBytes(int size);
// }
| import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import com.bottlerocketstudios.vault.salt.SaltGenerator;
import javax.crypto.SecretKey; | /*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.generator;
/**
* Create an AES256 key from a user supplied password.
*/
public class Aes256KeyFromPasswordFactory {
public static final int SALT_SIZE_BYTES = 512;
/**
* This will execute the key generation for the number of supplied iterations and use a unique random salt.
* This will block for a while depending on processor speed.
*/
public static SecretKey createKey(String password, int pbkdfIterations) { | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/SaltGenerator.java
// public interface SaltGenerator {
// byte[] createSaltBytes(int size);
// }
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256KeyFromPasswordFactory.java
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import com.bottlerocketstudios.vault.salt.SaltGenerator;
import javax.crypto.SecretKey;
/*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.generator;
/**
* Create an AES256 key from a user supplied password.
*/
public class Aes256KeyFromPasswordFactory {
public static final int SALT_SIZE_BYTES = 512;
/**
* This will execute the key generation for the number of supplied iterations and use a unique random salt.
* This will block for a while depending on processor speed.
*/
public static SecretKey createKey(String password, int pbkdfIterations) { | return createKey(password, pbkdfIterations, new PrngSaltGenerator()); |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256KeyFromPasswordFactory.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/SaltGenerator.java
// public interface SaltGenerator {
// byte[] createSaltBytes(int size);
// }
| import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import com.bottlerocketstudios.vault.salt.SaltGenerator;
import javax.crypto.SecretKey; | /*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.generator;
/**
* Create an AES256 key from a user supplied password.
*/
public class Aes256KeyFromPasswordFactory {
public static final int SALT_SIZE_BYTES = 512;
/**
* This will execute the key generation for the number of supplied iterations and use a unique random salt.
* This will block for a while depending on processor speed.
*/
public static SecretKey createKey(String password, int pbkdfIterations) {
return createKey(password, pbkdfIterations, new PrngSaltGenerator());
}
/**
* This will execute the key generation for the number of supplied iterations and use salt from the
* supplied source. This will block for a while depending on processor speed.
*/ | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/SaltGenerator.java
// public interface SaltGenerator {
// byte[] createSaltBytes(int size);
// }
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256KeyFromPasswordFactory.java
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import com.bottlerocketstudios.vault.salt.SaltGenerator;
import javax.crypto.SecretKey;
/*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.generator;
/**
* Create an AES256 key from a user supplied password.
*/
public class Aes256KeyFromPasswordFactory {
public static final int SALT_SIZE_BYTES = 512;
/**
* This will execute the key generation for the number of supplied iterations and use a unique random salt.
* This will block for a while depending on processor speed.
*/
public static SecretKey createKey(String password, int pbkdfIterations) {
return createKey(password, pbkdfIterations, new PrngSaltGenerator());
}
/**
* This will execute the key generation for the number of supplied iterations and use salt from the
* supplied source. This will block for a while depending on processor speed.
*/ | public static SecretKey createKey(String password, int pbkdfIterations, SaltGenerator saltGenerator) { |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256KeyFromPasswordFactory.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/SaltGenerator.java
// public interface SaltGenerator {
// byte[] createSaltBytes(int size);
// }
| import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import com.bottlerocketstudios.vault.salt.SaltGenerator;
import javax.crypto.SecretKey; | /*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.generator;
/**
* Create an AES256 key from a user supplied password.
*/
public class Aes256KeyFromPasswordFactory {
public static final int SALT_SIZE_BYTES = 512;
/**
* This will execute the key generation for the number of supplied iterations and use a unique random salt.
* This will block for a while depending on processor speed.
*/
public static SecretKey createKey(String password, int pbkdfIterations) {
return createKey(password, pbkdfIterations, new PrngSaltGenerator());
}
/**
* This will execute the key generation for the number of supplied iterations and use salt from the
* supplied source. This will block for a while depending on processor speed.
*/
public static SecretKey createKey(String password, int pbkdfIterations, SaltGenerator saltGenerator) { | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/SaltGenerator.java
// public interface SaltGenerator {
// byte[] createSaltBytes(int size);
// }
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256KeyFromPasswordFactory.java
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import com.bottlerocketstudios.vault.salt.SaltGenerator;
import javax.crypto.SecretKey;
/*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.generator;
/**
* Create an AES256 key from a user supplied password.
*/
public class Aes256KeyFromPasswordFactory {
public static final int SALT_SIZE_BYTES = 512;
/**
* This will execute the key generation for the number of supplied iterations and use a unique random salt.
* This will block for a while depending on processor speed.
*/
public static SecretKey createKey(String password, int pbkdfIterations) {
return createKey(password, pbkdfIterations, new PrngSaltGenerator());
}
/**
* This will execute the key generation for the number of supplied iterations and use salt from the
* supplied source. This will block for a while depending on processor speed.
*/
public static SecretKey createKey(String password, int pbkdfIterations, SaltGenerator saltGenerator) { | PbkdfKeyGenerator keyGenerator = new PbkdfKeyGenerator(pbkdfIterations, EncryptionConstants.AES_256_KEY_LENGTH_BITS, saltGenerator, SALT_SIZE_BYTES); |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/StandardSharedPreferenceVault.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/storage/KeyStorage.java
// public interface KeyStorage {
// /**
// * Load key from storage
// * @return Key if available or null
// */
// SecretKey loadKey(Context context);
//
// /**
// * Save key to storage
// * @return True if successful
// */
// boolean saveKey(Context context, SecretKey secretKey);
//
// /**
// * Remove key from storage
// */
// void clearKey(Context context);
//
// /**
// * Determine if key is available
// */
// boolean hasKey(Context context);
//
// /**
// * Return the type of key storage used.
// */
// KeyStorageType getKeyStorageType();
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/storage/KeyStorageType.java
// public enum KeyStorageType {
// ANDROID_KEYSTORE,
// ANDROID_KEYSTORE_AUTHENTICATED,
// OBFUSCATED,
// NOT_PERSISTENT
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import com.bottlerocketstudios.vault.keys.storage.KeyStorage;
import com.bottlerocketstudios.vault.keys.storage.KeyStorageType;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import javax.crypto.SecretKey; | /*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault;
/**
* SecureVault backed by a SharedPreference file.
*/
public class StandardSharedPreferenceVault implements SharedPreferenceVault {
private static final String TAG = StandardSharedPreferenceVault.class.getSimpleName();
private static final String STRING_SET_SEPARATOR = "1eRHtJaybutdAsFp2DkfrT1FqMJlLfT7DdgCpQtTaoQWheoeFBZRqt5pgFDH7Cf";
private static final Pattern FLOAT_REGEX = Pattern.compile("^-?\\d+\\.\\d+$");
private static final Pattern INTEGER_REGEX = Pattern.compile("^-?\\d+$");
private static final Pattern BOOLEAN_REGEX = Pattern.compile("^(true|false)$");
private final Context mContext;
private final boolean mEnableExceptions;
private final String mTransform; | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/storage/KeyStorage.java
// public interface KeyStorage {
// /**
// * Load key from storage
// * @return Key if available or null
// */
// SecretKey loadKey(Context context);
//
// /**
// * Save key to storage
// * @return True if successful
// */
// boolean saveKey(Context context, SecretKey secretKey);
//
// /**
// * Remove key from storage
// */
// void clearKey(Context context);
//
// /**
// * Determine if key is available
// */
// boolean hasKey(Context context);
//
// /**
// * Return the type of key storage used.
// */
// KeyStorageType getKeyStorageType();
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/storage/KeyStorageType.java
// public enum KeyStorageType {
// ANDROID_KEYSTORE,
// ANDROID_KEYSTORE_AUTHENTICATED,
// OBFUSCATED,
// NOT_PERSISTENT
// }
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/StandardSharedPreferenceVault.java
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import com.bottlerocketstudios.vault.keys.storage.KeyStorage;
import com.bottlerocketstudios.vault.keys.storage.KeyStorageType;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import javax.crypto.SecretKey;
/*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault;
/**
* SecureVault backed by a SharedPreference file.
*/
public class StandardSharedPreferenceVault implements SharedPreferenceVault {
private static final String TAG = StandardSharedPreferenceVault.class.getSimpleName();
private static final String STRING_SET_SEPARATOR = "1eRHtJaybutdAsFp2DkfrT1FqMJlLfT7DdgCpQtTaoQWheoeFBZRqt5pgFDH7Cf";
private static final Pattern FLOAT_REGEX = Pattern.compile("^-?\\d+\\.\\d+$");
private static final Pattern INTEGER_REGEX = Pattern.compile("^-?\\d+$");
private static final Pattern BOOLEAN_REGEX = Pattern.compile("^(true|false)$");
private final Context mContext;
private final boolean mEnableExceptions;
private final String mTransform; | private final KeyStorage mKeyStorage; |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/StandardSharedPreferenceVault.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/storage/KeyStorage.java
// public interface KeyStorage {
// /**
// * Load key from storage
// * @return Key if available or null
// */
// SecretKey loadKey(Context context);
//
// /**
// * Save key to storage
// * @return True if successful
// */
// boolean saveKey(Context context, SecretKey secretKey);
//
// /**
// * Remove key from storage
// */
// void clearKey(Context context);
//
// /**
// * Determine if key is available
// */
// boolean hasKey(Context context);
//
// /**
// * Return the type of key storage used.
// */
// KeyStorageType getKeyStorageType();
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/storage/KeyStorageType.java
// public enum KeyStorageType {
// ANDROID_KEYSTORE,
// ANDROID_KEYSTORE_AUTHENTICATED,
// OBFUSCATED,
// NOT_PERSISTENT
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import com.bottlerocketstudios.vault.keys.storage.KeyStorage;
import com.bottlerocketstudios.vault.keys.storage.KeyStorageType;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import javax.crypto.SecretKey; | mKeyStorage.clearKey(mContext);
}
@Override
public void rekeyStorage(SecretKey secretKey) {
clearStorage();
setKey(secretKey);
}
@Override
public void setKey(SecretKey secretKey) {
mKeyStorage.saveKey(mContext, secretKey);
}
@Override
public boolean isKeyAvailable() {
return mKeyStorage.hasKey(mContext);
}
@Override
public void setDebugEnabled(boolean enabled) {
mDebugEnabled = enabled;
}
@Override
public boolean isDebugEnabled() {
return mDebugEnabled;
}
@Override | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/storage/KeyStorage.java
// public interface KeyStorage {
// /**
// * Load key from storage
// * @return Key if available or null
// */
// SecretKey loadKey(Context context);
//
// /**
// * Save key to storage
// * @return True if successful
// */
// boolean saveKey(Context context, SecretKey secretKey);
//
// /**
// * Remove key from storage
// */
// void clearKey(Context context);
//
// /**
// * Determine if key is available
// */
// boolean hasKey(Context context);
//
// /**
// * Return the type of key storage used.
// */
// KeyStorageType getKeyStorageType();
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/storage/KeyStorageType.java
// public enum KeyStorageType {
// ANDROID_KEYSTORE,
// ANDROID_KEYSTORE_AUTHENTICATED,
// OBFUSCATED,
// NOT_PERSISTENT
// }
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/StandardSharedPreferenceVault.java
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import com.bottlerocketstudios.vault.keys.storage.KeyStorage;
import com.bottlerocketstudios.vault.keys.storage.KeyStorageType;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import javax.crypto.SecretKey;
mKeyStorage.clearKey(mContext);
}
@Override
public void rekeyStorage(SecretKey secretKey) {
clearStorage();
setKey(secretKey);
}
@Override
public void setKey(SecretKey secretKey) {
mKeyStorage.saveKey(mContext, secretKey);
}
@Override
public boolean isKeyAvailable() {
return mKeyStorage.hasKey(mContext);
}
@Override
public void setDebugEnabled(boolean enabled) {
mDebugEnabled = enabled;
}
@Override
public boolean isDebugEnabled() {
return mDebugEnabled;
}
@Override | public KeyStorageType getKeyStorageType() { |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/keys/storage/TestVaultOaepUpgrade.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
| import android.os.Build;
import android.test.AndroidTestCase;
import android.util.Log;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import javax.crypto.SecretKey; | /*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.storage;
/**
* Created on 9/21/16.
*/
public class TestVaultOaepUpgrade extends AndroidTestCase {
private static final String TAG = TestVaultUpgradePre18.class.getSimpleName();
private static final String KEY_FILE_NAME = "OaepUpgradeKeyFile";
private static final String KEY_ALIAS_1 = "OaepUpgradeKeyAlias";
private static final int KEY_INDEX_1 = 1223422;
private static final String PRESHARED_SECRET_1 = "a;sdlfkja;asdfa4548w1211xji22e;l2ihjl9jl9dj9";
public void testUpgrade() {
assertTrue("This test will not pass below API 23", Build.VERSION.SDK_INT >= Build.VERSION_CODES.M);
try { | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
// Path: AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/keys/storage/TestVaultOaepUpgrade.java
import android.os.Build;
import android.test.AndroidTestCase;
import android.util.Log;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import javax.crypto.SecretKey;
/*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.storage;
/**
* Created on 9/21/16.
*/
public class TestVaultOaepUpgrade extends AndroidTestCase {
private static final String TAG = TestVaultUpgradePre18.class.getSimpleName();
private static final String KEY_FILE_NAME = "OaepUpgradeKeyFile";
private static final String KEY_ALIAS_1 = "OaepUpgradeKeyAlias";
private static final int KEY_INDEX_1 = 1223422;
private static final String PRESHARED_SECRET_1 = "a;sdlfkja;asdfa4548w1211xji22e;l2ihjl9jl9dj9";
public void testUpgrade() {
assertTrue("This test will not pass below API 23", Build.VERSION.SDK_INT >= Build.VERSION_CODES.M);
try { | SecretKey originalKey = Aes256RandomKeyFactory.createKey(); |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/keys/storage/TestVaultOaepUpgrade.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
| import android.os.Build;
import android.test.AndroidTestCase;
import android.util.Log;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import javax.crypto.SecretKey; | SecretKey originalReadKey = keyStorageOld.loadKey(getContext());
assertNotNull("Key was null after creation and read from old storage.", originalReadKey);
assertTrue("Keys were not identical after creation and read from old storage", Arrays.equals(originalKey.getEncoded(), originalReadKey.getEncoded()));
KeyStorage keyStorageNew = getKeyStorage(CompatSharedPrefKeyStorageFactory.WRAPPER_TYPE_RSA_PKCS1, CompatSharedPrefKeyStorageFactory.WRAPPER_TYPE_RSA_OAEP);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageNew.getKeyStorageType());
SecretKey upgradedKey = keyStorageNew.loadKey(getContext());
assertNotNull("Key was null after upgrade.", upgradedKey);
assertTrue("Keys were not identical after upgrade", Arrays.equals(originalKey.getEncoded(), upgradedKey.getEncoded()));
KeyStorage keyStorageRead = getKeyStorage(CompatSharedPrefKeyStorageFactory.WRAPPER_TYPE_RSA_OAEP, CompatSharedPrefKeyStorageFactory.WRAPPER_TYPE_RSA_OAEP);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageRead.getKeyStorageType());
SecretKey upgradedReadKey = keyStorageRead.loadKey(getContext());
assertNotNull("Key was null after upgrade and read from storage.", upgradedReadKey);
assertTrue("Keys were not identical after upgrade and read from storage", Arrays.equals(originalKey.getEncoded(), upgradedReadKey.getEncoded()));
} catch (GeneralSecurityException e) {
Log.e(TAG, "Caught java.security.GeneralSecurityException", e);
assertTrue("Exception when creating keystores", false);
}
}
private KeyStorage getKeyStorage(int oldWrapperType, int newWrapperType) throws GeneralSecurityException {
return CompatSharedPrefKeyStorageFactory.createKeyStorage(
getContext(),
Build.VERSION.SDK_INT,
KEY_FILE_NAME,
KEY_ALIAS_1,
KEY_INDEX_1, | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
// Path: AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/keys/storage/TestVaultOaepUpgrade.java
import android.os.Build;
import android.test.AndroidTestCase;
import android.util.Log;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import javax.crypto.SecretKey;
SecretKey originalReadKey = keyStorageOld.loadKey(getContext());
assertNotNull("Key was null after creation and read from old storage.", originalReadKey);
assertTrue("Keys were not identical after creation and read from old storage", Arrays.equals(originalKey.getEncoded(), originalReadKey.getEncoded()));
KeyStorage keyStorageNew = getKeyStorage(CompatSharedPrefKeyStorageFactory.WRAPPER_TYPE_RSA_PKCS1, CompatSharedPrefKeyStorageFactory.WRAPPER_TYPE_RSA_OAEP);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageNew.getKeyStorageType());
SecretKey upgradedKey = keyStorageNew.loadKey(getContext());
assertNotNull("Key was null after upgrade.", upgradedKey);
assertTrue("Keys were not identical after upgrade", Arrays.equals(originalKey.getEncoded(), upgradedKey.getEncoded()));
KeyStorage keyStorageRead = getKeyStorage(CompatSharedPrefKeyStorageFactory.WRAPPER_TYPE_RSA_OAEP, CompatSharedPrefKeyStorageFactory.WRAPPER_TYPE_RSA_OAEP);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageRead.getKeyStorageType());
SecretKey upgradedReadKey = keyStorageRead.loadKey(getContext());
assertNotNull("Key was null after upgrade and read from storage.", upgradedReadKey);
assertTrue("Keys were not identical after upgrade and read from storage", Arrays.equals(originalKey.getEncoded(), upgradedReadKey.getEncoded()));
} catch (GeneralSecurityException e) {
Log.e(TAG, "Caught java.security.GeneralSecurityException", e);
assertTrue("Exception when creating keystores", false);
}
}
private KeyStorage getKeyStorage(int oldWrapperType, int newWrapperType) throws GeneralSecurityException {
return CompatSharedPrefKeyStorageFactory.createKeyStorage(
getContext(),
Build.VERSION.SDK_INT,
KEY_FILE_NAME,
KEY_ALIAS_1,
KEY_INDEX_1, | EncryptionConstants.AES_CIPHER, |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/keys/storage/TestVaultOaepUpgrade.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
| import android.os.Build;
import android.test.AndroidTestCase;
import android.util.Log;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import javax.crypto.SecretKey; | assertTrue("Keys were not identical after creation and read from old storage", Arrays.equals(originalKey.getEncoded(), originalReadKey.getEncoded()));
KeyStorage keyStorageNew = getKeyStorage(CompatSharedPrefKeyStorageFactory.WRAPPER_TYPE_RSA_PKCS1, CompatSharedPrefKeyStorageFactory.WRAPPER_TYPE_RSA_OAEP);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageNew.getKeyStorageType());
SecretKey upgradedKey = keyStorageNew.loadKey(getContext());
assertNotNull("Key was null after upgrade.", upgradedKey);
assertTrue("Keys were not identical after upgrade", Arrays.equals(originalKey.getEncoded(), upgradedKey.getEncoded()));
KeyStorage keyStorageRead = getKeyStorage(CompatSharedPrefKeyStorageFactory.WRAPPER_TYPE_RSA_OAEP, CompatSharedPrefKeyStorageFactory.WRAPPER_TYPE_RSA_OAEP);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageRead.getKeyStorageType());
SecretKey upgradedReadKey = keyStorageRead.loadKey(getContext());
assertNotNull("Key was null after upgrade and read from storage.", upgradedReadKey);
assertTrue("Keys were not identical after upgrade and read from storage", Arrays.equals(originalKey.getEncoded(), upgradedReadKey.getEncoded()));
} catch (GeneralSecurityException e) {
Log.e(TAG, "Caught java.security.GeneralSecurityException", e);
assertTrue("Exception when creating keystores", false);
}
}
private KeyStorage getKeyStorage(int oldWrapperType, int newWrapperType) throws GeneralSecurityException {
return CompatSharedPrefKeyStorageFactory.createKeyStorage(
getContext(),
Build.VERSION.SDK_INT,
KEY_FILE_NAME,
KEY_ALIAS_1,
KEY_INDEX_1,
EncryptionConstants.AES_CIPHER,
PRESHARED_SECRET_1, | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
// Path: AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/keys/storage/TestVaultOaepUpgrade.java
import android.os.Build;
import android.test.AndroidTestCase;
import android.util.Log;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import javax.crypto.SecretKey;
assertTrue("Keys were not identical after creation and read from old storage", Arrays.equals(originalKey.getEncoded(), originalReadKey.getEncoded()));
KeyStorage keyStorageNew = getKeyStorage(CompatSharedPrefKeyStorageFactory.WRAPPER_TYPE_RSA_PKCS1, CompatSharedPrefKeyStorageFactory.WRAPPER_TYPE_RSA_OAEP);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageNew.getKeyStorageType());
SecretKey upgradedKey = keyStorageNew.loadKey(getContext());
assertNotNull("Key was null after upgrade.", upgradedKey);
assertTrue("Keys were not identical after upgrade", Arrays.equals(originalKey.getEncoded(), upgradedKey.getEncoded()));
KeyStorage keyStorageRead = getKeyStorage(CompatSharedPrefKeyStorageFactory.WRAPPER_TYPE_RSA_OAEP, CompatSharedPrefKeyStorageFactory.WRAPPER_TYPE_RSA_OAEP);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageRead.getKeyStorageType());
SecretKey upgradedReadKey = keyStorageRead.loadKey(getContext());
assertNotNull("Key was null after upgrade and read from storage.", upgradedReadKey);
assertTrue("Keys were not identical after upgrade and read from storage", Arrays.equals(originalKey.getEncoded(), upgradedReadKey.getEncoded()));
} catch (GeneralSecurityException e) {
Log.e(TAG, "Caught java.security.GeneralSecurityException", e);
assertTrue("Exception when creating keystores", false);
}
}
private KeyStorage getKeyStorage(int oldWrapperType, int newWrapperType) throws GeneralSecurityException {
return CompatSharedPrefKeyStorageFactory.createKeyStorage(
getContext(),
Build.VERSION.SDK_INT,
KEY_FILE_NAME,
KEY_ALIAS_1,
KEY_INDEX_1,
EncryptionConstants.AES_CIPHER,
PRESHARED_SECRET_1, | new PrngSaltGenerator(), |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/test/TestKeyGeneration.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256KeyFromPasswordFactory.java
// public class Aes256KeyFromPasswordFactory {
//
// public static final int SALT_SIZE_BYTES = 512;
//
// /**
// * This will execute the key generation for the number of supplied iterations and use a unique random salt.
// * This will block for a while depending on processor speed.
// */
// public static SecretKey createKey(String password, int pbkdfIterations) {
// return createKey(password, pbkdfIterations, new PrngSaltGenerator());
// }
//
// /**
// * This will execute the key generation for the number of supplied iterations and use salt from the
// * supplied source. This will block for a while depending on processor speed.
// */
// public static SecretKey createKey(String password, int pbkdfIterations, SaltGenerator saltGenerator) {
// PbkdfKeyGenerator keyGenerator = new PbkdfKeyGenerator(pbkdfIterations, EncryptionConstants.AES_256_KEY_LENGTH_BITS, saltGenerator, SALT_SIZE_BYTES);
// return keyGenerator.generateKey(password);
// }
//
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
| import android.test.AndroidTestCase;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256KeyFromPasswordFactory;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import javax.crypto.SecretKey; | /*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.test;
/**
* Test secret key creation.
*/
public class TestKeyGeneration extends AndroidTestCase {
public void testRandomKey() { | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256KeyFromPasswordFactory.java
// public class Aes256KeyFromPasswordFactory {
//
// public static final int SALT_SIZE_BYTES = 512;
//
// /**
// * This will execute the key generation for the number of supplied iterations and use a unique random salt.
// * This will block for a while depending on processor speed.
// */
// public static SecretKey createKey(String password, int pbkdfIterations) {
// return createKey(password, pbkdfIterations, new PrngSaltGenerator());
// }
//
// /**
// * This will execute the key generation for the number of supplied iterations and use salt from the
// * supplied source. This will block for a while depending on processor speed.
// */
// public static SecretKey createKey(String password, int pbkdfIterations, SaltGenerator saltGenerator) {
// PbkdfKeyGenerator keyGenerator = new PbkdfKeyGenerator(pbkdfIterations, EncryptionConstants.AES_256_KEY_LENGTH_BITS, saltGenerator, SALT_SIZE_BYTES);
// return keyGenerator.generateKey(password);
// }
//
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
// Path: AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/test/TestKeyGeneration.java
import android.test.AndroidTestCase;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256KeyFromPasswordFactory;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import javax.crypto.SecretKey;
/*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.test;
/**
* Test secret key creation.
*/
public class TestKeyGeneration extends AndroidTestCase {
public void testRandomKey() { | SecretKey secretKey = Aes256RandomKeyFactory.createKey(); |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/test/TestKeyGeneration.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256KeyFromPasswordFactory.java
// public class Aes256KeyFromPasswordFactory {
//
// public static final int SALT_SIZE_BYTES = 512;
//
// /**
// * This will execute the key generation for the number of supplied iterations and use a unique random salt.
// * This will block for a while depending on processor speed.
// */
// public static SecretKey createKey(String password, int pbkdfIterations) {
// return createKey(password, pbkdfIterations, new PrngSaltGenerator());
// }
//
// /**
// * This will execute the key generation for the number of supplied iterations and use salt from the
// * supplied source. This will block for a while depending on processor speed.
// */
// public static SecretKey createKey(String password, int pbkdfIterations, SaltGenerator saltGenerator) {
// PbkdfKeyGenerator keyGenerator = new PbkdfKeyGenerator(pbkdfIterations, EncryptionConstants.AES_256_KEY_LENGTH_BITS, saltGenerator, SALT_SIZE_BYTES);
// return keyGenerator.generateKey(password);
// }
//
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
| import android.test.AndroidTestCase;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256KeyFromPasswordFactory;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import javax.crypto.SecretKey; | /*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.test;
/**
* Test secret key creation.
*/
public class TestKeyGeneration extends AndroidTestCase {
public void testRandomKey() {
SecretKey secretKey = Aes256RandomKeyFactory.createKey();
assertNotNull("Secret key was not created", secretKey); | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256KeyFromPasswordFactory.java
// public class Aes256KeyFromPasswordFactory {
//
// public static final int SALT_SIZE_BYTES = 512;
//
// /**
// * This will execute the key generation for the number of supplied iterations and use a unique random salt.
// * This will block for a while depending on processor speed.
// */
// public static SecretKey createKey(String password, int pbkdfIterations) {
// return createKey(password, pbkdfIterations, new PrngSaltGenerator());
// }
//
// /**
// * This will execute the key generation for the number of supplied iterations and use salt from the
// * supplied source. This will block for a while depending on processor speed.
// */
// public static SecretKey createKey(String password, int pbkdfIterations, SaltGenerator saltGenerator) {
// PbkdfKeyGenerator keyGenerator = new PbkdfKeyGenerator(pbkdfIterations, EncryptionConstants.AES_256_KEY_LENGTH_BITS, saltGenerator, SALT_SIZE_BYTES);
// return keyGenerator.generateKey(password);
// }
//
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
// Path: AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/test/TestKeyGeneration.java
import android.test.AndroidTestCase;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256KeyFromPasswordFactory;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import javax.crypto.SecretKey;
/*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.test;
/**
* Test secret key creation.
*/
public class TestKeyGeneration extends AndroidTestCase {
public void testRandomKey() {
SecretKey secretKey = Aes256RandomKeyFactory.createKey();
assertNotNull("Secret key was not created", secretKey); | assertEquals("Secret key was incorrect length", secretKey.getEncoded().length, EncryptionConstants.AES_256_KEY_LENGTH_BITS / 8); |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/test/TestKeyGeneration.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256KeyFromPasswordFactory.java
// public class Aes256KeyFromPasswordFactory {
//
// public static final int SALT_SIZE_BYTES = 512;
//
// /**
// * This will execute the key generation for the number of supplied iterations and use a unique random salt.
// * This will block for a while depending on processor speed.
// */
// public static SecretKey createKey(String password, int pbkdfIterations) {
// return createKey(password, pbkdfIterations, new PrngSaltGenerator());
// }
//
// /**
// * This will execute the key generation for the number of supplied iterations and use salt from the
// * supplied source. This will block for a while depending on processor speed.
// */
// public static SecretKey createKey(String password, int pbkdfIterations, SaltGenerator saltGenerator) {
// PbkdfKeyGenerator keyGenerator = new PbkdfKeyGenerator(pbkdfIterations, EncryptionConstants.AES_256_KEY_LENGTH_BITS, saltGenerator, SALT_SIZE_BYTES);
// return keyGenerator.generateKey(password);
// }
//
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
| import android.test.AndroidTestCase;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256KeyFromPasswordFactory;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import javax.crypto.SecretKey; | /*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.test;
/**
* Test secret key creation.
*/
public class TestKeyGeneration extends AndroidTestCase {
public void testRandomKey() {
SecretKey secretKey = Aes256RandomKeyFactory.createKey();
assertNotNull("Secret key was not created", secretKey);
assertEquals("Secret key was incorrect length", secretKey.getEncoded().length, EncryptionConstants.AES_256_KEY_LENGTH_BITS / 8);
}
public void testPasswordKey() { | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256KeyFromPasswordFactory.java
// public class Aes256KeyFromPasswordFactory {
//
// public static final int SALT_SIZE_BYTES = 512;
//
// /**
// * This will execute the key generation for the number of supplied iterations and use a unique random salt.
// * This will block for a while depending on processor speed.
// */
// public static SecretKey createKey(String password, int pbkdfIterations) {
// return createKey(password, pbkdfIterations, new PrngSaltGenerator());
// }
//
// /**
// * This will execute the key generation for the number of supplied iterations and use salt from the
// * supplied source. This will block for a while depending on processor speed.
// */
// public static SecretKey createKey(String password, int pbkdfIterations, SaltGenerator saltGenerator) {
// PbkdfKeyGenerator keyGenerator = new PbkdfKeyGenerator(pbkdfIterations, EncryptionConstants.AES_256_KEY_LENGTH_BITS, saltGenerator, SALT_SIZE_BYTES);
// return keyGenerator.generateKey(password);
// }
//
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
// Path: AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/test/TestKeyGeneration.java
import android.test.AndroidTestCase;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256KeyFromPasswordFactory;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import javax.crypto.SecretKey;
/*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.test;
/**
* Test secret key creation.
*/
public class TestKeyGeneration extends AndroidTestCase {
public void testRandomKey() {
SecretKey secretKey = Aes256RandomKeyFactory.createKey();
assertNotNull("Secret key was not created", secretKey);
assertEquals("Secret key was incorrect length", secretKey.getEncoded().length, EncryptionConstants.AES_256_KEY_LENGTH_BITS / 8);
}
public void testPasswordKey() { | SecretKey secretKey = Aes256KeyFromPasswordFactory.createKey("testPassword", 10000); |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
| import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import javax.crypto.SecretKey; | /*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.generator;
/**
* Create a new random AES256 key.
*/
public class Aes256RandomKeyFactory {
/**
* Create a randomly generated AES256 key.
*/
public static SecretKey createKey() { | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import javax.crypto.SecretKey;
/*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.generator;
/**
* Create a new random AES256 key.
*/
public class Aes256RandomKeyFactory {
/**
* Create a randomly generated AES256 key.
*/
public static SecretKey createKey() { | RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS); |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
| import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import javax.crypto.SecretKey; | /*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.generator;
/**
* Create a new random AES256 key.
*/
public class Aes256RandomKeyFactory {
/**
* Create a randomly generated AES256 key.
*/
public static SecretKey createKey() { | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import javax.crypto.SecretKey;
/*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.generator;
/**
* Create a new random AES256 key.
*/
public class Aes256RandomKeyFactory {
/**
* Create a randomly generated AES256 key.
*/
public static SecretKey createKey() { | RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS); |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/keys/storage/TestVaultUpgradePre18.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
| import android.os.Build;
import android.test.AndroidTestCase;
import android.util.Log;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import javax.crypto.SecretKey; | /*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.storage;
/**
* Test transition to version 18 from a pre-18 device if it receives an OS upgrade.
*/
public class TestVaultUpgradePre18 extends AndroidTestCase {
private static final String TAG = TestVaultUpgradePre18.class.getSimpleName();
private static final String KEY_FILE_NAME = "upgradeKeyFile";
private static final String KEY_ALIAS_1 = "upgradeKeyAlias";
private static final int KEY_INDEX_1 = 1232234;
private static final String PRESHARED_SECRET_1 = "a;sdlfkja;asdfae211;s122222e;l2ihjl9jl9dj9";
public void testUpgrade() {
try { | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
// Path: AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/keys/storage/TestVaultUpgradePre18.java
import android.os.Build;
import android.test.AndroidTestCase;
import android.util.Log;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import javax.crypto.SecretKey;
/*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.storage;
/**
* Test transition to version 18 from a pre-18 device if it receives an OS upgrade.
*/
public class TestVaultUpgradePre18 extends AndroidTestCase {
private static final String TAG = TestVaultUpgradePre18.class.getSimpleName();
private static final String KEY_FILE_NAME = "upgradeKeyFile";
private static final String KEY_ALIAS_1 = "upgradeKeyAlias";
private static final int KEY_INDEX_1 = 1232234;
private static final String PRESHARED_SECRET_1 = "a;sdlfkja;asdfae211;s122222e;l2ihjl9jl9dj9";
public void testUpgrade() {
try { | SecretKey originalKey = Aes256RandomKeyFactory.createKey(); |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/keys/storage/TestVaultUpgradePre18.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
| import android.os.Build;
import android.test.AndroidTestCase;
import android.util.Log;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import javax.crypto.SecretKey; | SecretKey originalReadKey = keyStorageOld.loadKey(getContext());
assertNotNull("Key was null after creation and read from old storage.", originalReadKey);
assertTrue("Keys were not identical after creation and read from old storage", Arrays.equals(originalKey.getEncoded(), originalReadKey.getEncoded()));
KeyStorage keyStorageNew = getKeyStorage(Build.VERSION_CODES.JELLY_BEAN_MR2);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageNew.getKeyStorageType());
SecretKey upgradedKey = keyStorageNew.loadKey(getContext());
assertNotNull("Key was null after upgrade.", upgradedKey);
assertTrue("Keys were not identical after upgrade", Arrays.equals(originalKey.getEncoded(), upgradedKey.getEncoded()));
KeyStorage keyStorageRead = getKeyStorage(Build.VERSION_CODES.JELLY_BEAN_MR2);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageRead.getKeyStorageType());
SecretKey upgradedReadKey = keyStorageRead.loadKey(getContext());
assertNotNull("Key was null after upgrade and read from storage.", upgradedReadKey);
assertTrue("Keys were not identical after upgrade and read from storage", Arrays.equals(originalKey.getEncoded(), upgradedReadKey.getEncoded()));
} catch (GeneralSecurityException e) {
Log.e(TAG, "Caught java.security.GeneralSecurityException", e);
assertTrue("Exception when creating keystores", false);
}
}
private KeyStorage getKeyStorage(int sdkInt) throws GeneralSecurityException {
return CompatSharedPrefKeyStorageFactory.createKeyStorage(
getContext(),
sdkInt,
KEY_FILE_NAME,
KEY_ALIAS_1,
KEY_INDEX_1, | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
// Path: AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/keys/storage/TestVaultUpgradePre18.java
import android.os.Build;
import android.test.AndroidTestCase;
import android.util.Log;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import javax.crypto.SecretKey;
SecretKey originalReadKey = keyStorageOld.loadKey(getContext());
assertNotNull("Key was null after creation and read from old storage.", originalReadKey);
assertTrue("Keys were not identical after creation and read from old storage", Arrays.equals(originalKey.getEncoded(), originalReadKey.getEncoded()));
KeyStorage keyStorageNew = getKeyStorage(Build.VERSION_CODES.JELLY_BEAN_MR2);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageNew.getKeyStorageType());
SecretKey upgradedKey = keyStorageNew.loadKey(getContext());
assertNotNull("Key was null after upgrade.", upgradedKey);
assertTrue("Keys were not identical after upgrade", Arrays.equals(originalKey.getEncoded(), upgradedKey.getEncoded()));
KeyStorage keyStorageRead = getKeyStorage(Build.VERSION_CODES.JELLY_BEAN_MR2);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageRead.getKeyStorageType());
SecretKey upgradedReadKey = keyStorageRead.loadKey(getContext());
assertNotNull("Key was null after upgrade and read from storage.", upgradedReadKey);
assertTrue("Keys were not identical after upgrade and read from storage", Arrays.equals(originalKey.getEncoded(), upgradedReadKey.getEncoded()));
} catch (GeneralSecurityException e) {
Log.e(TAG, "Caught java.security.GeneralSecurityException", e);
assertTrue("Exception when creating keystores", false);
}
}
private KeyStorage getKeyStorage(int sdkInt) throws GeneralSecurityException {
return CompatSharedPrefKeyStorageFactory.createKeyStorage(
getContext(),
sdkInt,
KEY_FILE_NAME,
KEY_ALIAS_1,
KEY_INDEX_1, | EncryptionConstants.AES_CIPHER, |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/keys/storage/TestVaultUpgradePre18.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
| import android.os.Build;
import android.test.AndroidTestCase;
import android.util.Log;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import javax.crypto.SecretKey; | assertTrue("Keys were not identical after creation and read from old storage", Arrays.equals(originalKey.getEncoded(), originalReadKey.getEncoded()));
KeyStorage keyStorageNew = getKeyStorage(Build.VERSION_CODES.JELLY_BEAN_MR2);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageNew.getKeyStorageType());
SecretKey upgradedKey = keyStorageNew.loadKey(getContext());
assertNotNull("Key was null after upgrade.", upgradedKey);
assertTrue("Keys were not identical after upgrade", Arrays.equals(originalKey.getEncoded(), upgradedKey.getEncoded()));
KeyStorage keyStorageRead = getKeyStorage(Build.VERSION_CODES.JELLY_BEAN_MR2);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageRead.getKeyStorageType());
SecretKey upgradedReadKey = keyStorageRead.loadKey(getContext());
assertNotNull("Key was null after upgrade and read from storage.", upgradedReadKey);
assertTrue("Keys were not identical after upgrade and read from storage", Arrays.equals(originalKey.getEncoded(), upgradedReadKey.getEncoded()));
} catch (GeneralSecurityException e) {
Log.e(TAG, "Caught java.security.GeneralSecurityException", e);
assertTrue("Exception when creating keystores", false);
}
}
private KeyStorage getKeyStorage(int sdkInt) throws GeneralSecurityException {
return CompatSharedPrefKeyStorageFactory.createKeyStorage(
getContext(),
sdkInt,
KEY_FILE_NAME,
KEY_ALIAS_1,
KEY_INDEX_1,
EncryptionConstants.AES_CIPHER,
PRESHARED_SECRET_1, | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
// Path: AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/keys/storage/TestVaultUpgradePre18.java
import android.os.Build;
import android.test.AndroidTestCase;
import android.util.Log;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import javax.crypto.SecretKey;
assertTrue("Keys were not identical after creation and read from old storage", Arrays.equals(originalKey.getEncoded(), originalReadKey.getEncoded()));
KeyStorage keyStorageNew = getKeyStorage(Build.VERSION_CODES.JELLY_BEAN_MR2);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageNew.getKeyStorageType());
SecretKey upgradedKey = keyStorageNew.loadKey(getContext());
assertNotNull("Key was null after upgrade.", upgradedKey);
assertTrue("Keys were not identical after upgrade", Arrays.equals(originalKey.getEncoded(), upgradedKey.getEncoded()));
KeyStorage keyStorageRead = getKeyStorage(Build.VERSION_CODES.JELLY_BEAN_MR2);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageRead.getKeyStorageType());
SecretKey upgradedReadKey = keyStorageRead.loadKey(getContext());
assertNotNull("Key was null after upgrade and read from storage.", upgradedReadKey);
assertTrue("Keys were not identical after upgrade and read from storage", Arrays.equals(originalKey.getEncoded(), upgradedReadKey.getEncoded()));
} catch (GeneralSecurityException e) {
Log.e(TAG, "Caught java.security.GeneralSecurityException", e);
assertTrue("Exception when creating keystores", false);
}
}
private KeyStorage getKeyStorage(int sdkInt) throws GeneralSecurityException {
return CompatSharedPrefKeyStorageFactory.createKeyStorage(
getContext(),
sdkInt,
KEY_FILE_NAME,
KEY_ALIAS_1,
KEY_INDEX_1,
EncryptionConstants.AES_CIPHER,
PRESHARED_SECRET_1, | new PrngSaltGenerator()); |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/storage/KeychainAuthenticatedKeyStorage.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
| import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.util.Log;
import com.bottlerocketstudios.vault.EncryptionConstants;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException; | /*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.storage;
/**
* Use Android Keystore to keep the SecretKey. Requires user authentication to be enabled and
* requires re-authentication at specified intervals.
*/
public class KeychainAuthenticatedKeyStorage implements KeyStorage {
private static final String TAG = KeychainAuthenticatedKeyStorage.class.getSimpleName();
private final String mKeyAlias;
private final String mAlgorithm;
private final String mBlockMode;
private final String mPadding;
private final int mAuthDurationSeconds;
private final String mKeyLock = "keyLock";
public KeychainAuthenticatedKeyStorage(String keyAlias, String algorithm, String blockMode, String padding, int authDurationSeconds) {
mKeyAlias = keyAlias;
mAlgorithm = algorithm;
mBlockMode = blockMode;
mPadding = padding;
mAuthDurationSeconds = authDurationSeconds;
}
@Override
public SecretKey loadKey(Context context) {
SecretKey secretKey = null;
synchronized (mKeyLock) {
try { | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/storage/KeychainAuthenticatedKeyStorage.java
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.util.Log;
import com.bottlerocketstudios.vault.EncryptionConstants;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
/*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.storage;
/**
* Use Android Keystore to keep the SecretKey. Requires user authentication to be enabled and
* requires re-authentication at specified intervals.
*/
public class KeychainAuthenticatedKeyStorage implements KeyStorage {
private static final String TAG = KeychainAuthenticatedKeyStorage.class.getSimpleName();
private final String mKeyAlias;
private final String mAlgorithm;
private final String mBlockMode;
private final String mPadding;
private final int mAuthDurationSeconds;
private final String mKeyLock = "keyLock";
public KeychainAuthenticatedKeyStorage(String keyAlias, String algorithm, String blockMode, String padding, int authDurationSeconds) {
mKeyAlias = keyAlias;
mAlgorithm = algorithm;
mBlockMode = blockMode;
mPadding = padding;
mAuthDurationSeconds = authDurationSeconds;
}
@Override
public SecretKey loadKey(Context context) {
SecretKey secretKey = null;
synchronized (mKeyLock) {
try { | KeyStore keyStore = KeyStore.getInstance(EncryptionConstants.ANDROID_KEY_STORE); |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/PbkdfKeyGenerator.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/SaltGenerator.java
// public interface SaltGenerator {
// byte[] createSaltBytes(int size);
// }
| import android.util.Log;
import com.bottlerocketstudios.vault.salt.SaltGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec; | /*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.generator;
/**
* Generate a SecretKey given a user supplied password string.
*/
public class PbkdfKeyGenerator {
private static final String TAG = PbkdfKeyGenerator.class.getSimpleName();
private static final String PBE_ALGORITHM = "PBKDF2WithHmacSHA1";
private final int mPbkdf2Iterations; | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/SaltGenerator.java
// public interface SaltGenerator {
// byte[] createSaltBytes(int size);
// }
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/PbkdfKeyGenerator.java
import android.util.Log;
import com.bottlerocketstudios.vault.salt.SaltGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
/*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.generator;
/**
* Generate a SecretKey given a user supplied password string.
*/
public class PbkdfKeyGenerator {
private static final String TAG = PbkdfKeyGenerator.class.getSimpleName();
private static final String PBE_ALGORITHM = "PBKDF2WithHmacSHA1";
private final int mPbkdf2Iterations; | private final SaltGenerator mSaltGenerator; |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/keys/storage/TestVaultUpgrade22To23.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
| import android.os.Build;
import android.test.AndroidTestCase;
import android.util.Log;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import javax.crypto.SecretKey; | /*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.storage;
/**
* Test transition to version 18 from a pre-18 device if it receives an OS upgrade.
*/
public class TestVaultUpgrade22To23 extends AndroidTestCase {
private static final String TAG = TestVaultUpgrade22To23.class.getSimpleName();
private static final String KEY_FILE_NAME = "upgrade22to23KeyFile";
private static final String KEY_ALIAS_1 = "upgrade22to23KeyAlias";
private static final int KEY_INDEX_1 = 1232734;
private static final String PRESHARED_SECRET_1 = "a;sdlfkja;asdfasds21222e;l2ihjl9jl9dj9";
public void testUpgrade() {
assertTrue("This test will not pass below API 23", Build.VERSION.SDK_INT >= Build.VERSION_CODES.M);
try { | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
// Path: AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/keys/storage/TestVaultUpgrade22To23.java
import android.os.Build;
import android.test.AndroidTestCase;
import android.util.Log;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import javax.crypto.SecretKey;
/*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.storage;
/**
* Test transition to version 18 from a pre-18 device if it receives an OS upgrade.
*/
public class TestVaultUpgrade22To23 extends AndroidTestCase {
private static final String TAG = TestVaultUpgrade22To23.class.getSimpleName();
private static final String KEY_FILE_NAME = "upgrade22to23KeyFile";
private static final String KEY_ALIAS_1 = "upgrade22to23KeyAlias";
private static final int KEY_INDEX_1 = 1232734;
private static final String PRESHARED_SECRET_1 = "a;sdlfkja;asdfasds21222e;l2ihjl9jl9dj9";
public void testUpgrade() {
assertTrue("This test will not pass below API 23", Build.VERSION.SDK_INT >= Build.VERSION_CODES.M);
try { | SecretKey originalKey = Aes256RandomKeyFactory.createKey(); |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/keys/storage/TestVaultUpgrade22To23.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
| import android.os.Build;
import android.test.AndroidTestCase;
import android.util.Log;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import javax.crypto.SecretKey; | SecretKey originalReadKey = keyStorageOld.loadKey(getContext());
assertNotNull("Key was null after creation and read from old storage.", originalReadKey);
assertTrue("Keys were not identical after creation and read from old storage", Arrays.equals(originalKey.getEncoded(), originalReadKey.getEncoded()));
KeyStorage keyStorageNew = getKeyStorage(Build.VERSION_CODES.M);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageNew.getKeyStorageType());
SecretKey upgradedKey = keyStorageNew.loadKey(getContext());
assertNotNull("Key was null after upgrade.", upgradedKey);
assertTrue("Keys were not identical after upgrade", Arrays.equals(originalKey.getEncoded(), upgradedKey.getEncoded()));
KeyStorage keyStorageRead = getKeyStorage(Build.VERSION_CODES.M);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageRead.getKeyStorageType());
SecretKey upgradedReadKey = keyStorageRead.loadKey(getContext());
assertNotNull("Key was null after upgrade and read from storage.", upgradedReadKey);
assertTrue("Keys were not identical after upgrade and read from storage", Arrays.equals(originalKey.getEncoded(), upgradedReadKey.getEncoded()));
} catch (GeneralSecurityException e) {
Log.e(TAG, "Caught java.security.GeneralSecurityException", e);
assertTrue("Exception when creating keystores", false);
}
}
private KeyStorage getKeyStorage(int sdkInt) throws GeneralSecurityException {
return CompatSharedPrefKeyStorageFactory.createKeyStorage(
getContext(),
sdkInt,
KEY_FILE_NAME,
KEY_ALIAS_1,
KEY_INDEX_1, | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
// Path: AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/keys/storage/TestVaultUpgrade22To23.java
import android.os.Build;
import android.test.AndroidTestCase;
import android.util.Log;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import javax.crypto.SecretKey;
SecretKey originalReadKey = keyStorageOld.loadKey(getContext());
assertNotNull("Key was null after creation and read from old storage.", originalReadKey);
assertTrue("Keys were not identical after creation and read from old storage", Arrays.equals(originalKey.getEncoded(), originalReadKey.getEncoded()));
KeyStorage keyStorageNew = getKeyStorage(Build.VERSION_CODES.M);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageNew.getKeyStorageType());
SecretKey upgradedKey = keyStorageNew.loadKey(getContext());
assertNotNull("Key was null after upgrade.", upgradedKey);
assertTrue("Keys were not identical after upgrade", Arrays.equals(originalKey.getEncoded(), upgradedKey.getEncoded()));
KeyStorage keyStorageRead = getKeyStorage(Build.VERSION_CODES.M);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageRead.getKeyStorageType());
SecretKey upgradedReadKey = keyStorageRead.loadKey(getContext());
assertNotNull("Key was null after upgrade and read from storage.", upgradedReadKey);
assertTrue("Keys were not identical after upgrade and read from storage", Arrays.equals(originalKey.getEncoded(), upgradedReadKey.getEncoded()));
} catch (GeneralSecurityException e) {
Log.e(TAG, "Caught java.security.GeneralSecurityException", e);
assertTrue("Exception when creating keystores", false);
}
}
private KeyStorage getKeyStorage(int sdkInt) throws GeneralSecurityException {
return CompatSharedPrefKeyStorageFactory.createKeyStorage(
getContext(),
sdkInt,
KEY_FILE_NAME,
KEY_ALIAS_1,
KEY_INDEX_1, | EncryptionConstants.AES_CIPHER, |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/keys/storage/TestVaultUpgrade22To23.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
| import android.os.Build;
import android.test.AndroidTestCase;
import android.util.Log;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import javax.crypto.SecretKey; | assertTrue("Keys were not identical after creation and read from old storage", Arrays.equals(originalKey.getEncoded(), originalReadKey.getEncoded()));
KeyStorage keyStorageNew = getKeyStorage(Build.VERSION_CODES.M);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageNew.getKeyStorageType());
SecretKey upgradedKey = keyStorageNew.loadKey(getContext());
assertNotNull("Key was null after upgrade.", upgradedKey);
assertTrue("Keys were not identical after upgrade", Arrays.equals(originalKey.getEncoded(), upgradedKey.getEncoded()));
KeyStorage keyStorageRead = getKeyStorage(Build.VERSION_CODES.M);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageRead.getKeyStorageType());
SecretKey upgradedReadKey = keyStorageRead.loadKey(getContext());
assertNotNull("Key was null after upgrade and read from storage.", upgradedReadKey);
assertTrue("Keys were not identical after upgrade and read from storage", Arrays.equals(originalKey.getEncoded(), upgradedReadKey.getEncoded()));
} catch (GeneralSecurityException e) {
Log.e(TAG, "Caught java.security.GeneralSecurityException", e);
assertTrue("Exception when creating keystores", false);
}
}
private KeyStorage getKeyStorage(int sdkInt) throws GeneralSecurityException {
return CompatSharedPrefKeyStorageFactory.createKeyStorage(
getContext(),
sdkInt,
KEY_FILE_NAME,
KEY_ALIAS_1,
KEY_INDEX_1,
EncryptionConstants.AES_CIPHER,
PRESHARED_SECRET_1, | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/EncryptionConstants.java
// public class EncryptionConstants {
// public static final String AES_CIPHER = "AES";
// public static final String BLOCK_MODE_CBC = "CBC";
// public static final String ENCRYPTION_PADDING_PKCS5 = "PKCS5Padding";
// public static final String ENCRYPTION_PADDING_PKCS7 = "PKCS7Padding";
//
// /**
// * While this specifies PKCS5Padding and a 256 bit key, a historical artifact in the Sun encryption
// * implementation interprets PKCS5 to be PKCS7 for block sizes over 8 bytes. In Android M this
// * appears to have been corrected so that PKCS7Padding will work when instantiating a Cipher object.
// */
// public static final String AES_CBC_PADDED_TRANSFORM = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS5;
// public static final String AES_CBC_PADDED_TRANSFORM_ANDROID_M = AES_CIPHER + "/" + BLOCK_MODE_CBC + "/" + ENCRYPTION_PADDING_PKCS7;
// public static final int AES_256_KEY_LENGTH_BITS = 256;
//
// public static final String DIGEST_SHA256 = "SHA256";
//
// public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/generator/Aes256RandomKeyFactory.java
// public class Aes256RandomKeyFactory {
//
// /**
// * Create a randomly generated AES256 key.
// */
// public static SecretKey createKey() {
// RandomKeyGenerator keyGenerator = new RandomKeyGenerator(new PrngSaltGenerator(), EncryptionConstants.AES_256_KEY_LENGTH_BITS);
// return keyGenerator.generateKey(EncryptionConstants.AES_CIPHER);
// }
// }
//
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/salt/PrngSaltGenerator.java
// public class PrngSaltGenerator implements SaltGenerator {
//
// SecureRandom mSecureRandom;
//
// public PrngSaltGenerator() {
// mSecureRandom = new SecureRandom();
// }
//
// @Override
// public byte[] createSaltBytes(int size) {
// byte[] result = new byte[size];
// mSecureRandom.nextBytes(result);
// return result;
// }
// }
// Path: AndroidVault/vault/src/androidTest/java/com/bottlerocketstudios/vault/keys/storage/TestVaultUpgrade22To23.java
import android.os.Build;
import android.test.AndroidTestCase;
import android.util.Log;
import com.bottlerocketstudios.vault.EncryptionConstants;
import com.bottlerocketstudios.vault.keys.generator.Aes256RandomKeyFactory;
import com.bottlerocketstudios.vault.salt.PrngSaltGenerator;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import javax.crypto.SecretKey;
assertTrue("Keys were not identical after creation and read from old storage", Arrays.equals(originalKey.getEncoded(), originalReadKey.getEncoded()));
KeyStorage keyStorageNew = getKeyStorage(Build.VERSION_CODES.M);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageNew.getKeyStorageType());
SecretKey upgradedKey = keyStorageNew.loadKey(getContext());
assertNotNull("Key was null after upgrade.", upgradedKey);
assertTrue("Keys were not identical after upgrade", Arrays.equals(originalKey.getEncoded(), upgradedKey.getEncoded()));
KeyStorage keyStorageRead = getKeyStorage(Build.VERSION_CODES.M);
assertEquals("Incorrect KeyStorageType", KeyStorageType.ANDROID_KEYSTORE, keyStorageRead.getKeyStorageType());
SecretKey upgradedReadKey = keyStorageRead.loadKey(getContext());
assertNotNull("Key was null after upgrade and read from storage.", upgradedReadKey);
assertTrue("Keys were not identical after upgrade and read from storage", Arrays.equals(originalKey.getEncoded(), upgradedReadKey.getEncoded()));
} catch (GeneralSecurityException e) {
Log.e(TAG, "Caught java.security.GeneralSecurityException", e);
assertTrue("Exception when creating keystores", false);
}
}
private KeyStorage getKeyStorage(int sdkInt) throws GeneralSecurityException {
return CompatSharedPrefKeyStorageFactory.createKeyStorage(
getContext(),
sdkInt,
KEY_FILE_NAME,
KEY_ALIAS_1,
KEY_INDEX_1,
EncryptionConstants.AES_CIPHER,
PRESHARED_SECRET_1, | new PrngSaltGenerator()); |
BottleRocketStudios/Android-Vault | AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/wrapper/SecretKeyWrapper.java | // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/storage/KeyStorageType.java
// public enum KeyStorageType {
// ANDROID_KEYSTORE,
// ANDROID_KEYSTORE_AUTHENTICATED,
// OBFUSCATED,
// NOT_PERSISTENT
// }
| import android.content.Context;
import com.bottlerocketstudios.vault.keys.storage.KeyStorageType;
import java.io.IOException;
import java.security.GeneralSecurityException;
import javax.crypto.SecretKey; | /*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.wrapper;
/**
* Interface that implementations of secret key wrapping operations must implement.
*/
public interface SecretKeyWrapper {
/**
* Wrap a {@link javax.crypto.SecretKey} using the public key assigned to this wrapper.
* Use {@link #unwrap(byte[], String)} to later recover the original
* {@link javax.crypto.SecretKey}.
*
* @return a wrapped version of the given {@link javax.crypto.SecretKey} that can be
* safely stored on untrusted storage.
*/
byte[] wrap(SecretKey key) throws GeneralSecurityException, IOException;
/**
* Unwrap a {@link javax.crypto.SecretKey} using the private key assigned to this
* wrapper.
*
* @param blob a wrapped {@link javax.crypto.SecretKey} as previously returned by
* {@link #wrap(javax.crypto.SecretKey)}.
*/
SecretKey unwrap(byte[] blob, String wrappedKeyAlgorithm) throws GeneralSecurityException, IOException;
/**
* Change key material so that next wrapping will use a different key pair.
* @throws GeneralSecurityException
*/
void clearKey(Context context) throws GeneralSecurityException, IOException;
| // Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/storage/KeyStorageType.java
// public enum KeyStorageType {
// ANDROID_KEYSTORE,
// ANDROID_KEYSTORE_AUTHENTICATED,
// OBFUSCATED,
// NOT_PERSISTENT
// }
// Path: AndroidVault/vault/src/main/java/com/bottlerocketstudios/vault/keys/wrapper/SecretKeyWrapper.java
import android.content.Context;
import com.bottlerocketstudios.vault.keys.storage.KeyStorageType;
import java.io.IOException;
import java.security.GeneralSecurityException;
import javax.crypto.SecretKey;
/*
* Copyright (c) 2016. Bottle Rocket LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bottlerocketstudios.vault.keys.wrapper;
/**
* Interface that implementations of secret key wrapping operations must implement.
*/
public interface SecretKeyWrapper {
/**
* Wrap a {@link javax.crypto.SecretKey} using the public key assigned to this wrapper.
* Use {@link #unwrap(byte[], String)} to later recover the original
* {@link javax.crypto.SecretKey}.
*
* @return a wrapped version of the given {@link javax.crypto.SecretKey} that can be
* safely stored on untrusted storage.
*/
byte[] wrap(SecretKey key) throws GeneralSecurityException, IOException;
/**
* Unwrap a {@link javax.crypto.SecretKey} using the private key assigned to this
* wrapper.
*
* @param blob a wrapped {@link javax.crypto.SecretKey} as previously returned by
* {@link #wrap(javax.crypto.SecretKey)}.
*/
SecretKey unwrap(byte[] blob, String wrappedKeyAlgorithm) throws GeneralSecurityException, IOException;
/**
* Change key material so that next wrapping will use a different key pair.
* @throws GeneralSecurityException
*/
void clearKey(Context context) throws GeneralSecurityException, IOException;
| public KeyStorageType getKeyStorageType(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.